OSDN Git Service

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