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