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