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