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