1 /******************************************************************************
2  *
3  *  Copyright 1999-2012 Broadcom Corporation
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 
19 /******************************************************************************
20  *
21  *  this file contains the Serial Port API code
22  *
23  ******************************************************************************/
24 
25 #define LOG_TAG "bt_port_api"
26 
27 #include "stack/include/port_api.h"
28 
29 #include <base/strings/stringprintf.h>
30 #include <bluetooth/log.h>
31 
32 #include <cstdint>
33 
34 #include "internal_include/bt_target.h"
35 #include "internal_include/bt_trace.h"
36 #include "os/logging/log_adapter.h"
37 #include "osi/include/allocator.h"
38 #include "osi/include/mutex.h"
39 #include "stack/include/bt_hdr.h"
40 #include "stack/include/bt_types.h"
41 #include "stack/include/bt_uuid16.h"
42 #include "stack/include/btm_log_history.h"
43 #include "stack/rfcomm/rfc_int.h"
44 #include "types/raw_address.h"
45 
46 using namespace bluetooth;
47 
48 /* Mapping from PORT_* result codes to human readable strings. */
49 static const char* result_code_strings[] = {"Success",
50                                             "Unknown error",
51                                             "Already opened",
52                                             "Command pending",
53                                             "App not registered",
54                                             "No memory",
55                                             "No resources",
56                                             "Bad BD address",
57                                             "Unspecified error",
58                                             "Bad handle",
59                                             "Not opened",
60                                             "Line error",
61                                             "Start failed",
62                                             "Parameter negotiation failed",
63                                             "Port negotiation failed",
64                                             "Sec failed",
65                                             "Peer connection failed",
66                                             "Peer failed",
67                                             "Peer timeout",
68                                             "Closed",
69                                             "TX full",
70                                             "Local closed",
71                                             "Local timeout",
72                                             "TX queue disabled",
73                                             "Page timeout",
74                                             "Invalid SCN",
75                                             "Unknown result code"};
76 
77 namespace {
78 const char kBtmLogTag[] = "RFCOMM";
79 }  // namespace
80 
81 /*******************************************************************************
82  *
83  * Function         RFCOMM_CreateConnectionWithSecurity
84  *
85  * Description      RFCOMM_CreateConnectionWithSecurity function is used from
86  *the application to establish serial port connection to the peer device, or
87  *allow RFCOMM to accept a connection from the peer application.
88  *
89  * Parameters:      scn          - Service Channel Number as registered with
90  *                                 the SDP (server) or obtained using SDP from
91  *                                 the peer device (client).
92  *                  is_server    - true if requesting application is a server
93  *                  mtu          - Maximum frame size the application can accept
94  *                  bd_addr      - address of the peer (client)
95  *                  p_handle     - OUT pointer to the handle.
96  *                  p_mgmt_callback - pointer to callback function to receive
97  *                                 connection up/down events.
98  *                  sec_mask     - bitmask of BTM_SEC_* values indicating the
99  *                                 minimum security requirements for this
100  *connection Notes:
101  *
102  * Server can call this function with the same scn parameter multiple times if
103  * it is ready to accept multiple simulteneous connections.
104  *
105  * DLCI for the connection is (scn * 2 + 1) if client originates connection on
106  * existing none initiator multiplexer channel.  Otherwise it is (scn * 2).
107  * For the server DLCI can be changed later if client will be calling it using
108  * (scn * 2 + 1) dlci.
109  *
110  ******************************************************************************/
RFCOMM_CreateConnectionWithSecurity(uint16_t uuid,uint8_t scn,bool is_server,uint16_t mtu,const RawAddress & bd_addr,uint16_t * p_handle,tPORT_MGMT_CALLBACK * p_mgmt_callback,uint16_t sec_mask)111 int RFCOMM_CreateConnectionWithSecurity(uint16_t uuid, uint8_t scn,
112                                         bool is_server, uint16_t mtu,
113                                         const RawAddress& bd_addr,
114                                         uint16_t* p_handle,
115                                         tPORT_MGMT_CALLBACK* p_mgmt_callback,
116                                         uint16_t sec_mask) {
117   *p_handle = 0;
118 
119   if ((scn == 0) || (scn > RFCOMM_MAX_SCN)) {
120     // Server Channel Number (SCN) should be in range [1, 30]
121     log::error(
122         "Invalid SCN, bd_addr={}, scn={}, is_server={}, mtu={}, uuid=0x{:x}",
123         bd_addr, static_cast<int>(scn), is_server, static_cast<int>(mtu), uuid);
124     return (PORT_INVALID_SCN);
125   }
126 
127   // For client that originates connection on the existing none initiator
128   // multiplexer channel, DLCI should be odd.
129   uint8_t dlci;
130   tRFC_MCB* p_mcb = port_find_mcb(bd_addr);
131   if (p_mcb && !p_mcb->is_initiator && !is_server) {
132     dlci = static_cast<uint8_t>((scn << 1) + 1);
133   } else {
134     dlci = (scn << 1);
135   }
136 
137   // On the client side, do not allow the same (dlci, bd_addr) to be opened
138   // twice by application
139   tPORT* p_port{nullptr};
140   if (!is_server) {
141     p_port = port_find_port(dlci, bd_addr);
142     if (p_port != nullptr) {
143       // if existing port is also a client port, error out
144       if (!p_port->is_server) {
145         log::error(
146             "already at opened state {}, RFC_state={}, MCB_state={}, "
147             "bd_addr={}, scn={}, is_server={}, mtu={}, uuid=0x{:x}, dlci={}, "
148             "p_mcb={}, port={}",
149             static_cast<int>(p_port->state),
150             static_cast<int>(p_port->rfc.state),
151             p_port->rfc.p_mcb ? p_port->rfc.p_mcb->state : 0, bd_addr, scn,
152             is_server, mtu, uuid, dlci, fmt::ptr(p_mcb), p_port->handle);
153         *p_handle = p_port->handle;
154         return (PORT_ALREADY_OPENED);
155       }
156     }
157   }
158 
159   // On the server side, always allocate a new port.
160   p_port = port_allocate_port(dlci, bd_addr);
161   if (p_port == nullptr) {
162     log::error(
163         "no resources, bd_addr={}, scn={}, is_server={}, mtu={}, uuid=0x{:x}, "
164         "dlci={}",
165         bd_addr, scn, is_server, mtu, uuid, dlci);
166     return PORT_NO_RESOURCES;
167   }
168   p_port->sec_mask = sec_mask;
169   *p_handle = p_port->handle;
170 
171   // Get default signal state
172   switch (uuid) {
173     case UUID_PROTOCOL_OBEX:
174       p_port->default_signal_state = PORT_OBEX_DEFAULT_SIGNAL_STATE;
175       break;
176     case UUID_SERVCLASS_SERIAL_PORT:
177       p_port->default_signal_state = PORT_SPP_DEFAULT_SIGNAL_STATE;
178       break;
179     case UUID_SERVCLASS_LAN_ACCESS_USING_PPP:
180       p_port->default_signal_state = PORT_PPP_DEFAULT_SIGNAL_STATE;
181       break;
182     case UUID_SERVCLASS_DIALUP_NETWORKING:
183     case UUID_SERVCLASS_FAX:
184       p_port->default_signal_state = PORT_DUN_DEFAULT_SIGNAL_STATE;
185       break;
186     default:
187       p_port->default_signal_state =
188           (PORT_DTRDSR_ON | PORT_CTSRTS_ON | PORT_DCD_ON);
189       break;
190   }
191 
192   // Assign port specific values
193   p_port->state = PORT_CONNECTION_STATE_OPENING;
194   p_port->uuid = uuid;
195   p_port->is_server = is_server;
196   p_port->scn = scn;
197   p_port->ev_mask = 0;
198 
199   // Find MTU
200   // If the MTU is not specified (0), keep MTU decision until the PN frame has
201   // to be send at that time connection should be established and we will know
202   // for sure our prefered MTU
203   uint16_t rfcomm_mtu = L2CAP_MTU_SIZE - RFCOMM_DATA_OVERHEAD;
204   if (mtu) {
205     p_port->mtu = (mtu < rfcomm_mtu) ? mtu : rfcomm_mtu;
206   } else {
207     p_port->mtu = rfcomm_mtu;
208   }
209 
210   // Other states
211   // server doesn't need to release port when closing
212   if (is_server) {
213     p_port->keep_port_handle = true;
214     // keep mtu that user asked, p_port->mtu could be updated during param
215     // negotiation
216     p_port->keep_mtu = p_port->mtu;
217   }
218   p_port->local_ctrl.modem_signal = p_port->default_signal_state;
219   p_port->local_ctrl.fc = false;
220   p_port->p_mgmt_callback = p_mgmt_callback;
221   p_port->bd_addr = bd_addr;
222 
223   log::info(
224       "bd_addr={}, scn={}, is_server={}, mtu={}, uuid=0x{:x}, dlci={}, "
225       "signal_state=0x{:x}, p_port={}",
226       bd_addr, scn, is_server, mtu, uuid, dlci, p_port->default_signal_state,
227       fmt::ptr(p_port));
228 
229   // If this is not initiator of the connection need to just wait
230   if (p_port->is_server) {
231     BTM_LogHistory(kBtmLogTag, bd_addr, "Server started",
232                    base::StringPrintf("handle:%hu scn:%hhu dlci:%hhu mtu:%hu",
233                                       *p_handle, scn, dlci, mtu));
234     return (PORT_SUCCESS);
235   }
236 
237   BTM_LogHistory(kBtmLogTag, bd_addr, "Connection opened",
238                  base::StringPrintf("handle:%hu scn:%hhu dlci:%hhu mtu:%hu",
239                                     *p_handle, scn, dlci, mtu));
240 
241   // Open will be continued after security checks are passed
242   return port_open_continue(p_port);
243 }
244 
245 /*******************************************************************************
246  *
247  * Function         RFCOMM_ControlReqFromBTSOCK
248  *
249  * Description      Send control parameters to the peer.
250  *                  So far only for qualification use.
251  *                  RFCOMM layer starts the control request only when it is the
252  *                  client. This API allows the host to start the control
253  *                  request while it works as a RFCOMM server.
254  *
255  * Parameters:      dlci             - the DLCI to send the MSC command
256  *                  bd_addr          - bd_addr of the peer
257  *                  modem_signal     - [DTR/DSR | RTS/CTS | RI | DCD]
258  *                  break_signal     - 0-3 s in steps of 200 ms
259  *                  discard_buffers  - 0 for do not discard, 1 for discard
260  *                  break_signal_seq - ASAP or in sequence
261  *                  fc               - true when the device is unable to accept
262  *                                     frames
263  *
264  ******************************************************************************/
RFCOMM_ControlReqFromBTSOCK(uint8_t dlci,const RawAddress & bd_addr,uint8_t modem_signal,uint8_t break_signal,uint8_t discard_buffers,uint8_t break_signal_seq,bool fc)265 int RFCOMM_ControlReqFromBTSOCK(uint8_t dlci, const RawAddress& bd_addr,
266                                 uint8_t modem_signal, uint8_t break_signal,
267                                 uint8_t discard_buffers,
268                                 uint8_t break_signal_seq, bool fc) {
269   tRFC_MCB* p_mcb = port_find_mcb(bd_addr);
270   if (!p_mcb) {
271     return PORT_BAD_BD_ADDR;
272   }
273   tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci);
274   if (!p_port) {
275     return PORT_NOT_OPENED;
276   }
277   p_port->local_ctrl.modem_signal = modem_signal;
278   p_port->local_ctrl.break_signal = break_signal;
279   p_port->local_ctrl.discard_buffers = discard_buffers;
280   p_port->local_ctrl.break_signal_seq = break_signal_seq;
281   p_port->local_ctrl.fc = fc;
282   RFCOMM_ControlReq(p_mcb, dlci, &p_port->local_ctrl);
283   return PORT_SUCCESS;
284 }
285 
get_port_from_handle(uint16_t handle)286 static tPORT* get_port_from_handle(uint16_t handle) {
287   /* Check if handle is valid to avoid crashing */
288   if ((handle == 0) || (handle > MAX_RFC_PORTS)) {
289     return nullptr;
290   }
291   return &rfc_cb.port.port[handle - 1];
292 }
293 
294 /*******************************************************************************
295  *
296  * Function         RFCOMM_RemoveConnection
297  *
298  * Description      This function is called to close the specified connection.
299  *
300  * Parameters:      handle     - Handle returned in the RFCOMM_CreateConnection
301  *
302  ******************************************************************************/
RFCOMM_RemoveConnection(uint16_t handle)303 int RFCOMM_RemoveConnection(uint16_t handle) {
304   log::verbose("RFCOMM_RemoveConnection() handle:{}", handle);
305 
306   tPORT* p_port = get_port_from_handle(handle);
307   if (p_port == nullptr) {
308     log::error("Unable to get RFCOMM port control block bad handle:{}", handle);
309     return (PORT_BAD_HANDLE);
310   }
311 
312   if (!p_port->in_use || (p_port->state == PORT_CONNECTION_STATE_CLOSED)) {
313     log::verbose("RFCOMM_RemoveConnection() Not opened:{}", handle);
314     return (PORT_SUCCESS);
315   }
316 
317   const RawAddress bd_addr =
318       (p_port->rfc.p_mcb) ? (p_port->rfc.p_mcb->bd_addr) : (RawAddress::kEmpty);
319   BTM_LogHistory(
320       kBtmLogTag, bd_addr, "Connection closed",
321       base::StringPrintf("handle:%hu scn:%hhu dlci:%hhu is_server:%s", handle,
322                          p_port->scn, p_port->dlci,
323                          p_port->is_server ? "true" : "false"));
324 
325   p_port->state = PORT_CONNECTION_STATE_CLOSING;
326 
327   port_start_close(p_port);
328 
329   return (PORT_SUCCESS);
330 }
331 
332 /*******************************************************************************
333  *
334  * Function         RFCOMM_RemoveServer
335  *
336  * Description      This function is called to close the server port.
337  *
338  * Parameters:      handle     - Handle returned in the RFCOMM_CreateConnection
339  *
340  ******************************************************************************/
RFCOMM_RemoveServer(uint16_t handle)341 int RFCOMM_RemoveServer(uint16_t handle) {
342   tPORT* p_port = get_port_from_handle(handle);
343   if (p_port == nullptr) {
344     log::error("Unable to get RFCOMM port control block bad handle:{}", handle);
345     return (PORT_BAD_HANDLE);
346   }
347 
348   /* Do not report any events to the client any more. */
349   p_port->p_mgmt_callback = nullptr;
350 
351   if (!p_port->in_use || (p_port->state == PORT_CONNECTION_STATE_CLOSED)) {
352     log::debug("handle {} not opened", handle);
353     return (PORT_SUCCESS);
354   }
355   log::info("handle={}", handle);
356 
357   const RawAddress bd_addr =
358       (p_port->rfc.p_mcb) ? (p_port->rfc.p_mcb->bd_addr) : (RawAddress::kEmpty);
359   BTM_LogHistory(
360       kBtmLogTag, bd_addr, "Server stopped",
361       base::StringPrintf("handle:%hu scn:%hhu dlci:%hhu is_server:%s", handle,
362                          p_port->scn, p_port->dlci,
363                          p_port->is_server ? "true" : "false"));
364 
365   /* this port will be deallocated after closing */
366   p_port->keep_port_handle = false;
367   p_port->state = PORT_CONNECTION_STATE_CLOSING;
368 
369   port_start_close(p_port);
370 
371   return (PORT_SUCCESS);
372 }
373 
PORT_SetEventMaskAndCallback(uint16_t handle,uint32_t mask,tPORT_CALLBACK * p_port_cb)374 int PORT_SetEventMaskAndCallback(uint16_t handle, uint32_t mask,
375                                  tPORT_CALLBACK* p_port_cb) {
376   log::verbose("PORT_SetEventMask() handle:{} mask:0x{:x}", handle, mask);
377   tPORT* p_port = get_port_from_handle(handle);
378   if (p_port == nullptr) {
379     log::error("Unable to get RFCOMM port control block bad handle:{}", handle);
380     return (PORT_BAD_HANDLE);
381   }
382 
383   if (!p_port->in_use || (p_port->state == PORT_CONNECTION_STATE_CLOSED)) {
384     return (PORT_NOT_OPENED);
385   }
386 
387   p_port->ev_mask = mask;
388   p_port->p_callback = p_port_cb;
389 
390   return (PORT_SUCCESS);
391 }
392 
393 /*******************************************************************************
394  *
395  * Function         PORT_ClearKeepHandleFlag
396  *
397  * Description      Clear the keep handle flag, which will cause not to keep the
398  *                  port handle open when closed
399  * Parameters:      handle     - Handle returned in the RFCOMM_CreateConnection
400  *
401  ******************************************************************************/
402 
PORT_ClearKeepHandleFlag(uint16_t handle)403 int PORT_ClearKeepHandleFlag(uint16_t handle) {
404   tPORT* p_port = get_port_from_handle(handle);
405   if (p_port == nullptr) {
406     log::error("Unable to get RFCOMM port control block bad handle:{}", handle);
407     return (PORT_BAD_HANDLE);
408   }
409   p_port->keep_port_handle = 0;
410   return (PORT_SUCCESS);
411 }
412 
413 /*******************************************************************************
414  *
415  * Function         PORT_SetCODataCallback
416  *
417  * Description      This function is when a data packet is received
418  *
419  * Parameters:      handle     - Handle returned in the RFCOMM_CreateConnection
420  *                  p_callback - address of the callback function which should
421  *                               be called from the RFCOMM when data packet
422  *                               is received.
423  *
424  *
425  ******************************************************************************/
PORT_SetDataCOCallback(uint16_t handle,tPORT_DATA_CO_CALLBACK * p_port_cb)426 int PORT_SetDataCOCallback(uint16_t handle, tPORT_DATA_CO_CALLBACK* p_port_cb) {
427   log::verbose("PORT_SetDataCOCallback() handle:{} cb 0x{}", handle,
428                fmt::ptr(p_port_cb));
429 
430   tPORT* p_port = get_port_from_handle(handle);
431   if (p_port == nullptr) {
432     log::error("Unable to get RFCOMM port control block bad handle:{}", handle);
433     return (PORT_BAD_HANDLE);
434   }
435   if (!p_port->in_use || (p_port->state == PORT_CONNECTION_STATE_CLOSED)) {
436     return (PORT_NOT_OPENED);
437   }
438 
439   p_port->p_data_co_callback = p_port_cb;
440 
441   return (PORT_SUCCESS);
442 }
443 
444 /*******************************************************************************
445  *
446  * Function         PORT_CheckConnection
447  *
448  * Description      This function returns PORT_SUCCESS if connection referenced
449  *                  by handle is up and running
450  *
451  * Parameters:      handle     - Handle returned in the RFCOMM_CreateConnection
452  *                  bd_addr    - OUT bd_addr of the peer
453  *                  p_lcid     - OUT L2CAP's LCID
454  *
455  ******************************************************************************/
PORT_CheckConnection(uint16_t handle,RawAddress * bd_addr,uint16_t * p_lcid)456 int PORT_CheckConnection(uint16_t handle, RawAddress* bd_addr,
457                          uint16_t* p_lcid) {
458   tPORT* p_port = get_port_from_handle(handle);
459   if (p_port == nullptr) {
460     log::error("Unable to get RFCOMM port control block bad handle:{}", handle);
461     return (PORT_BAD_HANDLE);
462   }
463   log::verbose(
464       "handle={}, in_use={}, port_state={}, p_mcb={}, peer_ready={}, "
465       "rfc_state={}",
466       handle, p_port->in_use, p_port->state, fmt::ptr(p_port->rfc.p_mcb),
467       p_port->rfc.p_mcb ? p_port->rfc.p_mcb->peer_ready : -1,
468       p_port->rfc.state);
469 
470   if (!p_port->in_use || (p_port->state == PORT_CONNECTION_STATE_CLOSED)) {
471     return (PORT_NOT_OPENED);
472   }
473 
474   if (!p_port->rfc.p_mcb || !p_port->rfc.p_mcb->peer_ready ||
475       (p_port->rfc.state != RFC_STATE_OPENED)) {
476     return (PORT_LINE_ERR);
477   }
478 
479   *bd_addr = p_port->rfc.p_mcb->bd_addr;
480   if (p_lcid) *p_lcid = p_port->rfc.p_mcb->lcid;
481 
482   return (PORT_SUCCESS);
483 }
484 
485 /*******************************************************************************
486  *
487  * Function         PORT_IsOpening
488  *
489  * Description      This function returns true if there is any RFCOMM connection
490  *                  opening in process.
491  *
492  * Parameters:      true if any connection opening is found
493  *                  bd_addr    - bd_addr of the peer
494  *
495  ******************************************************************************/
PORT_IsOpening(RawAddress * bd_addr)496 bool PORT_IsOpening(RawAddress* bd_addr) {
497   /* Check for any rfc_mcb which is in the middle of opening. */
498   for (auto& multiplexer_cb : rfc_cb.port.rfc_mcb) {
499     if ((multiplexer_cb.state > RFC_MX_STATE_IDLE) &&
500         (multiplexer_cb.state < RFC_MX_STATE_CONNECTED)) {
501       *bd_addr = multiplexer_cb.bd_addr;
502       log::info(
503           "Found a rfc_mcb in the middle of opening a port, returning true");
504       return true;
505     }
506 
507     if (multiplexer_cb.state == RFC_MX_STATE_CONNECTED) {
508       tPORT* p_port = nullptr;
509 
510       for (tPORT& port : rfc_cb.port.port) {
511         if (port.rfc.p_mcb == &multiplexer_cb) {
512           p_port = &port;
513           break;
514         }
515       }
516 
517       log::info("RFC_MX_STATE_CONNECTED, found_port={}, tRFC_PORT_STATE={}",
518                 (p_port != nullptr) ? "T" : "F",
519                 (p_port != nullptr) ? p_port->rfc.state : 0);
520       if ((p_port == nullptr) || (p_port->rfc.state < RFC_STATE_OPENED)) {
521         /* Port is not established yet. */
522         *bd_addr = multiplexer_cb.bd_addr;
523         log::info(
524             "In RFC_MX_STATE_CONNECTED but port is not established yet, "
525             "returning true");
526         return true;
527       }
528     }
529   }
530   log::info("false");
531   return false;
532 }
533 
534 /*******************************************************************************
535  *
536  * Function         PORT_SetState
537  *
538  * Description      This function configures connection according to the
539  *                  specifications in the tPORT_STATE structure.
540  *
541  * Parameters:      handle     - Handle returned in the RFCOMM_CreateConnection
542  *                  p_settings - Pointer to a tPORT_STATE structure containing
543  *                               configuration information for the connection.
544  *
545  *
546  ******************************************************************************/
PORT_SetState(uint16_t handle,tPORT_STATE * p_settings)547 int PORT_SetState(uint16_t handle, tPORT_STATE* p_settings) {
548   uint8_t baud_rate;
549 
550   log::verbose("PORT_SetState() handle:{}", handle);
551   tPORT* p_port = get_port_from_handle(handle);
552   if (p_port == nullptr) {
553     log::error("Unable to get RFCOMM port control block bad handle:{}", handle);
554     return (PORT_BAD_HANDLE);
555   }
556 
557   if (!p_port->in_use || (p_port->state == PORT_CONNECTION_STATE_CLOSED)) {
558     return (PORT_NOT_OPENED);
559   }
560 
561   if (p_port->line_status) {
562     return (PORT_LINE_ERR);
563   }
564 
565   log::verbose("PORT_SetState() handle:{} FC_TYPE:0x{:x}", handle,
566                p_settings->fc_type);
567 
568   baud_rate = p_port->user_port_pars.baud_rate;
569   p_port->user_port_pars = *p_settings;
570 
571   /* for now we've been asked to pass only baud rate */
572   if (baud_rate != p_settings->baud_rate) {
573     port_start_par_neg(p_port);
574   }
575   return (PORT_SUCCESS);
576 }
577 
578 /*******************************************************************************
579  *
580  * Function         PORT_GetState
581  *
582  * Description      This function is called to fill tPORT_STATE structure
583  *                  with the curremt control settings for the port
584  *
585  * Parameters:      handle     - Handle returned in the RFCOMM_CreateConnection
586  *                  p_settings - Pointer to a tPORT_STATE structure in which
587  *                               configuration information is returned.
588  *
589  ******************************************************************************/
PORT_GetState(uint16_t handle,tPORT_STATE * p_settings)590 int PORT_GetState(uint16_t handle, tPORT_STATE* p_settings) {
591   log::verbose("PORT_GetState() handle:{}", handle);
592 
593   tPORT* p_port = get_port_from_handle(handle);
594   if (p_port == nullptr) {
595     log::error("Unable to get RFCOMM port control block bad handle:{}", handle);
596     return (PORT_BAD_HANDLE);
597   }
598 
599   if (!p_port->in_use || (p_port->state == PORT_CONNECTION_STATE_CLOSED)) {
600     return (PORT_NOT_OPENED);
601   }
602 
603   if (p_port->line_status) {
604     return (PORT_LINE_ERR);
605   }
606 
607   *p_settings = p_port->user_port_pars;
608   return (PORT_SUCCESS);
609 }
610 
611 /*******************************************************************************
612  *
613  * Function         PORT_FlowControl_MaxCredit
614  *
615  * Description      This function directs a specified connection to pass
616  *                  flow control message to the peer device.  Enable flag passed
617  *                  shows if port can accept more data. It also sends max credit
618  *                  when data flow enabled
619  *
620  * Parameters:      handle     - Handle returned in the RFCOMM_CreateConnection
621  *                  enable     - enables data flow
622  *
623  ******************************************************************************/
624 
PORT_FlowControl_MaxCredit(uint16_t handle,bool enable)625 int PORT_FlowControl_MaxCredit(uint16_t handle, bool enable) {
626   bool old_fc;
627   uint32_t events;
628 
629   log::verbose("PORT_FlowControl() handle:{} enable: {}", handle, enable);
630 
631   tPORT* p_port = get_port_from_handle(handle);
632   if (p_port == nullptr) {
633     log::error("Unable to get RFCOMM port control block bad handle:{}", handle);
634     return (PORT_BAD_HANDLE);
635   }
636 
637   if (!p_port->in_use || (p_port->state == PORT_CONNECTION_STATE_CLOSED)) {
638     return (PORT_NOT_OPENED);
639   }
640 
641   if (!p_port->rfc.p_mcb) {
642     return (PORT_NOT_OPENED);
643   }
644 
645   p_port->rx.user_fc = !enable;
646 
647   if (p_port->rfc.p_mcb->flow == PORT_FC_CREDIT) {
648     if (!p_port->rx.user_fc) {
649       port_flow_control_peer(p_port, true, p_port->credit_rx);
650     }
651   } else {
652     old_fc = p_port->local_ctrl.fc;
653 
654     /* FC is set if user is set or peer is set */
655     p_port->local_ctrl.fc = (p_port->rx.user_fc | p_port->rx.peer_fc);
656 
657     if (p_port->local_ctrl.fc != old_fc) port_start_control(p_port);
658   }
659 
660   /* Need to take care of the case when we could not deliver events */
661   /* to the application because we were flow controlled */
662   if (enable && (p_port->rx.queue_size != 0)) {
663     events = PORT_EV_RXCHAR;
664     if (p_port->rx_flag_ev_pending) {
665       p_port->rx_flag_ev_pending = false;
666       events |= PORT_EV_RXFLAG;
667     }
668 
669     events &= p_port->ev_mask;
670     if (p_port->p_callback && events) {
671       p_port->p_callback(events, p_port->handle);
672     }
673   }
674   return (PORT_SUCCESS);
675 }
676 
677 /*******************************************************************************
678  *
679  * Function         PORT_ReadData
680  *
681  * Description      Normally not GKI aware application will call this function
682  *                  after receiving PORT_EV_RXCHAR event.
683  *
684  * Parameters:      handle     - Handle returned in the RFCOMM_CreateConnection
685  *                  p_data      - Data area
686  *                  max_len     - Byte count requested
687  *                  p_len       - Byte count received
688  *
689  ******************************************************************************/
PORT_ReadData(uint16_t handle,char * p_data,uint16_t max_len,uint16_t * p_len)690 int PORT_ReadData(uint16_t handle, char* p_data, uint16_t max_len,
691                   uint16_t* p_len) {
692   BT_HDR* p_buf;
693   uint16_t count;
694 
695   log::verbose("PORT_ReadData() handle:{} max_len:{}", handle, max_len);
696 
697   /* Initialize this in case of an error */
698   *p_len = 0;
699 
700   tPORT* p_port = get_port_from_handle(handle);
701   if (p_port == nullptr) {
702     log::error("Unable to get RFCOMM port control block bad handle:{}", handle);
703     return (PORT_BAD_HANDLE);
704   }
705 
706   if (!p_port->in_use || (p_port->state == PORT_CONNECTION_STATE_CLOSED)) {
707     return (PORT_NOT_OPENED);
708   }
709 
710   if (p_port->state == PORT_CONNECTION_STATE_OPENING) {
711     log::warn("Trying to read a port in PORT_CONNECTION_STATE_OPENING state");
712   }
713 
714   if (p_port->line_status) {
715     return (PORT_LINE_ERR);
716   }
717 
718   if (fixed_queue_is_empty(p_port->rx.queue)) {
719     log::warn("Read on empty input queue");
720     return (PORT_SUCCESS);
721   }
722 
723   count = 0;
724 
725   while (max_len) {
726     p_buf = (BT_HDR*)fixed_queue_try_peek_first(p_port->rx.queue);
727     if (p_buf == NULL) break;
728 
729     if (p_buf->len > max_len) {
730       memcpy(p_data, (uint8_t*)(p_buf + 1) + p_buf->offset, max_len);
731       p_buf->offset += max_len;
732       p_buf->len -= max_len;
733 
734       *p_len += max_len;
735 
736       mutex_global_lock();
737 
738       p_port->rx.queue_size -= max_len;
739 
740       mutex_global_unlock();
741 
742       break;
743     } else {
744       memcpy(p_data, (uint8_t*)(p_buf + 1) + p_buf->offset, p_buf->len);
745 
746       *p_len += p_buf->len;
747       max_len -= p_buf->len;
748 
749       mutex_global_lock();
750 
751       p_port->rx.queue_size -= p_buf->len;
752 
753       if (max_len) {
754         p_data += p_buf->len;
755       }
756 
757       osi_free(fixed_queue_try_dequeue(p_port->rx.queue));
758 
759       mutex_global_unlock();
760 
761       count++;
762     }
763   }
764 
765   if (*p_len == 1) {
766     log::verbose("PORT_ReadData queue:{} returned:{} {:x}",
767                  p_port->rx.queue_size, *p_len, p_data[0]);
768   } else {
769     log::verbose("PORT_ReadData queue:{} returned:{}", p_port->rx.queue_size,
770                  *p_len);
771   }
772 
773   /* If rfcomm suspended traffic from the peer based on the rx_queue_size */
774   /* check if it can be resumed now */
775   port_flow_control_peer(p_port, true, count);
776 
777   return (PORT_SUCCESS);
778 }
779 
780 /*******************************************************************************
781  *
782  * Function         port_write
783  *
784  * Description      This function when a data packet is received from the apper
785  *                  layer task.
786  *
787  * Parameters:      p_port     - pointer to address of port control block
788  *                  p_buf      - pointer to address of buffer with data,
789  *
790  ******************************************************************************/
port_write(tPORT * p_port,BT_HDR * p_buf)791 static int port_write(tPORT* p_port, BT_HDR* p_buf) {
792   /* We should not allow to write data in to server port when connection is not
793    * opened */
794   if (p_port->is_server && (p_port->rfc.state != RFC_STATE_OPENED)) {
795     osi_free(p_buf);
796     return (PORT_CLOSED);
797   }
798 
799   /* Keep the data in pending queue if peer does not allow data, or */
800   /* Peer is not ready or Port is not yet opened or initial port control */
801   /* command has not been sent */
802   if (p_port->tx.peer_fc || !p_port->rfc.p_mcb ||
803       !p_port->rfc.p_mcb->peer_ready ||
804       (p_port->rfc.state != RFC_STATE_OPENED) ||
805       ((p_port->port_ctrl & (PORT_CTRL_REQ_SENT | PORT_CTRL_IND_RECEIVED)) !=
806        (PORT_CTRL_REQ_SENT | PORT_CTRL_IND_RECEIVED))) {
807     if ((p_port->tx.queue_size > PORT_TX_CRITICAL_WM) ||
808         (fixed_queue_length(p_port->tx.queue) > PORT_TX_BUF_CRITICAL_WM)) {
809       log::warn("PORT_Write: Queue size: {}", p_port->tx.queue_size);
810 
811       osi_free(p_buf);
812 
813       if ((p_port->p_callback != NULL) && (p_port->ev_mask & PORT_EV_ERR))
814         p_port->p_callback(PORT_EV_ERR, p_port->handle);
815 
816       return (PORT_TX_FULL);
817     }
818 
819     log::verbose(
820         "PORT_Write : Data is enqued. flow disabled {} peer_ready {} state {} "
821         "ctrl_state {:x}",
822         p_port->tx.peer_fc, p_port->rfc.p_mcb && p_port->rfc.p_mcb->peer_ready,
823         p_port->rfc.state, p_port->port_ctrl);
824 
825     fixed_queue_enqueue(p_port->tx.queue, p_buf);
826     p_port->tx.queue_size += p_buf->len;
827 
828     return (PORT_CMD_PENDING);
829   } else {
830     log::verbose("PORT_Write : Data is being sent");
831 
832     RFCOMM_DataReq(p_port->rfc.p_mcb, p_port->dlci, p_buf);
833     return (PORT_SUCCESS);
834   }
835 }
836 
837 /*******************************************************************************
838  *
839  * Function         PORT_WriteDataCO
840  *
841  * Description      Normally not GKI aware application will call this function
842  *                  to send data to the port by callout functions
843  *
844  * Parameters:      handle     - Handle returned in the RFCOMM_CreateConnection
845  *                  fd         - socket fd
846  *                  p_len      - Byte count returned
847  *
848  ******************************************************************************/
PORT_WriteDataCO(uint16_t handle,int * p_len)849 int PORT_WriteDataCO(uint16_t handle, int* p_len) {
850   BT_HDR* p_buf;
851   uint32_t event = 0;
852   int rc = 0;
853   uint16_t length;
854 
855   log::verbose("PORT_WriteDataCO() handle:{}", handle);
856   *p_len = 0;
857 
858   tPORT* p_port = get_port_from_handle(handle);
859   if (p_port == nullptr) {
860     log::error("Unable to get RFCOMM port control block bad handle:{}", handle);
861     return (PORT_BAD_HANDLE);
862   }
863 
864   if (!p_port->in_use || (p_port->state == PORT_CONNECTION_STATE_CLOSED)) {
865     log::warn("PORT_WriteDataByFd() no port state:{}", p_port->state);
866     return (PORT_NOT_OPENED);
867   }
868 
869   if (!p_port->peer_mtu) {
870     log::error("PORT_WriteDataByFd() peer_mtu:{}", p_port->peer_mtu);
871     return (PORT_UNKNOWN_ERROR);
872   }
873   int available = 0;
874   // if(ioctl(fd, FIONREAD, &available) < 0)
875   if (!p_port->p_data_co_callback(handle, (uint8_t*)&available,
876                                   sizeof(available),
877                                   DATA_CO_CALLBACK_TYPE_OUTGOING_SIZE)) {
878     log::error(
879         "p_data_co_callback DATA_CO_CALLBACK_TYPE_INCOMING_SIZE failed, "
880         "available:{}",
881         available);
882     return (PORT_UNKNOWN_ERROR);
883   }
884   if (available == 0) return PORT_SUCCESS;
885   /* Length for each buffer is the smaller of GKI buffer, peer MTU, or max_len
886    */
887   length = RFCOMM_DATA_BUF_SIZE -
888            (uint16_t)(sizeof(BT_HDR) + L2CAP_MIN_OFFSET + RFCOMM_DATA_OVERHEAD);
889 
890   /* If there are buffers scheduled for transmission check if requested */
891   /* data fits into the end of the queue */
892   mutex_global_lock();
893 
894   p_buf = (BT_HDR*)fixed_queue_try_peek_last(p_port->tx.queue);
895   if ((p_buf != NULL) &&
896       (((int)p_buf->len + available) <= (int)p_port->peer_mtu) &&
897       (((int)p_buf->len + available) <= (int)length)) {
898     // if(recv(fd, (uint8_t *)(p_buf + 1) + p_buf->offset + p_buf->len,
899     // available, 0) != available)
900     if (!p_port->p_data_co_callback(
901             handle, (uint8_t*)(p_buf + 1) + p_buf->offset + p_buf->len,
902             available, DATA_CO_CALLBACK_TYPE_OUTGOING))
903 
904     {
905       log::error(
906           "p_data_co_callback DATA_CO_CALLBACK_TYPE_OUTGOING failed, "
907           "available:{}",
908           available);
909       mutex_global_unlock();
910       return (PORT_UNKNOWN_ERROR);
911     }
912     // memcpy ((uint8_t *)(p_buf + 1) + p_buf->offset + p_buf->len, p_data,
913     // max_len);
914     p_port->tx.queue_size += (uint16_t)available;
915 
916     *p_len = available;
917     p_buf->len += (uint16_t)available;
918 
919     mutex_global_unlock();
920 
921     return (PORT_SUCCESS);
922   }
923 
924   mutex_global_unlock();
925 
926   // int max_read = length < p_port->peer_mtu ? length : p_port->peer_mtu;
927 
928   // max_read = available < max_read ? available : max_read;
929 
930   while (available) {
931     /* if we're over buffer high water mark, we're done */
932     if ((p_port->tx.queue_size > PORT_TX_HIGH_WM) ||
933         (fixed_queue_length(p_port->tx.queue) > PORT_TX_BUF_HIGH_WM)) {
934       port_flow_control_user(p_port);
935       event |= PORT_EV_FC;
936       log::verbose(
937           "tx queue is full,tx.queue_size:{},tx.queue.count:{},available:{}",
938           p_port->tx.queue_size, fixed_queue_length(p_port->tx.queue),
939           available);
940       break;
941     }
942 
943     /* continue with rfcomm data write */
944     p_buf = (BT_HDR*)osi_malloc(RFCOMM_DATA_BUF_SIZE);
945     p_buf->offset = L2CAP_MIN_OFFSET + RFCOMM_MIN_OFFSET;
946     p_buf->layer_specific = handle;
947 
948     if (p_port->peer_mtu < length) length = p_port->peer_mtu;
949     if (available < (int)length) length = (uint16_t)available;
950     p_buf->len = length;
951     p_buf->event = BT_EVT_TO_BTU_SP_DATA;
952 
953     // memcpy ((uint8_t *)(p_buf + 1) + p_buf->offset, p_data, length);
954     // if(recv(fd, (uint8_t *)(p_buf + 1) + p_buf->offset, (int)length, 0) !=
955     // (int)length)
956     if (!p_port->p_data_co_callback(handle,
957                                     (uint8_t*)(p_buf + 1) + p_buf->offset,
958                                     length, DATA_CO_CALLBACK_TYPE_OUTGOING)) {
959       log::error(
960           "p_data_co_callback DATA_CO_CALLBACK_TYPE_OUTGOING failed, length:{}",
961           length);
962       return (PORT_UNKNOWN_ERROR);
963     }
964 
965     log::verbose("PORT_WriteData {} bytes", length);
966 
967     rc = port_write(p_port, p_buf);
968 
969     /* If queue went below the threashold need to send flow control */
970     event |= port_flow_control_user(p_port);
971 
972     if (rc == PORT_SUCCESS) event |= PORT_EV_TXCHAR;
973 
974     if ((rc != PORT_SUCCESS) && (rc != PORT_CMD_PENDING)) break;
975 
976     *p_len += length;
977     available -= (int)length;
978   }
979   if (!available && (rc != PORT_CMD_PENDING) && (rc != PORT_TX_QUEUE_DISABLED))
980     event |= PORT_EV_TXEMPTY;
981 
982   /* Mask out all events that are not of interest to user */
983   event &= p_port->ev_mask;
984 
985   /* Send event to the application */
986   if (p_port->p_callback && event) (p_port->p_callback)(event, p_port->handle);
987 
988   return (PORT_SUCCESS);
989 }
990 
991 /*******************************************************************************
992  *
993  * Function         PORT_WriteData
994  *
995  * Description      Normally not GKI aware application will call this function
996  *                  to send data to the port.
997  *
998  * Parameters:      handle     - Handle returned in the RFCOMM_CreateConnection
999  *                  p_data      - Data area
1000  *                  max_len     - Byte count requested
1001  *                  p_len       - Byte count received
1002  *
1003  ******************************************************************************/
PORT_WriteData(uint16_t handle,const char * p_data,uint16_t max_len,uint16_t * p_len)1004 int PORT_WriteData(uint16_t handle, const char* p_data, uint16_t max_len,
1005                    uint16_t* p_len) {
1006   BT_HDR* p_buf;
1007   uint32_t event = 0;
1008   int rc = 0;
1009   uint16_t length;
1010 
1011   log::verbose("PORT_WriteData() max_len:{}", max_len);
1012 
1013   *p_len = 0;
1014 
1015   tPORT* p_port = get_port_from_handle(handle);
1016   if (p_port == nullptr) {
1017     log::error("Unable to get RFCOMM port control block bad handle:{}", handle);
1018     return (PORT_BAD_HANDLE);
1019   }
1020 
1021   if (!p_port->in_use || (p_port->state == PORT_CONNECTION_STATE_CLOSED)) {
1022     log::warn("PORT_WriteData() no port state:{}", p_port->state);
1023     return (PORT_NOT_OPENED);
1024   }
1025 
1026   if (p_port->state == PORT_CONNECTION_STATE_OPENING) {
1027     log::warn("Write data received but port is in OPENING state");
1028   }
1029 
1030   if (!max_len || !p_port->peer_mtu) {
1031     log::error("PORT_WriteData() peer_mtu:{}", p_port->peer_mtu);
1032     return (PORT_UNKNOWN_ERROR);
1033   }
1034 
1035   /* Length for each buffer is the smaller of GKI buffer, peer MTU, or max_len
1036    */
1037   length = RFCOMM_DATA_BUF_SIZE -
1038            (uint16_t)(sizeof(BT_HDR) + L2CAP_MIN_OFFSET + RFCOMM_DATA_OVERHEAD);
1039 
1040   /* If there are buffers scheduled for transmission check if requested */
1041   /* data fits into the end of the queue */
1042   mutex_global_lock();
1043 
1044   p_buf = (BT_HDR*)fixed_queue_try_peek_last(p_port->tx.queue);
1045   if ((p_buf != NULL) && ((p_buf->len + max_len) <= p_port->peer_mtu) &&
1046       ((p_buf->len + max_len) <= length)) {
1047     memcpy((uint8_t*)(p_buf + 1) + p_buf->offset + p_buf->len, p_data, max_len);
1048     p_port->tx.queue_size += max_len;
1049 
1050     *p_len = max_len;
1051     p_buf->len += max_len;
1052 
1053     mutex_global_unlock();
1054 
1055     return (PORT_SUCCESS);
1056   }
1057 
1058   mutex_global_unlock();
1059 
1060   while (max_len) {
1061     /* if we're over buffer high water mark, we're done */
1062     if ((p_port->tx.queue_size > PORT_TX_HIGH_WM) ||
1063         (fixed_queue_length(p_port->tx.queue) > PORT_TX_BUF_HIGH_WM))
1064       break;
1065 
1066     /* continue with rfcomm data write */
1067     p_buf = (BT_HDR*)osi_malloc(RFCOMM_DATA_BUF_SIZE);
1068     p_buf->offset = L2CAP_MIN_OFFSET + RFCOMM_MIN_OFFSET;
1069     p_buf->layer_specific = handle;
1070 
1071     if (p_port->peer_mtu < length) length = p_port->peer_mtu;
1072     if (max_len < length) length = max_len;
1073     p_buf->len = length;
1074     p_buf->event = BT_EVT_TO_BTU_SP_DATA;
1075 
1076     memcpy((uint8_t*)(p_buf + 1) + p_buf->offset, p_data, length);
1077 
1078     log::verbose("PORT_WriteData {} bytes", length);
1079 
1080     rc = port_write(p_port, p_buf);
1081 
1082     /* If queue went below the threashold need to send flow control */
1083     event |= port_flow_control_user(p_port);
1084 
1085     if (rc == PORT_SUCCESS) event |= PORT_EV_TXCHAR;
1086 
1087     if ((rc != PORT_SUCCESS) && (rc != PORT_CMD_PENDING)) break;
1088 
1089     *p_len += length;
1090     max_len -= length;
1091     p_data += length;
1092   }
1093   if (!max_len && (rc != PORT_CMD_PENDING) && (rc != PORT_TX_QUEUE_DISABLED))
1094     event |= PORT_EV_TXEMPTY;
1095 
1096   /* Mask out all events that are not of interest to user */
1097   event &= p_port->ev_mask;
1098 
1099   /* Send event to the application */
1100   if (p_port->p_callback && event) (p_port->p_callback)(event, p_port->handle);
1101 
1102   return (PORT_SUCCESS);
1103 }
1104 
1105 /*******************************************************************************
1106  *
1107  * Function         RFCOMM_Init
1108  *
1109  * Description      This function is called to initialize RFCOMM layer
1110  *
1111  ******************************************************************************/
RFCOMM_Init(void)1112 void RFCOMM_Init(void) {
1113   memset(&rfc_cb, 0, sizeof(tRFC_CB)); /* Init RFCOMM control block */
1114   rfc_lcid_mcb = {};
1115 
1116   rfc_cb.rfc.last_mux = MAX_BD_CONNECTIONS;
1117 
1118   rfcomm_l2cap_if_init();
1119 }
1120 
1121 /*******************************************************************************
1122  *
1123  * Function         PORT_GetResultString
1124  *
1125  * Description      This function returns the human-readable string for a given
1126  *                  result code.
1127  *
1128  * Returns          a pointer to the human-readable string for the given result.
1129  *
1130  ******************************************************************************/
PORT_GetResultString(const uint8_t result_code)1131 const char* PORT_GetResultString(const uint8_t result_code) {
1132   if (result_code > PORT_ERR_MAX) {
1133     return result_code_strings[PORT_ERR_MAX];
1134   }
1135 
1136   return result_code_strings[result_code];
1137 }
1138 
1139 /*******************************************************************************
1140  *
1141  * Function         PORT_GetSecurityMask
1142  *
1143  * Description      This function returns the security bitmask for a port.
1144  *
1145  * Returns          A result code, and writes the bitmask into the output
1146  *parameter.
1147  *
1148  ******************************************************************************/
PORT_GetSecurityMask(uint16_t handle,uint16_t * sec_mask)1149 int PORT_GetSecurityMask(uint16_t handle, uint16_t* sec_mask) {
1150   tPORT* p_port = get_port_from_handle(handle);
1151   if (p_port == nullptr) {
1152     log::error("Unable to get RFCOMM port control block bad handle:{}", handle);
1153     return (PORT_BAD_HANDLE);
1154   }
1155   *sec_mask = p_port->sec_mask;
1156   return (PORT_SUCCESS);
1157 }
1158