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