• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2 * Copyright (C) 2014 Samsung System LSI
3 * Copyright (C) 2013 The Android Open Source Project
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 #include <hardware/bluetooth.h>
19 #include <hardware/bt_sock.h>
20 #include <stdlib.h>
21 #include <sys/types.h>
22 #include <sys/socket.h>
23 #include <errno.h>
24 #include <sys/ioctl.h>
25 #include <pthread.h>
26 
27 #define LOG_TAG "BTIF_SOCK"
28 #include "osi/include/allocator.h"
29 #include "btif_common.h"
30 #include "btif_util.h"
31 
32 #include "bta_api.h"
33 #include "btif_sock_thread.h"
34 #include "btif_sock_sdp.h"
35 #include "btif_sock_util.h"
36 #include "btif_sock_l2cap.h"
37 #include "l2cdefs.h"
38 
39 #include "bt_target.h"
40 #include "gki.h"
41 #include "hcimsgs.h"
42 #include "sdp_api.h"
43 #include "btu.h"
44 #include "btm_api.h"
45 #include "btm_int.h"
46 #include "bta_jv_api.h"
47 #include "bta_jv_co.h"
48 #include "port_api.h"
49 #include "l2c_api.h"
50 
51 #include <cutils/log.h>
52 #include <hardware/bluetooth.h>
53 #define asrt(s) if (!(s)) APPL_TRACE_ERROR("## %s assert %s failed at line:%d ##",__FUNCTION__, \
54         #s, __LINE__)
55 
56 static pthread_mutex_t slot_lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
57 
58 
59 struct packet {
60     struct packet *next, *prev;
61     uint32_t len;
62     uint8_t *data;
63 };
64 
65 typedef struct l2cap_socket {
66 
67     struct l2cap_socket   *prev;                 //link to prev list item
68     struct l2cap_socket   *next;                 //link to next list item
69     bt_bdaddr_t            addr;                 //other side's address
70     char                   name[256];            //user-friendly name of the service
71     uint32_t               id;                   //just a tag to find this struct
72     int                    handle;               //handle from lower layers
73     unsigned               security;             //security flags
74     int                    channel;              //channel (fixed_chan) or PSM (!fixed_chan)
75     int                    our_fd;               //fd from our side
76     int                    app_fd;               //fd from app's side
77 
78     unsigned               bytes_buffered;
79     struct packet         *first_packet;         //fist packet to be delivered to app
80     struct packet         *last_packet;          //last packet to be delivered to app
81 
82     BUFFER_Q               incoming_que;         //data that came in but has not yet been read
83     unsigned               fixed_chan       :1;  //fixed channel (or psm?)
84     unsigned               server           :1;  //is a server? (or connecting?)
85     unsigned               connected        :1;  //is connected?
86     unsigned               outgoing_congest :1;  //should we hold?
87     unsigned               server_psm_sent  :1;  //The server shall only send PSM once.
88 }l2cap_socket;
89 
90 static bt_status_t btSock_start_l2cap_server_l(l2cap_socket *sock);
91 
92 static pthread_mutex_t state_lock;
93 
94 l2cap_socket *socks = NULL;
95 static int pth = -1;
96 
97 static void btsock_l2cap_cbk(tBTA_JV_EVT event, tBTA_JV *p_data, void *user_data);
98 
99 /* TODO: Consider to remove this buffer, as we have a buffer in l2cap as well, and we risk
100  *       a buffer overflow with this implementation if the socket data is not read from
101  *       JAVA for a while. In such a case we should use flow control to tell the sender to
102  *       back off.
103  *       BUT remember we need to avoid blocking the BTA task execution - hence we cannot
104  *       directly write to the socket.
105  *       we should be able to change to store the data pointer here, and just wait
106  *       confirming the l2cap_ind until we have more space in the buffer. */
107 
108 /* returns FALSE if none - caller must free "data" memory when done with it */
packet_get_head_l(l2cap_socket * sock,uint8_t ** data,uint32_t * len)109 static char packet_get_head_l(l2cap_socket *sock, uint8_t **data, uint32_t *len)
110 {
111     struct packet *p = sock->first_packet;
112 
113     if (!p)
114         return FALSE;
115 
116     if (data)
117         *data = sock->first_packet->data;
118     if (len)
119         *len = sock->first_packet->len;
120     sock->first_packet = p->next;
121     if (sock->first_packet)
122         sock->first_packet->prev = NULL;
123     else
124         sock->last_packet = NULL;
125 
126     if(len)
127         sock->bytes_buffered -= *len;
128 
129     osi_free(p);
130 
131     return TRUE;
132 }
133 
packet_alloc(const uint8_t * data,uint32_t len)134 static struct packet *packet_alloc(const uint8_t *data, uint32_t len)
135 {
136     struct packet *p = osi_calloc(sizeof(*p));
137     uint8_t *buf = osi_malloc(len);
138 
139     if (p && buf) {
140 
141         p->data = buf;
142         p->len = len;
143         memcpy(p->data, data, len);
144         return p;
145 
146     } else if (p)
147        osi_free(p);
148     else if (buf)
149        osi_free(buf);
150 
151     return NULL;
152 }
153 
154 /* makes a copy of the data, returns TRUE on success */
packet_put_head_l(l2cap_socket * sock,const void * data,uint32_t len)155 static char packet_put_head_l(l2cap_socket *sock, const void *data, uint32_t len)
156 {
157     struct packet *p = packet_alloc((const uint8_t*)data, len);
158 
159     /*
160      * We do not check size limits here since this is used to undo "getting" a
161      * packet that the user read incompletely. That is to say the packet was
162      * already in the queue. We do check thos elimits in packet_put_tail_l() since
163      * that function is used to put new data into the queue.
164      */
165 
166     if (!p)
167         return FALSE;
168 
169     p->prev = NULL;
170     p->next = sock->first_packet;
171     sock->first_packet = p;
172     if (p->next)
173         p->next->prev = p;
174     else
175         sock->last_packet = p;
176 
177     sock->bytes_buffered += len;
178 
179     return TRUE;
180 }
181 
182 /* makes a copy of the data, returns TRUE on success */
packet_put_tail_l(l2cap_socket * sock,const void * data,uint32_t len)183 static char packet_put_tail_l(l2cap_socket *sock, const void *data, uint32_t len)
184 {
185     struct packet *p = packet_alloc((const uint8_t*)data, len);
186 
187     if (sock->bytes_buffered >= L2CAP_MAX_RX_BUFFER) {
188         ALOGE("packet_put_tail_l: buffer overflow");
189         return FALSE;
190     }
191 
192     if (!p) {
193         ALOGE("packet_put_tail_l: unable to allocate packet...");
194         return FALSE;
195     }
196 
197     p->next = NULL;
198     p->prev = sock->last_packet;
199     sock->last_packet = p;
200     if (p->prev)
201         p->prev->next = p;
202     else
203         sock->first_packet = p;
204 
205     sock->bytes_buffered += len;
206 
207     return TRUE;
208 }
209 
bd_copy(UINT8 * dest,UINT8 * src,BOOLEAN swap)210 static inline void bd_copy(UINT8* dest, UINT8* src, BOOLEAN swap)
211 {
212     if (swap) {
213         int i;
214         for (i =0; i < 6 ;i++)
215             dest[i]= src[5-i];
216     }
217     else memcpy(dest, src, 6);
218 }
219 
is_inited(void)220 static char is_inited(void)
221 {
222     char ret;
223 
224 
225     pthread_mutex_lock(&state_lock);
226     ret = pth != -1;
227     pthread_mutex_unlock(&state_lock);
228 
229     return ret;
230 }
231 
232 /* only call with mutex taken */
btsock_l2cap_find_by_id_l(uint32_t id)233 static l2cap_socket *btsock_l2cap_find_by_id_l(uint32_t id)
234 {
235     l2cap_socket *sock = socks;
236 
237     while (sock && sock->id != id)
238         sock = sock->next;
239 
240     return sock;
241 }
242 
btsock_l2cap_free_l(l2cap_socket * sock)243 static void btsock_l2cap_free_l(l2cap_socket *sock)
244 {
245     uint8_t *buf;
246     l2cap_socket *t = socks;
247 
248     while(t && t != sock)
249         t = t->next;
250 
251     if (!t) /* prever double-frees */
252         return;
253 
254     if (sock->next)
255         sock->next->prev = sock->prev;
256 
257     if (sock->prev)
258         sock->prev->next = sock->next;
259     else
260         socks = sock->next;
261 
262     shutdown(sock->our_fd, SHUT_RDWR);
263     close(sock->our_fd);
264     if (sock->app_fd != -1) {
265         close(sock->app_fd);
266     } else {
267         APPL_TRACE_ERROR("SOCK_LIST: free(id = %d) - NO app_fd!", sock->id);
268     }
269 
270     while (packet_get_head_l(sock, &buf, NULL))
271         osi_free(buf);
272 
273     //lower-level close() should be idempotent... so let's call it and see...
274     // Only call if we are non server connections
275     if (sock->handle && (sock->server == FALSE)) {
276         if (sock->fixed_chan)
277             BTA_JvL2capCloseLE(sock->handle);
278         else
279             BTA_JvL2capClose(sock->handle);
280     }
281     if ((sock->channel >= 0) && (sock->server == TRUE)) {
282         if (sock->fixed_chan) {
283             BTA_JvFreeChannel(sock->channel, BTA_JV_CONN_TYPE_L2CAP_LE);
284         } else {
285             BTA_JvFreeChannel(sock->channel, BTA_JV_CONN_TYPE_L2CAP);
286         }
287     }
288 
289     APPL_TRACE_DEBUG("SOCK_LIST: free(id = %d)", sock->id);
290     osi_free(sock);
291 }
292 
btsock_l2cap_free(l2cap_socket * sock)293 static void btsock_l2cap_free(l2cap_socket *sock)
294 {
295     pthread_mutex_lock(&state_lock);
296     btsock_l2cap_free_l(sock);
297     pthread_mutex_unlock(&state_lock);
298 }
299 
btsock_l2cap_alloc_l(const char * name,const bt_bdaddr_t * addr,char is_server,int flags)300 static l2cap_socket *btsock_l2cap_alloc_l(const char *name, const bt_bdaddr_t *addr,
301         char is_server, int flags)
302 {
303     l2cap_socket *sock;
304     unsigned security = 0;
305     int fds[2];
306 
307     if (flags & BTSOCK_FLAG_ENCRYPT)
308         security |= is_server ? BTM_SEC_IN_ENCRYPT : BTM_SEC_OUT_ENCRYPT;
309     if (flags & BTSOCK_FLAG_AUTH)
310         security |= is_server ? BTM_SEC_IN_AUTHENTICATE : BTM_SEC_OUT_AUTHENTICATE;
311     if (flags & BTSOCK_FLAG_AUTH_MITM)
312         security |= is_server ? BTM_SEC_IN_MITM : BTM_SEC_OUT_MITM;
313     if (flags & BTSOCK_FLAG_AUTH_16_DIGIT)
314         security |= BTM_SEC_IN_MIN_16_DIGIT_PIN;
315 
316     sock = osi_calloc(sizeof(*sock));
317     if (!sock) {
318         APPL_TRACE_ERROR("alloc failed");
319         goto fail_alloc;
320     }
321 
322     if (socketpair(AF_LOCAL, SOCK_SEQPACKET, 0, fds)) {
323         APPL_TRACE_ERROR("socketpair failed, errno:%d", errno);
324         goto fail_sockpair;
325     }
326 
327     sock->our_fd = fds[0];
328     sock->app_fd = fds[1];
329     sock->security = security;
330     sock->server = is_server;
331     sock->connected = FALSE;
332     sock->handle = 0;
333     sock->server_psm_sent = FALSE;
334 
335     if (name)
336         strncpy(sock->name, name, sizeof(sock->name) - 1);
337     if (addr)
338         sock->addr = *addr;
339 
340     sock->first_packet = NULL;
341     sock->last_packet = NULL;
342 
343     sock->next = socks;
344     sock->prev = NULL;
345     if (socks)
346         socks->prev = sock;
347     sock->id = (socks ? socks->id : 0) + 1;
348     socks = sock;
349     /* paranoia cap on: verify no ID duplicates due to overflow and fix as needed */
350     while (1) {
351         l2cap_socket *t;
352         t = socks->next;
353         while (t && t->id != sock->id) {
354             t = t->next;
355         }
356         if (!t && sock->id) /* non-zeor handle is unique -> we're done */
357             break;
358         /* if we're here, we found a duplicate */
359         if (!++sock->id) /* no zero IDs allowed */
360             sock->id++;
361     }
362     APPL_TRACE_DEBUG("SOCK_LIST: alloc(id = %d)", sock->id);
363     return sock;
364 
365 fail_sockpair:
366     osi_free(sock);
367 
368 fail_alloc:
369     return NULL;
370 }
371 
btsock_l2cap_alloc(const char * name,const bt_bdaddr_t * addr,char is_server,int flags)372 static l2cap_socket *btsock_l2cap_alloc(const char *name, const bt_bdaddr_t *addr,
373         char is_server, int flags)
374 {
375     l2cap_socket *ret;
376 
377     pthread_mutex_lock(&state_lock);
378     ret = btsock_l2cap_alloc_l(name, addr, is_server, flags);
379     pthread_mutex_unlock(&state_lock);
380 
381     return ret;
382 }
383 
btsock_l2cap_init(int handle)384 bt_status_t btsock_l2cap_init(int handle)
385 {
386     APPL_TRACE_DEBUG("btsock_l2cap_init...");
387     pthread_mutex_lock(&state_lock);
388     pth = handle;
389     socks = NULL;
390     pthread_mutex_unlock(&state_lock);
391 
392     return BT_STATUS_SUCCESS;
393 }
394 
btsock_l2cap_cleanup()395 bt_status_t btsock_l2cap_cleanup()
396 {
397     pthread_mutex_lock(&state_lock);
398     pth = -1;
399     while (socks)
400         btsock_l2cap_free_l(socks);
401     pthread_mutex_unlock(&state_lock);
402 
403     return BT_STATUS_SUCCESS;
404 }
405 
send_app_psm_or_chan_l(l2cap_socket * sock)406 static inline BOOLEAN send_app_psm_or_chan_l(l2cap_socket *sock)
407 {
408     return sock_send_all(sock->our_fd, (const uint8_t*)&sock->channel, sizeof(sock->channel))
409             == sizeof(sock->channel);
410 }
411 
send_app_connect_signal(int fd,const bt_bdaddr_t * addr,int channel,int status,int send_fd,int tx_mtu)412 static BOOLEAN send_app_connect_signal(int fd, const bt_bdaddr_t* addr,
413         int channel, int status, int send_fd, int tx_mtu)
414 {
415     sock_connect_signal_t cs;
416     cs.size = sizeof(cs);
417     cs.bd_addr = *addr;
418     cs.channel = channel;
419     cs.status = status;
420     cs.max_rx_packet_size = L2CAP_MAX_SDU_LENGTH;
421     cs.max_tx_packet_size = tx_mtu;
422     if (send_fd != -1) {
423         if (sock_send_fd(fd, (const uint8_t*)&cs, sizeof(cs), send_fd) == sizeof(cs))
424             return TRUE;
425         else APPL_TRACE_ERROR("sock_send_fd failed, fd:%d, send_fd:%d", fd, send_fd);
426     } else if (sock_send_all(fd, (const uint8_t*)&cs, sizeof(cs)) == sizeof(cs)) {
427         return TRUE;
428     }
429     return FALSE;
430 }
431 
on_srv_l2cap_listen_started(tBTA_JV_L2CAP_START * p_start,uint32_t id)432 static void on_srv_l2cap_listen_started(tBTA_JV_L2CAP_START *p_start, uint32_t id)
433 {
434     l2cap_socket *sock;
435 
436     pthread_mutex_lock(&state_lock);
437     sock = btsock_l2cap_find_by_id_l(id);
438     if (sock) {
439         if (p_start->status != BTA_JV_SUCCESS) {
440             APPL_TRACE_ERROR("Error starting l2cap_listen - status: 0x%04x", p_start->status);
441             btsock_l2cap_free_l(sock);
442         }
443         else {
444             sock->handle = p_start->handle;
445             APPL_TRACE_DEBUG("on_srv_l2cap_listen_started() sock->handle =%d id:%d",
446                     sock->handle, sock->id);
447             if(sock->server_psm_sent == FALSE) {
448                 if (!send_app_psm_or_chan_l(sock)) {
449                     //closed
450                     APPL_TRACE_DEBUG("send_app_psm() failed, close rs->id:%d", sock->id);
451                     btsock_l2cap_free_l(sock);
452                 } else {
453                     sock->server_psm_sent = TRUE;
454                 }
455             }
456         }
457     }
458     pthread_mutex_unlock(&state_lock);
459 }
460 
on_cl_l2cap_init(tBTA_JV_L2CAP_CL_INIT * p_init,uint32_t id)461 static void on_cl_l2cap_init(tBTA_JV_L2CAP_CL_INIT *p_init, uint32_t id)
462 {
463     l2cap_socket *sock;
464 
465     pthread_mutex_lock(&state_lock);
466     sock = btsock_l2cap_find_by_id_l(id);
467     if (sock) {
468         if (p_init->status != BTA_JV_SUCCESS) {
469             btsock_l2cap_free_l(sock);
470         } else {
471             sock->handle = p_init->handle;
472         }
473     }
474     pthread_mutex_unlock(&state_lock);
475 }
476 
477 /**
478  * Here we allocate a new sock instance to mimic the BluetoothSocket. The socket will be a clone
479  * of the sock representing the BluetoothServerSocket.
480  * */
on_srv_l2cap_psm_connect_l(tBTA_JV_L2CAP_OPEN * p_open,l2cap_socket * sock)481 static void on_srv_l2cap_psm_connect_l(tBTA_JV_L2CAP_OPEN *p_open, l2cap_socket *sock)
482 {
483     l2cap_socket *accept_rs;
484     uint32_t new_listen_id;
485 
486     // Mutex locked by caller
487     accept_rs = btsock_l2cap_alloc_l(sock->name, (const bt_bdaddr_t*)p_open->rem_bda, FALSE, 0);
488     accept_rs->connected = TRUE;
489     accept_rs->security = sock->security;
490     accept_rs->fixed_chan = sock->fixed_chan;
491     accept_rs->channel = sock->channel;
492     accept_rs->handle = sock->handle;
493     sock->handle = -1; /* We should no longer associate this handle with the server socket */
494 
495     /* Swap IDs to hand over the GAP connection to the accepted socket, and start a new server on
496        the newly create socket ID. */
497     new_listen_id = accept_rs->id;
498     accept_rs->id = sock->id;
499     sock->id = new_listen_id;
500 
501     if (accept_rs) {
502         //start monitor the socket
503         btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_EXCEPTION, sock->id);
504         btsock_thread_add_fd(pth, accept_rs->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD,
505                 accept_rs->id);
506         APPL_TRACE_DEBUG("sending connect signal & app fd: %d to app server to accept() the"
507                 " connection", accept_rs->app_fd);
508         APPL_TRACE_DEBUG("server fd:%d, scn:%d", sock->our_fd, sock->channel);
509         send_app_connect_signal(sock->our_fd, &accept_rs->addr, sock->channel, 0,
510                 accept_rs->app_fd, p_open->tx_mtu);
511         accept_rs->app_fd = -1; // The fd is closed after sent to app in send_app_connect_signal()
512                                 // But for some reason we still leak a FD - either the server socket
513                                 // one or the accept socket one.
514         if(btSock_start_l2cap_server_l(sock) != BT_STATUS_SUCCESS) {
515             btsock_l2cap_free_l(sock);
516         }
517     }
518 }
519 
on_srv_l2cap_le_connect_l(tBTA_JV_L2CAP_LE_OPEN * p_open,l2cap_socket * sock)520 static void on_srv_l2cap_le_connect_l(tBTA_JV_L2CAP_LE_OPEN *p_open, l2cap_socket *sock)
521 {
522     l2cap_socket *accept_rs;
523     uint32_t new_listen_id;
524 
525     // mutex locked by caller
526     accept_rs = btsock_l2cap_alloc_l(sock->name, (const bt_bdaddr_t*)p_open->rem_bda, FALSE, 0);
527     if (accept_rs) {
528 
529         //swap IDs
530         new_listen_id = accept_rs->id;
531         accept_rs->id = sock->id;
532         sock->id = new_listen_id;
533 
534         accept_rs->handle = p_open->handle;
535         accept_rs->connected = TRUE;
536         accept_rs->security = sock->security;
537         accept_rs->fixed_chan = sock->fixed_chan;
538         accept_rs->channel = sock->channel;
539 
540         //if we do not set a callback, this socket will be dropped */
541         *(p_open->p_p_cback) = (void*)btsock_l2cap_cbk;
542         *(p_open->p_user_data) = (void*)accept_rs->id;
543 
544         //start monitor the socket
545         btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_EXCEPTION, sock->id);
546         btsock_thread_add_fd(pth, accept_rs->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD,
547                 accept_rs->id);
548         APPL_TRACE_DEBUG("sending connect signal & app fd:%dto app server to accept() the"
549                 " connection", accept_rs->app_fd);
550         APPL_TRACE_DEBUG("server fd:%d, scn:%d", sock->our_fd, sock->channel);
551         send_app_connect_signal(sock->our_fd, &accept_rs->addr, sock->channel, 0,
552                 accept_rs->app_fd, p_open->tx_mtu);
553         accept_rs->app_fd = -1; //the fd is closed after sent to app
554     }
555 }
556 
on_cl_l2cap_psm_connect_l(tBTA_JV_L2CAP_OPEN * p_open,l2cap_socket * sock)557 static void on_cl_l2cap_psm_connect_l(tBTA_JV_L2CAP_OPEN *p_open, l2cap_socket *sock)
558 {
559     bd_copy(sock->addr.address, p_open->rem_bda, 0);
560 
561     if (!send_app_psm_or_chan_l(sock)) {
562         APPL_TRACE_ERROR("send_app_psm_or_chan_l failed");
563         return;
564     }
565 
566     if (send_app_connect_signal(sock->our_fd, &sock->addr, sock->channel, 0, -1, p_open->tx_mtu)) {
567         //start monitoring the socketpair to get call back when app writing data
568         APPL_TRACE_DEBUG("on_l2cap_connect_ind, connect signal sent, slot id:%d, psm:%d,"
569                 " server:%d", sock->id, sock->channel, sock->server);
570         btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD, sock->id);
571         sock->connected = TRUE;
572     }
573     else APPL_TRACE_ERROR("send_app_connect_signal failed");
574 }
575 
on_cl_l2cap_le_connect_l(tBTA_JV_L2CAP_LE_OPEN * p_open,l2cap_socket * sock)576 static void on_cl_l2cap_le_connect_l(tBTA_JV_L2CAP_LE_OPEN *p_open, l2cap_socket *sock)
577 {
578     bd_copy(sock->addr.address, p_open->rem_bda, 0);
579 
580     if (!send_app_psm_or_chan_l(sock)) {
581         APPL_TRACE_ERROR("send_app_psm_or_chan_l failed");
582         return;
583     }
584 
585     if (send_app_connect_signal(sock->our_fd, &sock->addr, sock->channel, 0, -1, p_open->tx_mtu)) {
586         //start monitoring the socketpair to get call back when app writing data
587         APPL_TRACE_DEBUG("on_l2cap_connect_ind, connect signal sent, slot id:%d, Chan:%d,"
588                 " server:%d", sock->id, sock->channel, sock->server);
589         btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD, sock->id);
590         sock->connected = TRUE;
591     }
592     else APPL_TRACE_ERROR("send_app_connect_signal failed");
593 }
594 
on_l2cap_connect(tBTA_JV * p_data,uint32_t id)595 static void on_l2cap_connect(tBTA_JV *p_data, uint32_t id)
596 {
597     l2cap_socket *sock;
598     tBTA_JV_L2CAP_OPEN *psm_open = &p_data->l2c_open;
599     tBTA_JV_L2CAP_LE_OPEN *le_open = &p_data->l2c_le_open;
600 
601     pthread_mutex_lock(&state_lock);
602     sock = btsock_l2cap_find_by_id_l(id);
603     if (!sock) {
604         APPL_TRACE_ERROR("on_l2cap_connect on unknown socket");
605     } else {
606         if (sock->fixed_chan && le_open->status == BTA_JV_SUCCESS) {
607             if (!sock->server)
608                 on_cl_l2cap_le_connect_l(le_open, sock);
609             else
610                 on_srv_l2cap_le_connect_l(le_open, sock);
611         } else if (!sock->fixed_chan && psm_open->status == BTA_JV_SUCCESS) {
612             if (!sock->server)
613                 on_cl_l2cap_psm_connect_l(psm_open, sock);
614             else
615                 on_srv_l2cap_psm_connect_l(psm_open, sock);
616         }
617         else
618             btsock_l2cap_free_l(sock);
619     }
620     pthread_mutex_unlock(&state_lock);
621 }
622 
on_l2cap_close(tBTA_JV_L2CAP_CLOSE * p_close,uint32_t id)623 static void on_l2cap_close(tBTA_JV_L2CAP_CLOSE * p_close, uint32_t id)
624 {
625     l2cap_socket *sock;
626 
627     pthread_mutex_lock(&state_lock);
628     sock = btsock_l2cap_find_by_id_l(id);
629     if (sock) {
630         APPL_TRACE_DEBUG("on_l2cap_close, slot id:%d, fd:%d, %s:%d, server:%d",
631                 sock->id, sock->our_fd, sock->fixed_chan ? "fixed_chan" : "PSM",
632                 sock->channel, sock->server);
633         sock->handle = 0;
634         // TODO: This does not seem to be called...
635         // I'm not sure if this will be called for non-server sockets?
636         if(!sock->fixed_chan && (sock->server == TRUE)) {
637             BTA_JvFreeChannel(sock->channel, BTA_JV_CONN_TYPE_L2CAP);
638         }
639         btsock_l2cap_free_l(sock);
640     }
641     pthread_mutex_unlock(&state_lock);
642 }
643 
on_l2cap_outgoing_congest(tBTA_JV_L2CAP_CONG * p,uint32_t id)644 static void on_l2cap_outgoing_congest(tBTA_JV_L2CAP_CONG *p, uint32_t id)
645 {
646     l2cap_socket *sock;
647 
648     pthread_mutex_lock(&state_lock);
649     sock = btsock_l2cap_find_by_id_l(id);
650     if (sock) {
651         sock->outgoing_congest = p->cong ? 1 : 0;
652         //mointer the fd for any outgoing data
653         if (!sock->outgoing_congest) {
654             APPL_TRACE_DEBUG("on_l2cap_outgoing_congest: adding fd to btsock_thread...");
655             btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD, sock->id);
656 
657         }
658     }
659     pthread_mutex_unlock(&state_lock);
660 }
661 
on_l2cap_write_done(void * req_id,uint32_t id)662 static void on_l2cap_write_done(void* req_id, uint32_t id)
663 {
664     l2cap_socket *sock;
665 
666     if (req_id != NULL) {
667         osi_free(req_id); //free the buffer
668     }
669 
670     pthread_mutex_lock(&state_lock);
671     sock = btsock_l2cap_find_by_id_l(id);
672     if (sock && !sock->outgoing_congest) {
673         //monitor the fd for any outgoing data
674         APPL_TRACE_DEBUG("on_l2cap_write_done: adding fd to btsock_thread...");
675         btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD, sock->id);
676     }
677     pthread_mutex_unlock(&state_lock);
678 }
679 
on_l2cap_write_fixed_done(void * req_id,uint32_t id)680 static void on_l2cap_write_fixed_done(void* req_id, uint32_t id)
681 {
682     l2cap_socket *sock;
683 
684     if (req_id != NULL) {
685         osi_free(req_id); //free the buffer
686     }
687 
688     pthread_mutex_lock(&state_lock);
689     sock = btsock_l2cap_find_by_id_l(id);
690     if (sock && !sock->outgoing_congest) {
691         //monitor the fd for any outgoing data
692         btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD, sock->id);
693     }
694     pthread_mutex_unlock(&state_lock);
695 }
696 
697 
698 
on_l2cap_data_ind(tBTA_JV * evt,uint32_t id)699 static void on_l2cap_data_ind(tBTA_JV *evt, uint32_t id)
700 {
701     l2cap_socket *sock;
702 
703     pthread_mutex_lock(&state_lock);
704     sock = btsock_l2cap_find_by_id_l(id);
705     if (sock) {
706         if (sock->fixed_chan) { /* we do these differently */
707 
708             tBTA_JV_LE_DATA_IND *p_le_data_ind = &evt->le_data_ind;
709             BT_HDR *p_buf = p_le_data_ind->p_buf;
710             uint8_t *data = (uint8_t*)(p_buf + 1) + p_buf->offset;
711 
712             if (packet_put_tail_l(sock, data, p_buf->len))
713                 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_WR, sock->id);
714             else {//connection must be dropped
715                 APPL_TRACE_DEBUG("on_l2cap_data_ind() unable to push data to socket - closing"
716                         " fixed channel");
717                 BTA_JvL2capCloseLE(sock->handle);
718                 btsock_l2cap_free_l(sock);
719             }
720 
721         } else {
722 
723             tBTA_JV_DATA_IND *p_data_ind = &evt->data_ind;
724             UINT8 buffer[L2CAP_MAX_SDU_LENGTH];
725             UINT32  count;
726 
727             if (BTA_JvL2capReady(sock->handle, &count) == BTA_JV_SUCCESS) {
728                 if (BTA_JvL2capRead(sock->handle, sock->id, buffer, count) == BTA_JV_SUCCESS) {
729                     if (packet_put_tail_l(sock, buffer, count))
730                         btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_WR,
731                                 sock->id);
732                     else {//connection must be dropped
733                         APPL_TRACE_DEBUG("on_l2cap_data_ind() unable to push data to socket"
734                                 " - closing channel");
735                         BTA_JvL2capClose(sock->handle);
736                         btsock_l2cap_free_l(sock);
737                     }
738                 }
739             }
740         }
741     }
742     pthread_mutex_unlock(&state_lock);
743 }
744 
btsock_l2cap_cbk(tBTA_JV_EVT event,tBTA_JV * p_data,void * user_data)745 static void btsock_l2cap_cbk(tBTA_JV_EVT event, tBTA_JV *p_data, void *user_data)
746 {
747     int rc;
748 
749     switch (event) {
750     case BTA_JV_L2CAP_START_EVT:
751         on_srv_l2cap_listen_started(&p_data->l2c_start, (uint32_t)user_data);
752         break;
753 
754     case BTA_JV_L2CAP_CL_INIT_EVT:
755         on_cl_l2cap_init(&p_data->l2c_cl_init, (uint32_t)user_data);
756         break;
757 
758     case BTA_JV_L2CAP_OPEN_EVT:
759         on_l2cap_connect(p_data, (uint32_t)user_data);
760         BTA_JvSetPmProfile(p_data->l2c_open.handle,BTA_JV_PM_ID_1,BTA_JV_CONN_OPEN);
761         break;
762 
763     case BTA_JV_L2CAP_CLOSE_EVT:
764         APPL_TRACE_DEBUG("BTA_JV_L2CAP_CLOSE_EVT: user_data:%d", (uint32_t)user_data);
765         on_l2cap_close(&p_data->l2c_close, (uint32_t)user_data);
766         break;
767 
768     case BTA_JV_L2CAP_DATA_IND_EVT:
769         on_l2cap_data_ind(p_data, (uint32_t)user_data);
770         APPL_TRACE_DEBUG("BTA_JV_L2CAP_DATA_IND_EVT");
771         break;
772 
773     case BTA_JV_L2CAP_READ_EVT:
774         APPL_TRACE_DEBUG("BTA_JV_L2CAP_READ_EVT not used");
775         break;
776 
777     case BTA_JV_L2CAP_RECEIVE_EVT:
778         APPL_TRACE_DEBUG("BTA_JV_L2CAP_RECEIVE_EVT not used");
779         break;
780 
781     case BTA_JV_L2CAP_WRITE_EVT:
782         APPL_TRACE_DEBUG("BTA_JV_L2CAP_WRITE_EVT id: %d", (int)user_data);
783         on_l2cap_write_done((void*)p_data->l2c_write.req_id, (uint32_t)user_data);
784         break;
785 
786     case BTA_JV_L2CAP_WRITE_FIXED_EVT:
787         APPL_TRACE_DEBUG("BTA_JV_L2CAP_WRITE_FIXED_EVT id: %d", (int)user_data);
788         on_l2cap_write_fixed_done((void*)p_data->l2c_write_fixed.req_id, (uint32_t)user_data);
789         break;
790 
791     case BTA_JV_L2CAP_CONG_EVT:
792         on_l2cap_outgoing_congest(&p_data->l2c_cong, (uint32_t)user_data);
793         break;
794 
795     default:
796         APPL_TRACE_ERROR("unhandled event %d, slot id:%d", event, (uint32_t)user_data);
797         break;
798     }
799 }
800 
801 /* L2CAP default options for OBEX socket connections */
802 const tL2CAP_FCR_OPTS obex_l2c_fcr_opts_def =
803 {
804     L2CAP_FCR_ERTM_MODE,            /* Mandatory for OBEX over l2cap */
805     OBX_FCR_OPT_TX_WINDOW_SIZE_BR_EDR,/* Tx window size */
806     OBX_FCR_OPT_MAX_TX_B4_DISCNT,   /* Maximum transmissions before disconnecting */
807     OBX_FCR_OPT_RETX_TOUT,          /* Retransmission timeout (2 secs) */
808     OBX_FCR_OPT_MONITOR_TOUT,       /* Monitor timeout (12 secs) */
809     OBX_FCR_OPT_MAX_PDU_SIZE        /* MPS segment size */
810 };
811 const tL2CAP_ERTM_INFO obex_l2c_etm_opt =
812 {
813         L2CAP_FCR_ERTM_MODE,            /* Mandatory for OBEX over l2cap */
814         L2CAP_FCR_CHAN_OPT_ERTM,        /* Mandatory for OBEX over l2cap */
815         OBX_USER_RX_POOL_ID,
816         OBX_USER_TX_POOL_ID,
817         OBX_FCR_RX_POOL_ID,
818         OBX_FCR_TX_POOL_ID
819 };
820 
821 /**
822  * When using a dynamic PSM, a PSM allocation is requested from btsock_l2cap_listen_or_connect().
823  * The PSM allocation event is refeived in the JV-callback - currently located in RFC-code -
824  * and this function is called with the newly allocated PSM.
825  */
on_l2cap_psm_assigned(int id,int psm)826 void on_l2cap_psm_assigned(int id, int psm) {
827     l2cap_socket *sock;
828     /* Setup ETM settings:
829      *  mtu will be set below */
830     pthread_mutex_lock(&state_lock);
831     sock = btsock_l2cap_find_by_id_l(id);
832     sock->channel = psm;
833 
834     if(btSock_start_l2cap_server_l(sock) != BT_STATUS_SUCCESS) {
835         btsock_l2cap_free_l(sock);
836     }
837 
838     pthread_mutex_unlock(&state_lock);
839 
840 }
841 
btSock_start_l2cap_server_l(l2cap_socket * sock)842 static bt_status_t btSock_start_l2cap_server_l(l2cap_socket *sock) {
843     tL2CAP_CFG_INFO cfg;
844     bt_status_t stat = BT_STATUS_SUCCESS;
845     /* Setup ETM settings:
846      *  mtu will be set below */
847     memset(&cfg, 0, sizeof(tL2CAP_CFG_INFO));
848 
849     cfg.fcr_present = TRUE;
850     cfg.fcr = obex_l2c_fcr_opts_def;
851 
852     if (sock->fixed_chan) {
853 
854         if (BTA_JvL2capStartServerLE(sock->security, 0, NULL, sock->channel,
855                 L2CAP_DEFAULT_MTU, NULL, btsock_l2cap_cbk, (void*)sock->id)
856                 != BTA_JV_SUCCESS)
857             stat = BT_STATUS_FAIL;
858 
859     } else {
860         /* If we have a channel specified in the request, just start the server,
861          * else we request a PSM and start the server after we receive a PSM. */
862         if(sock->channel < 0) {
863             if(BTA_JvGetChannelId(BTA_JV_CONN_TYPE_L2CAP, (void*)sock->id, 0)
864                     != BTA_JV_SUCCESS)
865                 stat = BT_STATUS_FAIL;
866         } else {
867             if (BTA_JvL2capStartServer(sock->security, 0, &obex_l2c_etm_opt,
868                     sock->channel, L2CAP_MAX_SDU_LENGTH, &cfg, btsock_l2cap_cbk, (void*)sock->id)
869                     != BTA_JV_SUCCESS)
870                 stat = BT_STATUS_FAIL;
871         }
872     }
873     return stat;
874 }
875 
btsock_l2cap_listen_or_connect(const char * name,const bt_bdaddr_t * addr,int channel,int * sock_fd,int flags,char listen)876 static bt_status_t btsock_l2cap_listen_or_connect(const char *name, const bt_bdaddr_t *addr,
877         int channel, int* sock_fd, int flags, char listen)
878 {
879     bt_status_t stat;
880     int fixed_chan = 1;
881     l2cap_socket *sock;
882     tL2CAP_CFG_INFO cfg;
883 
884     if (!sock_fd)
885         return BT_STATUS_PARM_INVALID;
886 
887     if(channel < 0) {
888         // We need to auto assign a PSM
889         fixed_chan = 0;
890     } else {
891         fixed_chan = (channel & L2CAP_MASK_FIXED_CHANNEL) != 0;
892         channel &=~ L2CAP_MASK_FIXED_CHANNEL;
893     }
894 
895     if (!is_inited())
896         return BT_STATUS_NOT_READY;
897 
898     // TODO: This is kind of bad to lock here, but it is needed for the current design.
899     pthread_mutex_lock(&state_lock);
900 
901     sock = btsock_l2cap_alloc_l(name, addr, listen, flags);
902     if (!sock)
903         return BT_STATUS_NOMEM;
904 
905     sock->fixed_chan = fixed_chan;
906     sock->channel = channel;
907 
908     stat = BT_STATUS_SUCCESS;
909 
910     /* Setup ETM settings:
911      *  mtu will be set below */
912     memset(&cfg, 0, sizeof(tL2CAP_CFG_INFO));
913 
914     cfg.fcr_present = TRUE;
915     cfg.fcr = obex_l2c_fcr_opts_def;
916 
917     /* "role" is never initialized in rfcomm code */
918     if (listen) {
919         stat = btSock_start_l2cap_server_l(sock);
920     } else {
921         if (fixed_chan) {
922             if (BTA_JvL2capConnectLE(sock->security, 0, NULL, channel,
923                     L2CAP_DEFAULT_MTU, NULL, sock->addr.address, btsock_l2cap_cbk,
924                     (void*)sock->id) != BTA_JV_SUCCESS)
925                 stat = BT_STATUS_FAIL;
926 
927         } else {
928             if (BTA_JvL2capConnect(sock->security, 0, &obex_l2c_etm_opt,
929                     channel, L2CAP_MAX_SDU_LENGTH, &cfg, sock->addr.address,
930                     btsock_l2cap_cbk, (void*)sock->id) != BTA_JV_SUCCESS)
931                 stat = BT_STATUS_FAIL;
932         }
933     }
934 
935     if (stat == BT_STATUS_SUCCESS) {
936         *sock_fd = sock->app_fd;
937         /* We pass the FD to JAVA, but since it runs in another process, we need to also close
938          * it in native, either straight away, as done when accepting an incoming connection,
939          * or when doing cleanup after this socket */
940         sock->app_fd = -1;  /*This leaks the file descriptor. The FD should be closed in
941                               JAVA but it apparently do not work */
942         btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_EXCEPTION,
943                 sock->id);
944     } else {
945        btsock_l2cap_free_l(sock);
946     }
947     pthread_mutex_unlock(&state_lock);
948 
949     return stat;
950 }
951 
btsock_l2cap_listen(const char * name,int channel,int * sock_fd,int flags)952 bt_status_t btsock_l2cap_listen(const char* name, int channel, int* sock_fd, int flags)
953 {
954     return btsock_l2cap_listen_or_connect(name, NULL, channel, sock_fd, flags, 1);
955 }
956 
btsock_l2cap_connect(const bt_bdaddr_t * bd_addr,int channel,int * sock_fd,int flags)957 bt_status_t btsock_l2cap_connect(const bt_bdaddr_t *bd_addr, int channel, int* sock_fd, int flags)
958 {
959     return btsock_l2cap_listen_or_connect(NULL, bd_addr, channel, sock_fd, flags, 0);
960 }
961 
962 /* return TRUE if we have more to send and should wait for user readiness, FALSE else
963  * (for example: unrecoverable error or no data)
964  */
flush_incoming_que_on_wr_signal_l(l2cap_socket * sock)965 static BOOLEAN flush_incoming_que_on_wr_signal_l(l2cap_socket *sock)
966 {
967     uint8_t *buf;
968     uint32_t len;
969 
970     while (packet_get_head_l(sock, &buf, &len)) {
971         int sent = TEMP_FAILURE_RETRY(send(sock->our_fd, buf, len, MSG_DONTWAIT));
972 
973         if (sent == (signed)len)
974             osi_free(buf);
975         else if (sent >= 0) {
976             packet_put_head_l(sock, buf + sent, len - sent);
977             osi_free(buf);
978             if (!sent) /* special case if other end not keeping up */
979                 return TRUE;
980         }
981         else {
982             packet_put_head_l(sock, buf, len);
983             osi_free(buf);
984             return errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN;
985         }
986     }
987 
988     return FALSE;
989 }
990 
btsock_l2cap_signaled(int fd,int flags,uint32_t user_id)991 void btsock_l2cap_signaled(int fd, int flags, uint32_t user_id)
992 {
993     l2cap_socket *sock;
994     char drop_it = FALSE;
995 
996     /* We use MSG_DONTWAIT when sending data to JAVA, hence it can be accepted to hold the lock. */
997     pthread_mutex_lock(&state_lock);
998     sock = btsock_l2cap_find_by_id_l(user_id);
999     if (sock) {
1000         if ((flags & SOCK_THREAD_FD_RD) && !sock->server) {
1001             //app sending data
1002             if (sock->connected) {
1003                 int size = 0;
1004 
1005                 if (!(flags & SOCK_THREAD_FD_EXCEPTION) || (TEMP_FAILURE_RETRY(ioctl(sock->our_fd, FIONREAD, &size))
1006                         == 0 && size)) {
1007                     uint8_t *buffer = osi_malloc(L2CAP_MAX_SDU_LENGTH);
1008                     //uint8_t *buffer = (uint8_t*)GKI_getbuf(L2CAP_MAX_SDU_LENGTH);
1009                     /* Apparently we hijack the req_id (UINT32) to pass the pointer to the buffer to
1010                      * the write complete callback, which call a free... wonder if this works on a
1011                      * 64 bit platform? */
1012                     if (buffer != NULL) {
1013                         /* The socket is created with SOCK_SEQPACKET, hence we read one message at
1014                          * the time. The maximum size of a message is allocated to ensure data is
1015                          * not lost. This is okay to do as Android uses virtual memory, hence even
1016                          * if we only use a fraction of the memory it should not block for others
1017                          * to use the memory. As the definition of ioctl(FIONREAD) do not clearly
1018                          * define what value will be returned if multiple messages are written to
1019                          * the socket before any message is read from the socket, we could
1020                          * potentially risk to allocate way more memory than needed. One of the use
1021                          * cases for this socket is obex where multiple 64kbyte messages are
1022                          * typically written to the socket in a tight loop, hence we risk the ioctl
1023                          * will return the total amount of data in the buffer, which could be
1024                          * multiple 64kbyte chunks.
1025                          * UPDATE: As bluedroid cannot handle 64kbyte buffers, the size is reduced
1026                          * to around 8kbyte - and using malloc for buffer allocation here seems to
1027                          * be wrong
1028                          * UPDATE: Since we are responsible for freeing the buffer in the
1029                          * write_complete_ind, it is OK to use malloc. */
1030 
1031                         int count = TEMP_FAILURE_RETRY(recv(fd, buffer, L2CAP_MAX_SDU_LENGTH,
1032                                 MSG_NOSIGNAL | MSG_DONTWAIT));
1033                         APPL_TRACE_DEBUG("btsock_l2cap_signaled - %d bytes received from socket",
1034                                 count);
1035                         if (sock->fixed_chan) {
1036                             if(BTA_JvL2capWriteFixed(sock->channel, (BD_ADDR*)&sock->addr,
1037                                     (UINT32)buffer, btsock_l2cap_cbk, buffer, count,
1038                                     (void *)user_id) != BTA_JV_SUCCESS) {
1039                                 // On fail, free the buffer
1040                                 on_l2cap_write_fixed_done(buffer, user_id);
1041                             }
1042                         } else {
1043                             if(BTA_JvL2capWrite(sock->handle, (UINT32)buffer, buffer, count,
1044                                     (void *)user_id) != BTA_JV_SUCCESS) {
1045                                 // On fail, free the buffer
1046                                 on_l2cap_write_done(buffer, user_id);
1047                             }
1048                         }
1049                     } else {
1050                         // This cannot happen.
1051                         APPL_TRACE_ERROR("Unable to allocate memory for data packet from JAVA...")
1052                     }
1053                 }
1054             } else
1055                 drop_it = TRUE;
1056         }
1057         if (flags & SOCK_THREAD_FD_WR) {
1058             //app is ready to receive more data, tell stack to enable the data flow
1059             if (flush_incoming_que_on_wr_signal_l(sock) && sock->connected)
1060                 btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_WR, sock->id);
1061         }
1062         if (drop_it || (flags & SOCK_THREAD_FD_EXCEPTION)) {
1063             int size = 0;
1064             if (drop_it || TEMP_FAILURE_RETRY(ioctl(sock->our_fd, FIONREAD, &size)) != 0 || size == 0)
1065                 btsock_l2cap_free_l(sock);
1066         }
1067     }
1068     pthread_mutex_unlock(&state_lock);
1069 }
1070 
1071 
1072 
1073