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 <com_android_bluetooth_flags.h>
20 #include <sys/ioctl.h>
21 #include <sys/socket.h>
22 #include <sys/types.h>
23 #include <unistd.h>
24 
25 #include <cstdint>
26 #include <cstring>
27 #include <mutex>
28 
29 #include "bta/include/bta_jv_api.h"
30 #include "btif/include/btif_dm.h"
31 #include "btif/include/btif_sock.h"
32 #include "btif/include/btif_sock_logging.h"
33 #include "btif/include/btif_sock_thread.h"
34 #include "btif/include/btif_sock_util.h"
35 #include "btif/include/btif_uid.h"
36 #include "gd/os/rand.h"
37 #include "include/hardware/bluetooth.h"
38 #include "internal_include/bt_target.h"
39 #include "lpp/lpp_offload_interface.h"
40 #include "main/shim/entry.h"
41 #include "osi/include/allocator.h"
42 #include "osi/include/osi.h"
43 #include "stack/include/bt_hdr.h"
44 #include "stack/include/l2cdefs.h"
45 #include "types/raw_address.h"
46 
47 // TODO(b/369381361) Enfore -Wmissing-prototypes
48 #pragma GCC diagnostic ignored "-Wmissing-prototypes"
49 
50 using namespace bluetooth;
51 
52 struct packet {
53   struct packet *next, *prev;
54   uint32_t len;
55   uint8_t* data;
56 };
57 
58 typedef struct l2cap_socket {
59   struct l2cap_socket* prev;  // link to prev list item
60   struct l2cap_socket* next;  // link to next list item
61   RawAddress addr;            // other side's address
62   char name[256];             // user-friendly name of the service
63   uint32_t id;                // just a tag to find this struct
64   int app_uid;                // The UID of the app who requested this socket
65   int handle;                 // handle from lower layers
66   unsigned security;          // security flags
67   int channel;                // PSM
68   int our_fd;                 // fd from our side
69   int app_fd;                 // fd from app's side
70   int listen_fd;              // listen socket fd from our side
71 
72   unsigned bytes_buffered;
73   struct packet* first_packet;  // fist packet to be delivered to app
74   struct packet* last_packet;   // last packet to be delivered to app
75 
76   unsigned server : 1;            // is a server? (or connecting?)
77   unsigned connected : 1;         // is connected?
78   unsigned outgoing_congest : 1;  // should we hold?
79   unsigned server_psm_sent : 1;   // The server shall only send PSM once.
80   bool is_le_coc;                 // is le connection oriented channel?
81   uint16_t rx_mtu;
82   uint16_t tx_mtu;
83   // Cumulative number of bytes transmitted on this socket
84   int64_t tx_bytes;
85   // Cumulative number of bytes received on this socket
86   int64_t rx_bytes;
87   uint16_t local_cid;   // The local CID
88   uint16_t remote_cid;  // The remote CID
89   Uuid conn_uuid;       // The connection uuid
90   uint64_t socket_id;   // Socket ID in connected state
91   btsock_data_path_t data_path;  // socket data path
92   char socket_name[128];         // descriptive socket name
93   uint64_t hub_id;               // ID of the hub to which the end point belongs
94   uint64_t endpoint_id;          // ID of the hub end point
95   bool is_accepting;             // is app accepting on server socket?
96 } l2cap_socket;
97 
98 static void btsock_l2cap_server_listen(l2cap_socket* sock);
99 static uint64_t btif_l2cap_sock_generate_socket_id();
100 static void on_cl_l2cap_psm_connect_offload_l(tBTA_JV_L2CAP_OPEN* p_open, l2cap_socket* sock);
101 static void on_srv_l2cap_psm_connect_offload_l(tBTA_JV_L2CAP_OPEN* p_open, l2cap_socket* sock);
102 
103 static std::mutex state_lock;
104 
105 l2cap_socket* socks = NULL;
106 static uint32_t last_sock_id = 0;
107 static uid_set_t* uid_set = NULL;
108 static int pth = -1;
109 
110 static void btsock_l2cap_cbk(tBTA_JV_EVT event, tBTA_JV* p_data, uint32_t l2cap_socket_id);
111 
112 /* TODO: Consider to remove this buffer, as we have a buffer in l2cap as well,
113  * and we risk
114  *       a buffer overflow with this implementation if the socket data is not
115  * read from
116  *       JAVA for a while. In such a case we should use flow control to tell the
117  * sender to
118  *       back off.
119  *       BUT remember we need to avoid blocking the BTA task execution - hence
120  * we cannot
121  *       directly write to the socket.
122  *       we should be able to change to store the data pointer here, and just
123  * wait
124  *       confirming the l2cap_ind until we have more space in the buffer. */
125 
126 /* 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)127 static char packet_get_head_l(l2cap_socket* sock, uint8_t** data, uint32_t* len) {
128   struct packet* p = sock->first_packet;
129 
130   if (!p) {
131     return false;
132   }
133 
134   if (data) {
135     *data = sock->first_packet->data;
136   }
137   if (len) {
138     *len = sock->first_packet->len;
139   }
140   sock->first_packet = p->next;
141   if (sock->first_packet) {
142     sock->first_packet->prev = NULL;
143   } else {
144     sock->last_packet = NULL;
145   }
146 
147   if (len) {
148     sock->bytes_buffered -= *len;
149   }
150 
151   osi_free(p);
152 
153   return true;
154 }
155 
packet_alloc(const uint8_t * data,uint32_t len)156 static struct packet* packet_alloc(const uint8_t* data, uint32_t len) {
157   struct packet* p = (struct packet*)osi_calloc(sizeof(*p));
158   uint8_t* buf = (uint8_t*)osi_malloc(len);
159 
160   p->data = buf;
161   p->len = len;
162   memcpy(p->data, data, len);
163   return p;
164 }
165 
166 /* makes a copy of the data, returns true on success */
packet_put_head_l(l2cap_socket * sock,const void * data,uint32_t len)167 static char packet_put_head_l(l2cap_socket* sock, const void* data, uint32_t len) {
168   struct packet* p = packet_alloc((const uint8_t*)data, len);
169 
170   /*
171    * We do not check size limits here since this is used to undo "getting" a
172    * packet that the user read incompletely. That is to say the packet was
173    * already in the queue. We do check thos elimits in packet_put_tail_l() since
174    * that function is used to put new data into the queue.
175    */
176 
177   if (!p) {
178     return false;
179   }
180 
181   p->prev = NULL;
182   p->next = sock->first_packet;
183   sock->first_packet = p;
184   if (p->next) {
185     p->next->prev = p;
186   } else {
187     sock->last_packet = p;
188   }
189 
190   sock->bytes_buffered += len;
191 
192   return true;
193 }
194 
195 /* makes a copy of the data, returns true on success */
packet_put_tail_l(l2cap_socket * sock,const void * data,uint32_t len)196 static char packet_put_tail_l(l2cap_socket* sock, const void* data, uint32_t len) {
197   if (sock->bytes_buffered >= L2CAP_MAX_RX_BUFFER) {
198     log::error("Unable to add to buffer due to buffer overflow socket_id:{}", sock->id);
199     return false;
200   }
201 
202   struct packet* p = packet_alloc((const uint8_t*)data, len);
203   p->next = NULL;
204   p->prev = sock->last_packet;
205   sock->last_packet = p;
206   if (p->prev) {
207     p->prev->next = p;
208   } else {
209     sock->first_packet = p;
210   }
211 
212   sock->bytes_buffered += len;
213 
214   return true;
215 }
216 
is_inited(void)217 static char is_inited(void) {
218   std::unique_lock<std::mutex> lock(state_lock);
219   return pth != -1;
220 }
221 
222 /* only call with std::mutex taken */
btsock_l2cap_find_by_id_l(uint32_t id)223 static l2cap_socket* btsock_l2cap_find_by_id_l(uint32_t id) {
224   l2cap_socket* sock = socks;
225 
226   while (sock && sock->id != id) {
227     sock = sock->next;
228   }
229 
230   return sock;
231 }
232 
233 /* only call with std::mutex taken */
btsock_l2cap_find_by_conn_uuid_l(Uuid & conn_uuid)234 static l2cap_socket* btsock_l2cap_find_by_conn_uuid_l(Uuid& conn_uuid) {
235   l2cap_socket* sock = socks;
236 
237   while (sock) {
238     if (sock->conn_uuid == conn_uuid) {
239       return sock;
240     }
241     sock = sock->next;
242   }
243 
244   return nullptr;
245 }
246 
btsock_l2cap_free_l(l2cap_socket * sock)247 static void btsock_l2cap_free_l(l2cap_socket* sock) {
248   uint8_t* buf;
249   l2cap_socket* t = socks;
250 
251   while (t && t != sock) {
252     t = t->next;
253   }
254 
255   if (!t) { /* prever double-frees */
256     return;
257   }
258 
259   log::info(
260           "Disconnected L2CAP connection for device: {}, channel: {}, app_uid: {}, "
261           "id: {}, is_le: {}, socket_id: {}",
262           sock->addr, sock->channel, sock->app_uid, sock->id, sock->is_le_coc, sock->socket_id);
263   btif_sock_connection_logger(
264           sock->addr, sock->id, sock->is_le_coc ? BTSOCK_L2CAP_LE : BTSOCK_L2CAP,
265           SOCKET_CONNECTION_STATE_DISCONNECTED,
266           sock->server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION, sock->app_uid, sock->channel,
267           sock->tx_bytes, sock->rx_bytes, sock->name);
268   if (com::android::bluetooth::flags::socket_settings_api()) {
269     if (sock->data_path == BTSOCK_DATA_PATH_HARDWARE_OFFLOAD && !sock->server &&
270         sock->socket_id != 0) {
271       bluetooth::shim::GetLppOffloadManager()->SocketClosed(sock->socket_id);
272     }
273   }
274   if (sock->next) {
275     sock->next->prev = sock->prev;
276   }
277 
278   if (sock->prev) {
279     sock->prev->next = sock->next;
280   } else {
281     socks = sock->next;
282   }
283 
284   shutdown(sock->our_fd, SHUT_RDWR);
285   close(sock->our_fd);
286   if (sock->app_fd != -1) {
287     close(sock->app_fd);
288   } else {
289     log::info("Application has already closed l2cap socket socket_id:{}", sock->id);
290   }
291 
292   while (packet_get_head_l(sock, &buf, NULL)) {
293     osi_free(buf);
294   }
295 
296   // lower-level close() should be idempotent... so let's call it and see...
297   if (sock->is_le_coc) {
298     // Only call if we are non server connections
299     if (sock->handle >= 0 && (!sock->server)) {
300       BTA_JvL2capClose(sock->handle);
301     }
302     if ((sock->channel >= 0) && (sock->server)) {
303       BTA_JvFreeChannel(sock->channel, tBTA_JV_CONN_TYPE::L2CAP_LE);
304       log::info("Stopped L2CAP LE COC server socket_id:{} channel:{}", sock->id, sock->channel);
305       BTA_JvL2capStopServer(sock->channel, sock->id);
306     }
307   } else {
308     // Only call if we are non server connections
309     if ((sock->handle >= 0) && (!sock->server)) {
310       BTA_JvL2capClose(sock->handle);
311     }
312     if ((sock->channel >= 0) && (sock->server)) {
313       BTA_JvFreeChannel(sock->channel, tBTA_JV_CONN_TYPE::L2CAP);
314       BTA_JvL2capStopServer(sock->channel, sock->id);
315     }
316   }
317 
318   osi_free(sock);
319 }
320 
btsock_l2cap_alloc_l(const char * name,const RawAddress * addr,char is_server,int flags)321 static l2cap_socket* btsock_l2cap_alloc_l(const char* name, const RawAddress* addr, char is_server,
322                                           int flags) {
323   unsigned security = 0;
324   int fds[2];
325   l2cap_socket* sock = (l2cap_socket*)osi_calloc(sizeof(*sock));
326   int sock_type = SOCK_SEQPACKET;
327 
328   if (flags & BTSOCK_FLAG_ENCRYPT) {
329     security |= is_server ? BTM_SEC_IN_ENCRYPT : BTM_SEC_OUT_ENCRYPT;
330   }
331   if (flags & BTSOCK_FLAG_AUTH) {
332     security |= is_server ? BTM_SEC_IN_AUTHENTICATE : BTM_SEC_OUT_AUTHENTICATE;
333   }
334   if (flags & BTSOCK_FLAG_AUTH_MITM) {
335     security |= is_server ? BTM_SEC_IN_MITM : BTM_SEC_OUT_MITM;
336   }
337   if (flags & BTSOCK_FLAG_AUTH_16_DIGIT) {
338     security |= BTM_SEC_IN_MIN_16_DIGIT_PIN;
339   }
340 
341 #if TARGET_FLOSS
342   //Changed socket type to SOCK_STREAM to address a platform issue on FLOSS.
343   //This is a workaround and not the recommended approach.
344   //SOCK_SEQPACKET is preferred for L2CAP LE CoC channels because it preserves L2CAP
345   //packet boundaries, ensuring message integrity.
346   sock_type = SOCK_STREAM;
347 #endif
348   if (socketpair(AF_LOCAL, sock_type, 0, fds)) {
349     log::error("socketpair failed:{}", strerror(errno));
350     goto fail_sockpair;
351   }
352 
353   sock->our_fd = fds[0];
354   sock->app_fd = fds[1];
355   sock->listen_fd = -1;
356   sock->security = security;
357   sock->server = is_server;
358   sock->connected = false;
359   sock->handle = 0;
360   sock->server_psm_sent = false;
361   sock->app_uid = -1;
362   sock->conn_uuid = Uuid::kEmpty;
363   sock->socket_id = 0;
364   sock->data_path = BTSOCK_DATA_PATH_NO_OFFLOAD;
365   sock->hub_id = 0;
366   sock->endpoint_id = 0;
367   sock->is_accepting = false;
368 
369   if (name) {
370     strncpy(sock->name, name, sizeof(sock->name) - 1);
371   }
372   if (addr) {
373     sock->addr = *addr;
374   }
375 
376   sock->first_packet = NULL;
377   sock->last_packet = NULL;
378 
379   sock->tx_mtu = L2CAP_LE_MIN_MTU;
380 
381   sock->next = socks;
382   sock->prev = NULL;
383   if (socks) {
384     socks->prev = sock;
385   }
386   sock->id = last_sock_id + 1;
387   sock->tx_bytes = 0;
388   sock->rx_bytes = 0;
389   socks = sock;
390   /* paranoia cap on: verify no ID duplicates due to overflow and fix as needed
391    */
392   while (1) {
393     l2cap_socket* t;
394     t = socks->next;
395     while (t && t->id != sock->id) {
396       t = t->next;
397     }
398     if (!t && sock->id) { /* non-zeor handle is unique -> we're done */
399       break;
400     }
401     /* if we're here, we found a duplicate */
402     if (!++sock->id) { /* no zero IDs allowed */
403       sock->id++;
404     }
405   }
406   last_sock_id = sock->id;
407   log::info("Allocated l2cap socket structure socket_id:{}", sock->id);
408   return sock;
409 
410 fail_sockpair:
411   osi_free(sock);
412   return NULL;
413 }
414 
btsock_l2cap_init(int handle,uid_set_t * set)415 bt_status_t btsock_l2cap_init(int handle, uid_set_t* set) {
416   std::unique_lock<std::mutex> lock(state_lock);
417   pth = handle;
418   socks = NULL;
419   uid_set = set;
420   return BT_STATUS_SUCCESS;
421 }
422 
btsock_l2cap_cleanup()423 bt_status_t btsock_l2cap_cleanup() {
424   std::unique_lock<std::mutex> lock(state_lock);
425   pth = -1;
426   while (socks) {
427     btsock_l2cap_free_l(socks);
428   }
429   return BT_STATUS_SUCCESS;
430 }
431 
send_app_psm_or_chan_l(l2cap_socket * sock)432 static inline bool send_app_psm_or_chan_l(l2cap_socket* sock) {
433   log::info("Sending l2cap socket socket_id:{} channel:{}", sock->id, sock->channel);
434   return sock_send_all(sock->our_fd, (const uint8_t*)&sock->channel, sizeof(sock->channel)) ==
435          sizeof(sock->channel);
436 }
437 
send_app_err_code(l2cap_socket * sock,tBTA_JV_L2CAP_REASON code)438 static bool send_app_err_code(l2cap_socket* sock, tBTA_JV_L2CAP_REASON code) {
439   log::info("Sending l2cap failure reason socket_id:{} reason code:{}", sock->id, code);
440   int err_channel = 0;
441   if (sock_send_all(sock->our_fd, (const uint8_t*)&err_channel, sizeof(err_channel)) !=
442       sizeof(err_channel)) {
443     return false;
444   }
445   return sock_send_all(sock->our_fd, (const uint8_t*)&code, sizeof(code)) == sizeof(code);
446 }
447 
uuid_lsb(const Uuid & uuid)448 static uint64_t uuid_lsb(const Uuid& uuid) {
449   uint64_t lsb = 0;
450 
451   auto uu = uuid.To128BitBE();
452   for (int i = 8; i <= 15; i++) {
453     lsb <<= 8;
454     lsb |= uu[i];
455   }
456 
457   return lsb;
458 }
459 
uuid_msb(const Uuid & uuid)460 static uint64_t uuid_msb(const Uuid& uuid) {
461   uint64_t msb = 0;
462 
463   auto uu = uuid.To128BitBE();
464   for (int i = 0; i <= 7; i++) {
465     msb <<= 8;
466     msb |= uu[i];
467   }
468 
469   return msb;
470 }
471 
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,uint64_t socket_id)472 static bool send_app_connect_signal(int fd, const RawAddress* addr, int channel, int status,
473                                     int send_fd, uint16_t rx_mtu, uint16_t tx_mtu,
474                                     const Uuid& conn_uuid, uint64_t socket_id) {
475   sock_connect_signal_t cs;
476   cs.size = sizeof(cs);
477   cs.bd_addr = *addr;
478   cs.channel = channel;
479   cs.status = status;
480   cs.max_rx_packet_size = rx_mtu;
481   cs.max_tx_packet_size = tx_mtu;
482   cs.conn_uuid_lsb = uuid_lsb(conn_uuid);
483   cs.conn_uuid_msb = uuid_msb(conn_uuid);
484   cs.socket_id = socket_id;
485   if (send_fd != -1) {
486     if (sock_send_fd(fd, (const uint8_t*)&cs, sizeof(cs), send_fd) == sizeof(cs)) {
487       return true;
488     }
489   } else if (sock_send_all(fd, (const uint8_t*)&cs, sizeof(cs)) == sizeof(cs)) {
490     return true;
491   }
492 
493   log::error("Unable to send data to socket fd:{} send_fd:{}", fd, send_fd);
494   return false;
495 }
496 
on_srv_l2cap_listen_started(tBTA_JV_L2CAP_START * p_start,uint32_t id)497 static void on_srv_l2cap_listen_started(tBTA_JV_L2CAP_START* p_start, uint32_t id) {
498   l2cap_socket* sock;
499 
500   std::unique_lock<std::mutex> lock(state_lock);
501   sock = btsock_l2cap_find_by_id_l(id);
502   if (!sock) {
503     log::error("Unable to find l2cap socket with socket_id:{}", id);
504     return;
505   }
506 
507   if (p_start->status != tBTA_JV_STATUS::SUCCESS) {
508     log::error("Unable to start l2cap server socket_id:{}", sock->id);
509     btsock_l2cap_free_l(sock);
510     return;
511   }
512 
513   sock->handle = p_start->handle;
514 
515   log::info(
516           "Listening for L2CAP connection for device: {}, channel: {}, app_uid: "
517           "{}, id: {}, is_le: {}",
518           sock->addr, sock->channel, sock->app_uid, sock->id, sock->is_le_coc);
519   btif_sock_connection_logger(sock->addr, sock->id,
520                               sock->is_le_coc ? BTSOCK_L2CAP_LE : BTSOCK_L2CAP,
521                               SOCKET_CONNECTION_STATE_LISTENING,
522                               sock->server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION,
523                               sock->app_uid, sock->channel, 0, 0, sock->name);
524 
525   if (!sock->server_psm_sent) {
526     if (!send_app_psm_or_chan_l(sock)) {
527       // closed
528       log::info("Unable to send socket to application socket_id:{}", sock->id);
529       btsock_l2cap_free_l(sock);
530     } else {
531       sock->server_psm_sent = true;
532     }
533   }
534 }
535 
on_cl_l2cap_init(tBTA_JV_L2CAP_CL_INIT * p_init,uint32_t id)536 static void on_cl_l2cap_init(tBTA_JV_L2CAP_CL_INIT* p_init, uint32_t id) {
537   l2cap_socket* sock;
538 
539   std::unique_lock<std::mutex> lock(state_lock);
540   sock = btsock_l2cap_find_by_id_l(id);
541   if (!sock) {
542     log::error("Unable to find l2cap socket with socket_id:{}", id);
543     return;
544   }
545 
546   if (p_init->status != tBTA_JV_STATUS::SUCCESS) {
547     log::error("Initialization status failed socket_id:{}", id);
548     btsock_l2cap_free_l(sock);
549     return;
550   }
551 
552   sock->handle = p_init->handle;
553 }
554 
555 /**
556  * Here we allocate a new sock instance to mimic the BluetoothSocket. The socket
557  * will be a clone of the sock representing the BluetoothServerSocket.
558  * */
on_srv_l2cap_psm_connect_l(tBTA_JV_L2CAP_OPEN * p_open,l2cap_socket * sock)559 static void on_srv_l2cap_psm_connect_l(tBTA_JV_L2CAP_OPEN* p_open, l2cap_socket* sock) {
560   // state_lock taken by caller
561   l2cap_socket* accept_rs = btsock_l2cap_alloc_l(sock->name, &p_open->rem_bda, false, 0);
562   accept_rs->connected = true;
563   accept_rs->security = sock->security;
564   accept_rs->channel = sock->channel;
565   accept_rs->handle = sock->handle;
566   accept_rs->app_uid = sock->app_uid;
567   sock->handle = -1; /* We should no longer associate this handle with the server socket */
568   accept_rs->is_le_coc = sock->is_le_coc;
569   accept_rs->tx_mtu = sock->tx_mtu = p_open->tx_mtu;
570   if (com::android::bluetooth::flags::socket_settings_api()) {  // Added with aosp/3349374
571     accept_rs->rx_mtu = sock->rx_mtu;
572   }
573   accept_rs->local_cid = p_open->local_cid;
574   accept_rs->remote_cid = p_open->remote_cid;
575   // TODO(b/342012881) Remove connection uuid when offload socket API is landed.
576   Uuid uuid = Uuid::From128BitBE(bluetooth::os::GenerateRandom<Uuid::kNumBytes128>());
577   accept_rs->conn_uuid = uuid;
578   if (com::android::bluetooth::flags::socket_settings_api()) {  // Added with aosp/3349374
579     accept_rs->socket_id = btif_l2cap_sock_generate_socket_id();
580     accept_rs->data_path = sock->data_path;
581     strncpy(accept_rs->socket_name, sock->socket_name, sizeof(accept_rs->socket_name) - 1);
582     accept_rs->socket_name[sizeof(accept_rs->socket_name) - 1] = '\0';
583     accept_rs->hub_id = sock->hub_id;
584     accept_rs->endpoint_id = sock->endpoint_id;
585   }
586 
587   /* Swap IDs to hand over the GAP connection to the accepted socket, and start
588      a new server on the newly create socket ID. */
589   uint32_t new_listen_id = accept_rs->id;
590   accept_rs->id = sock->id;
591   sock->id = new_listen_id;
592 
593   log::info(
594           "Connected to L2CAP connection for device: {}, channel: {}, app_uid: {}, "
595           "id: {}, is_le: {}, socket_id: {}, rx_mtu: {}",
596           sock->addr, sock->channel, sock->app_uid, sock->id, sock->is_le_coc, accept_rs->socket_id,
597           accept_rs->rx_mtu);
598   btif_sock_connection_logger(accept_rs->addr, accept_rs->id,
599                               accept_rs->is_le_coc ? BTSOCK_L2CAP_LE : BTSOCK_L2CAP,
600                               SOCKET_CONNECTION_STATE_CONNECTED,
601                               accept_rs->server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION,
602                               accept_rs->app_uid, accept_rs->channel, 0, 0, accept_rs->name);
603 
604   // start monitor the socket
605   btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_EXCEPTION, sock->id);
606   btsock_thread_add_fd(pth, accept_rs->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD, accept_rs->id);
607   send_app_connect_signal(sock->our_fd, &accept_rs->addr, sock->channel, 0, accept_rs->app_fd,
608                           sock->rx_mtu, p_open->tx_mtu, accept_rs->conn_uuid, accept_rs->socket_id);
609   accept_rs->app_fd = -1;  // The fd is closed after sent to app in send_app_connect_signal()
610   // But for some reason we still leak a FD - either the server socket
611   // one or the accept socket one.
612   btsock_l2cap_server_listen(sock);
613   // start monitoring the socketpair to get call back when app is accepting on server socket
614   if (com::android::bluetooth::flags::socket_settings_api()) {  // Added with aosp/3349375
615     btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD, sock->id);
616   }
617 }
618 
on_cl_l2cap_psm_connect_l(tBTA_JV_L2CAP_OPEN * p_open,l2cap_socket * sock)619 static void on_cl_l2cap_psm_connect_l(tBTA_JV_L2CAP_OPEN* p_open, l2cap_socket* sock) {
620   sock->addr = p_open->rem_bda;
621   sock->tx_mtu = p_open->tx_mtu;
622   sock->local_cid = p_open->local_cid;
623   sock->remote_cid = p_open->remote_cid;
624   // TODO(b/342012881) Remove connection uuid when offload socket API is landed.
625   Uuid uuid = Uuid::From128BitBE(bluetooth::os::GenerateRandom<Uuid::kNumBytes128>());
626   sock->conn_uuid = uuid;
627   if (com::android::bluetooth::flags::socket_settings_api()) {  // Added with aosp/3349374
628     sock->socket_id = btif_l2cap_sock_generate_socket_id();
629   }
630 
631   if (!send_app_psm_or_chan_l(sock)) {
632     log::error("Unable to send l2cap socket to application socket_id:{}", sock->id);
633     return;
634   }
635 
636   if (!send_app_connect_signal(sock->our_fd, &sock->addr, sock->channel, 0, -1, sock->rx_mtu,
637                                p_open->tx_mtu, sock->conn_uuid, sock->socket_id)) {
638     log::error("Unable to connect l2cap socket to application socket_id:{}", sock->id);
639     return;
640   }
641 
642   log::info(
643           "Connected to L2CAP connection for device: {}, channel: {}, app_uid: {}, "
644           "id: {}, is_le: {}, socket_id: {}, rx_mtu: {}",
645           sock->addr, sock->channel, sock->app_uid, sock->id, sock->is_le_coc, sock->socket_id,
646           sock->rx_mtu);
647   btif_sock_connection_logger(sock->addr, sock->id,
648                               sock->is_le_coc ? BTSOCK_L2CAP_LE : BTSOCK_L2CAP,
649                               SOCKET_CONNECTION_STATE_CONNECTED,
650                               sock->server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION,
651                               sock->app_uid, sock->channel, 0, 0, sock->name);
652 
653   // start monitoring the socketpair to get call back when app writing data
654   btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD, sock->id);
655   log::info("Connected l2cap socket socket_id:{}", sock->id);
656   sock->connected = true;
657 }
658 
on_l2cap_connect(tBTA_JV * p_data,uint32_t id)659 static void on_l2cap_connect(tBTA_JV* p_data, uint32_t id) {
660   tBTA_JV_L2CAP_OPEN* psm_open = &p_data->l2c_open;
661   tBTA_JV_L2CAP_LE_OPEN* le_open = &p_data->l2c_le_open;
662 
663   std::unique_lock<std::mutex> lock(state_lock);
664   l2cap_socket* sock = btsock_l2cap_find_by_id_l(id);
665   if (!sock) {
666     log::error("Unable to find l2cap socket with socket_id:{}", id);
667     return;
668   }
669 
670   sock->tx_mtu = le_open->tx_mtu;
671   if (psm_open->status == tBTA_JV_STATUS::SUCCESS) {
672     if (!com::android::bluetooth::flags::socket_settings_api() ||  // Added with aosp/3349378
673         sock->data_path == BTSOCK_DATA_PATH_NO_OFFLOAD) {
674       if (!sock->server) {
675         on_cl_l2cap_psm_connect_l(psm_open, sock);
676       } else {
677         on_srv_l2cap_psm_connect_l(psm_open, sock);
678       }
679     } else {
680       if (!sock->server) {
681         on_cl_l2cap_psm_connect_offload_l(psm_open, sock);
682       } else {
683         on_srv_l2cap_psm_connect_offload_l(psm_open, sock);
684       }
685     }
686   } else {
687     log::error("Unable to open socket after receiving connection socket_id:{}", sock->id);
688     btsock_l2cap_free_l(sock);
689   }
690 }
691 
on_l2cap_close(tBTA_JV_L2CAP_CLOSE * p_close,uint32_t id)692 static void on_l2cap_close(tBTA_JV_L2CAP_CLOSE* p_close, uint32_t id) {
693   l2cap_socket* sock;
694 
695   std::unique_lock<std::mutex> lock(state_lock);
696   sock = btsock_l2cap_find_by_id_l(id);
697   if (!sock) {
698     log::info("Unable to find probably already closed l2cap socket with socket_id:{}", id);
699     return;
700   }
701 
702   log::info(
703           "Disconnecting from L2CAP connection for device: {}, channel: {}, "
704           "app_uid: {}, id: {}, is_le: {}",
705           sock->addr, sock->channel, sock->app_uid, sock->id, sock->is_le_coc);
706   btif_sock_connection_logger(sock->addr, sock->id,
707                               sock->is_le_coc ? BTSOCK_L2CAP_LE : BTSOCK_L2CAP,
708                               SOCKET_CONNECTION_STATE_DISCONNECTING,
709                               sock->server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION,
710                               sock->app_uid, sock->channel, 0, 0, sock->name);
711   if (com::android::bluetooth::flags::donot_push_error_code_to_app_when_connected()) {
712     if (!sock->connected) {
713       if (!send_app_err_code(sock, p_close->reason)) {
714         log::error("Unable to send l2cap socket to application socket_id:{}", sock->id);
715       }
716     } else {
717       log::info("Don't push error for already connected socket:{}", sock->id);
718     }
719   } else {
720     if (!send_app_err_code(sock, p_close->reason)) {
721       log::error("Unable to send l2cap socket to application socket_id:{}", sock->id);
722     }
723   }
724   // TODO: This does not seem to be called...
725   // I'm not sure if this will be called for non-server sockets?
726   if (sock->server) {
727     BTA_JvFreeChannel(sock->channel, tBTA_JV_CONN_TYPE::L2CAP);
728   }
729   btsock_l2cap_free_l(sock);
730 }
731 
on_l2cap_outgoing_congest(tBTA_JV_L2CAP_CONG * p,uint32_t id)732 static void on_l2cap_outgoing_congest(tBTA_JV_L2CAP_CONG* p, uint32_t id) {
733   l2cap_socket* sock;
734 
735   std::unique_lock<std::mutex> lock(state_lock);
736   sock = btsock_l2cap_find_by_id_l(id);
737   if (!sock) {
738     log::error("Unable to find l2cap socket with socket_id:{}", id);
739     return;
740   }
741 
742   sock->outgoing_congest = p->cong ? 1 : 0;
743 
744   if (!sock->outgoing_congest) {
745     log::verbose("Monitoring l2cap socket for outgoing data socket_id:{}", sock->id);
746     btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD, sock->id);
747   }
748 }
749 
on_l2cap_write_done(uint16_t len,uint32_t id)750 static void on_l2cap_write_done(uint16_t len, uint32_t id) {
751   std::unique_lock<std::mutex> lock(state_lock);
752   l2cap_socket* sock = btsock_l2cap_find_by_id_l(id);
753   if (!sock) {
754     log::error("Unable to find l2cap socket with socket_id:{}", id);
755     return;
756   }
757 
758   int app_uid = sock->app_uid;
759   if (!sock->outgoing_congest) {
760     btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD, sock->id);
761   } else {
762     log::info("Socket congestion on socket_id:{}", sock->id);
763   }
764 
765   sock->tx_bytes += len;
766   uid_set_add_tx(uid_set, app_uid, len);
767 }
768 
on_l2cap_data_ind(tBTA_JV *,uint32_t id)769 static void on_l2cap_data_ind(tBTA_JV* /* evt */, uint32_t id) {
770   l2cap_socket* sock;
771 
772   int app_uid = -1;
773   uint32_t bytes_read = 0;
774 
775   std::unique_lock<std::mutex> lock(state_lock);
776   sock = btsock_l2cap_find_by_id_l(id);
777   if (!sock) {
778     log::error("Unable to find l2cap socket with socket_id:{}", id);
779     return;
780   }
781 
782   app_uid = sock->app_uid;
783 
784   uint32_t count;
785 
786   if (BTA_JvL2capReady(sock->handle, &count) == tBTA_JV_STATUS::SUCCESS) {
787     std::vector<uint8_t> buffer(count);
788     if (BTA_JvL2capRead(sock->handle, sock->id, buffer.data(), count) == tBTA_JV_STATUS::SUCCESS) {
789       if (packet_put_tail_l(sock, buffer.data(), count)) {
790         bytes_read = count;
791         btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_WR, sock->id);
792       } else {  // connection must be dropped
793         log::warn("Closing socket as unable to push data to socket socket_id:{}", sock->id);
794         BTA_JvL2capClose(sock->handle);
795         btsock_l2cap_free_l(sock);
796         return;
797       }
798     }
799   }
800 
801   sock->rx_bytes += bytes_read;
802   uid_set_add_rx(uid_set, app_uid, bytes_read);
803 }
804 
btsock_l2cap_cbk(tBTA_JV_EVT event,tBTA_JV * p_data,uint32_t l2cap_socket_id)805 static void btsock_l2cap_cbk(tBTA_JV_EVT event, tBTA_JV* p_data, uint32_t l2cap_socket_id) {
806   switch (event) {
807     case BTA_JV_L2CAP_START_EVT:
808       on_srv_l2cap_listen_started(&p_data->l2c_start, l2cap_socket_id);
809       break;
810 
811     case BTA_JV_L2CAP_CL_INIT_EVT:
812       on_cl_l2cap_init(&p_data->l2c_cl_init, l2cap_socket_id);
813       break;
814 
815     case BTA_JV_L2CAP_OPEN_EVT:
816       on_l2cap_connect(p_data, l2cap_socket_id);
817       BTA_JvSetPmProfile(p_data->l2c_open.handle, BTA_JV_PM_ID_1, BTA_JV_CONN_OPEN);
818       break;
819 
820     case BTA_JV_L2CAP_CLOSE_EVT:
821       on_l2cap_close(&p_data->l2c_close, l2cap_socket_id);
822       break;
823 
824     case BTA_JV_L2CAP_DATA_IND_EVT:
825       on_l2cap_data_ind(p_data, l2cap_socket_id);
826       break;
827 
828     case BTA_JV_L2CAP_READ_EVT:
829       break;
830 
831     case BTA_JV_L2CAP_WRITE_EVT:
832       on_l2cap_write_done(p_data->l2c_write.len, l2cap_socket_id);
833       break;
834 
835     case BTA_JV_L2CAP_CONG_EVT:
836       on_l2cap_outgoing_congest(&p_data->l2c_cong, l2cap_socket_id);
837       break;
838 
839     default:
840       log::error("Unhandled event:{} l2cap_socket_id:{}", bta_jv_event_text(event),
841                  l2cap_socket_id);
842       break;
843   }
844 }
845 
846 const tL2CAP_ERTM_INFO obex_l2c_etm_opt = {L2CAP_FCR_ERTM_MODE,
847                                            /* Mandatory for OBEX over l2cap */};
848 
849 /**
850  * When using a dynamic PSM, a PSM allocation is requested from
851  * btsock_l2cap_listen_or_connect().
852  * The PSM allocation event is refeived in the JV-callback - currently located
853  * in RFC-code -
854  * and this function is called with the newly allocated PSM.
855  */
on_l2cap_psm_assigned(int id,int psm)856 void on_l2cap_psm_assigned(int id, int psm) {
857   /* Setup ETM settings:
858    *  mtu will be set below */
859   std::unique_lock<std::mutex> lock(state_lock);
860   l2cap_socket* sock = btsock_l2cap_find_by_id_l(id);
861   if (!sock) {
862     log::error("Unable to find l2cap socket with socket_id:{}", id);
863     return;
864   }
865 
866   sock->channel = psm;
867 
868   btsock_l2cap_server_listen(sock);
869 }
870 
btsock_l2cap_server_listen(l2cap_socket * sock)871 static void btsock_l2cap_server_listen(l2cap_socket* sock) {
872   tBTA_JV_CONN_TYPE connection_type =
873           sock->is_le_coc ? tBTA_JV_CONN_TYPE::L2CAP_LE : tBTA_JV_CONN_TYPE::L2CAP;
874 
875   /* If we have a channel specified in the request, just start the server,
876    * else we request a PSM and start the server after we receive a PSM. */
877   if (sock->channel <= 0) {
878     BTA_JvGetChannelId(connection_type, sock->id, 0);
879     return;
880   }
881 
882   /* Setup ETM settings: mtu will be set below */
883   std::unique_ptr<tL2CAP_CFG_INFO> cfg = std::make_unique<tL2CAP_CFG_INFO>(
884           tL2CAP_CFG_INFO{.fcr_present = true, .fcr = kDefaultErtmOptions});
885   /* For hardware offload data path, host stack sets the initial credits to 0. The offload stack
886    * should send initial credits to peer device through L2CAP signaling command when the data path
887    * is switched successfully. */
888   if (com::android::bluetooth::flags::socket_settings_api()) {  // Added with aosp/3349376
889     if (sock->data_path == BTSOCK_DATA_PATH_HARDWARE_OFFLOAD) {
890       cfg->init_credit_present = true;
891       cfg->init_credit = 0;
892     }
893   }
894 
895   std::unique_ptr<tL2CAP_ERTM_INFO> ertm_info;
896   if (!sock->is_le_coc) {
897     ertm_info.reset(new tL2CAP_ERTM_INFO(obex_l2c_etm_opt));
898   }
899 
900   BTA_JvL2capStartServer(connection_type, sock->security, std::move(ertm_info), sock->channel,
901                          sock->rx_mtu, std::move(cfg), btsock_l2cap_cbk, sock->id);
902 }
903 
904 /*
905  * Determine the local MTU for the offloaded L2CAP connection.
906  *
907  * The local MTU is selected as the minimum of:
908  *   - The socket hal's offload capabilities (socket_cap.leCocCapabilities.mtu)
909  *   - The application's requested maximum RX packet size (app_max_rx_packet_size)
910  *
911  * However, the MTU must be at least the minimum required by the L2CAP LE
912  * specification (L2CAP_SDU_LENGTH_LE_MIN).
913  */
914 
btsock_l2cap_get_offload_mtu(uint16_t * rx_mtu,uint16_t app_max_rx_packet_size)915 static bool btsock_l2cap_get_offload_mtu(uint16_t* rx_mtu, uint16_t app_max_rx_packet_size) {
916   hal::SocketCapabilities socket_cap =
917           bluetooth::shim::GetLppOffloadManager()->GetSocketCapabilities();
918   if (!socket_cap.le_coc_capabilities.number_of_supported_sockets) {
919     return false;
920   }
921   /* Socket HAL client has already verified that the MTU is in a valid range. */
922   uint16_t mtu = static_cast<uint16_t>(socket_cap.le_coc_capabilities.mtu);
923   mtu = std::min(mtu, app_max_rx_packet_size);
924   if (mtu < L2CAP_SDU_LENGTH_LE_MIN) {
925     mtu = L2CAP_SDU_LENGTH_LE_MIN;
926   }
927   *rx_mtu = mtu;
928   return true;
929 }
930 
btsock_l2cap_listen_or_connect(const char * name,const RawAddress * addr,int channel,int * sock_fd,int flags,char listen,int app_uid,btsock_data_path_t data_path,const char * socket_name,uint64_t hub_id,uint64_t endpoint_id,int max_rx_packet_size)931 static bt_status_t btsock_l2cap_listen_or_connect(const char* name, const RawAddress* addr,
932                                                   int channel, int* sock_fd, int flags, char listen,
933                                                   int app_uid, btsock_data_path_t data_path,
934                                                   const char* socket_name, uint64_t hub_id,
935                                                   uint64_t endpoint_id, int max_rx_packet_size) {
936   if (!is_inited()) {
937     return BT_STATUS_NOT_READY;
938   }
939 
940   bool is_le_coc = (flags & BTSOCK_FLAG_LE_COC) != 0;
941 
942   if (is_le_coc) {
943     if (listen) {
944       if (flags & BTSOCK_FLAG_NO_SDP) {
945         /* For LE COC server; set channel to zero so that it will be assigned */
946         channel = 0;
947       } else if (channel <= 0) {
948         log::error("type BTSOCK_L2CAP_LE: invalid channel={}", channel);
949         return BT_STATUS_SOCKET_ERROR;
950       }
951     } else {
952       // Ensure device is in inquiry database during L2CAP CoC connection
953       btif_check_device_in_inquiry_db(*addr);
954     }
955   }
956 
957   if (!sock_fd) {
958     log::info("Invalid socket descriptor");
959     return BT_STATUS_PARM_INVALID;
960   }
961 
962   // TODO: This is kind of bad to lock here, but it is needed for the current
963   // design.
964   std::unique_lock<std::mutex> lock(state_lock);
965   l2cap_socket* sock = btsock_l2cap_alloc_l(name, addr, listen, flags);
966   if (!sock) {
967     return BT_STATUS_NOMEM;
968   }
969 
970   sock->channel = channel;
971   sock->app_uid = app_uid;
972   sock->is_le_coc = is_le_coc;
973   if (com::android::bluetooth::flags::socket_settings_api() &&  // Added with aosp/3349377
974       data_path == BTSOCK_DATA_PATH_HARDWARE_OFFLOAD) {
975     if (!btsock_l2cap_get_offload_mtu(&sock->rx_mtu, static_cast<uint16_t>(max_rx_packet_size))) {
976       return BT_STATUS_UNSUPPORTED;
977     }
978   } else {
979     sock->rx_mtu = is_le_coc ? L2CAP_SDU_LENGTH_LE_MAX : L2CAP_SDU_LENGTH_MAX;
980   }
981   if (com::android::bluetooth::flags::socket_settings_api()) {  // Added with aosp/3349374
982     sock->data_path = data_path;
983     if (socket_name) {
984       strncpy(sock->socket_name, socket_name, sizeof(sock->socket_name) - 1);
985       sock->socket_name[sizeof(sock->socket_name) - 1] = '\0';
986     }
987     sock->hub_id = hub_id;
988     sock->endpoint_id = endpoint_id;
989   }
990 
991   /* "role" is never initialized in rfcomm code */
992   if (listen) {
993     btsock_l2cap_server_listen(sock);
994     // start monitoring the socketpair to get call back when app is accepting on server socket
995     if (com::android::bluetooth::flags::socket_settings_api()) {  // Added with aosp/3349375
996       btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD, sock->id);
997     }
998   } else {
999     tBTA_JV_CONN_TYPE connection_type =
1000             sock->is_le_coc ? tBTA_JV_CONN_TYPE::L2CAP_LE : tBTA_JV_CONN_TYPE::L2CAP;
1001 
1002     /* Setup ETM settings: mtu will be set below */
1003     std::unique_ptr<tL2CAP_CFG_INFO> cfg = std::make_unique<tL2CAP_CFG_INFO>(
1004             tL2CAP_CFG_INFO{.fcr_present = true, .fcr = kDefaultErtmOptions});
1005     /* For hardware offload data path, host stack sets the initial credits to 0. The offload stack
1006      * should send initial credits to peer device through L2CAP signaling command when the data path
1007      * is switched successfully. */
1008     if (com::android::bluetooth::flags::socket_settings_api()) {  // Added with aosp/3349376
1009       if (sock->data_path == BTSOCK_DATA_PATH_HARDWARE_OFFLOAD) {
1010         cfg->init_credit_present = true;
1011         cfg->init_credit = 0;
1012       }
1013     }
1014 
1015     std::unique_ptr<tL2CAP_ERTM_INFO> ertm_info;
1016     if (!sock->is_le_coc) {
1017       ertm_info.reset(new tL2CAP_ERTM_INFO(obex_l2c_etm_opt));
1018     }
1019 
1020     BTA_JvL2capConnect(connection_type, sock->security, std::move(ertm_info), channel, sock->rx_mtu,
1021                        std::move(cfg), sock->addr, btsock_l2cap_cbk, sock->id);
1022   }
1023 
1024   *sock_fd = sock->app_fd;
1025   /* We pass the FD to JAVA, but since it runs in another process, we need to
1026    * also close it in native, either straight away, as done when accepting an
1027    * incoming connection, or when doing cleanup after this socket */
1028   sock->app_fd = -1;
1029   /*This leaks the file descriptor. The FD should be closed in JAVA but it
1030    * apparently do not work */
1031   btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_EXCEPTION, sock->id);
1032 
1033   return BT_STATUS_SUCCESS;
1034 }
1035 
btsock_l2cap_listen(const char * name,int channel,int * sock_fd,int flags,int app_uid,btsock_data_path_t data_path,const char * socket_name,uint64_t hub_id,uint64_t endpoint_id,int max_rx_packet_size)1036 bt_status_t btsock_l2cap_listen(const char* name, int channel, int* sock_fd, int flags, int app_uid,
1037                                 btsock_data_path_t data_path, const char* socket_name,
1038                                 uint64_t hub_id, uint64_t endpoint_id, int max_rx_packet_size) {
1039   return btsock_l2cap_listen_or_connect(name, NULL, channel, sock_fd, flags, 1, app_uid, data_path,
1040                                         socket_name, hub_id, endpoint_id, max_rx_packet_size);
1041 }
1042 
btsock_l2cap_connect(const RawAddress * bd_addr,int channel,int * sock_fd,int flags,int app_uid,btsock_data_path_t data_path,const char * socket_name,uint64_t hub_id,uint64_t endpoint_id,int max_rx_packet_size)1043 bt_status_t btsock_l2cap_connect(const RawAddress* bd_addr, int channel, int* sock_fd, int flags,
1044                                  int app_uid, btsock_data_path_t data_path, const char* socket_name,
1045                                  uint64_t hub_id, uint64_t endpoint_id, int max_rx_packet_size) {
1046   return btsock_l2cap_listen_or_connect(NULL, bd_addr, channel, sock_fd, flags, 0, app_uid,
1047                                         data_path, socket_name, hub_id, endpoint_id,
1048                                         max_rx_packet_size);
1049 }
1050 
1051 /* return true if we have more to send and should wait for user readiness, false
1052  * else
1053  * (for example: unrecoverable error or no data)
1054  */
flush_incoming_que_on_wr_signal_l(l2cap_socket * sock)1055 static bool flush_incoming_que_on_wr_signal_l(l2cap_socket* sock) {
1056   uint8_t* buf;
1057   uint32_t len;
1058 
1059   while (packet_get_head_l(sock, &buf, &len)) {
1060     ssize_t sent;
1061     OSI_NO_INTR(sent = send(sock->our_fd, buf, len, MSG_DONTWAIT));
1062     int saved_errno = errno;
1063 
1064     if (sent == (signed)len) {
1065       osi_free(buf);
1066     } else if (sent >= 0) {
1067       packet_put_head_l(sock, buf + sent, len - sent);
1068       osi_free(buf);
1069       if (!sent) { /* special case if other end not keeping up */
1070         return true;
1071       }
1072     } else {
1073       packet_put_head_l(sock, buf, len);
1074       osi_free(buf);
1075       return saved_errno == EWOULDBLOCK || saved_errno == EAGAIN;
1076     }
1077   }
1078 
1079   return false;
1080 }
1081 
malloc_l2cap_buf(uint16_t len)1082 inline BT_HDR* malloc_l2cap_buf(uint16_t len) {
1083   // We need FCS only for L2CAP_FCR_ERTM_MODE, but it's just 2 bytes so it's ok
1084   BT_HDR* msg = (BT_HDR*)osi_malloc(BT_HDR_SIZE + L2CAP_MIN_OFFSET + len + L2CAP_FCS_LENGTH);
1085   msg->offset = L2CAP_MIN_OFFSET;
1086   msg->len = len;
1087   return msg;
1088 }
1089 
get_l2cap_sdu_start_ptr(BT_HDR * msg)1090 inline uint8_t* get_l2cap_sdu_start_ptr(BT_HDR* msg) {
1091   return (uint8_t*)(msg) + BT_HDR_SIZE + msg->offset;
1092 }
1093 
1094 // state_lock taken by caller
btsock_l2cap_read_signaled_on_connected_socket(int fd,int flags,uint32_t user_id,l2cap_socket * sock)1095 bool btsock_l2cap_read_signaled_on_connected_socket(int fd, int flags, uint32_t user_id,
1096                                                     l2cap_socket* sock) {
1097   if (!sock->connected) {
1098     return false;
1099   }
1100   int size = 0;
1101   bool ioctl_success = ioctl(sock->our_fd, FIONREAD, &size) == 0;
1102   if (!(flags & SOCK_THREAD_FD_EXCEPTION) || (ioctl_success && size)) {
1103     /* FIONREAD return number of bytes that are immediately available for
1104       reading, might be bigger than awaiting packet.
1105 
1106       BluetoothSocket.write(...) guarantees that any packet send to this
1107       socket is broken into pieces no bigger than MTU bytes (as requested
1108       by BT spec). */
1109     size = std::min(size, (int)sock->tx_mtu);
1110 
1111     BT_HDR* buffer = malloc_l2cap_buf(size);
1112     /* The socket is created with SOCK_SEQPACKET, hence we read one message
1113      * at the time. */
1114     ssize_t count;
1115     OSI_NO_INTR(count = recv(fd, get_l2cap_sdu_start_ptr(buffer), size,
1116                              MSG_NOSIGNAL | MSG_DONTWAIT | MSG_TRUNC));
1117     if (count > sock->tx_mtu) {
1118       /* This can't happen thanks to check in BluetoothSocket.java but leave
1119        * this in case this socket is ever used anywhere else*/
1120       log::error("recv more than MTU. Data will be lost: {}", count);
1121       count = sock->tx_mtu;
1122     }
1123 
1124     /* When multiple packets smaller than MTU are flushed to the socket, the
1125       size of the single packet read could be smaller than the ioctl
1126       reported total size of awaiting packets. Hence, we adjust the buffer
1127       length. */
1128     buffer->len = count;
1129 
1130     // will take care of freeing buffer
1131     BTA_JvL2capWrite(sock->handle, PTR_TO_UINT(buffer), buffer, user_id);
1132   }
1133   return true;
1134 }
1135 
1136 // state_lock taken by caller
btsock_l2cap_read_signaled_on_listen_socket(int fd,int,uint32_t,l2cap_socket * sock)1137 bool btsock_l2cap_read_signaled_on_listen_socket(int fd, int /* flags */, uint32_t /* user_id */,
1138                                                  l2cap_socket* sock) {
1139   int size = 0;
1140   bool ioctl_success = ioctl(sock->our_fd, FIONREAD, &size) == 0;
1141   if (ioctl_success && size) {
1142     sock_accept_signal_t accept_signal = {};
1143     ssize_t count;
1144     OSI_NO_INTR(count = recv(fd, reinterpret_cast<uint8_t*>(&accept_signal), sizeof(accept_signal),
1145                              MSG_NOSIGNAL | MSG_DONTWAIT | MSG_TRUNC));
1146     if (count != sizeof(accept_signal) || count != accept_signal.size) {
1147       log::error("Unexpected count {} sizeof(accept_signal) {} accept_signal.size {}", count,
1148                  sizeof(accept_signal), accept_signal.size);
1149       return false;
1150     }
1151     sock->is_accepting = accept_signal.is_accepting;
1152     log::info("Server socket {} is_accepting {}", sock->id, sock->is_accepting);
1153   }
1154   return true;
1155 }
1156 
btsock_l2cap_signaled_flagged(int fd,int flags,uint32_t user_id)1157 void btsock_l2cap_signaled_flagged(int fd, int flags, uint32_t user_id) {
1158   char drop_it = false;
1159 
1160   /* We use MSG_DONTWAIT when sending data to JAVA, hence it can be accepted to
1161    * hold the lock. */
1162   std::unique_lock<std::mutex> lock(state_lock);
1163   l2cap_socket* sock = btsock_l2cap_find_by_id_l(user_id);
1164   if (!sock) {
1165     return;
1166   }
1167   if (flags & SOCK_THREAD_FD_RD) {
1168     if (!sock->server) {
1169       // app sending data on connection socket
1170       if (!btsock_l2cap_read_signaled_on_connected_socket(fd, flags, user_id, sock)) {
1171         drop_it = true;
1172       }
1173     } else {
1174       // app sending signal on listen socket
1175       if (!btsock_l2cap_read_signaled_on_listen_socket(fd, flags, user_id, sock)) {
1176         drop_it = true;
1177       }
1178     }
1179   }
1180   if (flags & SOCK_THREAD_FD_WR) {
1181     // app is ready to receive more data, tell stack to enable the data flow
1182     if (flush_incoming_que_on_wr_signal_l(sock) && sock->connected) {
1183       btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_WR, sock->id);
1184     }
1185   }
1186   if (drop_it || (flags & SOCK_THREAD_FD_EXCEPTION)) {
1187     int size = 0;
1188     if (drop_it || ioctl(sock->our_fd, FIONREAD, &size) != 0 || size == 0) {
1189       btsock_l2cap_free_l(sock);
1190     }
1191   }
1192 }
1193 
btsock_l2cap_signaled(int fd,int flags,uint32_t user_id)1194 void btsock_l2cap_signaled(int fd, int flags, uint32_t user_id) {
1195   if (com::android::bluetooth::flags::socket_settings_api()) {  // Added with aosp/3349375
1196     btsock_l2cap_signaled_flagged(fd, flags, user_id);
1197     return;
1198   }
1199   char drop_it = false;
1200 
1201   /* We use MSG_DONTWAIT when sending data to JAVA, hence it can be accepted to
1202    * hold the lock. */
1203   std::unique_lock<std::mutex> lock(state_lock);
1204   l2cap_socket* sock = btsock_l2cap_find_by_id_l(user_id);
1205   if (!sock) {
1206     return;
1207   }
1208 
1209   if ((flags & SOCK_THREAD_FD_RD) && !sock->server) {
1210     // app sending data
1211     if (sock->connected) {
1212       int size = 0;
1213       bool ioctl_success = ioctl(sock->our_fd, FIONREAD, &size) == 0;
1214       if (!(flags & SOCK_THREAD_FD_EXCEPTION) || (ioctl_success && size)) {
1215         /* FIONREAD return number of bytes that are immediately available for
1216            reading, might be bigger than awaiting packet.
1217 
1218            BluetoothSocket.write(...) guarantees that any packet send to this
1219            socket is broken into pieces no bigger than MTU bytes (as requested
1220            by BT spec). */
1221         size = std::min(size, (int)sock->tx_mtu);
1222 
1223         BT_HDR* buffer = malloc_l2cap_buf(size);
1224         /* The socket is created with SOCK_SEQPACKET, hence we read one message
1225          * at the time. */
1226         ssize_t count;
1227         OSI_NO_INTR(count = recv(fd, get_l2cap_sdu_start_ptr(buffer), size,
1228                                  MSG_NOSIGNAL | MSG_DONTWAIT | MSG_TRUNC));
1229         if (count > sock->tx_mtu) {
1230           /* This can't happen thanks to check in BluetoothSocket.java but leave
1231            * this in case this socket is ever used anywhere else*/
1232           log::error("recv more than MTU. Data will be lost: {}", count);
1233           count = sock->tx_mtu;
1234         }
1235 
1236         /* When multiple packets smaller than MTU are flushed to the socket, the
1237            size of the single packet read could be smaller than the ioctl
1238            reported total size of awaiting packets. Hence, we adjust the buffer
1239            length. */
1240         buffer->len = count;
1241 
1242         // will take care of freeing buffer
1243         BTA_JvL2capWrite(sock->handle, PTR_TO_UINT(buffer), buffer, user_id);
1244       }
1245     } else {
1246       drop_it = true;
1247     }
1248   }
1249   if (flags & SOCK_THREAD_FD_WR) {
1250     // app is ready to receive more data, tell stack to enable the data flow
1251     if (flush_incoming_que_on_wr_signal_l(sock) && sock->connected) {
1252       btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_WR, sock->id);
1253     }
1254   }
1255   if (drop_it || (flags & SOCK_THREAD_FD_EXCEPTION)) {
1256     int size = 0;
1257     if (drop_it || ioctl(sock->our_fd, FIONREAD, &size) != 0 || size == 0) {
1258       btsock_l2cap_free_l(sock);
1259     }
1260   }
1261 }
1262 
btsock_l2cap_disconnect(const RawAddress * bd_addr)1263 bt_status_t btsock_l2cap_disconnect(const RawAddress* bd_addr) {
1264   if (!bd_addr) {
1265     return BT_STATUS_PARM_INVALID;
1266   }
1267   if (!is_inited()) {
1268     return BT_STATUS_NOT_READY;
1269   }
1270 
1271   std::unique_lock<std::mutex> lock(state_lock);
1272   l2cap_socket* sock = socks;
1273 
1274   while (sock) {
1275     l2cap_socket* next = sock->next;
1276     if (sock->addr == *bd_addr) {
1277       btsock_l2cap_free_l(sock);
1278     }
1279     sock = next;
1280   }
1281 
1282   return BT_STATUS_SUCCESS;
1283 }
1284 
btsock_l2cap_get_l2cap_local_cid(Uuid & conn_uuid,uint16_t * cid)1285 bt_status_t btsock_l2cap_get_l2cap_local_cid(Uuid& conn_uuid, uint16_t* cid) {
1286   l2cap_socket* sock;
1287 
1288   std::unique_lock<std::mutex> lock(state_lock);
1289   sock = btsock_l2cap_find_by_conn_uuid_l(conn_uuid);
1290   if (!sock) {
1291     log::error("Unable to find l2cap socket with conn_uuid:{}", conn_uuid.ToString());
1292     return BT_STATUS_SOCKET_ERROR;
1293   }
1294   *cid = sock->local_cid;
1295   return BT_STATUS_SUCCESS;
1296 }
1297 
btsock_l2cap_get_l2cap_remote_cid(Uuid & conn_uuid,uint16_t * cid)1298 bt_status_t btsock_l2cap_get_l2cap_remote_cid(Uuid& conn_uuid, uint16_t* cid) {
1299   l2cap_socket* sock;
1300 
1301   std::unique_lock<std::mutex> lock(state_lock);
1302   sock = btsock_l2cap_find_by_conn_uuid_l(conn_uuid);
1303   if (!sock) {
1304     log::error("Unable to find l2cap socket with conn_uuid:{}", conn_uuid.ToString());
1305     return BT_STATUS_SOCKET_ERROR;
1306   }
1307   *cid = sock->remote_cid;
1308   return BT_STATUS_SUCCESS;
1309 }
1310 
1311 // TODO(b/380189525): Replace the randomized socket ID with static counter when we don't have
1312 // security concerns about using static counter.
btif_l2cap_sock_generate_socket_id()1313 static uint64_t btif_l2cap_sock_generate_socket_id() {
1314   uint64_t socket_id;
1315   do {
1316     socket_id = bluetooth::os::GenerateRandomUint64();
1317   } while (!socket_id);
1318   return socket_id;
1319 }
1320 
1321 /* only call with state_lock taken */
btsock_l2cap_find_by_socket_id_l(uint64_t socket_id)1322 static l2cap_socket* btsock_l2cap_find_by_socket_id_l(uint64_t socket_id) {
1323   l2cap_socket* sock = socks;
1324 
1325   while (sock) {
1326     if (sock->socket_id == socket_id) {
1327       return sock;
1328     }
1329     sock = sock->next;
1330   }
1331 
1332   return nullptr;
1333 }
1334 
on_btsocket_l2cap_opened_complete(uint64_t socket_id,bool success)1335 void on_btsocket_l2cap_opened_complete(uint64_t socket_id, bool success) {
1336   l2cap_socket* sock;
1337 
1338   std::unique_lock<std::mutex> lock(state_lock);
1339   sock = btsock_l2cap_find_by_socket_id_l(socket_id);
1340   if (!sock) {
1341     log::error("Unable to find l2cap socket with socket_id:{}", socket_id);
1342     return;
1343   }
1344   if (!success) {
1345     log::error("L2CAP opened complete failed with socket_id:{}", socket_id);
1346     btsock_l2cap_free_l(sock);
1347     return;
1348   }
1349   // If the socket was accepted from listen socket, use listen_fd.
1350   if (sock->listen_fd != -1) {
1351     send_app_connect_signal(sock->listen_fd, &sock->addr, sock->channel, 0, sock->app_fd,
1352                             sock->rx_mtu, sock->tx_mtu, sock->conn_uuid, sock->socket_id);
1353     // The fd is closed after sent to app in send_app_connect_signal()
1354     sock->app_fd = -1;
1355   } else {
1356     if (!send_app_psm_or_chan_l(sock)) {
1357       log::error("Unable to send l2cap socket to application socket_id:{}", sock->id);
1358       return;
1359     }
1360     if (!send_app_connect_signal(sock->our_fd, &sock->addr, sock->channel, 0, -1, sock->rx_mtu,
1361                                  sock->tx_mtu, sock->conn_uuid, sock->socket_id)) {
1362       log::error("Unable to connect l2cap socket to application socket_id:{}", sock->id);
1363       return;
1364     }
1365 
1366     log::info(
1367             "Connected to L2CAP connection for device: {}, channel: {}, app_uid: {}, id: {}, "
1368             "is_le: {}, socket_id: {}, rx_mtu: {}",
1369             sock->addr, sock->channel, sock->app_uid, sock->id, sock->is_le_coc, sock->socket_id,
1370             sock->rx_mtu);
1371     btif_sock_connection_logger(sock->addr, sock->id,
1372                                 sock->is_le_coc ? BTSOCK_L2CAP_LE : BTSOCK_L2CAP,
1373                                 SOCKET_CONNECTION_STATE_CONNECTED,
1374                                 sock->server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION,
1375                                 sock->app_uid, sock->channel, 0, 0, sock->name);
1376 
1377     log::info("Connected l2cap socket socket_id:{}", sock->id);
1378     sock->connected = true;
1379   }
1380 }
1381 
on_btsocket_l2cap_close(uint64_t socket_id)1382 void on_btsocket_l2cap_close(uint64_t socket_id) {
1383   l2cap_socket* sock;
1384 
1385   std::unique_lock<std::mutex> lock(state_lock);
1386   sock = btsock_l2cap_find_by_socket_id_l(socket_id);
1387   if (!sock) {
1388     log::error("Unable to find l2cap socket with socket_id:{}", socket_id);
1389     return;
1390   }
1391   log::info("L2CAP close request for socket_id:{}", socket_id);
1392   btsock_l2cap_free_l(sock);
1393 }
1394 
on_cl_l2cap_psm_connect_offload_l(tBTA_JV_L2CAP_OPEN * p_open,l2cap_socket * sock)1395 static void on_cl_l2cap_psm_connect_offload_l(tBTA_JV_L2CAP_OPEN* p_open, l2cap_socket* sock) {
1396   sock->addr = p_open->rem_bda;
1397   sock->tx_mtu = p_open->tx_mtu;
1398   sock->local_cid = p_open->local_cid;
1399   sock->remote_cid = p_open->remote_cid;
1400   // TODO(b/342012881) Remove connection uuid when offload socket API is landed.
1401   Uuid uuid = Uuid::From128BitBE(bluetooth::os::GenerateRandom<Uuid::kNumBytes128>());
1402   sock->conn_uuid = uuid;
1403   sock->socket_id = btif_l2cap_sock_generate_socket_id();
1404 
1405   log::info(
1406           "Connected to L2CAP connection for device: {}, channel: {}, app_uid: {}, "
1407           "id: {}, is_le: {}, socket_id: {}, rx_mtu: {}",
1408           sock->addr, sock->channel, sock->app_uid, sock->id, sock->is_le_coc, sock->socket_id,
1409           sock->rx_mtu);
1410   btif_sock_connection_logger(sock->addr, sock->id,
1411                               sock->is_le_coc ? BTSOCK_L2CAP_LE : BTSOCK_L2CAP,
1412                               SOCKET_CONNECTION_STATE_CONNECTED,
1413                               sock->server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION,
1414                               sock->app_uid, sock->channel, 0, 0, sock->name);
1415 
1416   bluetooth::hal::SocketContext socket_context = {
1417           .socket_id = sock->socket_id,
1418           .name = sock->socket_name,
1419           .acl_connection_handle = p_open->acl_handle,
1420           .channel_info = bluetooth::hal::LeCocChannelInfo(
1421                   p_open->local_cid, p_open->remote_cid, static_cast<uint16_t>(sock->channel),
1422                   sock->rx_mtu, sock->tx_mtu, p_open->local_coc_mps, p_open->remote_coc_mps,
1423                   p_open->local_coc_credit, p_open->remote_coc_credit),
1424           .endpoint_info.hub_id = sock->hub_id,
1425           .endpoint_info.endpoint_id = sock->endpoint_id,
1426   };
1427   if (!bluetooth::shim::GetLppOffloadManager()->SocketOpened(socket_context)) {
1428     log::warn("L2CAP socket opened failed. Disconnect the incoming connection.");
1429     btsock_l2cap_free_l(sock);
1430   } else {
1431     log::info(
1432             "L2CAP socket opened successful. Will send connect signal in "
1433             "on_btsocket_l2cap_opened_complete() asynchronously.");
1434   }
1435 }
1436 
on_srv_l2cap_psm_connect_offload_l(tBTA_JV_L2CAP_OPEN * p_open,l2cap_socket * sock)1437 static void on_srv_l2cap_psm_connect_offload_l(tBTA_JV_L2CAP_OPEN* p_open, l2cap_socket* sock) {
1438   // std::mutex locked by caller
1439   l2cap_socket* accept_rs = btsock_l2cap_alloc_l(sock->name, &p_open->rem_bda, false, 0);
1440   accept_rs->connected = true;
1441   accept_rs->security = sock->security;
1442   accept_rs->channel = sock->channel;
1443   accept_rs->handle = sock->handle;
1444   accept_rs->app_uid = sock->app_uid;
1445   sock->handle = -1; /* We should no longer associate this handle with the server socket */
1446   accept_rs->is_le_coc = sock->is_le_coc;
1447   accept_rs->tx_mtu = sock->tx_mtu = p_open->tx_mtu;
1448   accept_rs->rx_mtu = sock->rx_mtu;
1449   accept_rs->local_cid = p_open->local_cid;
1450   accept_rs->remote_cid = p_open->remote_cid;
1451   // TODO(b/342012881) Remove connection uuid when offload socket API is landed.
1452   Uuid uuid = Uuid::From128BitBE(bluetooth::os::GenerateRandom<Uuid::kNumBytes128>());
1453   accept_rs->conn_uuid = uuid;
1454   accept_rs->socket_id = btif_l2cap_sock_generate_socket_id();
1455   accept_rs->data_path = sock->data_path;
1456   strncpy(accept_rs->socket_name, sock->socket_name, sizeof(accept_rs->socket_name) - 1);
1457   accept_rs->socket_name[sizeof(accept_rs->socket_name) - 1] = '\0';
1458   accept_rs->hub_id = sock->hub_id;
1459   accept_rs->endpoint_id = sock->endpoint_id;
1460   accept_rs->listen_fd = sock->our_fd;
1461 
1462   /* Swap IDs to hand over the GAP connection to the accepted socket, and start
1463      a new server on the newly create socket ID. */
1464   uint32_t new_listen_id = accept_rs->id;
1465   accept_rs->id = sock->id;
1466   sock->id = new_listen_id;
1467 
1468   log::info(
1469           "Connected to L2CAP connection for device: {}, channel: {}, app_uid: {}, "
1470           "id: {}, is_le: {}, socket_id: {}, rx_mtu: {}",
1471           sock->addr, sock->channel, sock->app_uid, sock->id, sock->is_le_coc, accept_rs->socket_id,
1472           accept_rs->rx_mtu);
1473   btif_sock_connection_logger(accept_rs->addr, accept_rs->id,
1474                               accept_rs->is_le_coc ? BTSOCK_L2CAP_LE : BTSOCK_L2CAP,
1475                               SOCKET_CONNECTION_STATE_CONNECTED,
1476                               accept_rs->server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION,
1477                               accept_rs->app_uid, accept_rs->channel, 0, 0, accept_rs->name);
1478 
1479   bluetooth::hal::SocketContext socket_context = {
1480           .socket_id = accept_rs->socket_id,
1481           .name = accept_rs->socket_name,
1482           .acl_connection_handle = p_open->acl_handle,
1483           .channel_info = bluetooth::hal::LeCocChannelInfo(
1484                   p_open->local_cid, p_open->remote_cid, static_cast<uint16_t>(accept_rs->channel),
1485                   accept_rs->rx_mtu, accept_rs->tx_mtu, p_open->local_coc_mps,
1486                   p_open->remote_coc_mps, p_open->local_coc_credit, p_open->remote_coc_credit),
1487           .endpoint_info.hub_id = accept_rs->hub_id,
1488           .endpoint_info.endpoint_id = accept_rs->endpoint_id,
1489   };
1490   if (!sock->is_accepting) {
1491     log::warn("Server socket is not accepting. Disconnect the incoming connection.");
1492     btsock_l2cap_free_l(accept_rs);
1493   } else if (!bluetooth::shim::GetLppOffloadManager()->SocketOpened(socket_context)) {
1494     log::warn("L2CAP socket opened failed. Disconnect the incoming connection.");
1495     btsock_l2cap_free_l(accept_rs);
1496   } else {
1497     log::info("L2CAP socket opened successful. Will send connect signal in async callback.");
1498   }
1499   // start monitor the socket
1500   btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_EXCEPTION, sock->id);
1501   btsock_l2cap_server_listen(sock);
1502   // start monitoring the socketpair to get call back when app is accepting on server socket
1503   btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD, sock->id);
1504 }
1505