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 module contains functions for port emulation entity and RFCOMM
22  *  communications
23  *
24  ******************************************************************************/
25 #include <base/logging.h>
26 #include <string.h>
27 
28 #include "osi/include/mutex.h"
29 #include "osi/include/osi.h"
30 
31 #include "bt_common.h"
32 #include "bt_target.h"
33 #include "bt_utils.h"
34 #include "btm_api.h"
35 #include "btm_int.h"
36 #include "port_api.h"
37 #include "port_int.h"
38 #include "rfc_int.h"
39 #include "rfcdefs.h"
40 
41 /*
42  * Local function definitions
43 */
44 uint32_t port_rfc_send_tx_data(tPORT* p_port);
45 void port_rfc_closed(tPORT* p_port, uint8_t res);
46 void port_get_credits(tPORT* p_port, uint8_t k);
47 
48 /*******************************************************************************
49  *
50  * Function         port_open_continue
51  *
52  * Description      This function is called after security manager completes
53  *                  required security checks.
54  *
55  * Returns          void
56  *
57  ******************************************************************************/
port_open_continue(tPORT * p_port)58 int port_open_continue(tPORT* p_port) {
59   RFCOMM_TRACE_EVENT("port_open_continue, p_port:%p", p_port);
60 
61   /* Check if multiplexer channel has already been established */
62   tRFC_MCB* p_mcb = rfc_alloc_multiplexer_channel(p_port->bd_addr, true);
63   if (p_mcb == nullptr) {
64     RFCOMM_TRACE_WARNING("port_open_continue no mx channel");
65     port_release_port(p_port);
66     return (PORT_NO_RESOURCES);
67   }
68 
69   p_port->rfc.p_mcb = p_mcb;
70 
71   p_mcb->port_handles[p_port->dlci] = p_port->handle;
72 
73   /* Connection is up and we know local and remote features, select MTU */
74   port_select_mtu(p_port);
75 
76   if (p_mcb->state == RFC_MX_STATE_CONNECTED) {
77     RFCOMM_ParameterNegotiationRequest(p_mcb, p_port->dlci, p_port->mtu);
78   } else if ((p_mcb->state == RFC_MX_STATE_IDLE) ||
79              (p_mcb->state == RFC_MX_STATE_DISC_WAIT_UA)) {
80     // In RFC_MX_STATE_IDLE state, MX state machine will create connection
81     // In RFC_MX_STATE_DISC_WAIT_UA state, MX state machine will recreate
82     // connection after disconnecting is completed
83     RFCOMM_StartReq(p_mcb);
84   } else {
85     // MX state machine ignores RFC_MX_EVENT_START_REQ in these states
86     // When it enters RFC_MX_STATE_CONNECTED, it will check any openning ports
87     RFCOMM_TRACE_DEBUG(
88         "port_open_continue: mx state(%d) mx channel is openning",
89         p_mcb->state);
90   }
91   return (PORT_SUCCESS);
92 }
93 
94 /*******************************************************************************
95  *
96  * Function         port_start_control
97  *
98  * Description      This function is called in the BTU_TASK context to
99  *                  send control information
100  *
101  * Returns          void
102  *
103  ******************************************************************************/
port_start_control(tPORT * p_port)104 void port_start_control(tPORT* p_port) {
105   tRFC_MCB* p_mcb = p_port->rfc.p_mcb;
106 
107   if (p_mcb == NULL) return;
108 
109   RFCOMM_ControlReq(p_mcb, p_port->dlci, &p_port->local_ctrl);
110 }
111 
112 /*******************************************************************************
113  *
114  * Function         port_start_par_neg
115  *
116  * Description      This function is called in the BTU_TASK context to
117  *                  send configuration information
118  *
119  * Returns          void
120  *
121  ******************************************************************************/
port_start_par_neg(tPORT * p_port)122 void port_start_par_neg(tPORT* p_port) {
123   tRFC_MCB* p_mcb = p_port->rfc.p_mcb;
124 
125   if (p_mcb == NULL) return;
126 
127   RFCOMM_PortParameterNegotiationRequest(p_mcb, p_port->dlci,
128                                          &p_port->user_port_pars);
129 }
130 
131 /*******************************************************************************
132  *
133  * Function         port_start_close
134  *
135  * Description      This function is called in the BTU_TASK context to
136  *                  release DLC
137  *
138  * Returns          void
139  *
140  ******************************************************************************/
port_start_close(tPORT * p_port)141 void port_start_close(tPORT* p_port) {
142   tRFC_MCB* p_mcb = p_port->rfc.p_mcb;
143   uint8_t old_signals;
144   uint32_t events = 0;
145 
146   /* At first indicate to the user that signals on the connection were dropped
147    */
148   p_port->line_status |= LINE_STATUS_FAILED;
149   old_signals = p_port->peer_ctrl.modem_signal;
150 
151   p_port->peer_ctrl.modem_signal &=
152       ~(PORT_DTRDSR_ON | PORT_CTSRTS_ON | PORT_DCD_ON);
153 
154   events |= port_get_signal_changes(p_port, old_signals,
155                                     p_port->peer_ctrl.modem_signal);
156 
157   if (p_port->ev_mask & PORT_EV_CONNECT_ERR) events |= PORT_EV_CONNECT_ERR;
158 
159   if (p_port->ev_mask & PORT_EV_ERR) events |= PORT_EV_ERR;
160 
161   if ((p_port->p_callback != NULL) && events)
162     p_port->p_callback(events, p_port->handle);
163 
164   /* Check if RFCOMM side has been closed while the message was queued */
165   if ((p_mcb == NULL) || (p_port->rfc.state == RFC_STATE_CLOSED)) {
166     /* Call management callback function before calling port_release_port() to
167      * clear tPort */
168     if (p_port->p_mgmt_callback)
169       p_port->p_mgmt_callback(PORT_CLOSED, p_port->handle);
170 
171     port_release_port(p_port);
172   } else {
173     RFCOMM_DlcReleaseReq(p_mcb, p_port->dlci);
174   }
175 }
176 
177 /*******************************************************************************
178  *
179  * Function         PORT_StartCnf
180  *
181  * Description      This function is called from the RFCOMM layer when
182  *                  establishing of the multiplexer channel is completed.
183  *                  Continue establishing of the connection for all ports that
184  *                  are in the OPENING state
185  *
186  ******************************************************************************/
PORT_StartCnf(tRFC_MCB * p_mcb,uint16_t result)187 void PORT_StartCnf(tRFC_MCB* p_mcb, uint16_t result) {
188   bool no_ports_up = true;
189 
190   RFCOMM_TRACE_EVENT("%s: result %d", __func__, result);
191 
192   tPORT* p_port = &rfc_cb.port.port[0];
193   for (int i = 0; i < MAX_RFC_PORTS; i++, p_port++) {
194     if (p_port->rfc.p_mcb == p_mcb) {
195       no_ports_up = false;
196 
197       if (result == RFCOMM_SUCCESS) {
198         RFCOMM_TRACE_EVENT("%s: dlci %d", __func__, p_port->dlci);
199         RFCOMM_ParameterNegotiationRequest(p_mcb, p_port->dlci, p_port->mtu);
200       } else {
201         RFCOMM_TRACE_WARNING("%s: failed result:%d", __func__, result);
202 
203         /* Warning: result is also set to 4 when l2cap connection
204            fails due to l2cap connect cnf (no_resources) */
205         if (result == HCI_ERR_PAGE_TIMEOUT) {
206           p_port->error = PORT_PAGE_TIMEOUT;
207         } else {
208           p_port->error = PORT_START_FAILED;
209         }
210 
211         rfc_release_multiplexer_channel(p_mcb);
212 
213         /* Send event to the application */
214         if (p_port->p_callback && (p_port->ev_mask & PORT_EV_CONNECT_ERR)) {
215           (p_port->p_callback)(PORT_EV_CONNECT_ERR, p_port->handle);
216         }
217 
218         if (p_port->p_mgmt_callback) {
219           p_port->p_mgmt_callback(PORT_START_FAILED, p_port->handle);
220         }
221 
222         port_release_port(p_port);
223       }
224     }
225   }
226 
227   /* There can be a situation when after starting connection, user closes the */
228   /* port, we can catch it here to close multiplexor channel */
229   if (no_ports_up) {
230     rfc_check_mcb_active(p_mcb);
231   }
232 }
233 
234 /*******************************************************************************
235  *
236  * Function         PORT_StartInd
237  *
238  * Description      This function is called from the RFCOMM layer when
239  *                  some peer device wants to establish a multiplexer
240  *                  connection.  Check if there are any ports open with this
241  *                  or not assigned multiplexer.
242  *
243  ******************************************************************************/
PORT_StartInd(tRFC_MCB * p_mcb)244 void PORT_StartInd(tRFC_MCB* p_mcb) {
245   tPORT* p_port;
246   int i;
247 
248   RFCOMM_TRACE_EVENT("PORT_StartInd");
249 
250   p_port = &rfc_cb.port.port[0];
251   for (i = 0; i < MAX_RFC_PORTS; i++, p_port++) {
252     if ((p_port->rfc.p_mcb == NULL) || (p_port->rfc.p_mcb == p_mcb)) {
253       RFCOMM_TRACE_DEBUG(
254           "PORT_StartInd, RFCOMM_StartRsp RFCOMM_SUCCESS: p_mcb:%p", p_mcb);
255       RFCOMM_StartRsp(p_mcb, RFCOMM_SUCCESS);
256       return;
257     }
258   }
259   RFCOMM_StartRsp(p_mcb, RFCOMM_ERROR);
260 }
261 
262 /*******************************************************************************
263  *
264  * Function         PORT_ParNegInd
265  *
266  * Description      This function is called from the RFCOMM layer to change
267  *                  DLCI parameters (currently only MTU is negotiated).
268  *                  If can not find the port do not accept the request.
269  *                  Otherwise save the MTU size supported by the peer.
270  *
271  ******************************************************************************/
PORT_ParNegInd(tRFC_MCB * p_mcb,uint8_t dlci,uint16_t mtu,uint8_t cl,uint8_t k)272 void PORT_ParNegInd(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu, uint8_t cl,
273                     uint8_t k) {
274   RFCOMM_TRACE_EVENT("%s: bd_addr=%s, dlci=%d, mtu=%d", __func__,
275                      p_mcb->bd_addr.ToString().c_str(), dlci, mtu);
276   tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci);
277   if (!p_port) {
278     /* This can be a first request for this port */
279     p_port = port_find_dlci_port(dlci);
280     if (!p_port) {
281       LOG(ERROR) << __func__ << ": Disconnect RFCOMM, port not found, dlci="
282                  << std::to_string(dlci) << ", p_mcb=" << p_mcb
283                  << ", bd_addr=" << p_mcb->bd_addr;
284       /* If the port cannot be opened, send a DM.  Per Errata 1205 */
285       rfc_send_dm(p_mcb, dlci, false);
286       /* check if this is the last port open, some headsets have
287       problem, they don't disconnect if we send DM */
288       rfc_check_mcb_active(p_mcb);
289       return;
290     }
291     RFCOMM_TRACE_EVENT("%s: port_handles[dlci:%d]:%d->%d", __func__, dlci,
292                        p_mcb->port_handles[dlci], p_port->handle);
293     p_mcb->port_handles[dlci] = p_port->handle;
294   }
295 
296   p_port->bd_addr = p_mcb->bd_addr;
297 
298   /* Connection is up and we know local and remote features, select MTU */
299   port_select_mtu(p_port);
300 
301   p_port->rfc.p_mcb = p_mcb;
302   p_port->mtu = (p_port->mtu < mtu) ? p_port->mtu : mtu;
303   p_port->peer_mtu = p_port->mtu;
304 
305   /* Negotiate the flow control mechanism.  If flow control mechanism for */
306   /* mux has not been set yet, set it now.  If either we or peer wants TS 07.10,
307    */
308   /* use that.  Otherwise both must want credit based, so use that. If flow is
309    */
310   /* already defined for this mux, we respond with that value. */
311   if (p_mcb->flow == PORT_FC_UNDEFINED) {
312     if ((PORT_FC_DEFAULT == PORT_FC_TS710) ||
313         (cl == RFCOMM_PN_CONV_LAYER_TYPE_1)) {
314       p_mcb->flow = PORT_FC_TS710;
315     } else {
316       p_mcb->flow = PORT_FC_CREDIT;
317     }
318   }
319 
320   /* Regardless of our flow control mechanism, if the PN cl is zero, we must */
321   /* respond with zero.  "A responding implementation must set this field to 14
322    */
323   /* if (and only if) the PN request was 15."  This could happen if a PN is sent
324    */
325   /* after the DLCI is already established-- the PN in that case must have cl =
326    * 0. */
327   /* See RFCOMM spec 5.5.3 */
328   uint8_t our_cl;
329   uint8_t our_k;
330   if (cl == RFCOMM_PN_CONV_LAYER_TYPE_1) {
331     our_cl = RFCOMM_PN_CONV_LAYER_TYPE_1;
332     our_k = 0;
333   } else if (p_mcb->flow == PORT_FC_CREDIT) {
334     /* get credits */
335     port_get_credits(p_port, k);
336 
337     /* Set convergence layer and number of credits (k) */
338     our_cl = RFCOMM_PN_CONV_LAYER_CBFC_R;
339     our_k = (p_port->credit_rx_max < RFCOMM_K_MAX) ? p_port->credit_rx_max
340                                                    : RFCOMM_K_MAX;
341     p_port->credit_rx = our_k;
342   } else {
343     /* must not be using credit based flow control; use TS 7.10 */
344     our_cl = RFCOMM_PN_CONV_LAYER_TYPE_1;
345     our_k = 0;
346   }
347   RFCOMM_ParameterNegotiationResponse(p_mcb, dlci, p_port->mtu, our_cl, our_k);
348 }
349 
350 /*******************************************************************************
351  *
352  * Function         PORT_ParNegCnf
353  *
354  * Description      This function is called from the RFCOMM layer to change
355  *                  DLCI parameters (currently only MTU is negotiated).
356  *                  Save the MTU size supported by the peer.
357  *                  If the confirmation is received during the port opening
358  *                  procedure send EstablishRequest to continue.
359  *
360  ******************************************************************************/
PORT_ParNegCnf(tRFC_MCB * p_mcb,uint8_t dlci,uint16_t mtu,uint8_t cl,uint8_t k)361 void PORT_ParNegCnf(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu, uint8_t cl,
362                     uint8_t k) {
363   RFCOMM_TRACE_EVENT("PORT_ParNegCnf dlci:%d mtu:%d cl: %d k: %d", dlci, mtu,
364                      cl, k);
365   tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci);
366   if (!p_port) {
367     LOG(WARNING) << __func__ << ": port is null for " << p_mcb->bd_addr;
368     return;
369   }
370 
371   /* Flow control mechanism not set yet.  Negotiate flow control mechanism. */
372   if (p_mcb->flow == PORT_FC_UNDEFINED) {
373     /* Our stack is configured for TS07.10 and they responded with credit-based.
374      */
375     /* This is illegal-- negotiation fails. */
376     if ((PORT_FC_DEFAULT == PORT_FC_TS710) &&
377         (cl == RFCOMM_PN_CONV_LAYER_CBFC_R)) {
378       RFCOMM_TRACE_WARNING("%s, negotiation fails, index=%d", __func__,
379                            p_port->handle);
380       rfc_send_disc(p_mcb, p_port->dlci);
381       rfc_port_closed(p_port);
382       return;
383     } else if (cl == RFCOMM_PN_CONV_LAYER_CBFC_R) {
384       // Our stack is configured for credit-based and they responded with
385       // credit-based.
386       p_mcb->flow = PORT_FC_CREDIT;
387     } else {
388       // They responded with any other value.  Treat this as negotiation to
389       // TS07.10.
390       p_mcb->flow = PORT_FC_TS710;
391     }
392   }
393   /* If mux flow control mechanism set, we honor that setting regardless of */
394   /* the CL value in their response.  This allows us to gracefully accept any */
395   /* illegal PN negotiation scenarios. */
396 
397   p_port->mtu = (p_port->mtu < mtu) ? p_port->mtu : mtu;
398   p_port->peer_mtu = p_port->mtu;
399 
400   if (p_mcb->flow == PORT_FC_CREDIT) {
401     port_get_credits(p_port, k);
402   }
403 
404   if (p_port->state == PORT_STATE_OPENING)
405     RFCOMM_DlcEstablishReq(p_mcb, p_port->dlci, p_port->mtu);
406 }
407 
408 /*******************************************************************************
409  *
410  * Function         PORT_DlcEstablishInd
411  *
412  * Description      This function is called from the RFCOMM layer when peer
413  *                  device wants to establish a new DLC.  If this is not the
414  *                  first message in the establishment procedure port_handle
415  *                  has a handle to the port control block otherwise the control
416  *                  block should be found based on the muliplexer channel and
417  *                  dlci.  The block should be allocated allocated before
418  *                  meaning that application already made open.
419  *
420  ******************************************************************************/
PORT_DlcEstablishInd(tRFC_MCB * p_mcb,uint8_t dlci,uint16_t mtu)421 void PORT_DlcEstablishInd(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu) {
422   tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci);
423 
424   RFCOMM_TRACE_DEBUG(
425       "PORT_DlcEstablishInd p_mcb:%p, dlci:%d mtu:%di, p_port:%p", p_mcb, dlci,
426       mtu, p_port);
427   VLOG(1) << __func__ << " p_mcb addr:" << p_mcb->bd_addr;
428 
429   if (!p_port) {
430     /* This can be a first request for this port */
431     p_port = port_find_dlci_port(dlci);
432     if (!p_port) {
433       RFCOMM_DlcEstablishRsp(p_mcb, dlci, 0, RFCOMM_ERROR);
434       return;
435     }
436     p_mcb->port_handles[dlci] = p_port->handle;
437   }
438 
439   /* If L2CAP's mtu less then RFCOMM's take it */
440   if (mtu && (mtu < p_port->peer_mtu)) p_port->peer_mtu = mtu;
441 
442   /* If there was an inactivity timer running for MCB stop it */
443   rfc_timer_stop(p_mcb);
444 
445   RFCOMM_DlcEstablishRsp(p_mcb, dlci, p_port->mtu, RFCOMM_SUCCESS);
446 
447   /* This is the server side.  If application wants to know when connection */
448   /* is established, thats the place */
449   if (p_port->p_callback && (p_port->ev_mask & PORT_EV_CONNECTED))
450     (p_port->p_callback)(PORT_EV_CONNECTED, p_port->handle);
451 
452   if (p_port->p_mgmt_callback)
453     p_port->p_mgmt_callback(PORT_SUCCESS, p_port->handle);
454 
455   p_port->state = PORT_STATE_OPENED;
456 }
457 
458 /*******************************************************************************
459  *
460  * Function         PORT_DlcEstablishCnf
461  *
462  * Description      This function is called from the RFCOMM layer when peer
463  *                  acknowledges establish procedure (SABME/UA).  Send reply
464  *                  to the user and set state to OPENED if result was
465  *                  successfull.
466  *
467  ******************************************************************************/
PORT_DlcEstablishCnf(tRFC_MCB * p_mcb,uint8_t dlci,uint16_t mtu,uint16_t result)468 void PORT_DlcEstablishCnf(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu,
469                           uint16_t result) {
470   tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci);
471 
472   RFCOMM_TRACE_EVENT("PORT_DlcEstablishCnf dlci:%d mtu:%d result:%d", dlci, mtu,
473                      result);
474 
475   if (!p_port) return;
476 
477   if (result != RFCOMM_SUCCESS) {
478     p_port->error = PORT_START_FAILED;
479     port_rfc_closed(p_port, PORT_START_FAILED);
480     return;
481   }
482 
483   /* If L2CAP's mtu less then RFCOMM's take it */
484   if (mtu && (mtu < p_port->peer_mtu)) p_port->peer_mtu = mtu;
485 
486   /* If there was an inactivity timer running for MCB stop it */
487   rfc_timer_stop(p_mcb);
488 
489   if (p_port->p_callback && (p_port->ev_mask & PORT_EV_CONNECTED))
490     (p_port->p_callback)(PORT_EV_CONNECTED, p_port->handle);
491 
492   if (p_port->p_mgmt_callback)
493     p_port->p_mgmt_callback(PORT_SUCCESS, p_port->handle);
494 
495   p_port->state = PORT_STATE_OPENED;
496 
497   /* RPN is required only if we want to tell DTE how the port should be opened
498    */
499   if ((p_port->uuid == UUID_SERVCLASS_DIALUP_NETWORKING) ||
500       (p_port->uuid == UUID_SERVCLASS_FAX))
501     RFCOMM_PortParameterNegotiationRequest(p_port->rfc.p_mcb, p_port->dlci,
502                                            NULL);
503   else
504     RFCOMM_ControlReq(p_port->rfc.p_mcb, p_port->dlci, &p_port->local_ctrl);
505 }
506 
507 /*******************************************************************************
508  *
509  * Function         PORT_PortNegInd
510  *
511  * Description      This function is called from the RFCOMM layer when peer
512  *                  device wants to set parameters of the port.  As per the spec
513  *                  this message has to be sent before the first data packet
514  *                  and can be sent before establish.  The block should be
515  *                  allocated before meaning that application already made open.
516  *
517  ******************************************************************************/
PORT_PortNegInd(tRFC_MCB * p_mcb,uint8_t dlci,tPORT_STATE * p_pars,uint16_t param_mask)518 void PORT_PortNegInd(tRFC_MCB* p_mcb, uint8_t dlci, tPORT_STATE* p_pars,
519                      uint16_t param_mask) {
520   tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci);
521 
522   RFCOMM_TRACE_EVENT("PORT_PortNegInd");
523 
524   if (!p_port) {
525     /* This can be a first request for this port */
526     p_port = port_find_dlci_port(dlci);
527     if (!p_port) {
528       RFCOMM_PortParameterNegotiationResponse(p_mcb, dlci, p_pars, 0);
529       return;
530     }
531     p_mcb->port_handles[dlci] = p_port->handle;
532   }
533 
534   /* Check if the flow control is acceptable on local side */
535   p_port->peer_port_pars = *p_pars;
536   RFCOMM_PortParameterNegotiationResponse(p_mcb, dlci, p_pars, param_mask);
537 }
538 
539 /*******************************************************************************
540  *
541  * Function         PORT_PortNegCnf
542  *
543  * Description      This function is called from the RFCOMM layer to change
544  *                  state for the port.  Propagate change to the user.
545  *
546  ******************************************************************************/
PORT_PortNegCnf(tRFC_MCB * p_mcb,uint8_t dlci,UNUSED_ATTR tPORT_STATE * p_pars,uint16_t result)547 void PORT_PortNegCnf(tRFC_MCB* p_mcb, uint8_t dlci,
548                      UNUSED_ATTR tPORT_STATE* p_pars, uint16_t result) {
549   tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci);
550 
551   RFCOMM_TRACE_EVENT("PORT_PortNegCnf");
552 
553   if (!p_port) {
554     RFCOMM_TRACE_WARNING("PORT_PortNegCnf no port");
555     return;
556   }
557   /* Port negotiation failed. Drop the connection */
558   if (result != RFCOMM_SUCCESS) {
559     p_port->error = PORT_PORT_NEG_FAILED;
560 
561     RFCOMM_DlcReleaseReq(p_mcb, p_port->dlci);
562 
563     port_rfc_closed(p_port, PORT_PORT_NEG_FAILED);
564     return;
565   }
566 
567   if (!(p_port->port_ctrl & PORT_CTRL_REQ_SENT)) {
568     RFCOMM_ControlReq(p_port->rfc.p_mcb, p_port->dlci, &p_port->local_ctrl);
569   } else {
570     RFCOMM_TRACE_WARNING("PORT_PortNegCnf Control Already sent");
571   }
572 }
573 
574 /*******************************************************************************
575  *
576  * Function         PORT_ControlInd
577  *
578  * Description      This function is called from the RFCOMM layer on the modem
579  *                  signal change.  Propagate change to the user.
580  *
581  ******************************************************************************/
PORT_ControlInd(tRFC_MCB * p_mcb,uint8_t dlci,tPORT_CTRL * p_pars)582 void PORT_ControlInd(tRFC_MCB* p_mcb, uint8_t dlci, tPORT_CTRL* p_pars) {
583   tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci);
584   uint32_t event;
585   uint8_t old_signals;
586 
587   RFCOMM_TRACE_EVENT("PORT_ControlInd");
588 
589   if (!p_port) return;
590 
591   old_signals = p_port->peer_ctrl.modem_signal;
592 
593   event = port_get_signal_changes(p_port, old_signals, p_pars->modem_signal);
594 
595   p_port->peer_ctrl = *p_pars;
596 
597   if (!(p_port->port_ctrl & PORT_CTRL_REQ_SENT)) {
598     RFCOMM_ControlReq(p_port->rfc.p_mcb, p_port->dlci, &p_port->local_ctrl);
599   } else {
600     /* If this is the first time we received control RFCOMM is connected */
601     if (!(p_port->port_ctrl & PORT_CTRL_IND_RECEIVED)) {
602       event |= (PORT_EV_CONNECTED & p_port->ev_mask);
603     }
604 
605     if (p_port->port_ctrl & PORT_CTRL_REQ_CONFIRMED) {
606       event |= port_rfc_send_tx_data(p_port);
607     }
608   }
609 
610   p_port->port_ctrl |= (PORT_CTRL_IND_RECEIVED | PORT_CTRL_IND_RESPONDED);
611 
612   if (p_pars->break_signal) event |= (PORT_EV_BREAK & p_port->ev_mask);
613 
614   /* execute call back function only if the application is registered for events
615    */
616   if (event && p_port->p_callback) (p_port->p_callback)(event, p_port->handle);
617 
618   RFCOMM_TRACE_EVENT(
619       "PORT_ControlInd DTR_DSR : %d, RTS_CTS : %d, RI : %d, DCD : %d",
620       ((p_port->peer_ctrl.modem_signal & MODEM_SIGNAL_DTRDSR) ? 1 : 0),
621       ((p_port->peer_ctrl.modem_signal & MODEM_SIGNAL_RTSCTS) ? 1 : 0),
622       ((p_port->peer_ctrl.modem_signal & MODEM_SIGNAL_RI) ? 1 : 0),
623       ((p_port->peer_ctrl.modem_signal & MODEM_SIGNAL_DCD) ? 1 : 0));
624 }
625 
626 /*******************************************************************************
627  *
628  * Function         PORT_ControlCnf
629  *
630  * Description      This function is called from the RFCOMM layer when
631  *                  peer acknowleges change of the modem signals.
632  *
633  ******************************************************************************/
PORT_ControlCnf(tRFC_MCB * p_mcb,uint8_t dlci,UNUSED_ATTR tPORT_CTRL * p_pars)634 void PORT_ControlCnf(tRFC_MCB* p_mcb, uint8_t dlci,
635                      UNUSED_ATTR tPORT_CTRL* p_pars) {
636   tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci);
637   uint32_t event = 0;
638 
639   RFCOMM_TRACE_EVENT("PORT_ControlCnf");
640 
641   if (!p_port) return;
642 
643   if (!(p_port->port_ctrl & PORT_CTRL_REQ_CONFIRMED)) {
644     p_port->port_ctrl |= PORT_CTRL_REQ_CONFIRMED;
645 
646     if (p_port->port_ctrl & PORT_CTRL_IND_RECEIVED)
647       event = (p_port->ev_mask & PORT_EV_CONNECTED);
648   }
649 
650   if (p_port->port_ctrl & PORT_CTRL_IND_RECEIVED) {
651     event |= port_rfc_send_tx_data(p_port);
652   }
653 
654   /* execute call back function only if the application is registered for events
655    */
656   if (event && p_port->p_callback) (p_port->p_callback)(event, p_port->handle);
657 }
658 
659 /*******************************************************************************
660  *
661  * Function         PORT_LineStatusInd
662  *
663  * Description      This function is called from the RFCOMM layer when
664  *                  peer indicates change in the line status
665  *
666  ******************************************************************************/
PORT_LineStatusInd(tRFC_MCB * p_mcb,uint8_t dlci,uint8_t line_status)667 void PORT_LineStatusInd(tRFC_MCB* p_mcb, uint8_t dlci, uint8_t line_status) {
668   tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci);
669   uint32_t event = 0;
670 
671   RFCOMM_TRACE_EVENT("PORT_LineStatusInd");
672 
673   if (!p_port) return;
674 
675   p_port->line_status |= line_status;
676 
677   if (line_status & PORT_ERR_OVERRUN) event |= PORT_EV_OVERRUN;
678 
679   if (line_status & PORT_ERR_BREAK) event |= PORT_EV_BREAK;
680 
681   if (line_status & ~(PORT_ERR_OVERRUN | PORT_ERR_BREAK)) event |= PORT_EV_ERR;
682 
683   if ((p_port->p_callback != NULL) && (p_port->ev_mask & event))
684     p_port->p_callback((p_port->ev_mask & event), p_port->handle);
685 }
686 
687 /*******************************************************************************
688  *
689  * Function         PORT_DlcReleaseInd
690  *
691  * Description      This function is called from the RFCOMM layer when
692  *                  DLC connection is released.
693  *
694  ******************************************************************************/
PORT_DlcReleaseInd(tRFC_MCB * p_mcb,uint8_t dlci)695 void PORT_DlcReleaseInd(tRFC_MCB* p_mcb, uint8_t dlci) {
696   VLOG(1) << __func__ << ": dlci=" << std::to_string(dlci)
697           << ", bd_addr=" << p_mcb->bd_addr;
698   tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci);
699   if (!p_port) return;
700   port_rfc_closed(p_port, PORT_CLOSED);
701 }
702 
703 /*******************************************************************************
704  *
705  * Function         PORT_CloseInd
706  *
707  * Description      This function is called from the RFCOMM layer when
708  *                  multiplexer connection is released.
709  *
710  ******************************************************************************/
PORT_CloseInd(tRFC_MCB * p_mcb)711 void PORT_CloseInd(tRFC_MCB* p_mcb) {
712   tPORT* p_port;
713   int i;
714 
715   RFCOMM_TRACE_EVENT("PORT_CloseInd");
716 
717   p_port = &rfc_cb.port.port[0];
718   for (i = 0; i < MAX_RFC_PORTS; i++, p_port++) {
719     if (p_port->rfc.p_mcb == p_mcb) {
720       port_rfc_closed(p_port, PORT_PEER_CONNECTION_FAILED);
721     }
722   }
723   rfc_release_multiplexer_channel(p_mcb);
724 }
725 
726 /*******************************************************************************
727  *
728  * Function         Port_TimeOutCloseMux
729  *
730  * Description      This function is called when RFCOMM timesout on a command
731  *                  as a result multiplexer connection is closed.
732  *
733  ******************************************************************************/
Port_TimeOutCloseMux(tRFC_MCB * p_mcb)734 void Port_TimeOutCloseMux(tRFC_MCB* p_mcb) {
735   tPORT* p_port;
736   int i;
737 
738   RFCOMM_TRACE_EVENT("Port_TimeOutCloseMux");
739 
740   p_port = &rfc_cb.port.port[0];
741   for (i = 0; i < MAX_RFC_PORTS; i++, p_port++) {
742     if (p_port->rfc.p_mcb == p_mcb) {
743       port_rfc_closed(p_port, PORT_PEER_TIMEOUT);
744     }
745   }
746 }
747 
748 /*******************************************************************************
749  *
750  * Function         PORT_DataInd
751  *
752  * Description      This function is called from the RFCOMM layer when data
753  *                  buffer is received from the peer.
754  *
755  ******************************************************************************/
PORT_DataInd(tRFC_MCB * p_mcb,uint8_t dlci,BT_HDR * p_buf)756 void PORT_DataInd(tRFC_MCB* p_mcb, uint8_t dlci, BT_HDR* p_buf) {
757   tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci);
758   uint8_t rx_char1;
759   uint32_t events = 0;
760   uint8_t* p;
761   int i;
762 
763   RFCOMM_TRACE_EVENT(
764       "PORT_DataInd with data length %d, p_mcb:%p,p_port:%p,dlci:%d",
765       p_buf->len, p_mcb, p_port, dlci);
766   if (!p_port) {
767     osi_free(p_buf);
768     return;
769   }
770   /* If client registered callout callback with flow control we can just deliver
771    * receive data */
772   if (p_port->p_data_co_callback) {
773     /* Another packet is delivered to user.  Send credits to peer if required */
774     if (p_port->p_data_co_callback(p_port->handle, (uint8_t*)p_buf, -1,
775                                    DATA_CO_CALLBACK_TYPE_INCOMING)) {
776       port_flow_control_peer(p_port, true, 1);
777     } else {
778       port_flow_control_peer(p_port, false, 0);
779     }
780     // osi_free(p_buf);
781     return;
782   }
783   /* If client registered callback we can just deliver receive data */
784   if (p_port->p_data_callback) {
785     /* Another packet is delivered to user.  Send credits to peer if required */
786     port_flow_control_peer(p_port, true, 1);
787     p_port->p_data_callback(p_port->handle,
788                             (uint8_t*)(p_buf + 1) + p_buf->offset, p_buf->len);
789     osi_free(p_buf);
790     return;
791   }
792   /* Check if rx queue exceeds the limit */
793   if ((p_port->rx.queue_size + p_buf->len > PORT_RX_CRITICAL_WM) ||
794       (fixed_queue_length(p_port->rx.queue) + 1 > p_port->rx_buf_critical)) {
795     RFCOMM_TRACE_EVENT("PORT_DataInd. Buffer over run. Dropping the buffer");
796     osi_free(p_buf);
797     RFCOMM_LineStatusReq(p_mcb, dlci, LINE_STATUS_OVERRUN);
798     return;
799   }
800   /* If user registered to receive notification when a particular byte is */
801   /* received we mast check all received bytes */
802   if (((rx_char1 = p_port->user_port_pars.rx_char1) != 0) &&
803       (p_port->ev_mask & PORT_EV_RXFLAG)) {
804     for (i = 0, p = (uint8_t*)(p_buf + 1) + p_buf->offset; i < p_buf->len;
805          i++) {
806       if (*p++ == rx_char1) {
807         events |= PORT_EV_RXFLAG;
808         break;
809       }
810     }
811   }
812 
813   mutex_global_lock();
814 
815   fixed_queue_enqueue(p_port->rx.queue, p_buf);
816   p_port->rx.queue_size += p_buf->len;
817 
818   mutex_global_unlock();
819 
820   /* perform flow control procedures if necessary */
821   port_flow_control_peer(p_port, false, 0);
822 
823   /* If user indicated flow control can not deliver any notifications to them */
824   if (p_port->rx.user_fc) {
825     if (events & PORT_EV_RXFLAG) {
826       p_port->rx_flag_ev_pending = true;
827     }
828     return;
829   }
830 
831   events |= PORT_EV_RXCHAR;
832 
833   /* Mask out all events that are not of interest to user */
834   events &= p_port->ev_mask;
835 
836   if (p_port->p_callback && events) p_port->p_callback(events, p_port->handle);
837 }
838 
839 /*******************************************************************************
840  *
841  * Function         PORT_FlowInd
842  *
843  * Description      This function is called from the RFCOMM layer on the flow
844  *                  control signal change.  Propagate change to the user.
845  *
846  ******************************************************************************/
PORT_FlowInd(tRFC_MCB * p_mcb,uint8_t dlci,bool enable_data)847 void PORT_FlowInd(tRFC_MCB* p_mcb, uint8_t dlci, bool enable_data) {
848   tPORT* p_port = (tPORT*)NULL;
849   uint32_t events = 0;
850   int i;
851 
852   RFCOMM_TRACE_EVENT("PORT_FlowInd fc:%d", enable_data);
853 
854   if (dlci == 0) {
855     p_mcb->peer_ready = enable_data;
856   } else {
857     p_port = port_find_mcb_dlci_port(p_mcb, dlci);
858     if (p_port == NULL) return;
859 
860     p_port->tx.peer_fc = !enable_data;
861   }
862 
863   for (i = 0; i < MAX_RFC_PORTS; i++) {
864     /* If DLCI is 0 event applies to all ports */
865     if (dlci == 0) {
866       p_port = &rfc_cb.port.port[i];
867       if (!p_port->in_use || (p_port->rfc.p_mcb != p_mcb) ||
868           (p_port->rfc.state != RFC_STATE_OPENED))
869         continue;
870     }
871     events = 0;
872 
873     /* Check if flow of data is still enabled */
874     events |= port_flow_control_user(p_port);
875 
876     /* Check if data can be sent and send it */
877     events |= port_rfc_send_tx_data(p_port);
878 
879     /* Mask out all events that are not of interest to user */
880     events &= p_port->ev_mask;
881 
882     /* Send event to the application */
883     if (p_port->p_callback && events)
884       (p_port->p_callback)(events, p_port->handle);
885 
886     /* If DLCI is not 0 event applies to one port only */
887     if (dlci != 0) break;
888   }
889 }
890 
891 /*******************************************************************************
892  *
893  * Function         port_rfc_send_tx_data
894  *
895  * Description      This function is when forward data can be sent to the peer
896  *
897  ******************************************************************************/
port_rfc_send_tx_data(tPORT * p_port)898 uint32_t port_rfc_send_tx_data(tPORT* p_port) {
899   uint32_t events = 0;
900   BT_HDR* p_buf;
901 
902   /* if there is data to be sent */
903   if (p_port->tx.queue_size > 0) {
904     /* while the rfcomm peer is not flow controlling us, and peer is ready */
905     while (!p_port->tx.peer_fc && p_port->rfc.p_mcb &&
906            p_port->rfc.p_mcb->peer_ready) {
907       /* get data from tx queue and send it */
908       mutex_global_lock();
909 
910       p_buf = (BT_HDR*)fixed_queue_try_dequeue(p_port->tx.queue);
911       if (p_buf != NULL) {
912         p_port->tx.queue_size -= p_buf->len;
913 
914         mutex_global_unlock();
915 
916         RFCOMM_TRACE_DEBUG("Sending RFCOMM_DataReq tx.queue_size=%d",
917                            p_port->tx.queue_size);
918 
919         RFCOMM_DataReq(p_port->rfc.p_mcb, p_port->dlci, p_buf);
920 
921         events |= PORT_EV_TXCHAR;
922 
923         if (p_port->tx.queue_size == 0) {
924           events |= PORT_EV_TXEMPTY;
925           break;
926         }
927       }
928       /* queue is empty-- all data sent */
929       else {
930         mutex_global_unlock();
931 
932         events |= PORT_EV_TXEMPTY;
933         break;
934       }
935     }
936     /* If we flow controlled user based on the queue size enable data again */
937     events |= port_flow_control_user(p_port);
938   }
939   return (events & p_port->ev_mask);
940 }
941 
942 /*******************************************************************************
943  *
944  * Function         port_rfc_closed
945  *
946  * Description      Called when RFCOMM port is closed
947  *
948  ******************************************************************************/
port_rfc_closed(tPORT * p_port,uint8_t res)949 void port_rfc_closed(tPORT* p_port, uint8_t res) {
950   uint8_t old_signals;
951   uint32_t events = 0;
952   tRFC_MCB* p_mcb = p_port->rfc.p_mcb;
953 
954   if ((p_port->state == PORT_STATE_OPENING) && (p_port->is_server)) {
955     /* The server side was not informed that connection is up, ignore */
956     RFCOMM_TRACE_WARNING("port_rfc_closed in OPENING state ignored");
957 
958     rfc_port_timer_stop(p_port);
959     p_port->rfc.state = RFC_STATE_CLOSED;
960 
961     if (p_mcb) {
962       p_mcb->port_handles[p_port->dlci] = 0;
963 
964       /* If there are no more ports opened on this MCB release it */
965       rfc_check_mcb_active(p_mcb);
966       p_port->rfc.p_mcb = NULL;
967     }
968 
969     /* Need to restore DLCI to listening state
970      * if the server was on the initiating RFC
971      */
972     p_port->dlci &= 0xfe;
973 
974     return;
975   }
976 
977   if ((p_port->state != PORT_STATE_CLOSING) &&
978       (p_port->state != PORT_STATE_CLOSED)) {
979     p_port->line_status |= LINE_STATUS_FAILED;
980 
981     old_signals = p_port->peer_ctrl.modem_signal;
982 
983     p_port->peer_ctrl.modem_signal &=
984         ~(PORT_DTRDSR_ON | PORT_CTSRTS_ON | PORT_DCD_ON);
985 
986     events |= port_get_signal_changes(p_port, old_signals,
987                                       p_port->peer_ctrl.modem_signal);
988 
989     if (p_port->ev_mask & PORT_EV_CONNECT_ERR) events |= PORT_EV_CONNECT_ERR;
990   }
991 
992   if ((p_port->p_callback != NULL) && events)
993     p_port->p_callback(events, p_port->handle);
994 
995   if (p_port->p_mgmt_callback) p_port->p_mgmt_callback(res, p_port->handle);
996 
997   p_port->rfc.state = RFC_STATE_CLOSED;
998 
999   LOG(INFO) << __func__ << ": RFCOMM connection closed, index="
1000             << std::to_string(p_port->handle)
1001             << ", state=" << std::to_string(p_port->state)
1002             << ", reason=" << PORT_GetResultString(res) << "["
1003             << std::to_string(res) << "], UUID=" << loghex(p_port->uuid)
1004             << ", bd_addr=" << p_port->bd_addr
1005             << ", is_server=" << p_port->is_server;
1006 
1007   port_release_port(p_port);
1008 }
1009 
1010 /*******************************************************************************
1011  *
1012  * Function         port_get_credits
1013  *
1014  * Description      Set initial values for credits.
1015  *                  Adjust max number of rx credits based on negotiated MTU.
1016  *                  Check max allowed num of bytes, max allowed num buffers,
1017  *                  should be less then 255
1018  *
1019  ******************************************************************************/
port_get_credits(tPORT * p_port,uint8_t k)1020 void port_get_credits(tPORT* p_port, uint8_t k) {
1021   p_port->credit_tx = k;
1022   if (p_port->credit_tx == 0) p_port->tx.peer_fc = true;
1023 }
1024