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