1 /******************************************************************************
2  *
3  *  Copyright 2014 Google, Inc.
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 #define LOG_TAG "bt_hci_packet_fragmenter"
20 
21 #include "packet_fragmenter.h"
22 
23 #include <base/logging.h>
24 #include <string.h>
25 #include <unordered_map>
26 
27 #include "bt_target.h"
28 #include "buffer_allocator.h"
29 #include "device/include/controller.h"
30 #include "hci_internals.h"
31 #include "osi/include/log.h"
32 #include "osi/include/osi.h"
33 
34 #define APPLY_CONTINUATION_FLAG(handle) (((handle)&0xCFFF) | 0x1000)
35 #define APPLY_START_FLAG(handle) (((handle)&0xCFFF) | 0x2000)
36 #define SUB_EVENT(event) ((event)&MSG_SUB_EVT_MASK)
37 #define GET_BOUNDARY_FLAG(handle) (((handle) >> 12) & 0x0003)
38 #define GET_BROADCAST_FLAG(handle) (((handle) >> 14) & 0x0003)
39 
40 #define HANDLE_MASK 0x0FFF
41 #define START_PACKET_BOUNDARY 2
42 #define POINT_TO_POINT 0
43 #define L2CAP_HEADER_PDU_LEN_SIZE 2
44 #define L2CAP_HEADER_CID_SIZE 2
45 #define L2CAP_HEADER_SIZE (L2CAP_HEADER_PDU_LEN_SIZE + L2CAP_HEADER_CID_SIZE)
46 
47 // Our interface and callbacks
48 
49 static const allocator_t* buffer_allocator;
50 static const controller_t* controller;
51 static const packet_fragmenter_callbacks_t* callbacks;
52 
53 static std::unordered_map<uint16_t /* handle */, BT_HDR*> partial_packets;
54 static std::unordered_map<uint16_t /* handle */, BT_HDR*> partial_iso_packets;
55 
init(const packet_fragmenter_callbacks_t * result_callbacks)56 static void init(const packet_fragmenter_callbacks_t* result_callbacks) {
57   callbacks = result_callbacks;
58 }
59 
cleanup()60 static void cleanup() {
61   partial_packets.clear();
62   partial_iso_packets.clear();
63 }
64 
check_uint16_overflow(uint16_t a,uint16_t b)65 static bool check_uint16_overflow(uint16_t a, uint16_t b) {
66   return (UINT16_MAX - a) < b;
67 }
68 
69 static void fragment_and_dispatch_acl(BT_HDR* packet);
70 static void fragment_and_dispatch_iso(BT_HDR* packet);
71 
fragment_and_dispatch(BT_HDR * packet)72 static void fragment_and_dispatch(BT_HDR* packet) {
73   CHECK(packet != NULL);
74 
75   uint16_t event = packet->event & MSG_EVT_MASK;
76 
77   if (event == MSG_STACK_TO_HC_HCI_ACL) {
78     fragment_and_dispatch_acl(packet);
79   } else if (event == MSG_STACK_TO_HC_HCI_ISO) {
80     fragment_and_dispatch_iso(packet);
81   } else {
82     callbacks->fragmented(packet, true);
83   }
84 }
85 
fragment_and_dispatch_acl(BT_HDR * packet)86 static void fragment_and_dispatch_acl(BT_HDR* packet) {
87   uint16_t max_data_size =
88       SUB_EVENT(packet->event) == LOCAL_BR_EDR_CONTROLLER_ID
89           ? controller->get_acl_data_size_classic()
90           : controller->get_acl_data_size_ble();
91 
92   uint16_t max_packet_size = max_data_size + HCI_ACL_PREAMBLE_SIZE;
93   uint16_t remaining_length = packet->len;
94 
95   uint8_t* stream = packet->data + packet->offset;
96 
97   uint16_t continuation_handle;
98   STREAM_TO_UINT16(continuation_handle, stream);
99   continuation_handle = APPLY_CONTINUATION_FLAG(continuation_handle);
100 
101   while (remaining_length > max_packet_size) {
102     // Make sure we use the right ACL packet size
103     stream = packet->data + packet->offset;
104     STREAM_SKIP_UINT16(stream);
105     UINT16_TO_STREAM(stream, max_data_size);
106 
107     packet->len = max_packet_size;
108     callbacks->fragmented(packet, false);
109 
110     packet->offset += max_data_size;
111     remaining_length -= max_data_size;
112     packet->len = remaining_length;
113 
114     // Write the ACL header for the next fragment
115     stream = packet->data + packet->offset;
116     UINT16_TO_STREAM(stream, continuation_handle);
117     UINT16_TO_STREAM(stream, remaining_length - HCI_ACL_PREAMBLE_SIZE);
118 
119     // Apparently L2CAP can set layer_specific to a max number of segments to
120     // transmit
121     if (packet->layer_specific) {
122       packet->layer_specific--;
123 
124       if (packet->layer_specific == 0) {
125         packet->event = BT_EVT_TO_BTU_L2C_SEG_XMIT;
126         callbacks->transmit_finished(packet, false);
127         return;
128       }
129     }
130   }
131 
132   callbacks->fragmented(packet, true);
133 }
134 
fragment_and_dispatch_iso(BT_HDR * packet)135 static void fragment_and_dispatch_iso(BT_HDR* packet) {
136   uint8_t* stream = packet->data + packet->offset;
137   uint16_t max_data_size = controller->get_iso_data_size();
138   uint16_t max_packet_size = max_data_size + HCI_ISO_PREAMBLE_SIZE;
139   uint16_t remaining_length = packet->len;
140 
141   uint16_t handle;
142   STREAM_TO_UINT16(handle, stream);
143 
144   if (packet->layer_specific & BT_ISO_HDR_CONTAINS_TS) {
145     // First packet might have timestamp
146     handle = HCI_ISO_SET_TIMESTAMP_FLAG(handle);
147   }
148 
149   if (remaining_length <= max_packet_size) {
150     stream = packet->data + packet->offset;
151     UINT16_TO_STREAM(stream, HCI_ISO_SET_COMPLETE_FLAG(handle));
152   } else {
153     while (remaining_length > max_packet_size) {
154       // Make sure we use the right ISO packet size
155       stream = packet->data + packet->offset;
156       STREAM_SKIP_UINT16(stream);
157       UINT16_TO_STREAM(stream, max_data_size);
158 
159       packet->len = max_packet_size;
160       callbacks->fragmented(packet, false);
161 
162       packet->offset += max_data_size;
163       remaining_length -= max_data_size;
164       packet->len = remaining_length;
165 
166       // Write the ISO header for the next fragment
167       stream = packet->data + packet->offset;
168       if (remaining_length > max_packet_size) {
169         UINT16_TO_STREAM(stream,
170                          HCI_ISO_SET_CONTINUATION_FLAG(handle & HANDLE_MASK));
171       } else {
172         UINT16_TO_STREAM(stream,
173                          HCI_ISO_SET_END_FRAG_FLAG(handle & HANDLE_MASK));
174       }
175       UINT16_TO_STREAM(stream, remaining_length - HCI_ISO_PREAMBLE_SIZE);
176     }
177   }
178   callbacks->fragmented(packet, true);
179 }
180 
reassemble_and_dispatch_iso(UNUSED_ATTR BT_HDR * packet)181 static void reassemble_and_dispatch_iso(UNUSED_ATTR BT_HDR* packet) {
182   uint8_t* stream = packet->data;
183   uint16_t handle;
184   uint16_t iso_length;
185   uint8_t iso_hdr_len = HCI_ISO_HEADER_LEN_WITHOUT_TS;
186   BT_HDR* partial_packet;
187   uint16_t iso_full_len;
188 
189   STREAM_TO_UINT16(handle, stream);
190   STREAM_TO_UINT16(iso_length, stream);
191   // last 2 bits is RFU
192   iso_length = iso_length & 0x3FFF;
193 
194   CHECK(iso_length == packet->len - HCI_ISO_PREAMBLE_SIZE);
195 
196   uint8_t boundary_flag = GET_BOUNDARY_FLAG(handle);
197   uint8_t ts_flag = HCI_ISO_GET_TS_FLAG(handle);
198   handle = handle & HANDLE_MASK;
199 
200   auto map_iter = partial_iso_packets.find(handle);
201 
202   switch (boundary_flag) {
203     case HCI_ISO_BF_COMPLETE_PACKET:
204     case HCI_ISO_BF_FIRST_FRAGMENTED_PACKET:
205       uint16_t iso_sdu_length;
206       uint8_t packet_status_flags;
207 
208       if (map_iter != partial_iso_packets.end()) {
209         LOG_WARN(
210             "%s found unfinished packet for the iso handle with start packet. "
211             "Dropping old.",
212             __func__);
213         BT_HDR* hdl = map_iter->second;
214         partial_iso_packets.erase(map_iter);
215         buffer_allocator->free(hdl);
216       }
217 
218       if (ts_flag) {
219         /* Skip timestamp u32 */
220         STREAM_SKIP_UINT32(stream);
221         packet->layer_specific |= BT_ISO_HDR_CONTAINS_TS;
222         iso_hdr_len = HCI_ISO_HEADER_LEN_WITH_TS;
223       }
224 
225       if (iso_length < iso_hdr_len) {
226         LOG_WARN("%s ISO packet too small (%d < %d). Dropping it.", __func__,
227                  packet->len, iso_hdr_len);
228         buffer_allocator->free(packet);
229         return;
230       }
231 
232       /* Skip packet_seq. */
233       STREAM_SKIP_UINT16(stream);
234       STREAM_TO_UINT16(iso_sdu_length, stream);
235 
236       /* Silently ignore empty report if there's no 'lost data' flag set. */
237       if (iso_sdu_length == 0) {
238         buffer_allocator->free(packet);
239         return;
240       }
241 
242       packet_status_flags = HCI_ISO_GET_PACKET_STATUS_FLAGS(iso_sdu_length);
243       iso_sdu_length = iso_sdu_length & HCI_ISO_SDU_LENGTH_MASK;
244 
245       if (packet_status_flags)
246         LOG_ERROR("%s packet status flags: 0x%02x", __func__,
247                   packet_status_flags);
248 
249       iso_full_len = iso_sdu_length + iso_hdr_len + HCI_ISO_PREAMBLE_SIZE;
250       if ((iso_full_len + sizeof(BT_HDR)) > BT_DEFAULT_BUFFER_SIZE) {
251         LOG_ERROR("%s Dropping ISO packet with invalid length (%d).", __func__,
252                   iso_sdu_length);
253         buffer_allocator->free(packet);
254         return;
255       }
256 
257       if (((boundary_flag == HCI_ISO_BF_COMPLETE_PACKET) &&
258            (iso_full_len != packet->len)) ||
259           ((boundary_flag == HCI_ISO_BF_FIRST_FRAGMENTED_PACKET) &&
260            (iso_full_len <= packet->len))) {
261         LOG_ERROR("%s corrupted ISO frame", __func__);
262         return;
263       }
264 
265       partial_packet =
266           (BT_HDR*)buffer_allocator->alloc(iso_full_len + sizeof(BT_HDR));
267       if (!partial_packet) {
268         LOG_ERROR("%s cannot allocate partial packet", __func__);
269         buffer_allocator->free(packet);
270         return;
271       }
272 
273       partial_packet->event = packet->event;
274       partial_packet->len = iso_full_len;
275       partial_packet->layer_specific = packet->layer_specific;
276 
277       memcpy(partial_packet->data, packet->data, packet->len);
278 
279       // Update the ISO data size to indicate the full expected length
280       stream = partial_packet->data;
281       STREAM_SKIP_UINT16(stream);  // skip the ISO handle
282       UINT16_TO_STREAM(stream, iso_full_len - HCI_ISO_PREAMBLE_SIZE);
283 
284       if (boundary_flag == HCI_ISO_BF_FIRST_FRAGMENTED_PACKET) {
285         partial_packet->offset = packet->len;
286         partial_iso_packets[handle] = partial_packet;
287       } else {
288         packet->layer_specific |= BT_ISO_HDR_OFFSET_POINTS_DATA;
289         partial_packet->offset = iso_hdr_len + HCI_ISO_PREAMBLE_SIZE;
290         callbacks->reassembled(partial_packet);
291       }
292 
293       buffer_allocator->free(packet);
294       break;
295 
296     case HCI_ISO_BF_CONTINUATION_FRAGMENT_PACKET:
297       // pass-through
298     case HCI_ISO_BF_LAST_FRAGMENT_PACKET:
299       if (map_iter == partial_iso_packets.end()) {
300         LOG_WARN("%s got continuation for unknown packet. Dropping it.",
301                  __func__);
302         buffer_allocator->free(packet);
303         return;
304       }
305 
306       partial_packet = map_iter->second;
307       if (partial_packet->len <
308           (partial_packet->offset + packet->len - HCI_ISO_PREAMBLE_SIZE)) {
309         LOG_ERROR(
310             "%s got packet which would exceed expected length of %d. "
311             "dropping full packet",
312             __func__, partial_packet->len);
313         buffer_allocator->free(packet);
314         partial_iso_packets.erase(map_iter);
315         buffer_allocator->free(partial_packet);
316         return;
317       }
318 
319       memcpy(partial_packet->data + partial_packet->offset,
320              packet->data + HCI_ISO_PREAMBLE_SIZE,
321              packet->len - HCI_ISO_PREAMBLE_SIZE);
322 
323       if (boundary_flag == HCI_ISO_BF_CONTINUATION_FRAGMENT_PACKET) {
324         partial_packet->offset += packet->len - HCI_ISO_PREAMBLE_SIZE;
325         buffer_allocator->free(packet);
326         return;
327       }
328 
329       if (partial_packet->len !=
330           partial_packet->offset + packet->len - HCI_ISO_PREAMBLE_SIZE) {
331         LOG_ERROR(
332             "%s got last fragment, but it doesn't fill up the whole packet of "
333             "size %d",
334             __func__, partial_packet->len);
335         buffer_allocator->free(packet);
336         partial_iso_packets.erase(map_iter);
337         buffer_allocator->free(partial_packet);
338         return;
339       }
340 
341       partial_packet->layer_specific |= BT_ISO_HDR_OFFSET_POINTS_DATA;
342       partial_packet->offset = HCI_ISO_PREAMBLE_SIZE;
343       if (partial_packet->layer_specific & BT_ISO_HDR_CONTAINS_TS)
344         partial_packet->offset += HCI_ISO_HEADER_LEN_WITH_TS;
345       else
346         partial_packet->offset += HCI_ISO_HEADER_LEN_WITHOUT_TS;
347 
348       buffer_allocator->free(packet);
349 
350       partial_iso_packets.erase(map_iter);
351       callbacks->reassembled(partial_packet);
352 
353       break;
354     default:
355       LOG_ERROR("%s Unexpected packet, dropping full packet", __func__);
356       buffer_allocator->free(packet);
357       break;
358   }
359 }
360 
reassemble_and_dispatch(BT_HDR * packet)361 static void reassemble_and_dispatch(BT_HDR* packet) {
362   if ((packet->event & MSG_EVT_MASK) == MSG_HC_TO_STACK_HCI_ACL) {
363     uint8_t* stream = packet->data;
364     uint16_t handle;
365     uint16_t acl_length;
366 
367     STREAM_TO_UINT16(handle, stream);
368     STREAM_TO_UINT16(acl_length, stream);
369 
370     CHECK(acl_length == packet->len - HCI_ACL_PREAMBLE_SIZE);
371 
372     uint8_t boundary_flag = GET_BOUNDARY_FLAG(handle);
373     uint8_t broadcast_flag = GET_BROADCAST_FLAG(handle);
374     handle = handle & HANDLE_MASK;
375 
376     if (broadcast_flag != POINT_TO_POINT) {
377       LOG_WARN("dropping broadcast packet");
378       android_errorWriteLog(0x534e4554, "169327567");
379       buffer_allocator->free(packet);
380       return;
381     }
382 
383     if (boundary_flag == START_PACKET_BOUNDARY) {
384       if (acl_length < 2) {
385         LOG_WARN("%s invalid acl_length %d", __func__, acl_length);
386         buffer_allocator->free(packet);
387         return;
388       }
389       uint16_t l2cap_length;
390       STREAM_TO_UINT16(l2cap_length, stream);
391       auto map_iter = partial_packets.find(handle);
392       if (map_iter != partial_packets.end()) {
393         LOG_WARN(
394             "%s found unfinished packet for handle with start packet. "
395             "Dropping old.",
396             __func__);
397 
398         BT_HDR* hdl = map_iter->second;
399         partial_packets.erase(map_iter);
400         buffer_allocator->free(hdl);
401       }
402 
403       if (acl_length < L2CAP_HEADER_PDU_LEN_SIZE) {
404         LOG_WARN("%s L2CAP packet too small (%d < %d). Dropping it.", __func__,
405                  packet->len, L2CAP_HEADER_PDU_LEN_SIZE);
406         buffer_allocator->free(packet);
407         return;
408       }
409 
410       uint16_t full_length =
411           l2cap_length + L2CAP_HEADER_SIZE + HCI_ACL_PREAMBLE_SIZE;
412 
413       // Check for buffer overflow and that the full packet size + BT_HDR size
414       // is less than the max buffer size
415       if (check_uint16_overflow(l2cap_length,
416                                 (L2CAP_HEADER_SIZE + HCI_ACL_PREAMBLE_SIZE)) ||
417           ((full_length + sizeof(BT_HDR)) > BT_DEFAULT_BUFFER_SIZE)) {
418         LOG_ERROR("%s Dropping L2CAP packet with invalid length (%d).",
419                   __func__, l2cap_length);
420         buffer_allocator->free(packet);
421         return;
422       }
423 
424       if (full_length <= packet->len) {
425         if (full_length < packet->len)
426           LOG_WARN("%s found l2cap full length %d less than the hci length %d.",
427                    __func__, l2cap_length, packet->len);
428 
429         callbacks->reassembled(packet);
430         return;
431       }
432 
433       BT_HDR* partial_packet =
434           (BT_HDR*)buffer_allocator->alloc(full_length + sizeof(BT_HDR));
435       partial_packet->event = packet->event;
436       partial_packet->len = full_length;
437       partial_packet->offset = packet->len;
438 
439       memcpy(partial_packet->data, packet->data, packet->len);
440 
441       // Update the ACL data size to indicate the full expected length
442       stream = partial_packet->data;
443       STREAM_SKIP_UINT16(stream);  // skip the handle
444       UINT16_TO_STREAM(stream, full_length - HCI_ACL_PREAMBLE_SIZE);
445 
446       partial_packets[handle] = partial_packet;
447 
448       // Free the old packet buffer, since we don't need it anymore
449       buffer_allocator->free(packet);
450     } else {
451       auto map_iter = partial_packets.find(handle);
452       if (map_iter == partial_packets.end()) {
453         LOG_WARN("%s got continuation for unknown packet. Dropping it.",
454                  __func__);
455         buffer_allocator->free(packet);
456         return;
457       }
458       BT_HDR* partial_packet = map_iter->second;
459 
460       packet->offset = HCI_ACL_PREAMBLE_SIZE;
461       uint16_t projected_offset =
462           partial_packet->offset + (packet->len - HCI_ACL_PREAMBLE_SIZE);
463       if ((packet->len - packet->offset) >
464           (partial_packet->len - partial_packet->offset)) {
465         LOG_WARN(
466             "%s got packet which would exceed expected length of %d. "
467             "Truncating.",
468             __func__, partial_packet->len);
469         packet->len = (partial_packet->len - partial_packet->offset) + packet->offset;
470         projected_offset = partial_packet->len;
471       }
472 
473       memcpy(partial_packet->data + partial_packet->offset,
474              packet->data + packet->offset, packet->len - packet->offset);
475 
476       // Free the old packet buffer, since we don't need it anymore
477       buffer_allocator->free(packet);
478       partial_packet->offset = projected_offset;
479 
480       if (partial_packet->offset == partial_packet->len) {
481         partial_packets.erase(handle);
482         partial_packet->offset = 0;
483         callbacks->reassembled(partial_packet);
484       }
485     }
486   } else if ((packet->event & MSG_EVT_MASK) == MSG_HC_TO_STACK_HCI_ISO) {
487     reassemble_and_dispatch_iso(packet);
488   } else {
489     callbacks->reassembled(packet);
490   }
491 }
492 
493 static const packet_fragmenter_t interface = {init, cleanup,
494 
495                                               fragment_and_dispatch,
496                                               reassemble_and_dispatch};
497 
packet_fragmenter_get_interface()498 const packet_fragmenter_t* packet_fragmenter_get_interface() {
499   controller = controller_get_interface();
500   buffer_allocator = buffer_allocator_get_interface();
501   return &interface;
502 }
503 
packet_fragmenter_get_test_interface(const controller_t * controller_interface,const allocator_t * buffer_allocator_interface)504 const packet_fragmenter_t* packet_fragmenter_get_test_interface(
505     const controller_t* controller_interface,
506     const allocator_t* buffer_allocator_interface) {
507   controller = controller_interface;
508   buffer_allocator = buffer_allocator_interface;
509   return &interface;
510 }
511