OSDN Git Service

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