btif_pan.c revision bb2a4faddd9a7f03d13d37a23eb0da1ef52f9088
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_pan.c
22 *
23 *  Description:   PAN Profile Bluetooth Interface
24 *
25 *
26 ***********************************************************************************/
27#include <hardware/bluetooth.h>
28#include <hardware/bt_pan.h>
29#include <assert.h>
30#include <string.h>
31#include <signal.h>
32#include <ctype.h>
33#include <sys/select.h>
34#include <sys/poll.h>
35#include <sys/ioctl.h>
36#include <netinet/in.h>
37#include <netdb.h>
38#include <stdio.h>
39#include <string.h>
40#include <errno.h>
41#include <fcntl.h>
42#include <sys/socket.h>
43#include <sys/wait.h>
44#include <net/if.h>
45#include <linux/sockios.h>
46#include <sys/prctl.h>
47#include <linux/if_tun.h>
48#include <linux/if_ether.h>
49
50#define LOG_TAG "bt_btif_pan"
51#include "btif_common.h"
52#include "btif_util.h"
53#include "btm_api.h"
54#include "btcore/include/bdaddr.h"
55#include "device/include/controller.h"
56
57#include "bta_api.h"
58#include "bta_pan_api.h"
59#include "btif_sock_thread.h"
60#include "btif_sock_util.h"
61#include "btif_pan_internal.h"
62#include "gki.h"
63#include "osi/include/osi.h"
64#include "osi/include/log.h"
65
66#define FORWARD_IGNORE        1
67#define FORWARD_SUCCESS       0
68#define FORWARD_FAILURE     (-1)
69#define FORWARD_CONGEST     (-2)
70//#define PANU_DISABLED TRUE
71
72#if (PAN_NAP_DISABLED == TRUE) && (PANU_DISABLED == TRUE)
73#define BTPAN_LOCAL_ROLE BTPAN_ROLE_NONE
74#elif PAN_NAP_DISABLED == TRUE
75#define BTPAN_LOCAL_ROLE BTPAN_ROLE_PANU
76#elif PANU_DISABLED == TRUE
77#define BTPAN_LOCAL_ROLE BTPAN_ROLE_PANNAP
78#else
79#define BTPAN_LOCAL_ROLE (BTPAN_ROLE_PANU | BTPAN_ROLE_PANNAP)
80#endif
81
82#define asrt(s) if (!(s)) BTIF_TRACE_ERROR("btif_pan: ## %s assert %s failed at line:%d ##",__FUNCTION__, #s, __LINE__)
83
84#define MIN(x, y) (((x) < (y)) ? (x) : (y))
85
86btpan_cb_t btpan_cb;
87
88static bool jni_initialized;
89static bool stack_initialized;
90
91static bt_status_t btpan_jni_init(const btpan_callbacks_t* callbacks);
92static void btpan_jni_cleanup();
93static bt_status_t btpan_connect(const bt_bdaddr_t *bd_addr, int local_role, int remote_role);
94static bt_status_t btpan_disconnect(const bt_bdaddr_t *bd_addr);
95static bt_status_t btpan_enable(int local_role);
96static int btpan_get_local_role(void);
97
98static void btpan_tap_fd_signaled(int fd, int type, int flags, uint32_t user_id);
99static void btpan_cleanup_conn(btpan_conn_t* conn);
100static void bta_pan_callback(tBTA_PAN_EVT event, tBTA_PAN *p_data);
101static void btu_exec_tap_fd_read(void *p_param);
102
103static btpan_interface_t pan_if = {
104    sizeof(pan_if),
105    btpan_jni_init,
106    btpan_enable,
107    btpan_get_local_role,
108    btpan_connect,
109    btpan_disconnect,
110    btpan_jni_cleanup
111};
112
113btpan_interface_t *btif_pan_get_interface()
114{
115    return &pan_if;
116}
117
118/*******************************************************************************
119 **
120 ** Function        btif_pan_init
121 **
122 ** Description     initializes the pan interface
123 **
124 ** Returns         bt_status_t
125 **
126 *******************************************************************************/
127void btif_pan_init()
128{
129    BTIF_TRACE_DEBUG("jni_initialized = %d, btpan_cb.enabled:%d", jni_initialized, btpan_cb.enabled);
130    stack_initialized = true;
131
132    if (jni_initialized && !btpan_cb.enabled)
133    {
134        BTIF_TRACE_DEBUG("Enabling PAN....");
135        memset(&btpan_cb, 0, sizeof(btpan_cb));
136        btpan_cb.tap_fd = INVALID_FD;
137        btpan_cb.flow = 1;
138        for (int i = 0; i < MAX_PAN_CONNS; i++)
139            btpan_cleanup_conn(&btpan_cb.conns[i]);
140        BTA_PanEnable(bta_pan_callback);
141        btpan_cb.enabled = 1;
142        btpan_enable(BTPAN_LOCAL_ROLE);
143    }
144}
145
146static void pan_disable()
147{
148    if (btpan_cb.enabled)
149    {
150        btpan_cb.enabled = 0;
151        BTA_PanDisable();
152        if (btpan_cb.tap_fd != INVALID_FD)
153        {
154            btpan_tap_close(btpan_cb.tap_fd);
155            btpan_cb.tap_fd = INVALID_FD;
156        }
157    }
158}
159
160void btif_pan_cleanup()
161{
162    if (!stack_initialized)
163        return;
164
165    // Bluetooth is shuting down, invalidate all BTA PAN handles
166    for (int i = 0; i < MAX_PAN_CONNS; i++)
167        btpan_cleanup_conn(&btpan_cb.conns[i]);
168
169    pan_disable();
170    stack_initialized = false;
171}
172
173static btpan_callbacks_t callback;
174static bt_status_t btpan_jni_init(const btpan_callbacks_t* callbacks)
175{
176    BTIF_TRACE_DEBUG("stack_initialized = %d, btpan_cb.enabled:%d", stack_initialized, btpan_cb.enabled);
177    callback = *callbacks;
178    jni_initialized = TRUE;
179    if (stack_initialized && !btpan_cb.enabled)
180        btif_pan_init();
181    return BT_STATUS_SUCCESS;
182}
183
184static void btpan_jni_cleanup()
185{
186    pan_disable();
187    jni_initialized = false;
188}
189
190static inline int bta_role_to_btpan(int bta_pan_role)
191{
192    int btpan_role = 0;
193    BTIF_TRACE_DEBUG("bta_pan_role:0x%x", bta_pan_role);
194    if (bta_pan_role & PAN_ROLE_NAP_SERVER)
195        btpan_role |= BTPAN_ROLE_PANNAP;
196    if (bta_pan_role & PAN_ROLE_CLIENT)
197        btpan_role |= BTPAN_ROLE_PANU;
198    return btpan_role;
199}
200
201static inline int btpan_role_to_bta(int btpan_role)
202{
203    int bta_pan_role = PAN_ROLE_INACTIVE;
204    BTIF_TRACE_DEBUG("btpan_role:0x%x", btpan_role);
205    if (btpan_role & BTPAN_ROLE_PANNAP)
206        bta_pan_role |= PAN_ROLE_NAP_SERVER;
207    if (btpan_role & BTPAN_ROLE_PANU)
208        bta_pan_role |= PAN_ROLE_CLIENT;
209    return bta_pan_role;
210}
211
212static volatile int btpan_dev_local_role;
213static tBTA_PAN_ROLE_INFO bta_panu_info = {PANU_SERVICE_NAME, 0, PAN_SECURITY};
214static tBTA_PAN_ROLE_INFO bta_pan_nap_info = {PAN_NAP_SERVICE_NAME, 1, PAN_SECURITY};
215
216static bt_status_t btpan_enable(int local_role)
217{
218#if BTA_PAN_INCLUDED == TRUE
219    BTIF_TRACE_DEBUG("%s - local_role: %d", __func__, local_role);
220    int bta_pan_role = btpan_role_to_bta(local_role);
221    BTA_PanSetRole(bta_pan_role, &bta_panu_info, NULL, &bta_pan_nap_info);
222    btpan_dev_local_role = local_role;
223    return BT_STATUS_SUCCESS;
224#else
225    return BT_STATUS_FAIL;
226#endif
227}
228
229static int btpan_get_local_role()
230{
231    BTIF_TRACE_DEBUG("btpan_dev_local_role:%d", btpan_dev_local_role);
232    return btpan_dev_local_role;
233}
234
235static bt_status_t btpan_connect(const bt_bdaddr_t *bd_addr, int local_role, int remote_role)
236{
237    BTIF_TRACE_DEBUG("local_role:%d, remote_role:%d", local_role, remote_role);
238    int bta_local_role = btpan_role_to_bta(local_role);
239    int bta_remote_role = btpan_role_to_bta(remote_role);
240    btpan_new_conn(-1, bd_addr->address, bta_local_role, bta_remote_role);
241    BTA_PanOpen((UINT8*)bd_addr->address, bta_local_role, bta_remote_role);
242    return BT_STATUS_SUCCESS;
243}
244
245static void btif_in_pan_generic_evt(UINT16 event, char *p_param)
246{
247    BTIF_TRACE_EVENT("%s: event=%d", __FUNCTION__, event);
248    switch (event) {
249        case BTIF_PAN_CB_DISCONNECTING:
250        {
251            bt_bdaddr_t *bd_addr = (bt_bdaddr_t*)p_param;
252            btpan_conn_t* conn = btpan_find_conn_addr(bd_addr->address);
253            int btpan_conn_local_role;
254            int btpan_remote_role;
255            asrt(conn != NULL);
256            if (conn) {
257                btpan_conn_local_role = bta_role_to_btpan(conn->local_role);
258                btpan_remote_role = bta_role_to_btpan(conn->remote_role);
259                callback.connection_state_cb(BTPAN_STATE_DISCONNECTING, BT_STATUS_SUCCESS,
260                        (const bt_bdaddr_t*)conn->peer, btpan_conn_local_role, btpan_remote_role);
261            }
262        } break;
263        default:
264        {
265            BTIF_TRACE_WARNING("%s : Unknown event 0x%x", __FUNCTION__, event);
266        }
267        break;
268    }
269}
270
271static bt_status_t btpan_disconnect(const bt_bdaddr_t *bd_addr)
272{
273    btpan_conn_t* conn = btpan_find_conn_addr(bd_addr->address);
274    if (conn && conn->handle >= 0)
275    {
276        /* Inform the application that the disconnect has been initiated successfully */
277        btif_transfer_context(btif_in_pan_generic_evt, BTIF_PAN_CB_DISCONNECTING,
278                              (char *)bd_addr, sizeof(bt_bdaddr_t), NULL);
279        BTA_PanClose(conn->handle);
280        return BT_STATUS_SUCCESS;
281    }
282    return BT_STATUS_FAIL;
283}
284
285static int pan_pth = -1;
286void create_tap_read_thread(int tap_fd)
287{
288    if (pan_pth < 0)
289        pan_pth = btsock_thread_create(btpan_tap_fd_signaled, NULL);
290    if (pan_pth >= 0)
291        btsock_thread_add_fd(pan_pth, tap_fd, 0, SOCK_THREAD_FD_RD, 0);
292}
293
294void destroy_tap_read_thread(void)
295{
296    if (pan_pth >= 0)
297    {
298        btsock_thread_exit(pan_pth);
299        pan_pth = -1;
300    }
301}
302
303static int tap_if_up(const char *devname, const bt_bdaddr_t *addr)
304{
305    struct ifreq ifr;
306    int sk, err;
307
308    sk = socket(AF_INET, SOCK_DGRAM, 0);
309    if (sk < 0)
310        return -1;
311
312    //set mac addr
313    memset(&ifr, 0, sizeof(ifr));
314    strncpy(ifr.ifr_name, devname, IFNAMSIZ - 1);
315    err = ioctl(sk, SIOCGIFHWADDR, &ifr);
316    if (err < 0)
317    {
318        BTIF_TRACE_ERROR("Could not get network hardware for interface:%s, errno:%s", devname, strerror(errno));
319        close(sk);
320        return -1;
321    }
322
323    strncpy(ifr.ifr_name, devname, IFNAMSIZ - 1);
324    memcpy(ifr.ifr_hwaddr.sa_data, addr->address, 6);
325
326    /* The IEEE has specified that the most significant bit of the most significant byte is used to
327     * determine a multicast address. If its a 1, that means multicast, 0 means unicast.
328     * Kernel returns an error if we try to set a multicast address for the tun-tap ethernet interface.
329     * Mask this bit to avoid any issue with auto generated address.
330     */
331    if (ifr.ifr_hwaddr.sa_data[0] & 0x01) {
332        BTIF_TRACE_WARNING("Not a unicast MAC address, force multicast bit flipping");
333        ifr.ifr_hwaddr.sa_data[0] &= ~0x01;
334    }
335
336    err = ioctl(sk, SIOCSIFHWADDR, (caddr_t)&ifr);
337
338    if (err < 0) {
339        BTIF_TRACE_ERROR("Could not set bt address for interface:%s, errno:%s", devname, strerror(errno));
340        close(sk);
341        return -1;
342    }
343
344    //bring it up
345    memset(&ifr, 0, sizeof(ifr));
346    strncpy(ifr.ifr_name, devname, IF_NAMESIZE - 1);
347
348    ifr.ifr_flags |= IFF_UP;
349    ifr.ifr_flags |= IFF_MULTICAST;
350
351    err = ioctl(sk, SIOCSIFFLAGS, (caddr_t) &ifr);
352
353
354    if (err < 0) {
355        BTIF_TRACE_ERROR("Could not bring up network interface:%s, errno:%d", devname, errno);
356        close(sk);
357        return -1;
358    }
359    close(sk);
360    BTIF_TRACE_DEBUG("network interface: %s is up", devname);
361    return 0;
362}
363
364static int tap_if_down(const char *devname)
365{
366    struct ifreq ifr;
367    int sk;
368
369    sk = socket(AF_INET, SOCK_DGRAM, 0);
370    if (sk < 0)
371        return -1;
372
373    memset(&ifr, 0, sizeof(ifr));
374    strncpy(ifr.ifr_name, devname, IF_NAMESIZE - 1);
375
376    ifr.ifr_flags &= ~IFF_UP;
377
378    ioctl(sk, SIOCSIFFLAGS, (caddr_t) &ifr);
379
380    close(sk);
381
382    return 0;
383}
384
385void btpan_set_flow_control(BOOLEAN enable) {
386    if (btpan_cb.tap_fd == -1)
387        return;
388
389    btpan_cb.flow = enable;
390    if (enable) {
391        btsock_thread_add_fd(pan_pth, btpan_cb.tap_fd, 0, SOCK_THREAD_FD_RD, 0);
392        bta_dmexecutecallback(btu_exec_tap_fd_read, (void *)btpan_cb.tap_fd);
393    }
394}
395
396int btpan_tap_open()
397{
398    struct ifreq ifr;
399    int fd, err;
400    const char *clonedev = "/dev/tun";
401
402    /* open the clone device */
403
404    if ((fd = open(clonedev, O_RDWR)) < 0)
405    {
406        BTIF_TRACE_DEBUG("could not open %s, err:%d", clonedev, errno);
407        return fd;
408    }
409
410    memset(&ifr, 0, sizeof(ifr));
411    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
412
413    strncpy(ifr.ifr_name, TAP_IF_NAME, IFNAMSIZ);
414
415    /* try to create the device */
416    if ((err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0)
417    {
418        BTIF_TRACE_DEBUG("ioctl error:%d, errno:%s", err, strerror(errno));
419        close(fd);
420        return err;
421    }
422    if (tap_if_up(TAP_IF_NAME, controller_get_interface()->get_address()) == 0)
423    {
424        int flags = fcntl(fd, F_GETFL, 0);
425        fcntl(fd, F_SETFL, flags | O_NONBLOCK);
426        return fd;
427    }
428    BTIF_TRACE_ERROR("can not bring up tap interface:%s", TAP_IF_NAME);
429    close(fd);
430    return INVALID_FD;
431}
432
433int btpan_tap_send(int tap_fd, const BD_ADDR src, const BD_ADDR dst, UINT16 proto, const char* buf,
434                    UINT16 len, BOOLEAN ext, BOOLEAN forward)
435{
436    UNUSED(ext);
437    UNUSED(forward);
438    if (tap_fd != INVALID_FD)
439    {
440        tETH_HDR eth_hdr;
441        memcpy(&eth_hdr.h_dest, dst, ETH_ADDR_LEN);
442        memcpy(&eth_hdr.h_src, src, ETH_ADDR_LEN);
443        eth_hdr.h_proto = htons(proto);
444        char packet[TAP_MAX_PKT_WRITE_LEN + sizeof(tETH_HDR)];
445        memcpy(packet, &eth_hdr, sizeof(tETH_HDR));
446        if (len > TAP_MAX_PKT_WRITE_LEN)
447        {
448            LOG_ERROR("btpan_tap_send eth packet size:%d is exceeded limit!", len);
449            return -1;
450        }
451        memcpy(packet + sizeof(tETH_HDR), buf, len);
452
453        /* Send data to network interface */
454        int ret = write(tap_fd, packet, len + sizeof(tETH_HDR));
455        BTIF_TRACE_DEBUG("ret:%d", ret);
456        return ret;
457    }
458    return -1;
459
460}
461
462int btpan_tap_close(int fd)
463{
464    if (tap_if_down(TAP_IF_NAME) == 0)
465        close(fd);
466    if (pan_pth >= 0)
467        btsock_thread_wakeup(pan_pth);
468    return 0;
469}
470
471btpan_conn_t * btpan_find_conn_handle(UINT16 handle)
472{
473    for (int i = 0; i < MAX_PAN_CONNS; i++)
474    {
475        if (btpan_cb.conns[i].handle == handle)
476            return &btpan_cb.conns[i];
477    }
478    return NULL;
479}
480
481btpan_conn_t* btpan_find_conn_addr(const BD_ADDR addr)
482{
483    for (int i = 0; i < MAX_PAN_CONNS; i++)
484    {
485        if (memcmp(btpan_cb.conns[i].peer, addr, sizeof(BD_ADDR)) == 0)
486            return &btpan_cb.conns[i];
487    }
488    return NULL;
489}
490
491static void btpan_open_conn(btpan_conn_t* conn, tBTA_PAN *p_data)
492{
493    BTIF_TRACE_API("btpan_open_conn: local_role:%d, peer_role: %d,  handle:%d, conn: %p",
494            p_data->open.local_role, p_data->open.peer_role, p_data->open.handle, conn);
495
496    if (conn == NULL)
497        conn = btpan_new_conn(p_data->open.handle, p_data->open.bd_addr, p_data->open.local_role,
498                p_data->open.peer_role);
499    if (conn)
500    {
501        BTIF_TRACE_DEBUG("btpan_open_conn:tap_fd:%d, open_count:%d, "
502                "conn->handle:%d should = handle:%d, local_role:%d, remote_role:%d",
503                btpan_cb.tap_fd, btpan_cb.open_count, conn->handle, p_data->open.handle,
504                conn->local_role, conn->remote_role);
505
506        btpan_cb.open_count++;
507        conn->handle = p_data->open.handle;
508        if (btpan_cb.tap_fd < 0)
509        {
510            btpan_cb.tap_fd = btpan_tap_open();
511            if(btpan_cb.tap_fd >= 0)
512                create_tap_read_thread(btpan_cb.tap_fd);
513        }
514
515        if (btpan_cb.tap_fd >= 0)
516        {
517            btpan_cb.flow = 1;
518            conn->state = PAN_STATE_OPEN;
519        }
520    }
521}
522
523static void btpan_close_conn(btpan_conn_t* conn)
524{
525    BTIF_TRACE_API("btpan_close_conn: %p",conn);
526
527    if (conn && conn->state == PAN_STATE_OPEN)
528    {
529        BTIF_TRACE_DEBUG("btpan_close_conn: PAN_STATE_OPEN");
530
531        conn->state = PAN_STATE_CLOSE;
532        btpan_cb.open_count--;
533
534        if (btpan_cb.open_count == 0)
535        {
536            destroy_tap_read_thread();
537            if (btpan_cb.tap_fd != INVALID_FD)
538            {
539                btpan_tap_close(btpan_cb.tap_fd);
540                btpan_cb.tap_fd = INVALID_FD;
541            }
542        }
543    }
544}
545
546
547static void btpan_cleanup_conn(btpan_conn_t* conn)
548{
549    if (conn)
550    {
551        conn->handle = -1;
552        conn->state = -1;
553        memset(&conn->peer, 0, sizeof(conn->peer));
554        memset(&conn->eth_addr, 0, sizeof(conn->eth_addr));
555        conn->local_role = conn->remote_role = 0;
556    }
557}
558
559btpan_conn_t* btpan_new_conn(int handle, const BD_ADDR addr, int local_role, int remote_role)
560{
561    for (int i = 0; i < MAX_PAN_CONNS; i++)
562    {
563        BTIF_TRACE_DEBUG("conns[%d]:%d", i, btpan_cb.conns[i].handle);
564        if (btpan_cb.conns[i].handle == -1)
565        {
566            BTIF_TRACE_DEBUG("handle:%d, local_role:%d, remote_role:%d", handle, local_role, remote_role);
567
568            btpan_cb.conns[i].handle = handle;
569            bdcpy(btpan_cb.conns[i].peer, addr);
570            btpan_cb.conns[i].local_role = local_role;
571            btpan_cb.conns[i].remote_role = remote_role;
572            return &btpan_cb.conns[i];
573        }
574    }
575    BTIF_TRACE_DEBUG("MAX_PAN_CONNS:%d exceeded, return NULL as failed", MAX_PAN_CONNS);
576    return NULL;
577}
578
579void btpan_close_handle(btpan_conn_t *p)
580{
581    BTIF_TRACE_DEBUG("btpan_close_handle : close handle %d", p->handle);
582    p->handle = -1;
583    p->local_role = -1;
584    p->remote_role = -1;
585    memset(&p->peer, 0, 6);
586}
587
588static inline bool should_forward(tETH_HDR* hdr)
589{
590    uint16_t proto = ntohs(hdr->h_proto);
591    if (proto == ETH_P_IP || proto == ETH_P_ARP || proto == ETH_P_IPV6)
592        return true;
593    BTIF_TRACE_DEBUG("unknown proto:%x", proto);
594    return false;
595}
596
597static int forward_bnep(tETH_HDR* eth_hdr, BT_HDR *hdr) {
598    int broadcast = eth_hdr->h_dest[0] & 1;
599
600    // Find the right connection to send this frame over.
601    for (int i = 0; i < MAX_PAN_CONNS; i++)
602    {
603        UINT16 handle = btpan_cb.conns[i].handle;
604        if (handle != (UINT16)-1 &&
605                (broadcast || memcmp(btpan_cb.conns[i].eth_addr, eth_hdr->h_dest, sizeof(BD_ADDR)) == 0
606                 || memcmp(btpan_cb.conns[i].peer, eth_hdr->h_dest, sizeof(BD_ADDR)) == 0)) {
607            int result = PAN_WriteBuf(handle, eth_hdr->h_dest, eth_hdr->h_src, ntohs(eth_hdr->h_proto), hdr, 0);
608            switch (result) {
609                case PAN_Q_SIZE_EXCEEDED:
610                    return FORWARD_CONGEST;
611                case PAN_SUCCESS:
612                    return FORWARD_SUCCESS;
613                default:
614                    return FORWARD_FAILURE;
615            }
616        }
617    }
618    GKI_freebuf(hdr);
619    return FORWARD_IGNORE;
620}
621
622static void bta_pan_callback_transfer(UINT16 event, char *p_param)
623{
624    tBTA_PAN *p_data = (tBTA_PAN *)p_param;
625
626    switch(event)
627    {
628        case BTA_PAN_ENABLE_EVT:
629            BTIF_TRACE_DEBUG("BTA_PAN_ENABLE_EVT");
630            break;
631        case BTA_PAN_SET_ROLE_EVT:
632            {
633                int btpan_role = bta_role_to_btpan(p_data->set_role.role);
634                bt_status_t status = p_data->set_role.status == BTA_PAN_SUCCESS ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
635                btpan_control_state_t state = btpan_role == 0 ? BTPAN_STATE_DISABLED : BTPAN_STATE_ENABLED;
636                callback.control_state_cb(state, btpan_role, status, TAP_IF_NAME);
637                break;
638            }
639        case BTA_PAN_OPENING_EVT:
640            {
641                btpan_conn_t* conn;
642                bdstr_t bds;
643                bdaddr_to_string((bt_bdaddr_t *)p_data->opening.bd_addr, bds, sizeof(bds));
644                BTIF_TRACE_DEBUG("BTA_PAN_OPENING_EVT handle %d, addr: %s", p_data->opening.handle, bds);
645                conn = btpan_find_conn_addr(p_data->opening.bd_addr);
646
647                asrt(conn != NULL);
648                if (conn)
649                {
650                    conn->handle = p_data->opening.handle;
651                    int btpan_conn_local_role = bta_role_to_btpan(conn->local_role);
652                    int btpan_remote_role = bta_role_to_btpan(conn->remote_role);
653                    callback.connection_state_cb(BTPAN_STATE_CONNECTING, BT_STATUS_SUCCESS,
654                            (const bt_bdaddr_t*)p_data->opening.bd_addr, btpan_conn_local_role, btpan_remote_role);
655                }
656                else
657                    BTIF_TRACE_ERROR("connection not found");
658                break;
659            }
660        case BTA_PAN_OPEN_EVT:
661            {
662                btpan_connection_state_t state;
663                bt_status_t status;
664                btpan_conn_t *conn = btpan_find_conn_handle(p_data->open.handle);
665
666                LOG_VERBOSE("%s pan connection open status: %d", __func__, p_data->open.status);
667                if (p_data->open.status == BTA_PAN_SUCCESS)
668                {
669                    state = BTPAN_STATE_CONNECTED;
670                    status = BT_STATUS_SUCCESS;
671                    btpan_open_conn(conn, p_data);
672                }
673                else
674                {
675                    state = BTPAN_STATE_DISCONNECTED;
676                    status = BT_STATUS_FAIL;
677                    btpan_cleanup_conn(conn);
678                }
679                /* debug("BTA_PAN_OPEN_EVT handle:%d, conn:%p",  p_data->open.handle, conn); */
680                /* debug("conn bta local_role:%d, bta remote role:%d", conn->local_role, conn->remote_role); */
681                int btpan_conn_local_role = bta_role_to_btpan(p_data->open.local_role);
682                int btpan_remote_role = bta_role_to_btpan(p_data->open.peer_role);
683                callback.connection_state_cb(state, status, (const bt_bdaddr_t*)p_data->open.bd_addr,
684                        btpan_conn_local_role, btpan_remote_role);
685                break;
686            }
687        case BTA_PAN_CLOSE_EVT:
688            {
689                btpan_conn_t* conn = btpan_find_conn_handle(p_data->close.handle);
690
691                LOG_INFO("%s: event = BTA_PAN_CLOSE_EVT handle %d", __FUNCTION__, p_data->close.handle);
692                btpan_close_conn(conn);
693
694                if (conn && conn->handle >= 0)
695                {
696                    int btpan_conn_local_role = bta_role_to_btpan(conn->local_role);
697                    int btpan_remote_role = bta_role_to_btpan(conn->remote_role);
698                    callback.connection_state_cb(BTPAN_STATE_DISCONNECTED, 0, (const bt_bdaddr_t*)conn->peer,
699                            btpan_conn_local_role, btpan_remote_role);
700                    btpan_cleanup_conn(conn);
701                }
702                else
703                    BTIF_TRACE_ERROR("pan handle not found (%d)", p_data->close.handle);
704                break;
705            }
706        default:
707            BTIF_TRACE_WARNING("Unknown pan event %d", event);
708            break;
709    }
710}
711
712static void bta_pan_callback(tBTA_PAN_EVT event, tBTA_PAN *p_data)
713{
714    btif_transfer_context(bta_pan_callback_transfer, event, (char*)p_data, sizeof(tBTA_PAN), NULL);
715}
716
717#define IS_EXCEPTION(e) ((e) & (POLLHUP | POLLRDHUP | POLLERR | POLLNVAL))
718static void btu_exec_tap_fd_read(void *p_param) {
719    struct pollfd ufd;
720    int fd = (int)p_param;
721
722    if (fd == INVALID_FD || fd != btpan_cb.tap_fd)
723        return;
724
725    // Don't occupy BTU context too long, avoid GKI buffer overruns and
726    // give other profiles a chance to run by limiting the amount of memory
727    // PAN can use from the shared pool buffer.
728    for (int i = 0; i < PAN_POOL_MAX && btif_is_enabled() && btpan_cb.flow; i++) {
729        BT_HDR *buffer = (BT_HDR *)GKI_getpoolbuf(PAN_POOL_ID);
730        if (!buffer) {
731            BTIF_TRACE_WARNING("%s unable to allocate buffer for packet.", __func__);
732            break;
733        }
734        buffer->offset = PAN_MINIMUM_OFFSET;
735        buffer->len = GKI_get_buf_size(buffer) - sizeof(BT_HDR) - buffer->offset;
736
737        UINT8 *packet = (UINT8 *)buffer + sizeof(BT_HDR) + buffer->offset;
738
739        // If we don't have an undelivered packet left over, pull one from the TAP driver.
740        // We save it in the congest_packet right away in case we can't deliver it in this
741        // attempt.
742        if (!btpan_cb.congest_packet_size) {
743            ssize_t ret = read(fd, btpan_cb.congest_packet, sizeof(btpan_cb.congest_packet));
744            switch (ret) {
745                case -1:
746                    BTIF_TRACE_ERROR("%s unable to read from driver: %s", __func__, strerror(errno));
747                    GKI_freebuf(buffer);
748                    //add fd back to monitor thread to try it again later
749                    btsock_thread_add_fd(pan_pth, fd, 0, SOCK_THREAD_FD_RD, 0);
750                    return;
751                case 0:
752                    BTIF_TRACE_WARNING("%s end of file reached.", __func__);
753                    GKI_freebuf(buffer);
754                    //add fd back to monitor thread to process the exception
755                    btsock_thread_add_fd(pan_pth, fd, 0, SOCK_THREAD_FD_RD, 0);
756                    return;
757                default:
758                    btpan_cb.congest_packet_size = ret;
759                    break;
760            }
761        }
762
763        memcpy(packet, btpan_cb.congest_packet, MIN(btpan_cb.congest_packet_size, buffer->len));
764        buffer->len = MIN(btpan_cb.congest_packet_size, buffer->len);
765
766        if (buffer->len > sizeof(tETH_HDR) && should_forward((tETH_HDR *)packet)) {
767            // Extract the ethernet header from the buffer since the PAN_WriteBuf inside
768            // forward_bnep can't handle two pointers that point inside the same GKI buffer.
769            tETH_HDR hdr;
770            memcpy(&hdr, packet, sizeof(tETH_HDR));
771
772            // Skip the ethernet header.
773            buffer->len -= sizeof(tETH_HDR);
774            buffer->offset += sizeof(tETH_HDR);
775            if (forward_bnep(&hdr, buffer) != FORWARD_CONGEST)
776                btpan_cb.congest_packet_size = 0;
777        } else {
778            BTIF_TRACE_WARNING("%s dropping packet of length %d", __func__, buffer->len);
779            btpan_cb.congest_packet_size = 0;
780            GKI_freebuf(buffer);
781        }
782
783        // Bail out of the loop if reading from the TAP fd would block.
784        ufd.fd = fd;
785        ufd.events = POLLIN;
786        ufd.revents = 0;
787        if (poll(&ufd, 1, 0) <= 0 || IS_EXCEPTION(ufd.revents))
788            break;
789    }
790    //add fd back to monitor thread
791    btsock_thread_add_fd(pan_pth, fd, 0, SOCK_THREAD_FD_RD, 0);
792}
793
794static void btif_pan_close_all_conns() {
795    if (!stack_initialized)
796        return;
797
798    for (int i = 0; i < MAX_PAN_CONNS; ++i)
799    {
800        if (btpan_cb.conns[i].handle != -1)
801            BTA_PanClose(btpan_cb.conns[i].handle);
802    }
803}
804
805static void btpan_tap_fd_signaled(int fd, int type, int flags, uint32_t user_id) {
806    assert(btpan_cb.tap_fd == INVALID_FD || btpan_cb.tap_fd == fd);
807
808    if (btpan_cb.tap_fd != fd) {
809        BTIF_TRACE_WARNING("%s Signaled on mismatched fds exp:%d act:%d\n",
810                __func__, btpan_cb.tap_fd, fd);
811        return;
812    }
813
814    if (flags & SOCK_THREAD_FD_EXCEPTION) {
815        btpan_cb.tap_fd = INVALID_FD;
816        btpan_tap_close(fd);
817        btif_pan_close_all_conns();
818    } else if (flags & SOCK_THREAD_FD_RD)
819        bta_dmexecutecallback(btu_exec_tap_fd_read, (void *)fd);
820}
821