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 state machine and action routines for a port of the
22  *  RFCOMM unit
23  *
24  ******************************************************************************/
25 
26 #include <bluetooth/log.h>
27 #include <com_android_bluetooth_flags.h>
28 
29 #include <cstdint>
30 #include <cstring>
31 #include <set>
32 
33 #include "hal/snoop_logger.h"
34 #include "main/shim/entry.h"
35 #include "osi/include/allocator.h"
36 #include "stack/btm/btm_sec.h"
37 #include "stack/include/bt_hdr.h"
38 #include "stack/include/bt_uuid16.h"
39 #include "stack/include/btm_status.h"
40 #include "stack/l2cap/l2c_int.h"
41 #include "stack/rfcomm/port_int.h"
42 #include "stack/rfcomm/rfc_int.h"
43 #include "stack/rfcomm/rfc_state.h"
44 
45 using namespace bluetooth;
46 
47 static const std::set<uint16_t> uuid_logging_acceptlist = {
48         UUID_SERVCLASS_HEADSET_AUDIO_GATEWAY,
49         UUID_SERVCLASS_AG_HANDSFREE,
50 };
51 
52 /******************************************************************************/
53 /*            L O C A L    F U N C T I O N     P R O T O T Y P E S            */
54 /******************************************************************************/
55 static void rfc_port_sm_state_closed(tPORT* p_port, tRFC_PORT_EVENT event, void* p_data);
56 static void rfc_port_sm_sabme_wait_ua(tPORT* p_port, tRFC_PORT_EVENT event, void* p_data);
57 static void rfc_port_sm_opened(tPORT* p_port, tRFC_PORT_EVENT event, void* p_data);
58 static void rfc_port_sm_orig_wait_sec_check(tPORT* p_port, tRFC_PORT_EVENT event, void* p_data);
59 static void rfc_port_sm_term_wait_sec_check(tPORT* p_port, tRFC_PORT_EVENT event, void* p_data);
60 static void rfc_port_sm_disc_wait_ua(tPORT* p_port, tRFC_PORT_EVENT event, void* p_data);
61 
62 static void rfc_port_uplink_data(tPORT* p_port, BT_HDR* p_buf);
63 
64 static void rfc_set_port_settings(PortSettings* port_settings, MX_FRAME* p_frame);
65 
66 /*******************************************************************************
67  *
68  * Function         rfc_port_sm_execute
69  *
70  * Description      This function sends port events through the state
71  *                  machine.
72  *
73  * Returns          void
74  *
75  ******************************************************************************/
rfc_port_sm_execute(tPORT * p_port,tRFC_PORT_EVENT event,void * p_data)76 void rfc_port_sm_execute(tPORT* p_port, tRFC_PORT_EVENT event, void* p_data) {
77   log::assert_that(p_port != nullptr, "NULL port event {}", event);
78 
79   // logs for state RFC_STATE_OPENED handled in rfc_port_sm_opened()
80   if (p_port->rfc.state != RFC_STATE_OPENED) {
81     log::info("bd_addr:{}, handle:{}, state:{}, event:{}", p_port->bd_addr, p_port->handle,
82               rfcomm_port_state_text(p_port->rfc.state), rfcomm_port_event_text(event));
83   }
84   switch (p_port->rfc.state) {
85     case RFC_STATE_CLOSED:
86       rfc_port_sm_state_closed(p_port, event, p_data);
87       break;
88 
89     case RFC_STATE_SABME_WAIT_UA:
90       rfc_port_sm_sabme_wait_ua(p_port, event, p_data);
91       break;
92 
93     case RFC_STATE_ORIG_WAIT_SEC_CHECK:
94       rfc_port_sm_orig_wait_sec_check(p_port, event, p_data);
95       break;
96 
97     case RFC_STATE_TERM_WAIT_SEC_CHECK:
98       rfc_port_sm_term_wait_sec_check(p_port, event, p_data);
99       break;
100 
101     case RFC_STATE_OPENED:
102       rfc_port_sm_opened(p_port, event, p_data);
103       break;
104 
105     case RFC_STATE_DISC_WAIT_UA:
106       rfc_port_sm_disc_wait_ua(p_port, event, p_data);
107       break;
108   }
109 }
110 
111 /*******************************************************************************
112  *
113  * Function         rfc_port_sm_state_closed
114  *
115  * Description      This function handles events when the port is in
116  *                  CLOSED state. This state exists when port is
117  *                  being initially established.
118  *
119  * Returns          void
120  *
121  ******************************************************************************/
rfc_port_sm_state_closed(tPORT * p_port,tRFC_PORT_EVENT event,void * p_data)122 void rfc_port_sm_state_closed(tPORT* p_port, tRFC_PORT_EVENT event, void* p_data) {
123   switch (event) {
124     case RFC_PORT_EVENT_OPEN:
125       p_port->rfc.state = RFC_STATE_ORIG_WAIT_SEC_CHECK;
126       btm_sec_mx_access_request(p_port->rfc.p_mcb->bd_addr, true, p_port->sec_mask,
127                                 &rfc_sec_check_complete, p_port);
128       return;
129 
130     case RFC_PORT_EVENT_CLOSE:
131       break;
132 
133     case RFC_PORT_EVENT_CLEAR:
134       return;
135 
136     case RFC_PORT_EVENT_DATA:
137       osi_free(p_data);
138       break;
139 
140     case RFC_PORT_EVENT_SABME:
141       /* make sure the multiplexer disconnect timer is not running (reconnect
142        * case) */
143       rfc_timer_stop(p_port->rfc.p_mcb);
144 
145       /* Open will be continued after security checks are passed */
146       p_port->rfc.state = RFC_STATE_TERM_WAIT_SEC_CHECK;
147       btm_sec_mx_access_request(p_port->rfc.p_mcb->bd_addr, false, p_port->sec_mask,
148                                 &rfc_sec_check_complete, p_port);
149       return;
150 
151     case RFC_PORT_EVENT_UA:
152       return;
153 
154     case RFC_PORT_EVENT_DM:
155       log::warn("RFC_EVENT_DM, handle:{}", p_port->handle);
156       rfc_port_closed(p_port);
157       return;
158 
159     case RFC_PORT_EVENT_UIH:
160       osi_free(p_data);
161       rfc_send_dm(p_port->rfc.p_mcb, p_port->dlci, false);
162       return;
163 
164     case RFC_PORT_EVENT_DISC:
165       rfc_send_dm(p_port->rfc.p_mcb, p_port->dlci, false);
166       return;
167 
168     case RFC_PORT_EVENT_TIMEOUT:
169       PORT_TimeOutCloseMux(p_port->rfc.p_mcb);
170       log::error("Port error state {} event {}", p_port->rfc.state, event);
171       return;
172     default:
173       log::error("Received unexpected event:{} in state:{}", rfcomm_port_event_text(event),
174                  rfcomm_port_state_text(p_port->rfc.state));
175   }
176 
177   log::warn("Event ignored {}", rfcomm_port_event_text(event));
178   return;
179 }
180 
181 /*******************************************************************************
182  *
183  * Function         rfc_port_sm_sabme_wait_ua
184  *
185  * Description      This function handles events when SABME on the DLC was
186  *                  sent and SM is waiting for UA or DM.
187  *
188  * Returns          void
189  *
190  ******************************************************************************/
rfc_port_sm_sabme_wait_ua(tPORT * p_port,tRFC_PORT_EVENT event,void * p_data)191 void rfc_port_sm_sabme_wait_ua(tPORT* p_port, tRFC_PORT_EVENT event, void* p_data) {
192   switch (event) {
193     case RFC_PORT_EVENT_OPEN:
194     case RFC_PORT_EVENT_ESTABLISH_RSP:
195       log::error("Port error event:{}", event);
196       return;
197 
198     case RFC_PORT_EVENT_CLOSE:
199       rfc_port_timer_start(p_port, RFC_DISC_TIMEOUT);
200       rfc_send_disc(p_port->rfc.p_mcb, p_port->dlci);
201       p_port->rfc.expected_rsp = 0;
202       p_port->rfc.state = RFC_STATE_DISC_WAIT_UA;
203       return;
204 
205     case RFC_PORT_EVENT_CLEAR:
206       log::warn("RFC_PORT_EVENT_CLEAR, handle:{}", p_port->handle);
207       rfc_port_closed(p_port);
208       return;
209 
210     case RFC_PORT_EVENT_DATA:
211       osi_free(p_data);
212       break;
213 
214     case RFC_PORT_EVENT_UA:
215       rfc_port_timer_stop(p_port);
216       p_port->rfc.state = RFC_STATE_OPENED;
217 
218       if (uuid_logging_acceptlist.find(p_port->uuid) != uuid_logging_acceptlist.end()) {
219         // Find Channel Control Block by Channel ID
220         tL2C_CCB* p_ccb = l2cu_find_ccb_by_cid(nullptr, p_port->rfc.p_mcb->lcid);
221         if (p_ccb) {
222           bluetooth::shim::GetSnoopLogger()->AcceptlistRfcommDlci(
223                   p_ccb->p_lcb->Handle(), p_port->rfc.p_mcb->lcid, p_port->dlci);
224         }
225       }
226       if (p_port->rfc.p_mcb) {
227         uint16_t lcid;
228         tL2C_CCB* ccb;
229 
230         lcid = p_port->rfc.p_mcb->lcid;
231         ccb = l2cu_find_ccb_by_cid(nullptr, lcid);
232 
233         if (ccb) {
234           bluetooth::shim::GetSnoopLogger()->SetRfcommPortOpen(
235                   ccb->p_lcb->Handle(), lcid, p_port->dlci, p_port->uuid,
236                   p_port->rfc.p_mcb->flow == PORT_FC_CREDIT);
237         }
238       }
239 
240       PORT_DlcEstablishCnf(p_port->rfc.p_mcb, p_port->dlci, p_port->rfc.p_mcb->peer_l2cap_mtu,
241                            RFCOMM_SUCCESS);
242       return;
243 
244     case RFC_PORT_EVENT_DM:
245       log::warn("RFC_EVENT_DM, handle:{}", p_port->handle);
246       p_port->rfc.p_mcb->is_disc_initiator = true;
247       PORT_DlcEstablishCnf(p_port->rfc.p_mcb, p_port->dlci, p_port->rfc.p_mcb->peer_l2cap_mtu,
248                            RFCOMM_ERROR);
249       rfc_port_closed(p_port);
250       return;
251 
252     case RFC_PORT_EVENT_DISC:
253       log::warn("RFC_EVENT_DISC, handle:{}", p_port->handle);
254       rfc_send_ua(p_port->rfc.p_mcb, p_port->dlci);
255       PORT_DlcEstablishCnf(p_port->rfc.p_mcb, p_port->dlci, p_port->rfc.p_mcb->peer_l2cap_mtu,
256                            RFCOMM_ERROR);
257       rfc_port_closed(p_port);
258       return;
259 
260     case RFC_PORT_EVENT_SABME:
261       /* Continue to wait for the UA the SABME this side sent */
262       rfc_send_ua(p_port->rfc.p_mcb, p_port->dlci);
263       return;
264 
265     case RFC_PORT_EVENT_UIH:
266       osi_free(p_data);
267       return;
268 
269     case RFC_PORT_EVENT_TIMEOUT:
270       p_port->rfc.state = RFC_STATE_CLOSED;
271       PORT_DlcEstablishCnf(p_port->rfc.p_mcb, p_port->dlci, p_port->rfc.p_mcb->peer_l2cap_mtu,
272                            RFCOMM_ERROR);
273       return;
274     default:
275       log::error("Received unexpected event:{} in state:{}", rfcomm_port_event_text(event),
276                  rfcomm_port_state_text(static_cast<tRFC_PORT_STATE>(p_port->rfc.state)));
277   }
278   log::warn("Event ignored {}", rfcomm_port_event_text(event));
279 }
280 
281 /*******************************************************************************
282  *
283  * Function         rfc_port_sm_term_wait_sec_check
284  *
285  * Description      This function handles events for the port in the
286  *                  WAIT_SEC_CHECK state.  SABME has been received from the
287  *                  peer and Security Manager verifes address, before we can
288  *                  send ESTABLISH_IND to the Port entity
289  *
290  * Returns          void
291  *
292  ******************************************************************************/
rfc_port_sm_term_wait_sec_check(tPORT * p_port,tRFC_PORT_EVENT event,void * p_data)293 void rfc_port_sm_term_wait_sec_check(tPORT* p_port, tRFC_PORT_EVENT event, void* p_data) {
294   switch (event) {
295     case RFC_PORT_EVENT_SEC_COMPLETE:
296       if (*((tBTM_STATUS*)p_data) != tBTM_STATUS::BTM_SUCCESS) {
297         log::error("Security check failed result:{} state:{} port_handle:{}",
298                    btm_status_text(*((tBTM_STATUS*)p_data)),
299                    rfcomm_port_state_text(p_port->rfc.state), p_port->handle);
300         /* Authentication/authorization failed.  If link is still  */
301         /* up send DM and check if we need to start inactive timer */
302         if (p_port->rfc.p_mcb) {
303           rfc_send_dm(p_port->rfc.p_mcb, p_port->dlci, true);
304           p_port->rfc.p_mcb->is_disc_initiator = true;
305           port_rfc_closed(p_port, PORT_SEC_FAILED);
306         }
307       } else {
308         log::debug("Security check succeeded state:{} port_handle:{}",
309                    rfcomm_port_state_text(static_cast<tRFC_PORT_STATE>(p_port->rfc.state)),
310                    p_port->handle);
311         PORT_DlcEstablishInd(p_port->rfc.p_mcb, p_port->dlci, p_port->rfc.p_mcb->peer_l2cap_mtu);
312       }
313       return;
314 
315     case RFC_PORT_EVENT_OPEN:
316     case RFC_PORT_EVENT_CLOSE:
317       log::error("Port error event {}", rfcomm_port_event_text(event));
318       return;
319 
320     case RFC_PORT_EVENT_CLEAR:
321       log::warn("RFC_PORT_EVENT_CLEAR, handle:{}", p_port->handle);
322       btm_sec_abort_access_req(p_port->rfc.p_mcb->bd_addr);
323       rfc_port_closed(p_port);
324       return;
325 
326     case RFC_PORT_EVENT_DATA:
327       log::error("Port error event {}", rfcomm_port_event_text(event));
328       osi_free(p_data);
329       return;
330 
331     case RFC_PORT_EVENT_SABME:
332       /* Ignore SABME retransmission if client dares to do so */
333       return;
334 
335     case RFC_PORT_EVENT_DISC:
336       btm_sec_abort_access_req(p_port->rfc.p_mcb->bd_addr);
337       p_port->rfc.state = RFC_STATE_CLOSED;
338       rfc_send_ua(p_port->rfc.p_mcb, p_port->dlci);
339 
340       PORT_DlcReleaseInd(p_port->rfc.p_mcb, p_port->dlci);
341       return;
342 
343     case RFC_PORT_EVENT_UIH:
344       osi_free(p_data);
345       return;
346 
347     case RFC_PORT_EVENT_ESTABLISH_RSP:
348       if (*((uint8_t*)p_data) != RFCOMM_SUCCESS) {
349         if (p_port->rfc.p_mcb) {
350           rfc_send_dm(p_port->rfc.p_mcb, p_port->dlci, true);
351         }
352       } else {
353         rfc_send_ua(p_port->rfc.p_mcb, p_port->dlci);
354         p_port->rfc.state = RFC_STATE_OPENED;
355 
356         if (uuid_logging_acceptlist.find(p_port->uuid) != uuid_logging_acceptlist.end()) {
357           // Find Channel Control Block by Channel ID
358           tL2C_CCB* p_ccb = l2cu_find_ccb_by_cid(nullptr, p_port->rfc.p_mcb->lcid);
359           if (p_ccb) {
360             bluetooth::shim::GetSnoopLogger()->AcceptlistRfcommDlci(
361                     p_ccb->p_lcb->Handle(), p_port->rfc.p_mcb->lcid, p_port->dlci);
362           }
363         }
364         if (p_port->rfc.p_mcb) {
365           uint16_t lcid;
366           tL2C_CCB* ccb;
367 
368           lcid = p_port->rfc.p_mcb->lcid;
369           ccb = l2cu_find_ccb_by_cid(nullptr, lcid);
370 
371           if (ccb) {
372             bluetooth::shim::GetSnoopLogger()->SetRfcommPortOpen(
373                     ccb->p_lcb->Handle(), lcid, p_port->dlci, p_port->uuid,
374                     p_port->rfc.p_mcb->flow == PORT_FC_CREDIT);
375           }
376         }
377       }
378       return;
379     default:
380       log::error("Received unexpected event:{} in state:{}", rfcomm_port_event_text(event),
381                  rfcomm_port_state_text(p_port->rfc.state));
382   }
383   log::warn("Event ignored {}", event);
384 }
385 
386 /*******************************************************************************
387  *
388  * Function         rfc_port_sm_orig_wait_sec_check
389  *
390  * Description      This function handles events for the port in the
391  *                  ORIG_WAIT_SEC_CHECK state.  RFCOMM is waiting for Security
392  *                  manager to finish before sending SABME to the peer
393  *
394  * Returns          void
395  *
396  ******************************************************************************/
rfc_port_sm_orig_wait_sec_check(tPORT * p_port,tRFC_PORT_EVENT event,void * p_data)397 void rfc_port_sm_orig_wait_sec_check(tPORT* p_port, tRFC_PORT_EVENT event, void* p_data) {
398   switch (event) {
399     case RFC_PORT_EVENT_SEC_COMPLETE:
400       if (*((tBTM_STATUS*)p_data) != tBTM_STATUS::BTM_SUCCESS) {
401         log::error("Security check failed result:{} state:{} handle:{}",
402                    btm_status_text(*((tBTM_STATUS*)p_data)),
403                    rfcomm_port_state_text(p_port->rfc.state), p_port->handle);
404         p_port->rfc.p_mcb->is_disc_initiator = true;
405         PORT_DlcEstablishCnf(p_port->rfc.p_mcb, p_port->dlci, 0, RFCOMM_SECURITY_ERR);
406         rfc_port_closed(p_port);
407       } else {
408         log::debug("Security check succeeded state:{} handle:{}",
409                    rfcomm_port_state_text(p_port->rfc.state), p_port->handle);
410         rfc_send_sabme(p_port->rfc.p_mcb, p_port->dlci);
411         rfc_port_timer_start(p_port, RFC_PORT_T1_TIMEOUT);
412         p_port->rfc.state = RFC_STATE_SABME_WAIT_UA;
413       }
414       return;
415 
416     case RFC_PORT_EVENT_OPEN:
417     case RFC_PORT_EVENT_SABME: /* Peer should not use the same dlci */
418       log::error("Port error event {}", rfcomm_port_event_text(event));
419       return;
420 
421     case RFC_PORT_EVENT_CLOSE:
422       log::warn("RFC_PORT_EVENT_CLOSE, handle:{}", p_port->handle);
423       btm_sec_abort_access_req(p_port->rfc.p_mcb->bd_addr);
424       rfc_port_closed(p_port);
425       return;
426 
427     case RFC_PORT_EVENT_DATA:
428       log::error("Port error {}", rfcomm_port_event_text(event));
429       osi_free(p_data);
430       return;
431 
432     case RFC_PORT_EVENT_UIH:
433       osi_free(p_data);
434       return;
435     default:
436       log::error("Received unexpected event:{} in state:{}", rfcomm_port_event_text(event),
437                  rfcomm_port_state_text(p_port->rfc.state));
438   }
439   log::warn("Event ignored {}", rfcomm_port_event_text(event));
440 }
441 
442 /*******************************************************************************
443  *
444  * Function         rfc_port_sm_opened
445  *
446  * Description      This function handles events for the port in the OPENED
447  *                  state
448  *
449  * Returns          void
450  *
451  ******************************************************************************/
rfc_port_sm_opened(tPORT * p_port,tRFC_PORT_EVENT event,void * p_data)452 void rfc_port_sm_opened(tPORT* p_port, tRFC_PORT_EVENT event, void* p_data) {
453   switch (event) {
454     case RFC_PORT_EVENT_OPEN:
455       log::error("RFC_PORT_EVENT_OPEN bd_addr:{} handle:{} dlci:{} scn:{}", p_port->bd_addr,
456                  p_port->handle, p_port->dlci, p_port->scn);
457       return;
458 
459     case RFC_PORT_EVENT_CLOSE:
460       log::info("RFC_PORT_EVENT_CLOSE bd_addr:{}, handle:{} dlci:{} scn:{}", p_port->bd_addr,
461                 p_port->handle, p_port->dlci, p_port->scn);
462       rfc_port_timer_start(p_port, RFC_DISC_TIMEOUT);
463       rfc_send_disc(p_port->rfc.p_mcb, p_port->dlci);
464       p_port->rfc.expected_rsp = 0;
465       p_port->rfc.state = RFC_STATE_DISC_WAIT_UA;
466       return;
467 
468     case RFC_PORT_EVENT_CLEAR:
469       log::warn("RFC_PORT_EVENT_CLEAR bd_addr:{} handle:{} dlci:{} scn:{}", p_port->bd_addr,
470                 p_port->handle, p_port->dlci, p_port->scn);
471       rfc_port_closed(p_port);
472       return;
473 
474     case RFC_PORT_EVENT_DATA:
475       // Send credits in the frame.  Pass them in the layer specific member of the hdr.
476       // There might be an initial case when we reduced rx_max and credit_rx is still bigger.
477       // Make sure that we do not send 255
478       log::verbose("RFC_PORT_EVENT_DATA bd_addr:{} handle:{} dlci:{} scn:{}", p_port->bd_addr,
479                    p_port->handle, p_port->dlci, p_port->scn);
480       if ((p_port->rfc.p_mcb->flow == PORT_FC_CREDIT) &&
481           (((BT_HDR*)p_data)->len < p_port->peer_mtu) && (!p_port->rx.user_fc) &&
482           (p_port->credit_rx_max > p_port->credit_rx)) {
483         ((BT_HDR*)p_data)->layer_specific = (uint8_t)(p_port->credit_rx_max - p_port->credit_rx);
484         p_port->credit_rx = p_port->credit_rx_max;
485       } else {
486         ((BT_HDR*)p_data)->layer_specific = 0;
487       }
488       rfc_send_buf_uih(p_port->rfc.p_mcb, p_port->dlci, (BT_HDR*)p_data);
489       rfc_dec_credit(p_port);
490       return;
491 
492     case RFC_PORT_EVENT_UA:
493       log::verbose("RFC_PORT_EVENT_UA bd_addr:{} handle:{} dlci:{} scn:{}", p_port->bd_addr,
494                    p_port->handle, p_port->dlci, p_port->scn);
495       return;
496 
497     case RFC_PORT_EVENT_SABME:
498       log::verbose("RFC_PORT_EVENT_SABME bd_addr:{} handle:{} dlci:{} scn:{}", p_port->bd_addr,
499                    p_port->handle, p_port->dlci, p_port->scn);
500       rfc_send_ua(p_port->rfc.p_mcb, p_port->dlci);
501       return;
502 
503     case RFC_PORT_EVENT_DM:
504       log::info("RFC_EVENT_DM bd_addr:{} handle:{} dlci:{} scn:{}", p_port->bd_addr, p_port->handle,
505                 p_port->dlci, p_port->scn);
506       PORT_DlcReleaseInd(p_port->rfc.p_mcb, p_port->dlci);
507       rfc_port_closed(p_port);
508       return;
509 
510     case RFC_PORT_EVENT_DISC:
511       log::info("RFC_PORT_EVENT_DISC bd_addr:{} handle:{} dlci:{} scn:{}", p_port->bd_addr,
512                 p_port->handle, p_port->dlci, p_port->scn);
513       p_port->rfc.state = RFC_STATE_CLOSED;
514       rfc_send_ua(p_port->rfc.p_mcb, p_port->dlci);
515       if (!fixed_queue_is_empty(p_port->rx.queue)) {
516         /* give a chance to upper stack to close port properly */
517         log::verbose("port queue is not empty");
518         rfc_port_timer_start(p_port, RFC_DISC_TIMEOUT);
519       } else {
520         PORT_DlcReleaseInd(p_port->rfc.p_mcb, p_port->dlci);
521       }
522       return;
523 
524     case RFC_PORT_EVENT_UIH:
525       log::verbose("RFC_PORT_EVENT_UIH bd_addr:{}, handle:{} dlci:{} scn:{}", p_port->bd_addr,
526                    p_port->handle, p_port->dlci, p_port->scn);
527       rfc_port_uplink_data(p_port, (BT_HDR*)p_data);
528       return;
529 
530     case RFC_PORT_EVENT_TIMEOUT:
531       PORT_TimeOutCloseMux(p_port->rfc.p_mcb);
532       log::error("RFC_PORT_EVENT_TIMEOUT bd_addr:{} handle:{} dlci:{} scn:{}", p_port->bd_addr,
533                  p_port->handle, p_port->dlci, p_port->scn);
534       return;
535 
536     default:
537       log::error("Received unexpected event:{} bd_addr:{} handle:{} dlci:{} scn:{}",
538                  rfcomm_port_event_text(event), p_port->bd_addr, p_port->handle, p_port->dlci,
539                  p_port->scn);
540       break;
541   }
542   log::warn("Event ignored {}", rfcomm_port_event_text(event));
543 }
544 
545 /*******************************************************************************
546  *
547  * Function         rfc_port_sm_disc_wait_ua
548  *
549  * Description      This function handles events when DISC on the DLC was
550  *                  sent and SM is waiting for UA or DM.
551  *
552  * Returns          void
553  *
554  ******************************************************************************/
rfc_port_sm_disc_wait_ua(tPORT * p_port,tRFC_PORT_EVENT event,void * p_data)555 void rfc_port_sm_disc_wait_ua(tPORT* p_port, tRFC_PORT_EVENT event, void* p_data) {
556   switch (event) {
557     case RFC_PORT_EVENT_OPEN:
558     case RFC_PORT_EVENT_ESTABLISH_RSP:
559       log::error("Port error event {}", rfcomm_port_event_text(event));
560       return;
561 
562     case RFC_PORT_EVENT_CLEAR:
563       log::warn("RFC_PORT_EVENT_CLEAR, handle:{}", p_port->handle);
564       rfc_port_closed(p_port);
565       return;
566 
567     case RFC_PORT_EVENT_DATA:
568       osi_free(p_data);
569       return;
570 
571     case RFC_PORT_EVENT_UA:
572       p_port->rfc.p_mcb->is_disc_initiator = true;
573       FALLTHROUGH_INTENDED; /* FALLTHROUGH */
574 
575     case RFC_PORT_EVENT_DM:
576       log::warn("RFC_EVENT_DM|RFC_EVENT_UA[{}], handle:{}", event, p_port->handle);
577       if (com::android::bluetooth::flags::rfcomm_always_disc_initiator_in_disc_wait_ua()) {
578         // If we got a DM in RFC_STATE_DISC_WAIT_UA, it's likely that both ends
579         // attempt to DISC at the same time and both get a DM.
580         // Without setting this flag the both ends would start the same timers,
581         // wait, and still DISC the multiplexer at the same time eventually.
582         // The wait is meaningless and would block all other services that rely
583         // on RFCOMM such as HFP.
584         // Thus, setting this flag here to save us a timeout and doesn't
585         // introduce further RFCOMM event changes.
586         p_port->rfc.p_mcb->is_disc_initiator = true;
587       }
588       rfc_port_closed(p_port);
589       return;
590 
591     case RFC_PORT_EVENT_SABME:
592       rfc_send_dm(p_port->rfc.p_mcb, p_port->dlci, true);
593       return;
594 
595     case RFC_PORT_EVENT_DISC:
596       rfc_send_dm(p_port->rfc.p_mcb, p_port->dlci, true);
597       return;
598 
599     case RFC_PORT_EVENT_UIH:
600       osi_free(p_data);
601       rfc_send_dm(p_port->rfc.p_mcb, p_port->dlci, false);
602       return;
603 
604     case RFC_PORT_EVENT_TIMEOUT:
605       log::error("RFC_EVENT_TIMEOUT, handle:{}", p_port->handle);
606       rfc_port_closed(p_port);
607       return;
608     default:
609       log::error("Received unexpected event:{} in state:{}", rfcomm_port_event_text(event),
610                  rfcomm_port_state_text(p_port->rfc.state));
611   }
612 
613   log::warn("Event ignored {}", rfcomm_port_event_text(event));
614 }
615 
616 /*******************************************************************************
617  *
618  * Function         rfc_port_uplink_data
619  *
620  * Description      This function handles uplink information data frame.
621  *
622  ******************************************************************************/
rfc_port_uplink_data(tPORT * p_port,BT_HDR * p_buf)623 void rfc_port_uplink_data(tPORT* p_port, BT_HDR* p_buf) {
624   PORT_DataInd(p_port->rfc.p_mcb, p_port->dlci, p_buf);
625 }
626 
627 /*******************************************************************************
628  *
629  * Function         rfc_process_pn
630  *
631  * Description      This function handles DLC parameter negotiation frame.
632  *                  Record MTU and pass indication to the upper layer.
633  *
634  ******************************************************************************/
rfc_process_pn(tRFC_MCB * p_mcb,bool is_command,MX_FRAME * p_frame)635 void rfc_process_pn(tRFC_MCB* p_mcb, bool is_command, MX_FRAME* p_frame) {
636   log::verbose("is_initiator={}, is_cmd={}, state={}, bd_addr={}", p_mcb->is_initiator, is_command,
637                p_mcb->state, p_mcb->bd_addr);
638   uint8_t dlci = p_frame->dlci;
639 
640   if (is_command) {
641     /* Ignore if Multiplexer is being shut down */
642     if (p_mcb->state != RFC_MX_STATE_DISC_WAIT_UA) {
643       PORT_ParNegInd(p_mcb, dlci, p_frame->u.pn.mtu, p_frame->u.pn.conv_layer, p_frame->u.pn.k);
644     } else {
645       log::warn("MX PN while disconnecting, bd_addr={}, p_mcb={}", p_mcb->bd_addr,
646                 std::format_ptr(p_mcb));
647       rfc_send_dm(p_mcb, dlci, false);
648     }
649 
650     return;
651   }
652   /* If we are not awaiting response just ignore it */
653   tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci);
654   if ((p_port == nullptr) || !(p_port->rfc.expected_rsp & RFC_RSP_PN)) {
655     log::warn(": Ignore unwanted response, p_mcb={}, bd_addr={}, dlci={}", std::format_ptr(p_mcb),
656               p_mcb->bd_addr, dlci);
657     return;
658   }
659 
660   p_port->rfc.expected_rsp &= ~RFC_RSP_PN;
661 
662   rfc_port_timer_stop(p_port);
663 
664   PORT_ParNegCnf(p_mcb, dlci, p_frame->u.pn.mtu, p_frame->u.pn.conv_layer, p_frame->u.pn.k);
665 }
666 
667 /*******************************************************************************
668  *
669  * Function         rfc_process_rpn
670  *
671  * Description      This function handles Remote DLC parameter negotiation
672  *                  command/response.  Pass command to the user.
673  *
674  ******************************************************************************/
rfc_process_rpn(tRFC_MCB * p_mcb,bool is_command,bool is_request,MX_FRAME * p_frame)675 void rfc_process_rpn(tRFC_MCB* p_mcb, bool is_command, bool is_request, MX_FRAME* p_frame) {
676   PortSettings port_settings = {};
677   tPORT* p_port;
678 
679   p_port = port_find_mcb_dlci_port(p_mcb, p_frame->dlci);
680   if (p_port == nullptr) {
681     /* This is the first command on the port */
682     if (is_command) {
683       rfc_set_port_settings(&port_settings, p_frame);
684 
685       PORT_PortNegInd(p_mcb, p_frame->dlci, &port_settings, p_frame->u.rpn.param_mask);
686     }
687     return;
688   }
689 
690   if (is_command && is_request) {
691     /* This is the special situation when peer just request local pars */
692     rfc_send_rpn(p_mcb, p_frame->dlci, false, &p_port->peer_port_settings, 0);
693     return;
694   }
695 
696   port_settings = p_port->peer_port_settings;
697 
698   rfc_set_port_settings(&port_settings, p_frame);
699 
700   if (is_command) {
701     PORT_PortNegInd(p_mcb, p_frame->dlci, &port_settings, p_frame->u.rpn.param_mask);
702     return;
703   }
704 
705   // If we are not awaiting response just ignore it
706   p_port = port_find_mcb_dlci_port(p_mcb, p_frame->dlci);
707   if ((p_port == nullptr) || !(p_port->rfc.expected_rsp & (RFC_RSP_RPN | RFC_RSP_RPN_REPLY))) {
708     log::warn("ignore DLC parameter negotiation as we are not waiting for any");
709     return;
710   }
711 
712   // If we sent a request for port parameters to the peer it is replying with mask 0.
713   rfc_port_timer_stop(p_port);
714 
715   if (p_port->rfc.expected_rsp & RFC_RSP_RPN_REPLY) {
716     p_port->rfc.expected_rsp &= ~RFC_RSP_RPN_REPLY;
717 
718     p_port->peer_port_settings = port_settings;
719 
720     if ((port_settings.fc_type == (RFCOMM_FC_RTR_ON_INPUT | RFCOMM_FC_RTR_ON_OUTPUT)) ||
721         (port_settings.fc_type == (RFCOMM_FC_RTC_ON_INPUT | RFCOMM_FC_RTC_ON_OUTPUT))) {
722       /* This is satisfactory port parameters.  Set mask as it was Ok */
723       p_frame->u.rpn.param_mask = RFCOMM_RPN_PM_MASK;
724     } else {
725       /* Current peer parameters are not good, try to fix them */
726       p_port->peer_port_settings.fc_type = (RFCOMM_FC_RTR_ON_INPUT | RFCOMM_FC_RTR_ON_OUTPUT);
727 
728       p_port->rfc.expected_rsp |= RFC_RSP_RPN;
729       rfc_send_rpn(p_mcb, p_frame->dlci, true, &p_port->peer_port_settings,
730                    RFCOMM_RPN_PM_RTR_ON_INPUT | RFCOMM_RPN_PM_RTR_ON_OUTPUT);
731       rfc_port_timer_start(p_port, RFC_T2_TIMEOUT);
732       return;
733     }
734   } else {
735     p_port->rfc.expected_rsp &= ~RFC_RSP_RPN;
736   }
737 
738   /* Check if all suggested parameters were accepted */
739   if (((p_frame->u.rpn.param_mask & (RFCOMM_RPN_PM_RTR_ON_INPUT | RFCOMM_RPN_PM_RTR_ON_OUTPUT)) ==
740        (RFCOMM_RPN_PM_RTR_ON_INPUT | RFCOMM_RPN_PM_RTR_ON_OUTPUT)) ||
741       ((p_frame->u.rpn.param_mask & (RFCOMM_RPN_PM_RTC_ON_INPUT | RFCOMM_RPN_PM_RTC_ON_OUTPUT)) ==
742        (RFCOMM_RPN_PM_RTC_ON_INPUT | RFCOMM_RPN_PM_RTC_ON_OUTPUT))) {
743     PORT_PortNegCnf(p_mcb, p_port->dlci, &port_settings, RFCOMM_SUCCESS);
744     return;
745   }
746 
747   /* If we were proposing RTR flow control try RTC flow control */
748   /* If we were proposing RTC flow control try no flow control */
749   /* otherwise drop the connection */
750   if (p_port->peer_port_settings.fc_type == (RFCOMM_FC_RTR_ON_INPUT | RFCOMM_FC_RTR_ON_OUTPUT)) {
751     /* Current peer parameters are not good, try to fix them */
752     p_port->peer_port_settings.fc_type = (RFCOMM_FC_RTC_ON_INPUT | RFCOMM_FC_RTC_ON_OUTPUT);
753 
754     p_port->rfc.expected_rsp |= RFC_RSP_RPN;
755 
756     rfc_send_rpn(p_mcb, p_frame->dlci, true, &p_port->peer_port_settings,
757                  RFCOMM_RPN_PM_RTC_ON_INPUT | RFCOMM_RPN_PM_RTC_ON_OUTPUT);
758     rfc_port_timer_start(p_port, RFC_T2_TIMEOUT);
759     return;
760   }
761 
762   /* Other side does not support flow control */
763   if (p_port->peer_port_settings.fc_type == (RFCOMM_FC_RTC_ON_INPUT | RFCOMM_FC_RTC_ON_OUTPUT)) {
764     p_port->peer_port_settings.fc_type = RFCOMM_FC_OFF;
765     PORT_PortNegCnf(p_mcb, p_port->dlci, &port_settings, RFCOMM_SUCCESS);
766   }
767 }
768 
769 /*******************************************************************************
770  *
771  * Function         rfc_process_msc
772  *
773  * Description      This function handles Modem Status Command.
774  *                  Pass command to the user.
775  *
776  ******************************************************************************/
rfc_process_msc(tRFC_MCB * p_mcb,bool is_command,MX_FRAME * p_frame)777 void rfc_process_msc(tRFC_MCB* p_mcb, bool is_command, MX_FRAME* p_frame) {
778   tPORT_CTRL pars;
779   tPORT* p_port;
780   uint8_t modem_signals = p_frame->u.msc.signals;
781   bool new_peer_fc = false;
782 
783   p_port = port_find_mcb_dlci_port(p_mcb, p_frame->dlci);
784   if (p_port == NULL) {
785     return;
786   }
787 
788   pars.modem_signal = 0;
789 
790   if (modem_signals & RFCOMM_MSC_RTC) {
791     pars.modem_signal |= MODEM_SIGNAL_DTRDSR;
792   }
793 
794   if (modem_signals & RFCOMM_MSC_RTR) {
795     pars.modem_signal |= MODEM_SIGNAL_RTSCTS;
796   }
797 
798   if (modem_signals & RFCOMM_MSC_IC) {
799     pars.modem_signal |= MODEM_SIGNAL_RI;
800   }
801 
802   if (modem_signals & RFCOMM_MSC_DV) {
803     pars.modem_signal |= MODEM_SIGNAL_DCD;
804   }
805 
806   pars.fc = ((modem_signals & RFCOMM_MSC_FC) == RFCOMM_MSC_FC);
807 
808   pars.break_signal = (p_frame->u.msc.break_present) ? p_frame->u.msc.break_duration : 0;
809   pars.discard_buffers = 0;
810   pars.break_signal_seq = RFCOMM_CTRL_BREAK_IN_SEQ; /* this is default */
811 
812   /* Check if this command is passed only to indicate flow control */
813   if (is_command) {
814     rfc_send_msc(p_mcb, p_frame->dlci, false, &pars);
815 
816     if (p_port->rfc.p_mcb->flow != PORT_FC_CREDIT) {
817       /* Spec 1.1 indicates that only FC bit is used for flow control */
818       p_port->peer_ctrl.fc = new_peer_fc = pars.fc;
819 
820       if (new_peer_fc != p_port->tx.peer_fc) {
821         PORT_FlowInd(p_mcb, p_frame->dlci, (bool)!new_peer_fc);
822       }
823     }
824 
825     PORT_ControlInd(p_mcb, p_frame->dlci, &pars);
826 
827     return;
828   }
829 
830   /* If we are not awaiting response just ignore it */
831   if (!(p_port->rfc.expected_rsp & RFC_RSP_MSC)) {
832     return;
833   }
834 
835   p_port->rfc.expected_rsp &= ~RFC_RSP_MSC;
836 
837   rfc_port_timer_stop(p_port);
838 
839   PORT_ControlCnf(p_port->rfc.p_mcb, p_port->dlci, &pars);
840 }
841 
842 /*******************************************************************************
843  *
844  * Function         rfc_process_rls
845  *
846  * Description      This function handles Remote Line Status command.
847  *                  Pass command to the user.
848  *
849  ******************************************************************************/
rfc_process_rls(tRFC_MCB * p_mcb,bool is_command,MX_FRAME * p_frame)850 void rfc_process_rls(tRFC_MCB* p_mcb, bool is_command, MX_FRAME* p_frame) {
851   tPORT* p_port;
852 
853   if (is_command) {
854     PORT_LineStatusInd(p_mcb, p_frame->dlci, p_frame->u.rls.line_status);
855     rfc_send_rls(p_mcb, p_frame->dlci, false, p_frame->u.rls.line_status);
856   } else {
857     p_port = port_find_mcb_dlci_port(p_mcb, p_frame->dlci);
858 
859     /* If we are not awaiting response just ignore it */
860     if (!p_port || !(p_port->rfc.expected_rsp & RFC_RSP_RLS)) {
861       return;
862     }
863 
864     p_port->rfc.expected_rsp &= ~RFC_RSP_RLS;
865 
866     rfc_port_timer_stop(p_port);
867   }
868 }
869 
870 /*******************************************************************************
871  *
872  * Function         rfc_process_nsc
873  *
874  * Description      This function handles None Supported Command frame.
875  *
876  ******************************************************************************/
rfc_process_nsc(tRFC_MCB *,MX_FRAME *)877 void rfc_process_nsc(tRFC_MCB* /* p_mcb */, MX_FRAME* /* p_frame */) {}
878 
879 /*******************************************************************************
880  *
881  * Function         rfc_process_test
882  *
883  * Description      This function handles Test frame.  If this is a command
884  *                  reply to it.  Otherwise pass response to the user.
885  *
886  ******************************************************************************/
rfc_process_test_rsp(tRFC_MCB *,BT_HDR * p_buf)887 void rfc_process_test_rsp(tRFC_MCB* /* p_mcb */, BT_HDR* p_buf) { osi_free(p_buf); }
888 
889 /*******************************************************************************
890  *
891  * Function         rfc_process_fcon
892  *
893  * Description      This function handles FCON frame.  The peer entity is able
894  *                  to receive new information
895  *
896  ******************************************************************************/
rfc_process_fcon(tRFC_MCB * p_mcb,bool is_command)897 void rfc_process_fcon(tRFC_MCB* p_mcb, bool is_command) {
898   if (is_command) {
899     rfc_cb.rfc.peer_rx_disabled = false;
900 
901     rfc_send_fcon(p_mcb, false);
902 
903     if (!p_mcb->l2cap_congested) {
904       PORT_FlowInd(p_mcb, 0, true);
905     }
906   }
907 }
908 
909 /*******************************************************************************
910  *
911  * Function         rfc_process_fcoff
912  *
913  * Description      This function handles FCOFF frame.  The peer entity is
914  *                  unable to receive new information
915  *
916  ******************************************************************************/
rfc_process_fcoff(tRFC_MCB * p_mcb,bool is_command)917 void rfc_process_fcoff(tRFC_MCB* p_mcb, bool is_command) {
918   if (is_command) {
919     rfc_cb.rfc.peer_rx_disabled = true;
920 
921     if (!p_mcb->l2cap_congested) {
922       PORT_FlowInd(p_mcb, 0, false);
923     }
924 
925     rfc_send_fcoff(p_mcb, false);
926   }
927 }
928 
929 /*******************************************************************************
930  *
931  * Function         rfc_process_l2cap_congestion
932  *
933  * Description      This function handles L2CAP congestion messages
934  *
935  ******************************************************************************/
rfc_process_l2cap_congestion(tRFC_MCB * p_mcb,bool is_congested)936 void rfc_process_l2cap_congestion(tRFC_MCB* p_mcb, bool is_congested) {
937   p_mcb->l2cap_congested = is_congested;
938 
939   if (!is_congested) {
940     rfc_check_send_cmd(p_mcb, nullptr);
941   }
942 
943   if (!rfc_cb.rfc.peer_rx_disabled) {
944     PORT_FlowInd(p_mcb, 0, !is_congested);
945   }
946 }
947 
948 /*******************************************************************************
949  *
950  * Function         rfc_set_port_settings
951  *
952  * Description      This function sets the PortSettings structure given a
953  *                  p_frame.
954  *
955  ******************************************************************************/
956 
rfc_set_port_settings(PortSettings * port_settings,MX_FRAME * p_frame)957 void rfc_set_port_settings(PortSettings* port_settings, MX_FRAME* p_frame) {
958   if (p_frame->u.rpn.param_mask & RFCOMM_RPN_PM_BIT_RATE) {
959     port_settings->baud_rate = p_frame->u.rpn.baud_rate;
960   }
961   if (p_frame->u.rpn.param_mask & RFCOMM_RPN_PM_DATA_BITS) {
962     port_settings->byte_size = p_frame->u.rpn.byte_size;
963   }
964   if (p_frame->u.rpn.param_mask & RFCOMM_RPN_PM_STOP_BITS) {
965     port_settings->stop_bits = p_frame->u.rpn.stop_bits;
966   }
967   if (p_frame->u.rpn.param_mask & RFCOMM_RPN_PM_PARITY) {
968     port_settings->parity = p_frame->u.rpn.parity;
969   }
970   if (p_frame->u.rpn.param_mask & RFCOMM_RPN_PM_PARITY_TYPE) {
971     port_settings->parity_type = p_frame->u.rpn.parity_type;
972   }
973   if (p_frame->u.rpn.param_mask &
974       (RFCOMM_RPN_PM_XONXOFF_ON_INPUT | RFCOMM_RPN_PM_XONXOFF_ON_OUTPUT |
975        RFCOMM_RPN_PM_RTR_ON_INPUT | RFCOMM_RPN_PM_RTR_ON_OUTPUT | RFCOMM_RPN_PM_RTC_ON_INPUT |
976        RFCOMM_RPN_PM_RTC_ON_OUTPUT)) {
977     port_settings->fc_type = p_frame->u.rpn.fc_type;
978   }
979   if (p_frame->u.rpn.param_mask & RFCOMM_RPN_PM_XON_CHAR) {
980     port_settings->xon_char = p_frame->u.rpn.xon_char;
981   }
982   if (p_frame->u.rpn.param_mask & RFCOMM_RPN_PM_XOFF_CHAR) {
983     port_settings->xoff_char = p_frame->u.rpn.xoff_char;
984   }
985 }
986