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