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