1 /******************************************************************************
2  *
3  *  Copyright 2009-2012 Broadcom Corporation
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 
19 #define LOG_TAG "bt_btif_sock_rfcomm"
20 
21 #include <base/logging.h>
22 #include <errno.h>
23 #include <features.h>
24 #include <pthread.h>
25 #include <string.h>
26 #include <sys/ioctl.h>
27 #include <sys/socket.h>
28 #include <sys/types.h>
29 #include <unistd.h>
30 
31 #include <mutex>
32 
33 #include <frameworks/base/core/proto/android/bluetooth/enums.pb.h>
34 #include <hardware/bluetooth.h>
35 #include <hardware/bt_sock.h>
36 
37 #include "bt_common.h"
38 #include "bt_target.h"
39 #include "bta_api.h"
40 #include "bta_jv_api.h"
41 #include "bta_jv_co.h"
42 #include "btif_common.h"
43 #include "btif_sock_sdp.h"
44 #include "btif_sock_thread.h"
45 #include "btif_sock_util.h"
46 #include "btif_uid.h"
47 #include "btif_util.h"
48 #include "btm_api.h"
49 #include "btm_int.h"
50 #include "btu.h"
51 #include "common/metrics.h"
52 #include "hcimsgs.h"
53 #include "osi/include/compat.h"
54 #include "osi/include/list.h"
55 #include "osi/include/log.h"
56 #include "osi/include/osi.h"
57 #include "port_api.h"
58 #include "sdp_api.h"
59 
60 /* The JV interface can have only one user, hence we need to call a few
61  * L2CAP functions from this file. */
62 #include "btif_sock_l2cap.h"
63 
64 using bluetooth::Uuid;
65 
66 // Maximum number of RFCOMM channels (1-30 inclusive).
67 #define MAX_RFC_CHANNEL 30
68 
69 // Maximum number of devices we can have an RFCOMM connection with.
70 #define MAX_RFC_SESSION 7
71 
72 typedef struct {
73   int outgoing_congest : 1;
74   int pending_sdp_request : 1;
75   int doing_sdp_request : 1;
76   int server : 1;
77   int connected : 1;
78   int closing : 1;
79 } flags_t;
80 
81 typedef struct {
82   flags_t f;
83   uint32_t id;  // Non-zero indicates a valid (in-use) slot.
84   int security;
85   int scn;  // Server channel number
86   int scn_notified;
87   RawAddress addr;
88   int is_service_uuid_valid;
89   Uuid service_uuid;
90   char service_name[256];
91   int fd;
92   int app_fd;   // Temporary storage for the half of the socketpair that's sent
93                 // back to upper layers.
94   int app_uid;  // UID of the app for which this socket was created.
95   int mtu;
96   uint8_t* packet;
97   int sdp_handle;
98   int rfc_handle;
99   int rfc_port_handle;
100   int role;
101   list_t* incoming_queue;
102   // Cumulative number of bytes transmitted on this socket
103   int64_t tx_bytes;
104   // Cumulative number of bytes received on this socket
105   int64_t rx_bytes;
106 } rfc_slot_t;
107 
108 static rfc_slot_t rfc_slots[MAX_RFC_CHANNEL];
109 static uint32_t rfc_slot_id;
110 static volatile int pth = -1;  // poll thread handle
111 static std::recursive_mutex slot_lock;
112 static uid_set_t* uid_set = NULL;
113 
114 static rfc_slot_t* find_free_slot(void);
115 static void cleanup_rfc_slot(rfc_slot_t* rs);
116 static void jv_dm_cback(tBTA_JV_EVT event, tBTA_JV* p_data, uint32_t id);
117 static uint32_t rfcomm_cback(tBTA_JV_EVT event, tBTA_JV* p_data,
118                              uint32_t rfcomm_slot_id);
119 static bool send_app_scn(rfc_slot_t* rs);
120 
is_init_done(void)121 static bool is_init_done(void) { return pth != -1; }
122 
btsock_rfc_init(int poll_thread_handle,uid_set_t * set)123 bt_status_t btsock_rfc_init(int poll_thread_handle, uid_set_t* set) {
124   pth = poll_thread_handle;
125   uid_set = set;
126 
127   memset(rfc_slots, 0, sizeof(rfc_slots));
128   for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i) {
129     rfc_slots[i].scn = -1;
130     rfc_slots[i].sdp_handle = 0;
131     rfc_slots[i].fd = INVALID_FD;
132     rfc_slots[i].app_fd = INVALID_FD;
133     rfc_slots[i].incoming_queue = list_new(osi_free);
134     CHECK(rfc_slots[i].incoming_queue != NULL);
135   }
136 
137   BTA_JvEnable(jv_dm_cback);
138 
139   return BT_STATUS_SUCCESS;
140 }
141 
btsock_rfc_cleanup(void)142 void btsock_rfc_cleanup(void) {
143   pth = -1;
144   uid_set = NULL;
145 
146   BTA_JvDisable();
147 
148   std::unique_lock<std::recursive_mutex> lock(slot_lock);
149   for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i) {
150     if (rfc_slots[i].id) cleanup_rfc_slot(&rfc_slots[i]);
151     list_free(rfc_slots[i].incoming_queue);
152     rfc_slots[i].incoming_queue = NULL;
153   }
154 }
155 
find_free_slot(void)156 static rfc_slot_t* find_free_slot(void) {
157   for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i)
158     if (rfc_slots[i].fd == INVALID_FD) return &rfc_slots[i];
159   return NULL;
160 }
161 
find_rfc_slot_by_id(uint32_t id)162 static rfc_slot_t* find_rfc_slot_by_id(uint32_t id) {
163   CHECK(id != 0);
164 
165   for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i)
166     if (rfc_slots[i].id == id) return &rfc_slots[i];
167 
168   LOG_ERROR("%s unable to find RFCOMM slot id: %u", __func__, id);
169   return NULL;
170 }
171 
find_rfc_slot_by_pending_sdp(void)172 static rfc_slot_t* find_rfc_slot_by_pending_sdp(void) {
173   uint32_t min_id = UINT32_MAX;
174   int slot = -1;
175   for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i)
176     if (rfc_slots[i].id && rfc_slots[i].f.pending_sdp_request &&
177         rfc_slots[i].id < min_id) {
178       min_id = rfc_slots[i].id;
179       slot = i;
180     }
181 
182   return (slot == -1) ? NULL : &rfc_slots[slot];
183 }
184 
is_requesting_sdp(void)185 static bool is_requesting_sdp(void) {
186   for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i)
187     if (rfc_slots[i].id && rfc_slots[i].f.doing_sdp_request) return true;
188   return false;
189 }
190 
alloc_rfc_slot(const RawAddress * addr,const char * name,const Uuid & uuid,int channel,int flags,bool server)191 static rfc_slot_t* alloc_rfc_slot(const RawAddress* addr, const char* name,
192                                   const Uuid& uuid, int channel, int flags,
193                                   bool server) {
194   int security = 0;
195   if (flags & BTSOCK_FLAG_ENCRYPT)
196     security |= server ? BTM_SEC_IN_ENCRYPT : BTM_SEC_OUT_ENCRYPT;
197   if (flags & BTSOCK_FLAG_AUTH)
198     security |= server ? BTM_SEC_IN_AUTHENTICATE : BTM_SEC_OUT_AUTHENTICATE;
199   if (flags & BTSOCK_FLAG_AUTH_MITM)
200     security |= server ? BTM_SEC_IN_MITM : BTM_SEC_OUT_MITM;
201   if (flags & BTSOCK_FLAG_AUTH_16_DIGIT)
202     security |= BTM_SEC_IN_MIN_16_DIGIT_PIN;
203 
204   rfc_slot_t* slot = find_free_slot();
205   if (!slot) {
206     LOG_ERROR("%s unable to find free RFCOMM slot.", __func__);
207     return NULL;
208   }
209 
210   int fds[2] = {INVALID_FD, INVALID_FD};
211   if (socketpair(AF_LOCAL, SOCK_STREAM, 0, fds) == -1) {
212     LOG_ERROR("%s error creating socketpair: %s", __func__, strerror(errno));
213     return NULL;
214   }
215 
216   // Increment slot id and make sure we don't use id=0.
217   if (++rfc_slot_id == 0) rfc_slot_id = 1;
218 
219   slot->fd = fds[0];
220   slot->app_fd = fds[1];
221   slot->security = security;
222   slot->scn = channel;
223   slot->app_uid = -1;
224 
225   slot->is_service_uuid_valid = !uuid.IsEmpty();
226   slot->service_uuid = uuid;
227 
228   if (name && *name) {
229     strlcpy(slot->service_name, name, sizeof(slot->service_name));
230   } else {
231     memset(slot->service_name, 0, sizeof(slot->service_name));
232   }
233   if (addr) {
234     slot->addr = *addr;
235   } else {
236     slot->addr = RawAddress::kEmpty;
237   }
238   slot->id = rfc_slot_id;
239   slot->f.server = server;
240   slot->tx_bytes = 0;
241   slot->rx_bytes = 0;
242   return slot;
243 }
244 
create_srv_accept_rfc_slot(rfc_slot_t * srv_rs,const RawAddress * addr,int open_handle,int new_listen_handle)245 static rfc_slot_t* create_srv_accept_rfc_slot(rfc_slot_t* srv_rs,
246                                               const RawAddress* addr,
247                                               int open_handle,
248                                               int new_listen_handle) {
249   rfc_slot_t* accept_rs = alloc_rfc_slot(
250       addr, srv_rs->service_name, srv_rs->service_uuid, srv_rs->scn, 0, false);
251   if (!accept_rs) {
252     LOG_ERROR("%s unable to allocate RFCOMM slot.", __func__);
253     return NULL;
254   }
255 
256   accept_rs->f.server = false;
257   accept_rs->f.connected = true;
258   accept_rs->security = srv_rs->security;
259   accept_rs->mtu = srv_rs->mtu;
260   accept_rs->role = srv_rs->role;
261   accept_rs->rfc_handle = open_handle;
262   accept_rs->rfc_port_handle = BTA_JvRfcommGetPortHdl(open_handle);
263   accept_rs->app_uid = srv_rs->app_uid;
264 
265   srv_rs->rfc_handle = new_listen_handle;
266   srv_rs->rfc_port_handle = BTA_JvRfcommGetPortHdl(new_listen_handle);
267 
268   CHECK(accept_rs->rfc_port_handle != srv_rs->rfc_port_handle);
269 
270   // now swap the slot id
271   uint32_t new_listen_id = accept_rs->id;
272   accept_rs->id = srv_rs->id;
273   srv_rs->id = new_listen_id;
274 
275   return accept_rs;
276 }
277 
btsock_rfc_listen(const char * service_name,const Uuid * service_uuid,int channel,int * sock_fd,int flags,int app_uid)278 bt_status_t btsock_rfc_listen(const char* service_name,
279                               const Uuid* service_uuid, int channel,
280                               int* sock_fd, int flags, int app_uid) {
281   CHECK(sock_fd != NULL);
282   CHECK((service_uuid != NULL) ||
283         (channel >= 1 && channel <= MAX_RFC_CHANNEL) ||
284         ((flags & BTSOCK_FLAG_NO_SDP) != 0));
285 
286   *sock_fd = INVALID_FD;
287 
288   // TODO(sharvil): not sure that this check makes sense; seems like a logic
289   // error to call
290   // functions on RFCOMM sockets before initializing the module. Probably should
291   // be an assert.
292   if (!is_init_done()) return BT_STATUS_NOT_READY;
293 
294   if ((flags & BTSOCK_FLAG_NO_SDP) == 0) {
295     if (!service_uuid || service_uuid->IsEmpty()) {
296       APPL_TRACE_DEBUG(
297           "%s: service_uuid not set AND BTSOCK_FLAG_NO_SDP is not set - "
298           "changing to SPP",
299           __func__);
300       // Use serial port profile to listen to specified channel
301       service_uuid = &UUID_SPP;
302     } else {
303       // Check the service_uuid. overwrite the channel # if reserved
304       int reserved_channel = get_reserved_rfc_channel(*service_uuid);
305       if (reserved_channel > 0) {
306         channel = reserved_channel;
307       }
308     }
309   }
310 
311   std::unique_lock<std::recursive_mutex> lock(slot_lock);
312 
313   rfc_slot_t* slot =
314       alloc_rfc_slot(NULL, service_name, *service_uuid, channel, flags, true);
315   if (!slot) {
316     LOG_ERROR("%s unable to allocate RFCOMM slot.", __func__);
317     return BT_STATUS_FAIL;
318   }
319   APPL_TRACE_DEBUG("BTA_JvGetChannelId: service_name: %s - channel: %d",
320                    service_name, channel);
321   BTA_JvGetChannelId(BTA_JV_CONN_TYPE_RFCOMM, slot->id, channel);
322   *sock_fd = slot->app_fd;  // Transfer ownership of fd to caller.
323   /*TODO:
324    * We are leaking one of the app_fd's - either the listen socket, or the
325    connection socket.
326    * WE need to close this in native, as the FD might belong to another process
327     - This is the server socket FD
328     - For accepted connections, we close the FD after passing it to JAVA.
329     - Try to simply remove the = -1 to free the FD at rs cleanup.*/
330   //        close(rs->app_fd);
331   slot->app_fd = INVALID_FD;  // Drop our reference to the fd.
332   slot->app_uid = app_uid;
333   btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_EXCEPTION,
334                        slot->id);
335 
336   return BT_STATUS_SUCCESS;
337 }
338 
btsock_rfc_connect(const RawAddress * bd_addr,const Uuid * service_uuid,int channel,int * sock_fd,int flags,int app_uid)339 bt_status_t btsock_rfc_connect(const RawAddress* bd_addr,
340                                const Uuid* service_uuid, int channel,
341                                int* sock_fd, int flags, int app_uid) {
342   CHECK(sock_fd != NULL);
343   CHECK((service_uuid != NULL) || (channel >= 1 && channel <= MAX_RFC_CHANNEL));
344 
345   *sock_fd = INVALID_FD;
346 
347   // TODO(sharvil): not sure that this check makes sense; seems like a logic
348   // error to call
349   // functions on RFCOMM sockets before initializing the module. Probably should
350   // be an assert.
351   if (!is_init_done()) return BT_STATUS_NOT_READY;
352 
353   std::unique_lock<std::recursive_mutex> lock(slot_lock);
354 
355   rfc_slot_t* slot =
356       alloc_rfc_slot(bd_addr, NULL, *service_uuid, channel, flags, false);
357   if (!slot) {
358     LOG_ERROR("%s unable to allocate RFCOMM slot.", __func__);
359     return BT_STATUS_FAIL;
360   }
361 
362   if (!service_uuid || service_uuid->IsEmpty()) {
363     tBTA_JV_STATUS ret =
364         BTA_JvRfcommConnect(slot->security, slot->role, slot->scn, slot->addr,
365                             rfcomm_cback, slot->id);
366     if (ret != BTA_JV_SUCCESS) {
367       LOG_ERROR("%s unable to initiate RFCOMM connection: %d", __func__, ret);
368       cleanup_rfc_slot(slot);
369       return BT_STATUS_FAIL;
370     }
371 
372     if (!send_app_scn(slot)) {
373       LOG_ERROR("%s unable to send channel number.", __func__);
374       cleanup_rfc_slot(slot);
375       return BT_STATUS_FAIL;
376     }
377   } else {
378     if (!is_requesting_sdp()) {
379       BTA_JvStartDiscovery(*bd_addr, 1, service_uuid, slot->id);
380       slot->f.pending_sdp_request = false;
381       slot->f.doing_sdp_request = true;
382     } else {
383       slot->f.pending_sdp_request = true;
384       slot->f.doing_sdp_request = false;
385     }
386   }
387 
388   *sock_fd = slot->app_fd;    // Transfer ownership of fd to caller.
389   slot->app_fd = INVALID_FD;  // Drop our reference to the fd.
390   slot->app_uid = app_uid;
391   btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD,
392                        slot->id);
393 
394   return BT_STATUS_SUCCESS;
395 }
396 
create_server_sdp_record(rfc_slot_t * slot)397 static int create_server_sdp_record(rfc_slot_t* slot) {
398   if (slot->scn == 0) {
399     return false;
400   }
401   slot->sdp_handle =
402       add_rfc_sdp_rec(slot->service_name, slot->service_uuid, slot->scn);
403   return (slot->sdp_handle > 0);
404 }
405 
free_rfc_slot_scn(rfc_slot_t * slot)406 static void free_rfc_slot_scn(rfc_slot_t* slot) {
407   if (slot->scn <= 0) return;
408 
409   if (slot->f.server && !slot->f.closing && slot->rfc_handle) {
410     BTA_JvRfcommStopServer(slot->rfc_handle, slot->id);
411     slot->rfc_handle = 0;
412   }
413 
414   if (slot->f.server) BTM_FreeSCN(slot->scn);
415   slot->scn = 0;
416 }
417 
cleanup_rfc_slot(rfc_slot_t * slot)418 static void cleanup_rfc_slot(rfc_slot_t* slot) {
419   if (slot->fd != INVALID_FD) {
420     shutdown(slot->fd, SHUT_RDWR);
421     close(slot->fd);
422     bluetooth::common::LogSocketConnectionState(
423         slot->addr, slot->id, BTSOCK_RFCOMM,
424         android::bluetooth::SOCKET_CONNECTION_STATE_DISCONNECTED,
425         slot->tx_bytes, slot->rx_bytes, slot->app_uid, slot->scn,
426         slot->f.server ? android::bluetooth::SOCKET_ROLE_LISTEN
427                        : android::bluetooth::SOCKET_ROLE_CONNECTION);
428     slot->fd = INVALID_FD;
429   }
430 
431   if (slot->app_fd != INVALID_FD) {
432     close(slot->app_fd);
433     slot->app_fd = INVALID_FD;
434   }
435 
436   if (slot->sdp_handle > 0) {
437     del_rfc_sdp_rec(slot->sdp_handle);
438     slot->sdp_handle = 0;
439   }
440 
441   if (slot->rfc_handle && !slot->f.closing && !slot->f.server) {
442     BTA_JvRfcommClose(slot->rfc_handle, slot->id);
443     slot->rfc_handle = 0;
444   }
445 
446   free_rfc_slot_scn(slot);
447   list_clear(slot->incoming_queue);
448 
449   slot->rfc_port_handle = 0;
450   memset(&slot->f, 0, sizeof(slot->f));
451   slot->id = 0;
452   slot->scn_notified = false;
453   slot->tx_bytes = 0;
454   slot->rx_bytes = 0;
455 }
456 
send_app_scn(rfc_slot_t * slot)457 static bool send_app_scn(rfc_slot_t* slot) {
458   if (slot->scn_notified) {
459     // already send, just return success.
460     return true;
461   }
462   slot->scn_notified = true;
463   return sock_send_all(slot->fd, (const uint8_t*)&slot->scn,
464                        sizeof(slot->scn)) == sizeof(slot->scn);
465 }
466 
send_app_connect_signal(int fd,const RawAddress * addr,int channel,int status,int send_fd)467 static bool send_app_connect_signal(int fd, const RawAddress* addr, int channel,
468                                     int status, int send_fd) {
469   sock_connect_signal_t cs;
470   cs.size = sizeof(cs);
471   cs.bd_addr = *addr;
472   cs.channel = channel;
473   cs.status = status;
474   cs.max_rx_packet_size = 0;  // not used for RFCOMM
475   cs.max_tx_packet_size = 0;  // not used for RFCOMM
476   if (send_fd == INVALID_FD)
477     return sock_send_all(fd, (const uint8_t*)&cs, sizeof(cs)) == sizeof(cs);
478 
479   return sock_send_fd(fd, (const uint8_t*)&cs, sizeof(cs), send_fd) ==
480          sizeof(cs);
481 }
482 
on_cl_rfc_init(tBTA_JV_RFCOMM_CL_INIT * p_init,uint32_t id)483 static void on_cl_rfc_init(tBTA_JV_RFCOMM_CL_INIT* p_init, uint32_t id) {
484   std::unique_lock<std::recursive_mutex> lock(slot_lock);
485   rfc_slot_t* slot = find_rfc_slot_by_id(id);
486   if (!slot) return;
487 
488   if (p_init->status == BTA_JV_SUCCESS) {
489     slot->rfc_handle = p_init->handle;
490   } else {
491     cleanup_rfc_slot(slot);
492   }
493 }
494 
on_srv_rfc_listen_started(tBTA_JV_RFCOMM_START * p_start,uint32_t id)495 static void on_srv_rfc_listen_started(tBTA_JV_RFCOMM_START* p_start,
496                                       uint32_t id) {
497   std::unique_lock<std::recursive_mutex> lock(slot_lock);
498   rfc_slot_t* slot = find_rfc_slot_by_id(id);
499   if (!slot) return;
500 
501   if (p_start->status == BTA_JV_SUCCESS) {
502     slot->rfc_handle = p_start->handle;
503     bluetooth::common::LogSocketConnectionState(
504         slot->addr, slot->id, BTSOCK_RFCOMM,
505         android::bluetooth::SocketConnectionstateEnum::
506             SOCKET_CONNECTION_STATE_LISTENING,
507         0, 0, slot->app_uid, slot->scn,
508         slot->f.server ? android::bluetooth::SOCKET_ROLE_LISTEN
509                        : android::bluetooth::SOCKET_ROLE_CONNECTION);
510   } else {
511     cleanup_rfc_slot(slot);
512   }
513 }
514 
on_srv_rfc_connect(tBTA_JV_RFCOMM_SRV_OPEN * p_open,uint32_t id)515 static uint32_t on_srv_rfc_connect(tBTA_JV_RFCOMM_SRV_OPEN* p_open,
516                                    uint32_t id) {
517   std::unique_lock<std::recursive_mutex> lock(slot_lock);
518   rfc_slot_t* accept_rs;
519   rfc_slot_t* srv_rs = find_rfc_slot_by_id(id);
520   if (!srv_rs) return 0;
521 
522   accept_rs = create_srv_accept_rfc_slot(
523       srv_rs, &p_open->rem_bda, p_open->handle, p_open->new_listen_handle);
524   if (!accept_rs) return 0;
525 
526   bluetooth::common::LogSocketConnectionState(
527       accept_rs->addr, accept_rs->id, BTSOCK_RFCOMM,
528       android::bluetooth::SOCKET_CONNECTION_STATE_CONNECTED, 0, 0,
529       accept_rs->app_uid, accept_rs->scn,
530       accept_rs->f.server ? android::bluetooth::SOCKET_ROLE_LISTEN
531                           : android::bluetooth::SOCKET_ROLE_CONNECTION);
532 
533   // Start monitoring the socket.
534   btsock_thread_add_fd(pth, srv_rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_EXCEPTION,
535                        srv_rs->id);
536   btsock_thread_add_fd(pth, accept_rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD,
537                        accept_rs->id);
538   send_app_connect_signal(srv_rs->fd, &accept_rs->addr, srv_rs->scn, 0,
539                           accept_rs->app_fd);
540   accept_rs->app_fd =
541       INVALID_FD;  // Ownership of the application fd has been transferred.
542   return srv_rs->id;
543 }
544 
on_cli_rfc_connect(tBTA_JV_RFCOMM_OPEN * p_open,uint32_t id)545 static void on_cli_rfc_connect(tBTA_JV_RFCOMM_OPEN* p_open, uint32_t id) {
546   std::unique_lock<std::recursive_mutex> lock(slot_lock);
547   rfc_slot_t* slot = find_rfc_slot_by_id(id);
548   if (!slot) return;
549 
550   if (p_open->status != BTA_JV_SUCCESS) {
551     cleanup_rfc_slot(slot);
552     return;
553   }
554 
555   slot->rfc_port_handle = BTA_JvRfcommGetPortHdl(p_open->handle);
556   slot->addr = p_open->rem_bda;
557 
558   bluetooth::common::LogSocketConnectionState(
559       slot->addr, slot->id, BTSOCK_RFCOMM,
560       android::bluetooth::SOCKET_CONNECTION_STATE_CONNECTED, 0, 0,
561       slot->app_uid, slot->scn,
562       slot->f.server ? android::bluetooth::SOCKET_ROLE_LISTEN
563                      : android::bluetooth::SOCKET_ROLE_CONNECTION);
564 
565   if (send_app_connect_signal(slot->fd, &slot->addr, slot->scn, 0, -1)) {
566     slot->f.connected = true;
567   } else {
568     LOG_ERROR("%s unable to send connect completion signal to caller.",
569               __func__);
570   }
571 }
572 
on_rfc_close(UNUSED_ATTR tBTA_JV_RFCOMM_CLOSE * p_close,uint32_t id)573 static void on_rfc_close(UNUSED_ATTR tBTA_JV_RFCOMM_CLOSE* p_close,
574                          uint32_t id) {
575   std::unique_lock<std::recursive_mutex> lock(slot_lock);
576 
577   // rfc_handle already closed when receiving rfcomm close event from stack.
578   rfc_slot_t* slot = find_rfc_slot_by_id(id);
579   if (slot) {
580     bluetooth::common::LogSocketConnectionState(
581         slot->addr, slot->id, BTSOCK_RFCOMM,
582         android::bluetooth::SOCKET_CONNECTION_STATE_DISCONNECTING, 0, 0,
583         slot->app_uid, slot->scn,
584         slot->f.server ? android::bluetooth::SOCKET_ROLE_LISTEN
585                        : android::bluetooth::SOCKET_ROLE_CONNECTION);
586     cleanup_rfc_slot(slot);
587   }
588 }
589 
on_rfc_write_done(tBTA_JV_RFCOMM_WRITE * p,uint32_t id)590 static void on_rfc_write_done(tBTA_JV_RFCOMM_WRITE* p, uint32_t id) {
591   if (p->status != BTA_JV_SUCCESS) {
592     LOG_ERROR("%s error writing to RFCOMM socket with slot %u.", __func__,
593               p->req_id);
594     return;
595   }
596 
597   int app_uid = -1;
598   std::unique_lock<std::recursive_mutex> lock(slot_lock);
599 
600   rfc_slot_t* slot = find_rfc_slot_by_id(id);
601   if (slot) {
602     app_uid = slot->app_uid;
603     if (!slot->f.outgoing_congest) {
604       btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD,
605                            slot->id);
606     }
607     slot->tx_bytes += p->len;
608   }
609 
610   uid_set_add_tx(uid_set, app_uid, p->len);
611 }
612 
on_rfc_outgoing_congest(tBTA_JV_RFCOMM_CONG * p,uint32_t id)613 static void on_rfc_outgoing_congest(tBTA_JV_RFCOMM_CONG* p, uint32_t id) {
614   std::unique_lock<std::recursive_mutex> lock(slot_lock);
615 
616   rfc_slot_t* slot = find_rfc_slot_by_id(id);
617   if (slot) {
618     slot->f.outgoing_congest = p->cong ? 1 : 0;
619     if (!slot->f.outgoing_congest)
620       btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD,
621                            slot->id);
622   }
623 }
624 
rfcomm_cback(tBTA_JV_EVT event,tBTA_JV * p_data,uint32_t rfcomm_slot_id)625 static uint32_t rfcomm_cback(tBTA_JV_EVT event, tBTA_JV* p_data,
626                              uint32_t rfcomm_slot_id) {
627   uint32_t id = 0;
628 
629   switch (event) {
630     case BTA_JV_RFCOMM_START_EVT:
631       on_srv_rfc_listen_started(&p_data->rfc_start, rfcomm_slot_id);
632       break;
633 
634     case BTA_JV_RFCOMM_CL_INIT_EVT:
635       on_cl_rfc_init(&p_data->rfc_cl_init, rfcomm_slot_id);
636       break;
637 
638     case BTA_JV_RFCOMM_OPEN_EVT:
639       BTA_JvSetPmProfile(p_data->rfc_open.handle, BTA_JV_PM_ID_1,
640                          BTA_JV_CONN_OPEN);
641       on_cli_rfc_connect(&p_data->rfc_open, rfcomm_slot_id);
642       break;
643 
644     case BTA_JV_RFCOMM_SRV_OPEN_EVT:
645       BTA_JvSetPmProfile(p_data->rfc_srv_open.handle, BTA_JV_PM_ALL,
646                          BTA_JV_CONN_OPEN);
647       id = on_srv_rfc_connect(&p_data->rfc_srv_open, rfcomm_slot_id);
648       break;
649 
650     case BTA_JV_RFCOMM_CLOSE_EVT:
651       APPL_TRACE_DEBUG("BTA_JV_RFCOMM_CLOSE_EVT: rfcomm_slot_id:%d",
652                        rfcomm_slot_id);
653       on_rfc_close(&p_data->rfc_close, rfcomm_slot_id);
654       break;
655 
656     case BTA_JV_RFCOMM_WRITE_EVT:
657       on_rfc_write_done(&p_data->rfc_write, rfcomm_slot_id);
658       break;
659 
660     case BTA_JV_RFCOMM_CONG_EVT:
661       on_rfc_outgoing_congest(&p_data->rfc_cong, rfcomm_slot_id);
662       break;
663 
664     case BTA_JV_RFCOMM_DATA_IND_EVT:
665       // Unused.
666       break;
667 
668     default:
669       LOG_ERROR("%s unhandled event %d, slot id: %u", __func__, event,
670                 rfcomm_slot_id);
671       break;
672   }
673   return id;
674 }
675 
jv_dm_cback(tBTA_JV_EVT event,tBTA_JV * p_data,uint32_t id)676 static void jv_dm_cback(tBTA_JV_EVT event, tBTA_JV* p_data, uint32_t id) {
677   switch (event) {
678     case BTA_JV_GET_SCN_EVT: {
679       std::unique_lock<std::recursive_mutex> lock(slot_lock);
680       rfc_slot_t* rs = find_rfc_slot_by_id(id);
681       int new_scn = p_data->scn;
682 
683       if (rs && (new_scn != 0)) {
684         rs->scn = new_scn;
685         /* BTA_JvCreateRecordByUser will only create a record if a UUID is
686          * specified,
687          * else it just allocate a RFC channel and start the RFCOMM thread -
688          * needed
689          * for the java
690          * layer to get a RFCOMM channel.
691          * If uuid is null the create_sdp_record() will be called from Java when
692          * it
693          * has received the RFCOMM and L2CAP channel numbers through the
694          * sockets.*/
695 
696         // Send channel ID to java layer
697         if (!send_app_scn(rs)) {
698           // closed
699           APPL_TRACE_DEBUG("send_app_scn() failed, close rs->id:%d", rs->id);
700           cleanup_rfc_slot(rs);
701         } else {
702           if (rs->is_service_uuid_valid) {
703             // We already have data for SDP record, create it (RFC-only
704             // profiles)
705             BTA_JvCreateRecordByUser(rs->id);
706           } else {
707             APPL_TRACE_DEBUG(
708                 "is_service_uuid_valid==false - don't set SDP-record, "
709                 "just start the RFCOMM server",
710                 rs->id);
711             // now start the rfcomm server after sdp & channel # assigned
712             BTA_JvRfcommStartServer(rs->security, rs->role, rs->scn,
713                                     MAX_RFC_SESSION, rfcomm_cback, rs->id);
714           }
715         }
716       } else if (rs) {
717         APPL_TRACE_ERROR(
718             "jv_dm_cback: Error: allocate channel %d, slot found:%p", rs->scn,
719             rs);
720         cleanup_rfc_slot(rs);
721       }
722       break;
723     }
724     case BTA_JV_GET_PSM_EVT: {
725       APPL_TRACE_DEBUG("Received PSM: 0x%04x", p_data->psm);
726       on_l2cap_psm_assigned(id, p_data->psm);
727       break;
728     }
729     case BTA_JV_CREATE_RECORD_EVT: {
730       std::unique_lock<std::recursive_mutex> lock(slot_lock);
731       rfc_slot_t* slot = find_rfc_slot_by_id(id);
732 
733       if (slot && create_server_sdp_record(slot)) {
734         // Start the rfcomm server after sdp & channel # assigned.
735         BTA_JvRfcommStartServer(slot->security, slot->role, slot->scn,
736                                 MAX_RFC_SESSION, rfcomm_cback, slot->id);
737       } else if (slot) {
738         APPL_TRACE_ERROR("jv_dm_cback: cannot start server, slot found:%p",
739                          slot);
740         cleanup_rfc_slot(slot);
741       }
742       break;
743     }
744 
745     case BTA_JV_DISCOVERY_COMP_EVT: {
746       std::unique_lock<std::recursive_mutex> lock(slot_lock);
747       rfc_slot_t* slot = find_rfc_slot_by_id(id);
748       if (p_data->disc_comp.status == BTA_JV_SUCCESS && p_data->disc_comp.scn) {
749         if (slot && slot->f.doing_sdp_request) {
750           // Establish the connection if we successfully looked up a channel
751           // number to connect to.
752           if (BTA_JvRfcommConnect(slot->security, slot->role,
753                                   p_data->disc_comp.scn, slot->addr,
754                                   rfcomm_cback, slot->id) == BTA_JV_SUCCESS) {
755             slot->scn = p_data->disc_comp.scn;
756             slot->f.doing_sdp_request = false;
757             if (!send_app_scn(slot)) cleanup_rfc_slot(slot);
758           } else {
759             cleanup_rfc_slot(slot);
760           }
761         } else if (slot) {
762           // TODO(sharvil): this is really a logic error and we should probably
763           // assert.
764           LOG_ERROR(
765               "%s SDP response returned but RFCOMM slot %d did not "
766               "request SDP record.",
767               __func__, id);
768         }
769       } else if (slot) {
770         cleanup_rfc_slot(slot);
771       }
772 
773       // Find the next slot that needs to perform an SDP request and service it.
774       slot = find_rfc_slot_by_pending_sdp();
775       if (slot) {
776         BTA_JvStartDiscovery(slot->addr, 1, &slot->service_uuid, slot->id);
777         slot->f.pending_sdp_request = false;
778         slot->f.doing_sdp_request = true;
779       }
780       break;
781     }
782 
783     default:
784       APPL_TRACE_DEBUG("unhandled event:%d, slot id:%d", event, id);
785       break;
786   }
787 }
788 
789 typedef enum {
790   SENT_FAILED,
791   SENT_NONE,
792   SENT_PARTIAL,
793   SENT_ALL,
794 } sent_status_t;
795 
send_data_to_app(int fd,BT_HDR * p_buf)796 static sent_status_t send_data_to_app(int fd, BT_HDR* p_buf) {
797   if (p_buf->len == 0) return SENT_ALL;
798 
799   ssize_t sent;
800   OSI_NO_INTR(
801       sent = send(fd, p_buf->data + p_buf->offset, p_buf->len, MSG_DONTWAIT));
802 
803   if (sent == -1) {
804     if (errno == EAGAIN || errno == EWOULDBLOCK) return SENT_NONE;
805     LOG_ERROR("%s error writing RFCOMM data back to app: %s", __func__,
806               strerror(errno));
807     return SENT_FAILED;
808   }
809 
810   if (sent == 0) return SENT_FAILED;
811 
812   if (sent == p_buf->len) return SENT_ALL;
813 
814   p_buf->offset += sent;
815   p_buf->len -= sent;
816   return SENT_PARTIAL;
817 }
818 
flush_incoming_que_on_wr_signal(rfc_slot_t * slot)819 static bool flush_incoming_que_on_wr_signal(rfc_slot_t* slot) {
820   while (!list_is_empty(slot->incoming_queue)) {
821     BT_HDR* p_buf = (BT_HDR*)list_front(slot->incoming_queue);
822     switch (send_data_to_app(slot->fd, p_buf)) {
823       case SENT_NONE:
824       case SENT_PARTIAL:
825         // monitor the fd to get callback when app is ready to receive data
826         btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_WR,
827                              slot->id);
828         return true;
829 
830       case SENT_ALL:
831         list_remove(slot->incoming_queue, p_buf);
832         break;
833 
834       case SENT_FAILED:
835         list_remove(slot->incoming_queue, p_buf);
836         return false;
837     }
838   }
839 
840   // app is ready to receive data, tell stack to start the data flow
841   // fix me: need a jv flow control api to serialize the call in stack
842   APPL_TRACE_DEBUG(
843       "enable data flow, rfc_handle:0x%x, rfc_port_handle:0x%x, user_id:%d",
844       slot->rfc_handle, slot->rfc_port_handle, slot->id);
845   PORT_FlowControl_MaxCredit(slot->rfc_port_handle, true);
846   return true;
847 }
848 
btsock_rfc_signaled(UNUSED_ATTR int fd,int flags,uint32_t user_id)849 void btsock_rfc_signaled(UNUSED_ATTR int fd, int flags, uint32_t user_id) {
850   bool need_close = false;
851   std::unique_lock<std::recursive_mutex> lock(slot_lock);
852   rfc_slot_t* slot = find_rfc_slot_by_id(user_id);
853   if (!slot) return;
854 
855   // Data available from app, tell stack we have outgoing data.
856   if (flags & SOCK_THREAD_FD_RD && !slot->f.server) {
857     if (slot->f.connected) {
858       // Make sure there's data pending in case the peer closed the socket.
859       int size = 0;
860       if (!(flags & SOCK_THREAD_FD_EXCEPTION) ||
861           (ioctl(slot->fd, FIONREAD, &size) == 0 && size)) {
862         BTA_JvRfcommWrite(slot->rfc_handle, slot->id);
863       }
864     } else {
865       LOG_ERROR(
866           "%s socket signaled for read while disconnected, slot: %d, "
867           "channel: %d",
868           __func__, slot->id, slot->scn);
869       need_close = true;
870     }
871   }
872 
873   if (flags & SOCK_THREAD_FD_WR) {
874     // App is ready to receive more data, tell stack to enable data flow.
875     if (!slot->f.connected || !flush_incoming_que_on_wr_signal(slot)) {
876       LOG_ERROR(
877           "%s socket signaled for write while disconnected (or write "
878           "failure), slot: %d, channel: %d",
879           __func__, slot->id, slot->scn);
880       need_close = true;
881     }
882   }
883 
884   if (need_close || (flags & SOCK_THREAD_FD_EXCEPTION)) {
885     // Clean up if there's no data pending.
886     int size = 0;
887     if (need_close || ioctl(slot->fd, FIONREAD, &size) != 0 || !size)
888       cleanup_rfc_slot(slot);
889   }
890 }
891 
bta_co_rfc_data_incoming(uint32_t id,BT_HDR * p_buf)892 int bta_co_rfc_data_incoming(uint32_t id, BT_HDR* p_buf) {
893   int app_uid = -1;
894   uint64_t bytes_rx = 0;
895   int ret = 0;
896   std::unique_lock<std::recursive_mutex> lock(slot_lock);
897   rfc_slot_t* slot = find_rfc_slot_by_id(id);
898   if (!slot) return 0;
899 
900   app_uid = slot->app_uid;
901   bytes_rx = p_buf->len;
902 
903   if (list_is_empty(slot->incoming_queue)) {
904     switch (send_data_to_app(slot->fd, p_buf)) {
905       case SENT_NONE:
906       case SENT_PARTIAL:
907         list_append(slot->incoming_queue, p_buf);
908         btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_WR,
909                              slot->id);
910         break;
911 
912       case SENT_ALL:
913         osi_free(p_buf);
914         ret = 1;  // Enable data flow.
915         break;
916 
917       case SENT_FAILED:
918         osi_free(p_buf);
919         cleanup_rfc_slot(slot);
920         break;
921     }
922   } else {
923     list_append(slot->incoming_queue, p_buf);
924   }
925 
926   slot->rx_bytes += bytes_rx;
927   uid_set_add_rx(uid_set, app_uid, bytes_rx);
928 
929   return ret;  // Return 0 to disable data flow.
930 }
931 
bta_co_rfc_data_outgoing_size(uint32_t id,int * size)932 int bta_co_rfc_data_outgoing_size(uint32_t id, int* size) {
933   *size = 0;
934   std::unique_lock<std::recursive_mutex> lock(slot_lock);
935   rfc_slot_t* slot = find_rfc_slot_by_id(id);
936   if (!slot) return false;
937 
938   if (ioctl(slot->fd, FIONREAD, size) != 0) {
939     LOG_ERROR("%s unable to determine bytes remaining to be read on fd %d: %s",
940               __func__, slot->fd, strerror(errno));
941     cleanup_rfc_slot(slot);
942     return false;
943   }
944 
945   return true;
946 }
947 
bta_co_rfc_data_outgoing(uint32_t id,uint8_t * buf,uint16_t size)948 int bta_co_rfc_data_outgoing(uint32_t id, uint8_t* buf, uint16_t size) {
949   std::unique_lock<std::recursive_mutex> lock(slot_lock);
950   rfc_slot_t* slot = find_rfc_slot_by_id(id);
951   if (!slot) return false;
952 
953   ssize_t received;
954   OSI_NO_INTR(received = recv(slot->fd, buf, size, 0));
955 
956   if (received != size) {
957     LOG_ERROR("%s error receiving RFCOMM data from app: %s", __func__,
958               strerror(errno));
959     cleanup_rfc_slot(slot);
960     return false;
961   }
962 
963   return true;
964 }
965