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_pan_api.h"
58 #include "btif_common.h"
59 #include "btif_pan_internal.h"
60 #include "btif_sock_thread.h"
61 #include "btif_sock_util.h"
62 #include "btif_util.h"
63 #include "btm_api.h"
64 #include "device/include/controller.h"
65 #include "osi/include/log.h"
66 #include "osi/include/osi.h"
67 #include "stack/include/btu.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_main_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("btpan_tap_send eth packet size:%d is exceeded limit!", len);
424       return -1;
425     }
426     memcpy(packet + sizeof(tETH_HDR), buf, len);
427 
428     /* Send data to network interface */
429     ssize_t ret;
430     OSI_NO_INTR(ret = write(tap_fd, packet, len + sizeof(tETH_HDR)));
431     BTIF_TRACE_DEBUG("ret:%d", ret);
432     return (int)ret;
433   }
434   return -1;
435 }
436 
btpan_tap_close(int fd)437 int btpan_tap_close(int fd) {
438   if (tap_if_down(TAP_IF_NAME) == 0) close(fd);
439   if (pan_pth >= 0) btsock_thread_wakeup(pan_pth);
440   return 0;
441 }
442 
btpan_find_conn_handle(uint16_t handle)443 btpan_conn_t* btpan_find_conn_handle(uint16_t handle) {
444   for (int i = 0; i < MAX_PAN_CONNS; i++) {
445     if (btpan_cb.conns[i].handle == handle) return &btpan_cb.conns[i];
446   }
447   return NULL;
448 }
449 
btpan_find_conn_addr(const RawAddress & addr)450 btpan_conn_t* btpan_find_conn_addr(const RawAddress& addr) {
451   for (int i = 0; i < MAX_PAN_CONNS; i++) {
452     if (btpan_cb.conns[i].peer == addr) return &btpan_cb.conns[i];
453   }
454   return NULL;
455 }
456 
btpan_open_conn(btpan_conn_t * conn,tBTA_PAN * p_data)457 static void btpan_open_conn(btpan_conn_t* conn, tBTA_PAN* p_data) {
458   BTIF_TRACE_API(
459       "btpan_open_conn: local_role:%d, peer_role: %d,  handle:%d, conn: %p",
460       p_data->open.local_role, p_data->open.peer_role, p_data->open.handle,
461       conn);
462 
463   if (conn == NULL)
464     conn = btpan_new_conn(p_data->open.handle, p_data->open.bd_addr,
465                           p_data->open.local_role, p_data->open.peer_role);
466   if (conn) {
467     BTIF_TRACE_DEBUG(
468         "btpan_open_conn:tap_fd:%d, open_count:%d, "
469         "conn->handle:%d should = handle:%d, local_role:%d, remote_role:%d",
470         btpan_cb.tap_fd, btpan_cb.open_count, conn->handle, p_data->open.handle,
471         conn->local_role, conn->remote_role);
472 
473     btpan_cb.open_count++;
474     conn->handle = p_data->open.handle;
475     if (btpan_cb.tap_fd < 0) {
476       btpan_cb.tap_fd = btpan_tap_open();
477       if (btpan_cb.tap_fd >= 0) create_tap_read_thread(btpan_cb.tap_fd);
478     }
479 
480     if (btpan_cb.tap_fd >= 0) {
481       btpan_cb.flow = 1;
482       conn->state = PAN_STATE_OPEN;
483     }
484   }
485 }
486 
btpan_close_conn(btpan_conn_t * conn)487 static void btpan_close_conn(btpan_conn_t* conn) {
488   BTIF_TRACE_API("btpan_close_conn: %p", conn);
489 
490   if (conn && conn->state == PAN_STATE_OPEN) {
491     BTIF_TRACE_DEBUG("btpan_close_conn: PAN_STATE_OPEN");
492 
493     conn->state = PAN_STATE_CLOSE;
494     btpan_cb.open_count--;
495 
496     if (btpan_cb.open_count == 0) {
497       destroy_tap_read_thread();
498       if (btpan_cb.tap_fd != INVALID_FD) {
499         btpan_tap_close(btpan_cb.tap_fd);
500         btpan_cb.tap_fd = INVALID_FD;
501       }
502     }
503   }
504 }
505 
btpan_cleanup_conn(btpan_conn_t * conn)506 static void btpan_cleanup_conn(btpan_conn_t* conn) {
507   if (conn) {
508     conn->handle = -1;
509     conn->state = -1;
510     memset(&conn->peer, 0, sizeof(conn->peer));
511     memset(&conn->eth_addr, 0, sizeof(conn->eth_addr));
512     conn->local_role = conn->remote_role = 0;
513   }
514 }
515 
btpan_new_conn(int handle,const RawAddress & addr,int local_role,int remote_role)516 btpan_conn_t* btpan_new_conn(int handle, const RawAddress& addr, int local_role,
517                              int remote_role) {
518   for (int i = 0; i < MAX_PAN_CONNS; i++) {
519     BTIF_TRACE_DEBUG("conns[%d]:%d", i, btpan_cb.conns[i].handle);
520     if (btpan_cb.conns[i].handle == -1) {
521       BTIF_TRACE_DEBUG("handle:%d, local_role:%d, remote_role:%d", handle,
522                        local_role, remote_role);
523 
524       btpan_cb.conns[i].handle = handle;
525       btpan_cb.conns[i].peer = addr;
526       btpan_cb.conns[i].local_role = local_role;
527       btpan_cb.conns[i].remote_role = remote_role;
528       return &btpan_cb.conns[i];
529     }
530   }
531   BTIF_TRACE_DEBUG("MAX_PAN_CONNS:%d exceeded, return NULL as failed",
532                    MAX_PAN_CONNS);
533   return NULL;
534 }
535 
btpan_close_handle(btpan_conn_t * p)536 void btpan_close_handle(btpan_conn_t* p) {
537   BTIF_TRACE_DEBUG("btpan_close_handle : close handle %d", p->handle);
538   p->handle = -1;
539   p->local_role = -1;
540   p->remote_role = -1;
541   memset(&p->peer, 0, 6);
542 }
543 
should_forward(tETH_HDR * hdr)544 static inline bool should_forward(tETH_HDR* hdr) {
545   uint16_t proto = ntohs(hdr->h_proto);
546   if (proto == ETH_P_IP || proto == ETH_P_ARP || proto == ETH_P_IPV6)
547     return true;
548   BTIF_TRACE_DEBUG("unknown proto:%x", proto);
549   return false;
550 }
551 
forward_bnep(tETH_HDR * eth_hdr,BT_HDR * hdr)552 static int forward_bnep(tETH_HDR* eth_hdr, BT_HDR* hdr) {
553   int broadcast = eth_hdr->h_dest.address[0] & 1;
554 
555   // Find the right connection to send this frame over.
556   for (int i = 0; i < MAX_PAN_CONNS; i++) {
557     uint16_t handle = btpan_cb.conns[i].handle;
558     if (handle != (uint16_t)-1 &&
559         (broadcast || btpan_cb.conns[i].eth_addr == eth_hdr->h_dest ||
560          btpan_cb.conns[i].peer == eth_hdr->h_dest)) {
561       int result = PAN_WriteBuf(handle, eth_hdr->h_dest, eth_hdr->h_src,
562                                 ntohs(eth_hdr->h_proto), hdr, 0);
563       switch (result) {
564         case PAN_Q_SIZE_EXCEEDED:
565           return FORWARD_CONGEST;
566         case PAN_SUCCESS:
567           return FORWARD_SUCCESS;
568         default:
569           return FORWARD_FAILURE;
570       }
571     }
572   }
573   osi_free(hdr);
574   return FORWARD_IGNORE;
575 }
576 
bta_pan_callback_transfer(uint16_t event,char * p_param)577 static void bta_pan_callback_transfer(uint16_t event, char* p_param) {
578   tBTA_PAN* p_data = (tBTA_PAN*)p_param;
579 
580   switch (event) {
581     case BTA_PAN_ENABLE_EVT:
582       BTIF_TRACE_DEBUG("BTA_PAN_ENABLE_EVT");
583       break;
584     case BTA_PAN_SET_ROLE_EVT: {
585       int btpan_role = bta_role_to_btpan(p_data->set_role.role);
586       bt_status_t status = p_data->set_role.status == BTA_PAN_SUCCESS
587                                ? BT_STATUS_SUCCESS
588                                : BT_STATUS_FAIL;
589       btpan_control_state_t state =
590           btpan_role == 0 ? BTPAN_STATE_DISABLED : BTPAN_STATE_ENABLED;
591       callback.control_state_cb(state, btpan_role, status, TAP_IF_NAME);
592       break;
593     }
594     case BTA_PAN_OPENING_EVT: {
595       btpan_conn_t* conn;
596       BTIF_TRACE_DEBUG("BTA_PAN_OPENING_EVT handle %d, addr: %s",
597                        p_data->opening.handle,
598                        p_data->opening.bd_addr.ToString().c_str());
599       conn = btpan_find_conn_addr(p_data->opening.bd_addr);
600 
601       asrt(conn != NULL);
602       if (conn) {
603         conn->handle = p_data->opening.handle;
604         int btpan_conn_local_role = bta_role_to_btpan(conn->local_role);
605         int btpan_remote_role = bta_role_to_btpan(conn->remote_role);
606         callback.connection_state_cb(BTPAN_STATE_CONNECTING, BT_STATUS_SUCCESS,
607                                      &p_data->opening.bd_addr,
608                                      btpan_conn_local_role, btpan_remote_role);
609       } else
610         BTIF_TRACE_ERROR("connection not found");
611       break;
612     }
613     case BTA_PAN_OPEN_EVT: {
614       btpan_connection_state_t state;
615       bt_status_t status;
616       btpan_conn_t* conn = btpan_find_conn_handle(p_data->open.handle);
617 
618       LOG_VERBOSE("%s pan connection open status: %d", __func__,
619                   p_data->open.status);
620       if (p_data->open.status == BTA_PAN_SUCCESS) {
621         state = BTPAN_STATE_CONNECTED;
622         status = BT_STATUS_SUCCESS;
623         btpan_open_conn(conn, p_data);
624       } else {
625         state = BTPAN_STATE_DISCONNECTED;
626         status = BT_STATUS_FAIL;
627         btpan_cleanup_conn(conn);
628       }
629       /* debug("BTA_PAN_OPEN_EVT handle:%d, conn:%p",  p_data->open.handle,
630        * conn); */
631       /* debug("conn bta local_role:%d, bta remote role:%d", conn->local_role,
632        * conn->remote_role); */
633       int btpan_conn_local_role = bta_role_to_btpan(p_data->open.local_role);
634       int btpan_remote_role = bta_role_to_btpan(p_data->open.peer_role);
635       callback.connection_state_cb(state, status, &p_data->open.bd_addr,
636                                    btpan_conn_local_role, btpan_remote_role);
637       break;
638     }
639     case BTA_PAN_CLOSE_EVT: {
640       LOG_INFO("%s: event = BTA_PAN_CLOSE_EVT handle %d", __func__,
641                p_data->close.handle);
642       btpan_conn_t* conn = btpan_find_conn_handle(p_data->close.handle);
643       btpan_close_conn(conn);
644 
645       if (conn && conn->handle >= 0) {
646         int btpan_conn_local_role = bta_role_to_btpan(conn->local_role);
647         int btpan_remote_role = bta_role_to_btpan(conn->remote_role);
648         callback.connection_state_cb(BTPAN_STATE_DISCONNECTED, (bt_status_t)0,
649                                      &conn->peer, btpan_conn_local_role,
650                                      btpan_remote_role);
651         btpan_cleanup_conn(conn);
652       } else
653         BTIF_TRACE_ERROR("pan handle not found (%d)", p_data->close.handle);
654       break;
655     }
656     default:
657       BTIF_TRACE_WARNING("Unknown pan event %d", event);
658       break;
659   }
660 }
661 
bta_pan_callback(tBTA_PAN_EVT event,tBTA_PAN * p_data)662 static void bta_pan_callback(tBTA_PAN_EVT event, tBTA_PAN* p_data) {
663   btif_transfer_context(bta_pan_callback_transfer, event, (char*)p_data,
664                         sizeof(tBTA_PAN), NULL);
665 }
666 
667 #define IS_EXCEPTION(e) ((e) & (POLLHUP | POLLRDHUP | POLLERR | POLLNVAL))
btu_exec_tap_fd_read(int fd)668 static void btu_exec_tap_fd_read(int fd) {
669   struct pollfd ufd;
670 
671   if (fd == INVALID_FD || fd != btpan_cb.tap_fd) return;
672 
673   // Don't occupy BTU context too long, avoid buffer overruns and
674   // give other profiles a chance to run by limiting the amount of memory
675   // PAN can use.
676   for (int i = 0; i < PAN_BUF_MAX && btif_is_enabled() && btpan_cb.flow; i++) {
677     BT_HDR* buffer = (BT_HDR*)osi_malloc(PAN_BUF_SIZE);
678     buffer->offset = PAN_MINIMUM_OFFSET;
679     buffer->len = PAN_BUF_SIZE - sizeof(BT_HDR) - buffer->offset;
680 
681     uint8_t* packet = (uint8_t*)buffer + sizeof(BT_HDR) + buffer->offset;
682 
683     // If we don't have an undelivered packet left over, pull one from the TAP
684     // driver.
685     // We save it in the congest_packet right away in case we can't deliver it
686     // in this
687     // attempt.
688     if (!btpan_cb.congest_packet_size) {
689       ssize_t ret;
690       OSI_NO_INTR(ret = read(fd, btpan_cb.congest_packet,
691                              sizeof(btpan_cb.congest_packet)));
692       switch (ret) {
693         case -1:
694           BTIF_TRACE_ERROR("%s unable to read from driver: %s", __func__,
695                            strerror(errno));
696           osi_free(buffer);
697           // add fd back to monitor thread to try it again later
698           btsock_thread_add_fd(pan_pth, fd, 0, SOCK_THREAD_FD_RD, 0);
699           return;
700         case 0:
701           BTIF_TRACE_WARNING("%s end of file reached.", __func__);
702           osi_free(buffer);
703           // add fd back to monitor thread to process the exception
704           btsock_thread_add_fd(pan_pth, fd, 0, SOCK_THREAD_FD_RD, 0);
705           return;
706         default:
707           btpan_cb.congest_packet_size = ret;
708           break;
709       }
710     }
711 
712     memcpy(packet, btpan_cb.congest_packet,
713            MIN(btpan_cb.congest_packet_size, buffer->len));
714     buffer->len = MIN(btpan_cb.congest_packet_size, buffer->len);
715 
716     if (buffer->len > sizeof(tETH_HDR) && should_forward((tETH_HDR*)packet)) {
717       // Extract the ethernet header from the buffer since the PAN_WriteBuf
718       // inside
719       // forward_bnep can't handle two pointers that point inside the same GKI
720       // buffer.
721       tETH_HDR hdr;
722       memcpy(&hdr, packet, sizeof(tETH_HDR));
723 
724       // Skip the ethernet header.
725       buffer->len -= sizeof(tETH_HDR);
726       buffer->offset += sizeof(tETH_HDR);
727       if (forward_bnep(&hdr, buffer) != FORWARD_CONGEST)
728         btpan_cb.congest_packet_size = 0;
729     } else {
730       BTIF_TRACE_WARNING("%s dropping packet of length %d", __func__,
731                          buffer->len);
732       btpan_cb.congest_packet_size = 0;
733       osi_free(buffer);
734     }
735 
736     // Bail out of the loop if reading from the TAP fd would block.
737     ufd.fd = fd;
738     ufd.events = POLLIN;
739     ufd.revents = 0;
740 
741     int ret;
742     OSI_NO_INTR(ret = poll(&ufd, 1, 0));
743     if (ret <= 0 || IS_EXCEPTION(ufd.revents)) break;
744   }
745 
746   if (btpan_cb.flow) {
747     // add fd back to monitor thread when the flow is on
748     btsock_thread_add_fd(pan_pth, fd, 0, SOCK_THREAD_FD_RD, 0);
749   }
750 }
751 
btif_pan_close_all_conns()752 static void btif_pan_close_all_conns() {
753   if (!stack_initialized) return;
754 
755   for (int i = 0; i < MAX_PAN_CONNS; ++i) {
756     if (btpan_cb.conns[i].handle != -1) BTA_PanClose(btpan_cb.conns[i].handle);
757   }
758 }
759 
btpan_tap_fd_signaled(int fd,int type,int flags,uint32_t user_id)760 static void btpan_tap_fd_signaled(int fd, int type, int flags,
761                                   uint32_t user_id) {
762   CHECK(btpan_cb.tap_fd == INVALID_FD || btpan_cb.tap_fd == fd);
763 
764   if (btpan_cb.tap_fd != fd) {
765     BTIF_TRACE_WARNING("%s Signaled on mismatched fds exp:%d act:%d\n",
766                        __func__, btpan_cb.tap_fd, fd);
767     return;
768   }
769 
770   if (flags & SOCK_THREAD_FD_EXCEPTION) {
771     btpan_cb.tap_fd = INVALID_FD;
772     btpan_tap_close(fd);
773     btif_pan_close_all_conns();
774   } else if (flags & SOCK_THREAD_FD_RD) {
775     do_in_main_thread(FROM_HERE, base::Bind(btu_exec_tap_fd_read, fd));
776   }
777 }
778