OSDN Git Service

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