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