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