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