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/************************************************************************************
20 *
21 *  Filename:      btif_sock_rfc.c
22 *
23 *  Description:   Handsfree Profile Bluetooth Interface
24 *
25 ***********************************************************************************/
26#include <assert.h>
27#include <hardware/bluetooth.h>
28#include <hardware/bt_sock.h>
29#include <sys/types.h>
30#include <sys/socket.h>
31#include <errno.h>
32#include <sys/ioctl.h>
33
34#define LOG_TAG "BTIF_SOCK"
35#include "btif_common.h"
36#include "btif_util.h"
37
38#include "bd.h"
39
40#include "bta_api.h"
41#include "btif_sock_thread.h"
42#include "btif_sock_sdp.h"
43#include "btif_sock_util.h"
44
45#include "bt_target.h"
46#include "gki.h"
47#include "hcimsgs.h"
48#include "sdp_api.h"
49#include "btu.h"
50#include "btm_api.h"
51#include "btm_int.h"
52#include "bta_jv_api.h"
53#include "bta_jv_co.h"
54#include "port_api.h"
55#include "list.h"
56
57#include <cutils/log.h>
58#include <hardware/bluetooth.h>
59#define asrt(s) if(!(s)) APPL_TRACE_ERROR("## %s assert %s failed at line:%d ##",__FUNCTION__, #s, __LINE__)
60
61extern void uuid_to_string(bt_uuid_t *p_uuid, char *str);
62static inline void logu(const char* title, const uint8_t * p_uuid)
63{
64    char uuids[128];
65    uuid_to_string((bt_uuid_t*)p_uuid, uuids);
66    ALOGD("%s: %s", title, uuids);
67}
68
69
70
71#define MAX_RFC_CHANNEL 30
72#define MAX_RFC_SESSION BTA_JV_MAX_RFC_SR_SESSION //3 by default
73typedef struct {
74    int outgoing_congest : 1;
75    int pending_sdp_request : 1;
76    int doing_sdp_request : 1;
77    int server : 1;
78    int connected : 1;
79    int closing : 1;
80} flags_t;
81
82typedef struct {
83  flags_t f;
84  uint32_t id;
85  int security;
86  int scn;
87  bt_bdaddr_t addr;
88  uint8_t service_uuid[16];
89  char service_name[256];
90  int fd, app_fd;
91  int mtu;
92  uint8_t* packet;
93  int sdp_handle;
94  int rfc_handle;
95  int rfc_port_handle;
96  int role;
97  list_t *incoming_queue;
98} rfc_slot_t;
99
100static rfc_slot_t rfc_slots[MAX_RFC_CHANNEL];
101static uint32_t rfc_slot_id;
102static volatile int pth = -1; //poll thread handle
103static void jv_dm_cback(tBTA_JV_EVT event, tBTA_JV *p_data, void *user_data);
104static void cleanup_rfc_slot(rfc_slot_t* rs);
105static void *rfcomm_cback(tBTA_JV_EVT event, tBTA_JV *p_data, void *user_data);
106static inline BOOLEAN send_app_scn(rfc_slot_t* rs);
107static pthread_mutex_t slot_lock;
108#define is_init_done() (pth != -1)
109static inline void clear_slot_flag(flags_t* f)
110{
111    memset(f, 0, sizeof(*f));
112}
113
114static inline void bd_copy(UINT8* dest, UINT8* src, BOOLEAN swap)
115{
116    if (swap)
117    {
118        int i;
119        for (i =0; i < 6 ;i++)
120            dest[i]= src[5-i];
121    }
122    else memcpy(dest, src, 6);
123}
124static void init_rfc_slots()
125{
126    int i;
127    memset(rfc_slots, 0, sizeof(rfc_slot_t)*MAX_RFC_CHANNEL);
128    for(i = 0; i < MAX_RFC_CHANNEL; i++)
129    {
130        rfc_slots[i].scn = -1;
131        rfc_slots[i].sdp_handle = 0;
132        rfc_slots[i].fd = rfc_slots[i].app_fd = -1;
133        rfc_slots[i].incoming_queue = list_new(GKI_freebuf);
134        assert(rfc_slots[i].incoming_queue != NULL);
135    }
136    BTA_JvEnable(jv_dm_cback);
137    init_slot_lock(&slot_lock);
138}
139bt_status_t btsock_rfc_init(int poll_thread_handle)
140{
141    pth = poll_thread_handle;
142    init_rfc_slots();
143    return BT_STATUS_SUCCESS;
144}
145void btsock_rfc_cleanup()
146{
147    int curr_pth = pth;
148    pth = -1;
149    btsock_thread_exit(curr_pth);
150    lock_slot(&slot_lock);
151    int i;
152    for(i = 0; i < MAX_RFC_CHANNEL; i++)
153    {
154        if(rfc_slots[i].id) {
155            cleanup_rfc_slot(&rfc_slots[i]);
156            list_free(rfc_slots[i].incoming_queue);
157        }
158    }
159    unlock_slot(&slot_lock);
160}
161static inline rfc_slot_t* find_free_slot()
162{
163    int i;
164    for(i = 0; i < MAX_RFC_CHANNEL; i++)
165    {
166        if(rfc_slots[i].fd == -1)
167        {
168             return &rfc_slots[i];
169        }
170    }
171    return NULL;
172}
173static inline rfc_slot_t* find_rfc_slot_by_id(uint32_t id)
174{
175    int i;
176    if(id)
177    {
178        for(i = 0; i < MAX_RFC_CHANNEL; i++)
179        {
180            if(rfc_slots[i].id == id)
181            {
182                return &rfc_slots[i];
183            }
184        }
185    }
186    APPL_TRACE_WARNING("invalid rfc slot id: %d", id);
187    return NULL;
188}
189static inline rfc_slot_t* find_rfc_slot_by_pending_sdp()
190{
191    uint32_t min_id = (uint32_t)-1;
192    int slot = -1;
193    int i;
194    for(i = 0; i < MAX_RFC_CHANNEL; i++)
195    {
196        if(rfc_slots[i].id && rfc_slots[i].f.pending_sdp_request)
197        {
198            if(rfc_slots[i].id < min_id)
199            {
200                min_id = rfc_slots[i].id;
201                slot = i;
202            }
203        }
204    }
205    if(0<= slot && slot < MAX_RFC_CHANNEL)
206        return &rfc_slots[slot];
207    return NULL;
208}
209static inline rfc_slot_t* find_rfc_slot_requesting_sdp()
210{
211    int i;
212    for(i = 0; i < MAX_RFC_CHANNEL; i++)
213    {
214        if(rfc_slots[i].id && rfc_slots[i].f.doing_sdp_request)
215                return &rfc_slots[i];
216    }
217    APPL_TRACE_DEBUG("can not find any slot is requesting sdp");
218    return NULL;
219}
220
221static inline rfc_slot_t* find_rfc_slot_by_fd(int fd)
222{
223    int i;
224    if(fd >= 0)
225    {
226        for(i = 0; i < MAX_RFC_CHANNEL; i++)
227        {
228            if(rfc_slots[i].fd == fd)
229            {
230                if(rfc_slots[i].id)
231                    return &rfc_slots[i];
232                else
233                {
234                    APPL_TRACE_ERROR("invalid rfc slot id, cannot be 0");
235                    break;
236                }
237            }
238        }
239    }
240    return NULL;
241}
242static rfc_slot_t* alloc_rfc_slot(const bt_bdaddr_t *addr, const char* name, const uint8_t* uuid, int channel, int flags, BOOLEAN server)
243{
244    int security = 0;
245    if(flags & BTSOCK_FLAG_ENCRYPT)
246        security |= server ? BTM_SEC_IN_ENCRYPT : BTM_SEC_OUT_ENCRYPT;
247    if(flags & BTSOCK_FLAG_AUTH)
248        security |= server ? BTM_SEC_IN_AUTHENTICATE : BTM_SEC_OUT_AUTHENTICATE;
249
250    rfc_slot_t* rs = find_free_slot();
251    if(rs)
252    {
253        int fds[2] = {-1, -1};
254        if(socketpair(AF_LOCAL, SOCK_STREAM, 0, fds))
255        {
256            APPL_TRACE_ERROR("socketpair failed, errno:%d", errno);
257            return NULL;
258        }
259        rs->fd = fds[0];
260        rs->app_fd = fds[1];
261        rs->security = security;
262        rs->scn = channel;
263        if(uuid)
264            memcpy(rs->service_uuid, uuid, sizeof(rs->service_uuid));
265        else memset(rs->service_uuid, 0, sizeof(rs->service_uuid));
266        if(name && *name)
267            strncpy(rs->service_name, name, sizeof(rs->service_name) -1);
268        if(addr)
269            rs->addr = *addr;
270        ++rfc_slot_id;
271        if(rfc_slot_id == 0)
272            rfc_slot_id = 1; //skip 0 when wrapped
273        rs->id = rfc_slot_id;
274        rs->f.server = server;
275    }
276    return rs;
277}
278// rfc_slot_t* accept_rs = create_srv_accept_rfc_slot(srv_rs, p_open->rem_bda,p_opne->handle,  p_open->new_listen_handle);
279static inline rfc_slot_t* create_srv_accept_rfc_slot(rfc_slot_t* srv_rs, const bt_bdaddr_t* addr,
280                                        int open_handle, int new_listen_handle)
281{
282    rfc_slot_t *accept_rs = alloc_rfc_slot(addr, srv_rs->service_name, srv_rs->service_uuid, srv_rs->scn, 0, FALSE);
283    if( accept_rs)
284    {
285        clear_slot_flag(&accept_rs->f);
286        accept_rs->f.server = FALSE;
287        accept_rs->f.connected = TRUE;
288        accept_rs->security = srv_rs->security;
289        accept_rs->mtu = srv_rs->mtu;
290        accept_rs->role = srv_rs->role;
291        accept_rs->rfc_handle = open_handle;
292        accept_rs->rfc_port_handle = BTA_JvRfcommGetPortHdl(open_handle);
293        //now update listen rfc_handle of server slot
294        srv_rs->rfc_handle = new_listen_handle;
295        srv_rs->rfc_port_handle = BTA_JvRfcommGetPortHdl(new_listen_handle);
296        BTIF_TRACE_DEBUG("create_srv_accept__rfc_slot(open_handle: 0x%x, new_listen_handle:"
297                "0x%x) accept_rs->rfc_handle:0x%x, srv_rs_listen->rfc_handle:0x%x"
298                ,open_handle, new_listen_handle, accept_rs->rfc_port_handle, srv_rs->rfc_port_handle);
299        asrt(accept_rs->rfc_port_handle != srv_rs->rfc_port_handle);
300        //now swap the slot id
301        uint32_t new_listen_id = accept_rs->id;
302        accept_rs->id = srv_rs->id;
303        srv_rs->id = new_listen_id;
304
305        return accept_rs;
306    }
307    else
308    {
309        APPL_TRACE_ERROR(" accept_rs is NULL %s", __FUNCTION__);
310        return NULL;
311    }
312}
313bt_status_t btsock_rfc_listen(const char* service_name, const uint8_t* service_uuid, int channel,
314                            int* sock_fd, int flags)
315{
316
317    APPL_TRACE_DEBUG("btsock_rfc_listen, service_name:%s", service_name);
318    if(sock_fd == NULL || (service_uuid == NULL && (channel < 1 || channel > 30)))
319    {
320        APPL_TRACE_ERROR("invalid rfc channel:%d or sock_fd:%p, uuid:%p", channel, sock_fd, service_uuid);
321        return BT_STATUS_PARM_INVALID;
322    }
323    *sock_fd = -1;
324    if(!is_init_done())
325        return BT_STATUS_NOT_READY;
326    if(is_uuid_empty(service_uuid))
327        service_uuid = UUID_SPP; //use serial port profile to listen to specified channel
328    else
329    {
330        //Check the service_uuid. overwrite the channel # if reserved
331        int reserved_channel = get_reserved_rfc_channel(service_uuid);
332        if(reserved_channel > 0)
333        {
334            channel = reserved_channel;
335        }
336    }
337    int status = BT_STATUS_FAIL;
338    lock_slot(&slot_lock);
339    rfc_slot_t* rs = alloc_rfc_slot(NULL, service_name, service_uuid, channel, flags, TRUE);
340    if(rs)
341    {
342        APPL_TRACE_DEBUG("BTA_JvCreateRecordByUser:%s", service_name);
343        BTA_JvCreateRecordByUser((void *)(intptr_t)rs->id);
344        *sock_fd = rs->app_fd;
345        rs->app_fd = -1; //the fd ownership is transferred to app
346        if (btsock_thread_add_fd(pth, rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_EXCEPTION, rs->id)) {
347            status = BT_STATUS_SUCCESS;
348        }
349        else
350        {
351            cleanup_rfc_slot(rs);
352        }
353    }
354    unlock_slot(&slot_lock);
355    return status;
356}
357bt_status_t btsock_rfc_connect(const bt_bdaddr_t *bd_addr, const uint8_t* service_uuid,
358        int channel, int* sock_fd, int flags)
359{
360    if(sock_fd == NULL || (service_uuid == NULL && (channel < 1 || channel > 30)))
361    {
362        APPL_TRACE_ERROR("invalid rfc channel:%d or sock_fd:%p, uuid:%p", channel, sock_fd,
363                          service_uuid);
364        return BT_STATUS_PARM_INVALID;
365    }
366    *sock_fd = -1;
367    if(!is_init_done())
368        return BT_STATUS_NOT_READY;
369    int status = BT_STATUS_FAIL;
370    lock_slot(&slot_lock);
371    rfc_slot_t* rs = alloc_rfc_slot(bd_addr, NULL, service_uuid, channel, flags, FALSE);
372    if(rs)
373    {
374        if(is_uuid_empty(service_uuid))
375        {
376            APPL_TRACE_DEBUG("connecting to rfcomm channel:%d without service discovery", channel);
377            if(BTA_JvRfcommConnect(rs->security, rs->role, rs->scn, rs->addr.address,
378                        rfcomm_cback, (void*)(intptr_t)rs->id) == BTA_JV_SUCCESS)
379            {
380                if(send_app_scn(rs))
381                {
382                    btsock_thread_add_fd(pth, rs->fd, BTSOCK_RFCOMM,
383                                                        SOCK_THREAD_FD_RD, rs->id);
384                    *sock_fd = rs->app_fd;
385                    rs->app_fd = -1; //the fd ownership is transferred to app
386                    status = BT_STATUS_SUCCESS;
387                }
388                else cleanup_rfc_slot(rs);
389            }
390            else cleanup_rfc_slot(rs);
391        }
392        else
393        {
394            tSDP_UUID sdp_uuid;
395            sdp_uuid.len = 16;
396            memcpy(sdp_uuid.uu.uuid128, service_uuid, sizeof(sdp_uuid.uu.uuid128));
397            logu("service_uuid", service_uuid);
398            *sock_fd = rs->app_fd;
399            rs->app_fd = -1; //the fd ownership is transferred to app
400            status = BT_STATUS_SUCCESS;
401            rfc_slot_t* rs_doing_sdp = find_rfc_slot_requesting_sdp();
402            if(rs_doing_sdp == NULL)
403            {
404                BTA_JvStartDiscovery((UINT8*)bd_addr->address, 1, &sdp_uuid, (void*)(intptr_t)rs->id);
405                rs->f.pending_sdp_request = FALSE;
406                rs->f.doing_sdp_request = TRUE;
407            }
408            else
409            {
410                rs->f.pending_sdp_request = TRUE;
411                rs->f.doing_sdp_request = FALSE;
412            }
413            btsock_thread_add_fd(pth, rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, rs->id);
414        }
415    }
416    unlock_slot(&slot_lock);
417    return status;
418}
419
420static int create_server_sdp_record(rfc_slot_t* rs)
421{
422    int scn = rs->scn;
423    if(rs->scn > 0)
424    {
425        if(BTM_TryAllocateSCN(rs->scn) == FALSE)
426        {
427            APPL_TRACE_ERROR("rfc channel:%d already in use", scn);
428            return FALSE;
429        }
430    }
431    else if((rs->scn = BTM_AllocateSCN()) == 0)
432    {
433        APPL_TRACE_ERROR("run out of rfc channels");
434        return FALSE;
435    }
436    if((rs->sdp_handle = add_rfc_sdp_rec(rs->service_name, rs->service_uuid, rs->scn)) <= 0)
437    {
438        return FALSE;
439    }
440    return TRUE;
441}
442const char * jv_evt[] = {
443    "BTA_JV_ENABLE_EVT",
444    "BTA_JV_SET_DISCOVER_EVT",
445    "BTA_JV_LOCAL_ADDR_EVT",
446    "BTA_JV_LOCAL_NAME_EVT",
447    "BTA_JV_REMOTE_NAME_EVT",
448    "BTA_JV_SET_ENCRYPTION_EVT",
449    "BTA_JV_GET_SCN_EVT",
450    "BTA_JV_GET_PSM_EVT",
451    "BTA_JV_DISCOVERY_COMP_EVT",
452    "BTA_JV_SERVICES_LEN_EVT",
453    "BTA_JV_SERVICE_SEL_EVT",
454    "BTA_JV_CREATE_RECORD_EVT",
455    "BTA_JV_UPDATE_RECORD_EVT",
456    "BTA_JV_ADD_ATTR_EVT",
457    "BTA_JV_DELETE_ATTR_EVT",
458    "BTA_JV_CANCEL_DISCVRY_EVT",
459
460    "BTA_JV_L2CAP_OPEN_EVT",
461    "BTA_JV_L2CAP_CLOSE_EVT",
462    "BTA_JV_L2CAP_START_EVT",
463    "BTA_JV_L2CAP_CL_INIT_EVT",
464    "BTA_JV_L2CAP_DATA_IND_EVT",
465    "BTA_JV_L2CAP_CONG_EVT",
466    "BTA_JV_L2CAP_READ_EVT",
467    "BTA_JV_L2CAP_RECEIVE_EVT",
468    "BTA_JV_L2CAP_WRITE_EVT",
469
470    "BTA_JV_RFCOMM_OPEN_EVT",
471    "BTA_JV_RFCOMM_CLOSE_EVT",
472    "BTA_JV_RFCOMM_START_EVT",
473    "BTA_JV_RFCOMM_CL_INIT_EVT",
474    "BTA_JV_RFCOMM_DATA_IND_EVT",
475    "BTA_JV_RFCOMM_CONG_EVT",
476    "BTA_JV_RFCOMM_READ_EVT",
477    "BTA_JV_RFCOMM_WRITE_EVT",
478    "BTA_JV_RFCOMM_SRV_OPEN_EVT", //  33 /* open status of Server RFCOMM connection */
479    "BTA_JV_MAX_EVT"
480};
481static inline void free_rfc_slot_scn(rfc_slot_t* rs)
482{
483    if(rs->scn > 0)
484    {
485        if(rs->f.server && !rs->f.closing && rs->rfc_handle)
486        {
487            BTA_JvRfcommStopServer(rs->rfc_handle, (void*)(uintptr_t)rs->id);
488            rs->rfc_handle = 0;
489        }
490        if(rs->f.server)
491            BTM_FreeSCN(rs->scn);
492        rs->scn = 0;
493    }
494}
495static void cleanup_rfc_slot(rfc_slot_t* rs)
496{
497    APPL_TRACE_DEBUG("cleanup slot:%d, fd:%d, scn:%d, sdp_handle:0x%x", rs->id, rs->fd, rs->scn, rs->sdp_handle);
498    if(rs->fd != -1)
499    {
500        shutdown(rs->fd, 2);
501        close(rs->fd);
502        rs->fd = -1;
503    }
504    if(rs->app_fd != -1)
505    {
506        close(rs->app_fd);
507        rs->app_fd = -1;
508    }
509    if(rs->sdp_handle > 0)
510    {
511        del_rfc_sdp_rec(rs->sdp_handle);
512        rs->sdp_handle = 0;
513    }
514    if(rs->rfc_handle && !rs->f.closing && !rs->f.server)
515    {
516        APPL_TRACE_DEBUG("closing rfcomm connection, rfc_handle:0x%x", rs->rfc_handle);
517        BTA_JvRfcommClose(rs->rfc_handle, (void*)(uintptr_t)rs->id);
518        rs->rfc_handle = 0;
519    }
520    free_rfc_slot_scn(rs);
521    list_clear(rs->incoming_queue);
522
523    rs->rfc_port_handle = 0;
524    //cleanup the flag
525    memset(&rs->f, 0, sizeof(rs->f));
526    rs->id = 0;
527}
528static inline BOOLEAN send_app_scn(rfc_slot_t* rs)
529{
530    if(sock_send_all(rs->fd, (const uint8_t*)&rs->scn, sizeof(rs->scn)) == sizeof(rs->scn))
531    {
532        return TRUE;
533    }
534
535    return FALSE;
536}
537static BOOLEAN send_app_connect_signal(int fd, const bt_bdaddr_t* addr, int channel, int status, int send_fd)
538{
539/*
540    typedef struct {
541    short size;
542    bt_bdaddr_t bd_addr;
543    int channel;
544    int status;
545} __attribute__((packed)) sock_connect_signal_t;
546*/
547    sock_connect_signal_t cs;
548    cs.size = sizeof(cs);
549    cs.bd_addr = *addr;
550    cs.channel = channel;
551    cs.status = status;
552    if(send_fd != -1)
553    {
554        if(sock_send_fd(fd, (const uint8_t*)&cs, sizeof(cs), send_fd) == sizeof(cs))
555            return TRUE;
556        else APPL_TRACE_ERROR("sock_send_fd failed, fd:%d, send_fd:%d", fd, send_fd);
557    }
558    else if(sock_send_all(fd, (const uint8_t*)&cs, sizeof(cs)) == sizeof(cs))
559    {
560        return TRUE;
561    }
562    return FALSE;
563}
564static void on_cl_rfc_init(tBTA_JV_RFCOMM_CL_INIT *p_init, uint32_t id)
565{
566   lock_slot(&slot_lock);
567    rfc_slot_t* rs = find_rfc_slot_by_id(id);
568    if(rs)
569    {
570        if (p_init->status != BTA_JV_SUCCESS)
571            cleanup_rfc_slot(rs);
572        else
573        {
574            rs->rfc_handle = p_init->handle;
575        }
576    }
577    unlock_slot(&slot_lock);
578}
579static void  on_srv_rfc_listen_started(tBTA_JV_RFCOMM_START *p_start, uint32_t id)
580{
581    lock_slot(&slot_lock);
582    rfc_slot_t* rs = find_rfc_slot_by_id(id);
583    if(rs)
584    {
585        if (p_start->status != BTA_JV_SUCCESS)
586            cleanup_rfc_slot(rs);
587        else
588        {
589            rs->rfc_handle = p_start->handle;
590
591            if(!send_app_scn(rs))
592            {
593                //closed
594                APPL_TRACE_DEBUG("send_app_scn() failed, close rs->id:%d", rs->id);
595                cleanup_rfc_slot(rs);
596            }
597        }
598    }
599    unlock_slot(&slot_lock);
600}
601static uint32_t on_srv_rfc_connect(tBTA_JV_RFCOMM_SRV_OPEN *p_open, uint32_t id)
602{
603    uint32_t new_listen_slot_id = 0;
604    lock_slot(&slot_lock);
605    rfc_slot_t* srv_rs = find_rfc_slot_by_id(id);
606    if(srv_rs)
607    {
608        rfc_slot_t* accept_rs = create_srv_accept_rfc_slot(srv_rs, (const bt_bdaddr_t*)p_open->rem_bda,
609                                                           p_open->handle, p_open->new_listen_handle);
610        if(accept_rs)
611        {
612            //start monitor the socket
613            btsock_thread_add_fd(pth, srv_rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_EXCEPTION, srv_rs->id);
614            btsock_thread_add_fd(pth, accept_rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, accept_rs->id);
615            APPL_TRACE_DEBUG("sending connect signal & app fd:%dto app server to accept() the connection",
616                             accept_rs->app_fd);
617            APPL_TRACE_DEBUG("server fd:%d, scn:%d", srv_rs->fd, srv_rs->scn);
618            send_app_connect_signal(srv_rs->fd, &accept_rs->addr, srv_rs->scn, 0, accept_rs->app_fd);
619            accept_rs->app_fd = -1; //the fd is closed after sent to app
620            new_listen_slot_id = srv_rs->id;
621        }
622    }
623    unlock_slot(&slot_lock);
624    return new_listen_slot_id;
625}
626static void on_cli_rfc_connect(tBTA_JV_RFCOMM_OPEN *p_open, uint32_t id)
627{
628    lock_slot(&slot_lock);
629    rfc_slot_t* rs = find_rfc_slot_by_id(id);
630    if(rs && p_open->status == BTA_JV_SUCCESS)
631    {
632        rs->rfc_port_handle = BTA_JvRfcommGetPortHdl(p_open->handle);
633        bd_copy(rs->addr.address, p_open->rem_bda, 0);
634        //notify app rfc is connected
635        APPL_TRACE_DEBUG("call send_app_connect_signal, slot id:%d, fd:%d, rfc scn:%d, server:%d",
636                         rs->id, rs->fd, rs->scn, rs->f.server);
637        if(send_app_connect_signal(rs->fd, &rs->addr, rs->scn, 0, -1))
638        {
639            //start monitoring the socketpair to get call back when app writing data
640            APPL_TRACE_DEBUG("on_rfc_connect_ind, connect signal sent, slot id:%d, rfc scn:%d, server:%d",
641                             rs->id, rs->scn, rs->f.server);
642            rs->f.connected = TRUE;
643        }
644        else APPL_TRACE_ERROR("send_app_connect_signal failed");
645    }
646    else if(rs)
647        cleanup_rfc_slot(rs);
648    unlock_slot(&slot_lock);
649}
650static void on_rfc_close(tBTA_JV_RFCOMM_CLOSE * p_close, uint32_t id)
651{
652    UNUSED(p_close);
653    lock_slot(&slot_lock);
654    rfc_slot_t* rs = find_rfc_slot_by_id(id);
655    if(rs)
656    {
657        APPL_TRACE_DEBUG("on_rfc_close, slot id:%d, fd:%d, rfc scn:%d, server:%d",
658                         rs->id, rs->fd, rs->scn, rs->f.server);
659        free_rfc_slot_scn(rs);
660        // rfc_handle already closed when receiving rfcomm close event from stack.
661        rs->f.connected = FALSE;
662        cleanup_rfc_slot(rs);
663    }
664    unlock_slot(&slot_lock);
665}
666static void on_rfc_write_done(tBTA_JV_RFCOMM_WRITE *p, uint32_t id)
667{
668    UNUSED(p);
669
670    lock_slot(&slot_lock);
671    rfc_slot_t* rs = find_rfc_slot_by_id(id);
672    if(rs && !rs->f.outgoing_congest)
673    {
674        //mointer the fd for any outgoing data
675        btsock_thread_add_fd(pth, rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, rs->id);
676    }
677    unlock_slot(&slot_lock);
678}
679static void on_rfc_outgoing_congest(tBTA_JV_RFCOMM_CONG *p, uint32_t id)
680{
681    lock_slot(&slot_lock);
682    rfc_slot_t* rs = find_rfc_slot_by_id(id);
683    if(rs)
684    {
685        rs->f.outgoing_congest = p->cong ? 1 : 0;
686        //mointer the fd for any outgoing data
687        if(!rs->f.outgoing_congest)
688            btsock_thread_add_fd(pth, rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, rs->id);
689    }
690    unlock_slot(&slot_lock);
691}
692
693static void *rfcomm_cback(tBTA_JV_EVT event, tBTA_JV *p_data, void *user_data)
694{
695    int rc;
696    void* new_user_data = NULL;
697    APPL_TRACE_DEBUG("event=%s", jv_evt[event]);
698
699    switch (event)
700    {
701    case BTA_JV_RFCOMM_START_EVT:
702        on_srv_rfc_listen_started(&p_data->rfc_start, (uintptr_t)user_data);
703        break;
704
705    case BTA_JV_RFCOMM_CL_INIT_EVT:
706        on_cl_rfc_init(&p_data->rfc_cl_init, (uintptr_t)user_data);
707        break;
708
709    case BTA_JV_RFCOMM_OPEN_EVT:
710        BTA_JvSetPmProfile(p_data->rfc_open.handle,BTA_JV_PM_ID_1,BTA_JV_CONN_OPEN);
711        on_cli_rfc_connect(&p_data->rfc_open, (uintptr_t)user_data);
712        break;
713    case BTA_JV_RFCOMM_SRV_OPEN_EVT:
714        BTA_JvSetPmProfile(p_data->rfc_srv_open.handle,BTA_JV_PM_ALL,BTA_JV_CONN_OPEN);
715        new_user_data = (void*)(intptr_t)on_srv_rfc_connect(&p_data->rfc_srv_open, (uintptr_t)user_data);
716        break;
717
718    case BTA_JV_RFCOMM_CLOSE_EVT:
719        APPL_TRACE_DEBUG("BTA_JV_RFCOMM_CLOSE_EVT: user_data:%d", (uintptr_t)user_data);
720        on_rfc_close(&p_data->rfc_close, (uintptr_t)user_data);
721        break;
722
723    case BTA_JV_RFCOMM_READ_EVT:
724        APPL_TRACE_DEBUG("BTA_JV_RFCOMM_READ_EVT not used");
725        break;
726
727    case BTA_JV_RFCOMM_WRITE_EVT:
728        on_rfc_write_done(&p_data->rfc_write, (uintptr_t)user_data);
729        break;
730
731    case BTA_JV_RFCOMM_DATA_IND_EVT:
732        APPL_TRACE_DEBUG("BTA_JV_RFCOMM_DATA_IND_EVT not used");
733        break;
734
735    case BTA_JV_RFCOMM_CONG_EVT:
736        //on_rfc_cong(&p_data->rfc_cong);
737        on_rfc_outgoing_congest(&p_data->rfc_cong, (uintptr_t)user_data);
738        break;
739    default:
740        APPL_TRACE_ERROR("unhandled event %d, slot id:%d", event, (uintptr_t)user_data);
741        break;
742    }
743    return new_user_data;
744}
745
746static void jv_dm_cback(tBTA_JV_EVT event, tBTA_JV *p_data, void *user_data)
747{
748    uint32_t id = (uintptr_t)user_data;
749    APPL_TRACE_DEBUG("jv_dm_cback: event:%d, slot id:%d", event, id);
750    switch(event)
751    {
752        case BTA_JV_CREATE_RECORD_EVT:
753            {
754                lock_slot(&slot_lock);
755                rfc_slot_t* rs = find_rfc_slot_by_id(id);
756                if(rs && create_server_sdp_record(rs))
757                {
758                    //now start the rfcomm server after sdp & channel # assigned
759                    BTA_JvRfcommStartServer(rs->security, rs->role, rs->scn, MAX_RFC_SESSION, rfcomm_cback,
760                                            (void*)(uintptr_t)rs->id);
761                }
762                else if(rs)
763                {
764                    APPL_TRACE_ERROR("jv_dm_cback: cannot start server, slot found:%p", rs);
765                    cleanup_rfc_slot(rs);
766                }
767                unlock_slot(&slot_lock);
768                break;
769            }
770        case BTA_JV_DISCOVERY_COMP_EVT:
771            {
772                rfc_slot_t* rs = NULL;
773                lock_slot(&slot_lock);
774                if(p_data->disc_comp.status == BTA_JV_SUCCESS && p_data->disc_comp.scn)
775                {
776                    APPL_TRACE_DEBUG("BTA_JV_DISCOVERY_COMP_EVT, slot id:%d, status:%d, scn:%d",
777                                      id, p_data->disc_comp.status, p_data->disc_comp.scn);
778
779                    rs = find_rfc_slot_by_id(id);
780                    if(rs && rs->f.doing_sdp_request)
781                    {
782                        if(BTA_JvRfcommConnect(rs->security, rs->role, p_data->disc_comp.scn, rs->addr.address,
783                                    rfcomm_cback, (void*)(uintptr_t)rs->id) == BTA_JV_SUCCESS)
784                        {
785                            rs->scn = p_data->disc_comp.scn;
786                            rs->f.doing_sdp_request = FALSE;
787                            if(!send_app_scn(rs))
788                                cleanup_rfc_slot(rs);
789                        }
790                        else cleanup_rfc_slot(rs);
791                    }
792                    else if(rs)
793                    {
794                        APPL_TRACE_ERROR("DISCOVERY_COMP_EVT no pending sdp request, slot id:%d, \
795                                flag sdp pending:%d, flag sdp doing:%d",
796                                id, rs->f.pending_sdp_request, rs->f.doing_sdp_request);
797                    }
798                }
799                else
800                {
801                    APPL_TRACE_ERROR("DISCOVERY_COMP_EVT slot id:%d, failed to find channle, \
802                                      status:%d, scn:%d", id, p_data->disc_comp.status,
803                                      p_data->disc_comp.scn);
804                    rs = find_rfc_slot_by_id(id);
805                    if(rs)
806                        cleanup_rfc_slot(rs);
807                }
808                rs = find_rfc_slot_by_pending_sdp();
809                if(rs)
810                {
811                    APPL_TRACE_DEBUG("BTA_JV_DISCOVERY_COMP_EVT, start another pending scn sdp request");
812                    tSDP_UUID sdp_uuid;
813                    sdp_uuid.len = 16;
814                    memcpy(sdp_uuid.uu.uuid128, rs->service_uuid, sizeof(sdp_uuid.uu.uuid128));
815                    BTA_JvStartDiscovery((UINT8*)rs->addr.address, 1, &sdp_uuid, (void*)(uintptr_t)rs->id);
816                    rs->f.pending_sdp_request = FALSE;
817                    rs->f.doing_sdp_request = TRUE;
818                }
819                unlock_slot(&slot_lock);
820                break;
821            }
822        default:
823            APPL_TRACE_DEBUG("unhandled event:%d, slot id:%d", event, id);
824            break;
825    }
826
827}
828#define SENT_ALL 2
829#define SENT_PARTIAL 1
830#define SENT_NONE 0
831#define SENT_FAILED (-1)
832static int send_data_to_app(int fd, BT_HDR *p_buf)
833{
834    if(p_buf->len == 0)
835        return SENT_ALL;
836    int sent = send(fd, (UINT8 *)(p_buf + 1) + p_buf->offset,  p_buf->len, MSG_DONTWAIT);
837    if(sent == p_buf->len)
838        return SENT_ALL;
839
840    if(sent > 0 && sent < p_buf->len)
841    {
842        //sent partial
843        APPL_TRACE_ERROR("send partial, sent:%d, p_buf->len:%d", sent, p_buf->len);
844        p_buf->offset += sent;
845        p_buf->len -= sent;
846        return SENT_PARTIAL;
847
848    }
849    if(sent < 0 &&
850        (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR))
851    {
852        APPL_TRACE_ERROR("send none, EAGAIN or EWOULDBLOCK, errno:%d", errno);
853        return SENT_NONE;
854    }
855    APPL_TRACE_ERROR("unknown send() error, sent:%d, p_buf->len:%d,  errno:%d", sent, p_buf->len, errno);
856    return SENT_FAILED;
857}
858static BOOLEAN flush_incoming_que_on_wr_signal(rfc_slot_t* rs)
859{
860    while(!list_is_empty(rs->incoming_queue))
861    {
862        BT_HDR *p_buf = list_front(rs->incoming_queue);
863        int sent = send_data_to_app(rs->fd, p_buf);
864        switch(sent)
865        {
866            case SENT_NONE:
867            case SENT_PARTIAL:
868                //monitor the fd to get callback when app is ready to receive data
869                btsock_thread_add_fd(pth, rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_WR, rs->id);
870                return TRUE;
871            case SENT_ALL:
872                list_remove(rs->incoming_queue, p_buf);
873                break;
874            case SENT_FAILED:
875                list_remove(rs->incoming_queue, p_buf);
876                return FALSE;
877        }
878    }
879
880    //app is ready to receive data, tell stack to start the data flow
881    //fix me: need a jv flow control api to serialize the call in stack
882    APPL_TRACE_DEBUG("enable data flow, rfc_handle:0x%x, rfc_port_handle:0x%x, user_id:%d",
883                        rs->rfc_handle, rs->rfc_port_handle, rs->id);
884    extern int PORT_FlowControl_MaxCredit(UINT16 handle, BOOLEAN enable);
885    PORT_FlowControl_MaxCredit(rs->rfc_port_handle, TRUE);
886    return TRUE;
887}
888void btsock_rfc_signaled(int fd, int flags, uint32_t user_id)
889{
890    lock_slot(&slot_lock);
891    rfc_slot_t* rs = find_rfc_slot_by_id(user_id);
892    if(rs)
893    {
894        APPL_TRACE_DEBUG("rfc slot id:%d, fd:%d, flags:%x", rs->id, fd, flags);
895        BOOLEAN need_close = FALSE;
896        if(flags & SOCK_THREAD_FD_RD)
897        {
898            //data available from app, tell stack we have outgoing data
899            if(!rs->f.server)
900            {
901                if(rs->f.connected)
902                {
903                    int size = 0;
904                    //make sure there's data pending in case the peer closed the socket
905                    if(!(flags & SOCK_THREAD_FD_EXCEPTION) ||
906                                (ioctl(rs->fd, FIONREAD, &size) == 0 && size))
907                    {
908                        int rfc_handle = rs->rfc_handle;
909                        UINT32 rs_id = rs->id;
910                        //unlock before BTA_JvRfcommWrite to avoid deadlock on concurrnet multi rfcomm connectoins
911                        unlock_slot(&slot_lock);
912                        BTA_JvRfcommWrite(rfc_handle, rs_id);
913                        return;
914                    }
915                }
916                else
917                {
918                    APPL_TRACE_ERROR("SOCK_THREAD_FD_RD signaled when rfc is not connected, \
919                                      slot id:%d, channel:%d", rs->id, rs->scn);
920                    need_close = TRUE;
921                }
922            }
923        }
924        if(flags & SOCK_THREAD_FD_WR)
925        {
926            //app is ready to receive more data, tell stack to enable the data flow
927            if(!rs->f.connected || !flush_incoming_que_on_wr_signal(rs))
928            {
929                need_close = TRUE;
930                APPL_TRACE_ERROR("SOCK_THREAD_FD_WR signaled when rfc is not connected \
931                                  or app closed fd, slot id:%d, channel:%d", rs->id, rs->scn);
932            }
933
934        }
935        if(need_close || (flags & SOCK_THREAD_FD_EXCEPTION))
936        {
937            int size = 0;
938            if(need_close || ioctl(rs->fd, FIONREAD, &size) != 0 || size == 0 )
939            {
940                //cleanup when no data pending
941                APPL_TRACE_DEBUG("SOCK_THREAD_FD_EXCEPTION, cleanup, flags:%x, need_close:%d, pending size:%d",
942                                flags, need_close, size);
943                cleanup_rfc_slot(rs);
944            }
945            else
946                APPL_TRACE_DEBUG("SOCK_THREAD_FD_EXCEPTION, cleanup pending, flags:%x, need_close:%d, pending size:%d",
947                                flags, need_close, size);
948        }
949    }
950    unlock_slot(&slot_lock);
951}
952
953int bta_co_rfc_data_incoming(void *user_data, BT_HDR *p_buf)
954{
955    uint32_t id = (uintptr_t)user_data;
956    int ret = 0;
957    lock_slot(&slot_lock);
958    rfc_slot_t* rs = find_rfc_slot_by_id(id);
959    if(rs)
960    {
961        if(!list_is_empty(rs->incoming_queue))
962            list_append(rs->incoming_queue, p_buf);
963        else
964        {
965            int sent = send_data_to_app(rs->fd, p_buf);
966            switch(sent)
967            {
968                case SENT_NONE:
969                case SENT_PARTIAL:
970                    //add it to the end of the queue
971                    list_append(rs->incoming_queue, p_buf);
972                    //monitor the fd to get callback when app is ready to receive data
973                    btsock_thread_add_fd(pth, rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_WR, rs->id);
974                    break;
975                case SENT_ALL:
976                    GKI_freebuf(p_buf);
977                    ret = 1;//enable the data flow
978                    break;
979                case SENT_FAILED:
980                    GKI_freebuf(p_buf);
981                    cleanup_rfc_slot(rs);
982                    break;
983            }
984        }
985     }
986    unlock_slot(&slot_lock);
987    return ret;//return 0 to disable data flow
988}
989int bta_co_rfc_data_outgoing_size(void *user_data, int *size)
990{
991    uint32_t id = (uintptr_t)user_data;
992    int ret = FALSE;
993    *size = 0;
994    lock_slot(&slot_lock);
995    rfc_slot_t* rs = find_rfc_slot_by_id(id);
996    if(rs)
997    {
998        if(ioctl(rs->fd, FIONREAD, size) == 0)
999        {
1000            APPL_TRACE_DEBUG("ioctl read avaiable size:%d, fd:%d", *size, rs->fd);
1001            ret = TRUE;
1002        }
1003        else
1004        {
1005            APPL_TRACE_ERROR("ioctl FIONREAD error, errno:%d, fd:%d", errno, rs->fd);
1006            cleanup_rfc_slot(rs);
1007        }
1008    }
1009    else APPL_TRACE_ERROR("bta_co_rfc_data_outgoing_size, invalid slot id:%d", id);
1010    unlock_slot(&slot_lock);
1011    return ret;
1012}
1013int bta_co_rfc_data_outgoing(void *user_data, UINT8* buf, UINT16 size)
1014{
1015    uint32_t id = (uintptr_t)user_data;
1016    int ret = FALSE;
1017    lock_slot(&slot_lock);
1018    rfc_slot_t* rs = find_rfc_slot_by_id(id);
1019    if(rs)
1020    {
1021        int received = recv(rs->fd, buf, size, 0);
1022        if(received == size)
1023            ret = TRUE;
1024        else
1025        {
1026            APPL_TRACE_ERROR("recv error, errno:%d, fd:%d, size:%d, received:%d",
1027                             errno, rs->fd, size, received);
1028            cleanup_rfc_slot(rs);
1029        }
1030    }
1031    else APPL_TRACE_ERROR("bta_co_rfc_data_outgoing, invalid slot id:%d", id);
1032    unlock_slot(&slot_lock);
1033    return ret;
1034}
1035
1036