1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <android-base/logging.h>
18 #include <utils/SystemClock.h>
19 
20 #include "hidl_struct_util.h"
21 
22 namespace android {
23 namespace hardware {
24 namespace wifi {
25 namespace V1_2 {
26 namespace implementation {
27 namespace hidl_struct_util {
28 
29 WifiChannelWidthInMhz convertLegacyWifiChannelWidthToHidl(
30     legacy_hal::wifi_channel_width type);
31 
safeConvertChar(const char * str,size_t max_len)32 hidl_string safeConvertChar(const char* str, size_t max_len) {
33     const char* c = str;
34     size_t size = 0;
35     while (*c && (unsigned char)*c < 128 && size < max_len) {
36         ++size;
37         ++c;
38     }
39     return hidl_string(str, size);
40 }
41 
convertLegacyLoggerFeatureToHidlChipCapability(uint32_t feature)42 IWifiChip::ChipCapabilityMask convertLegacyLoggerFeatureToHidlChipCapability(
43     uint32_t feature) {
44     using HidlChipCaps = IWifiChip::ChipCapabilityMask;
45     switch (feature) {
46         case legacy_hal::WIFI_LOGGER_MEMORY_DUMP_SUPPORTED:
47             return HidlChipCaps::DEBUG_MEMORY_FIRMWARE_DUMP;
48         case legacy_hal::WIFI_LOGGER_DRIVER_DUMP_SUPPORTED:
49             return HidlChipCaps::DEBUG_MEMORY_DRIVER_DUMP;
50         case legacy_hal::WIFI_LOGGER_CONNECT_EVENT_SUPPORTED:
51             return HidlChipCaps::DEBUG_RING_BUFFER_CONNECT_EVENT;
52         case legacy_hal::WIFI_LOGGER_POWER_EVENT_SUPPORTED:
53             return HidlChipCaps::DEBUG_RING_BUFFER_POWER_EVENT;
54         case legacy_hal::WIFI_LOGGER_WAKE_LOCK_SUPPORTED:
55             return HidlChipCaps::DEBUG_RING_BUFFER_WAKELOCK_EVENT;
56     };
57     CHECK(false) << "Unknown legacy feature: " << feature;
58     return {};
59 }
60 
61 IWifiStaIface::StaIfaceCapabilityMask
convertLegacyLoggerFeatureToHidlStaIfaceCapability(uint32_t feature)62 convertLegacyLoggerFeatureToHidlStaIfaceCapability(uint32_t feature) {
63     using HidlStaIfaceCaps = IWifiStaIface::StaIfaceCapabilityMask;
64     switch (feature) {
65         case legacy_hal::WIFI_LOGGER_PACKET_FATE_SUPPORTED:
66             return HidlStaIfaceCaps::DEBUG_PACKET_FATE;
67     };
68     CHECK(false) << "Unknown legacy feature: " << feature;
69     return {};
70 }
71 
convertLegacyFeatureToHidlChipCapability(uint32_t feature)72 IWifiChip::ChipCapabilityMask convertLegacyFeatureToHidlChipCapability(
73     uint32_t feature) {
74     using HidlChipCaps = IWifiChip::ChipCapabilityMask;
75     switch (feature) {
76         case WIFI_FEATURE_SET_TX_POWER_LIMIT:
77             return HidlChipCaps::SET_TX_POWER_LIMIT;
78         case WIFI_FEATURE_USE_BODY_HEAD_SAR:
79             return HidlChipCaps::USE_BODY_HEAD_SAR;
80         case WIFI_FEATURE_D2D_RTT:
81             return HidlChipCaps::D2D_RTT;
82         case WIFI_FEATURE_D2AP_RTT:
83             return HidlChipCaps::D2AP_RTT;
84     };
85     CHECK(false) << "Unknown legacy feature: " << feature;
86     return {};
87 }
88 
89 IWifiStaIface::StaIfaceCapabilityMask
convertLegacyFeatureToHidlStaIfaceCapability(uint32_t feature)90 convertLegacyFeatureToHidlStaIfaceCapability(uint32_t feature) {
91     using HidlStaIfaceCaps = IWifiStaIface::StaIfaceCapabilityMask;
92     switch (feature) {
93         case WIFI_FEATURE_GSCAN:
94             return HidlStaIfaceCaps::BACKGROUND_SCAN;
95         case WIFI_FEATURE_LINK_LAYER_STATS:
96             return HidlStaIfaceCaps::LINK_LAYER_STATS;
97         case WIFI_FEATURE_RSSI_MONITOR:
98             return HidlStaIfaceCaps::RSSI_MONITOR;
99         case WIFI_FEATURE_CONTROL_ROAMING:
100             return HidlStaIfaceCaps::CONTROL_ROAMING;
101         case WIFI_FEATURE_IE_WHITELIST:
102             return HidlStaIfaceCaps::PROBE_IE_WHITELIST;
103         case WIFI_FEATURE_SCAN_RAND:
104             return HidlStaIfaceCaps::SCAN_RAND;
105         case WIFI_FEATURE_INFRA_5G:
106             return HidlStaIfaceCaps::STA_5G;
107         case WIFI_FEATURE_HOTSPOT:
108             return HidlStaIfaceCaps::HOTSPOT;
109         case WIFI_FEATURE_PNO:
110             return HidlStaIfaceCaps::PNO;
111         case WIFI_FEATURE_TDLS:
112             return HidlStaIfaceCaps::TDLS;
113         case WIFI_FEATURE_TDLS_OFFCHANNEL:
114             return HidlStaIfaceCaps::TDLS_OFFCHANNEL;
115         case WIFI_FEATURE_CONFIG_NDO:
116             return HidlStaIfaceCaps::ND_OFFLOAD;
117         case WIFI_FEATURE_MKEEP_ALIVE:
118             return HidlStaIfaceCaps::KEEP_ALIVE;
119     };
120     CHECK(false) << "Unknown legacy feature: " << feature;
121     return {};
122 }
123 
convertLegacyFeaturesToHidlChipCapabilities(uint32_t legacy_feature_set,uint32_t legacy_logger_feature_set,uint32_t * hidl_caps)124 bool convertLegacyFeaturesToHidlChipCapabilities(
125     uint32_t legacy_feature_set, uint32_t legacy_logger_feature_set,
126     uint32_t* hidl_caps) {
127     if (!hidl_caps) {
128         return false;
129     }
130     *hidl_caps = {};
131     using HidlChipCaps = IWifiChip::ChipCapabilityMask;
132     for (const auto feature : {legacy_hal::WIFI_LOGGER_MEMORY_DUMP_SUPPORTED,
133                                legacy_hal::WIFI_LOGGER_DRIVER_DUMP_SUPPORTED,
134                                legacy_hal::WIFI_LOGGER_CONNECT_EVENT_SUPPORTED,
135                                legacy_hal::WIFI_LOGGER_POWER_EVENT_SUPPORTED,
136                                legacy_hal::WIFI_LOGGER_WAKE_LOCK_SUPPORTED}) {
137         if (feature & legacy_logger_feature_set) {
138             *hidl_caps |=
139                 convertLegacyLoggerFeatureToHidlChipCapability(feature);
140         }
141     }
142     for (const auto feature : {WIFI_FEATURE_SET_TX_POWER_LIMIT,
143                                WIFI_FEATURE_USE_BODY_HEAD_SAR,
144                                WIFI_FEATURE_D2D_RTT, WIFI_FEATURE_D2AP_RTT}) {
145         if (feature & legacy_feature_set) {
146             *hidl_caps |= convertLegacyFeatureToHidlChipCapability(feature);
147         }
148     }
149     // There are no flags for these 3 in the legacy feature set. Adding them to
150     // the set because all the current devices support it.
151     *hidl_caps |= HidlChipCaps::DEBUG_RING_BUFFER_VENDOR_DATA;
152     *hidl_caps |= HidlChipCaps::DEBUG_HOST_WAKE_REASON_STATS;
153     *hidl_caps |= HidlChipCaps::DEBUG_ERROR_ALERTS;
154     return true;
155 }
156 
convertLegacyDebugRingBufferFlagsToHidl(uint32_t flag)157 WifiDebugRingBufferFlags convertLegacyDebugRingBufferFlagsToHidl(
158     uint32_t flag) {
159     switch (flag) {
160         case WIFI_RING_BUFFER_FLAG_HAS_BINARY_ENTRIES:
161             return WifiDebugRingBufferFlags::HAS_BINARY_ENTRIES;
162         case WIFI_RING_BUFFER_FLAG_HAS_ASCII_ENTRIES:
163             return WifiDebugRingBufferFlags::HAS_ASCII_ENTRIES;
164     };
165     CHECK(false) << "Unknown legacy flag: " << flag;
166     return {};
167 }
168 
convertLegacyDebugRingBufferStatusToHidl(const legacy_hal::wifi_ring_buffer_status & legacy_status,WifiDebugRingBufferStatus * hidl_status)169 bool convertLegacyDebugRingBufferStatusToHidl(
170     const legacy_hal::wifi_ring_buffer_status& legacy_status,
171     WifiDebugRingBufferStatus* hidl_status) {
172     if (!hidl_status) {
173         return false;
174     }
175     *hidl_status = {};
176     hidl_status->ringName =
177         safeConvertChar(reinterpret_cast<const char*>(legacy_status.name),
178                         sizeof(legacy_status.name));
179     hidl_status->flags = 0;
180     for (const auto flag : {WIFI_RING_BUFFER_FLAG_HAS_BINARY_ENTRIES,
181                             WIFI_RING_BUFFER_FLAG_HAS_ASCII_ENTRIES}) {
182         if (flag & legacy_status.flags) {
183             hidl_status->flags |= static_cast<
184                 std::underlying_type<WifiDebugRingBufferFlags>::type>(
185                 convertLegacyDebugRingBufferFlagsToHidl(flag));
186         }
187     }
188     hidl_status->ringId = legacy_status.ring_id;
189     hidl_status->sizeInBytes = legacy_status.ring_buffer_byte_size;
190     // Calculate free size of the ring the buffer. We don't need to send the
191     // exact read/write pointers that were there in the legacy HAL interface.
192     if (legacy_status.written_bytes >= legacy_status.read_bytes) {
193         hidl_status->freeSizeInBytes =
194             legacy_status.ring_buffer_byte_size -
195             (legacy_status.written_bytes - legacy_status.read_bytes);
196     } else {
197         hidl_status->freeSizeInBytes =
198             legacy_status.read_bytes - legacy_status.written_bytes;
199     }
200     hidl_status->verboseLevel = legacy_status.verbose_level;
201     return true;
202 }
203 
convertLegacyVectorOfDebugRingBufferStatusToHidl(const std::vector<legacy_hal::wifi_ring_buffer_status> & legacy_status_vec,std::vector<WifiDebugRingBufferStatus> * hidl_status_vec)204 bool convertLegacyVectorOfDebugRingBufferStatusToHidl(
205     const std::vector<legacy_hal::wifi_ring_buffer_status>& legacy_status_vec,
206     std::vector<WifiDebugRingBufferStatus>* hidl_status_vec) {
207     if (!hidl_status_vec) {
208         return false;
209     }
210     *hidl_status_vec = {};
211     for (const auto& legacy_status : legacy_status_vec) {
212         WifiDebugRingBufferStatus hidl_status;
213         if (!convertLegacyDebugRingBufferStatusToHidl(legacy_status,
214                                                       &hidl_status)) {
215             return false;
216         }
217         hidl_status_vec->push_back(hidl_status);
218     }
219     return true;
220 }
221 
convertLegacyWakeReasonStatsToHidl(const legacy_hal::WakeReasonStats & legacy_stats,WifiDebugHostWakeReasonStats * hidl_stats)222 bool convertLegacyWakeReasonStatsToHidl(
223     const legacy_hal::WakeReasonStats& legacy_stats,
224     WifiDebugHostWakeReasonStats* hidl_stats) {
225     if (!hidl_stats) {
226         return false;
227     }
228     *hidl_stats = {};
229     hidl_stats->totalCmdEventWakeCnt =
230         legacy_stats.wake_reason_cnt.total_cmd_event_wake;
231     hidl_stats->cmdEventWakeCntPerType = legacy_stats.cmd_event_wake_cnt;
232     hidl_stats->totalDriverFwLocalWakeCnt =
233         legacy_stats.wake_reason_cnt.total_driver_fw_local_wake;
234     hidl_stats->driverFwLocalWakeCntPerType =
235         legacy_stats.driver_fw_local_wake_cnt;
236     hidl_stats->totalRxPacketWakeCnt =
237         legacy_stats.wake_reason_cnt.total_rx_data_wake;
238     hidl_stats->rxPktWakeDetails.rxUnicastCnt =
239         legacy_stats.wake_reason_cnt.rx_wake_details.rx_unicast_cnt;
240     hidl_stats->rxPktWakeDetails.rxMulticastCnt =
241         legacy_stats.wake_reason_cnt.rx_wake_details.rx_multicast_cnt;
242     hidl_stats->rxPktWakeDetails.rxBroadcastCnt =
243         legacy_stats.wake_reason_cnt.rx_wake_details.rx_broadcast_cnt;
244     hidl_stats->rxMulticastPkWakeDetails.ipv4RxMulticastAddrCnt =
245         legacy_stats.wake_reason_cnt.rx_multicast_wake_pkt_info
246             .ipv4_rx_multicast_addr_cnt;
247     hidl_stats->rxMulticastPkWakeDetails.ipv6RxMulticastAddrCnt =
248         legacy_stats.wake_reason_cnt.rx_multicast_wake_pkt_info
249             .ipv6_rx_multicast_addr_cnt;
250     hidl_stats->rxMulticastPkWakeDetails.otherRxMulticastAddrCnt =
251         legacy_stats.wake_reason_cnt.rx_multicast_wake_pkt_info
252             .other_rx_multicast_addr_cnt;
253     hidl_stats->rxIcmpPkWakeDetails.icmpPkt =
254         legacy_stats.wake_reason_cnt.rx_wake_pkt_classification_info.icmp_pkt;
255     hidl_stats->rxIcmpPkWakeDetails.icmp6Pkt =
256         legacy_stats.wake_reason_cnt.rx_wake_pkt_classification_info.icmp6_pkt;
257     hidl_stats->rxIcmpPkWakeDetails.icmp6Ra =
258         legacy_stats.wake_reason_cnt.rx_wake_pkt_classification_info.icmp6_ra;
259     hidl_stats->rxIcmpPkWakeDetails.icmp6Na =
260         legacy_stats.wake_reason_cnt.rx_wake_pkt_classification_info.icmp6_na;
261     hidl_stats->rxIcmpPkWakeDetails.icmp6Ns =
262         legacy_stats.wake_reason_cnt.rx_wake_pkt_classification_info.icmp6_ns;
263     return true;
264 }
265 
convertHidlTxPowerScenarioToLegacy(V1_1::IWifiChip::TxPowerScenario hidl_scenario)266 legacy_hal::wifi_power_scenario convertHidlTxPowerScenarioToLegacy(
267     V1_1::IWifiChip::TxPowerScenario hidl_scenario) {
268     switch (hidl_scenario) {
269         // This is the only supported scenario for V1_1
270       case V1_1::IWifiChip::TxPowerScenario::VOICE_CALL:
271             return legacy_hal::WIFI_POWER_SCENARIO_VOICE_CALL;
272     };
273     CHECK(false);
274 }
275 
convertHidlTxPowerScenarioToLegacy_1_2(IWifiChip::TxPowerScenario hidl_scenario)276 legacy_hal::wifi_power_scenario convertHidlTxPowerScenarioToLegacy_1_2(
277     IWifiChip::TxPowerScenario hidl_scenario) {
278     switch (hidl_scenario) {
279         // This is the only supported scenario for V1_1
280         case IWifiChip::TxPowerScenario::VOICE_CALL:
281             return legacy_hal::WIFI_POWER_SCENARIO_VOICE_CALL;
282         // Those are the supported scenarios for V1_2
283         case IWifiChip::TxPowerScenario::ON_HEAD_CELL_OFF:
284             return legacy_hal::WIFI_POWER_SCENARIO_ON_HEAD_CELL_OFF;
285         case IWifiChip::TxPowerScenario::ON_HEAD_CELL_ON:
286             return legacy_hal::WIFI_POWER_SCENARIO_ON_HEAD_CELL_ON;
287         case IWifiChip::TxPowerScenario::ON_BODY_CELL_OFF:
288             return legacy_hal::WIFI_POWER_SCENARIO_ON_BODY_CELL_OFF;
289         case IWifiChip::TxPowerScenario::ON_BODY_CELL_ON:
290             return legacy_hal::WIFI_POWER_SCENARIO_ON_BODY_CELL_ON;
291     };
292     CHECK(false);
293 }
294 
convertLegacyWifiMacInfoToHidl(const legacy_hal::WifiMacInfo & legacy_mac_info,IWifiChipEventCallback::RadioModeInfo * hidl_radio_mode_info)295 bool convertLegacyWifiMacInfoToHidl(
296     const legacy_hal::WifiMacInfo& legacy_mac_info,
297     IWifiChipEventCallback::RadioModeInfo* hidl_radio_mode_info) {
298     if (!hidl_radio_mode_info) {
299         return false;
300     }
301     *hidl_radio_mode_info = {};
302 
303     hidl_radio_mode_info->radioId = legacy_mac_info.wlan_mac_id;
304     // Convert from bitmask of bands in the legacy HAL to enum value in
305     // the HIDL interface.
306     if (legacy_mac_info.mac_band & legacy_hal::WLAN_MAC_2_4_BAND &&
307         legacy_mac_info.mac_band & legacy_hal::WLAN_MAC_5_0_BAND) {
308         hidl_radio_mode_info->bandInfo = WifiBand::BAND_24GHZ_5GHZ;
309     } else if (legacy_mac_info.mac_band & legacy_hal::WLAN_MAC_2_4_BAND) {
310         hidl_radio_mode_info->bandInfo = WifiBand::BAND_24GHZ;
311     } else if (legacy_mac_info.mac_band & legacy_hal::WLAN_MAC_5_0_BAND) {
312         hidl_radio_mode_info->bandInfo = WifiBand::BAND_5GHZ;
313     } else {
314         hidl_radio_mode_info->bandInfo = WifiBand::BAND_UNSPECIFIED;
315     }
316     std::vector<IWifiChipEventCallback::IfaceInfo> iface_info_vec;
317     for (const auto& legacy_iface_info : legacy_mac_info.iface_infos) {
318         IWifiChipEventCallback::IfaceInfo iface_info;
319         iface_info.name = legacy_iface_info.name;
320         iface_info.channel = legacy_iface_info.channel;
321         iface_info_vec.push_back(iface_info);
322     }
323     hidl_radio_mode_info->ifaceInfos = iface_info_vec;
324     return true;
325 }
326 
convertLegacyWifiMacInfosToHidl(const std::vector<legacy_hal::WifiMacInfo> & legacy_mac_infos,std::vector<IWifiChipEventCallback::RadioModeInfo> * hidl_radio_mode_infos)327 bool convertLegacyWifiMacInfosToHidl(
328     const std::vector<legacy_hal::WifiMacInfo>& legacy_mac_infos,
329     std::vector<IWifiChipEventCallback::RadioModeInfo>* hidl_radio_mode_infos) {
330     if (!hidl_radio_mode_infos) {
331         return false;
332     }
333     *hidl_radio_mode_infos = {};
334 
335     for (const auto& legacy_mac_info : legacy_mac_infos) {
336         IWifiChipEventCallback::RadioModeInfo hidl_radio_mode_info;
337         if (!convertLegacyWifiMacInfoToHidl(legacy_mac_info,
338                                             &hidl_radio_mode_info)) {
339             return false;
340         }
341         hidl_radio_mode_infos->push_back(hidl_radio_mode_info);
342     }
343     return true;
344 }
345 
convertLegacyFeaturesToHidlStaCapabilities(uint32_t legacy_feature_set,uint32_t legacy_logger_feature_set,uint32_t * hidl_caps)346 bool convertLegacyFeaturesToHidlStaCapabilities(
347     uint32_t legacy_feature_set, uint32_t legacy_logger_feature_set,
348     uint32_t* hidl_caps) {
349     if (!hidl_caps) {
350         return false;
351     }
352     *hidl_caps = {};
353     using HidlStaIfaceCaps = IWifiStaIface::StaIfaceCapabilityMask;
354     for (const auto feature : {legacy_hal::WIFI_LOGGER_PACKET_FATE_SUPPORTED}) {
355         if (feature & legacy_logger_feature_set) {
356             *hidl_caps |=
357                 convertLegacyLoggerFeatureToHidlStaIfaceCapability(feature);
358         }
359     }
360     for (const auto feature :
361          {WIFI_FEATURE_GSCAN, WIFI_FEATURE_LINK_LAYER_STATS,
362           WIFI_FEATURE_RSSI_MONITOR, WIFI_FEATURE_CONTROL_ROAMING,
363           WIFI_FEATURE_IE_WHITELIST, WIFI_FEATURE_SCAN_RAND,
364           WIFI_FEATURE_INFRA_5G, WIFI_FEATURE_HOTSPOT, WIFI_FEATURE_PNO,
365           WIFI_FEATURE_TDLS, WIFI_FEATURE_TDLS_OFFCHANNEL,
366           WIFI_FEATURE_CONFIG_NDO, WIFI_FEATURE_MKEEP_ALIVE}) {
367         if (feature & legacy_feature_set) {
368             *hidl_caps |= convertLegacyFeatureToHidlStaIfaceCapability(feature);
369         }
370     }
371     // There is no flag for this one in the legacy feature set. Adding it to the
372     // set because all the current devices support it.
373     *hidl_caps |= HidlStaIfaceCaps::APF;
374     return true;
375 }
376 
convertLegacyApfCapabilitiesToHidl(const legacy_hal::PacketFilterCapabilities & legacy_caps,StaApfPacketFilterCapabilities * hidl_caps)377 bool convertLegacyApfCapabilitiesToHidl(
378     const legacy_hal::PacketFilterCapabilities& legacy_caps,
379     StaApfPacketFilterCapabilities* hidl_caps) {
380     if (!hidl_caps) {
381         return false;
382     }
383     *hidl_caps = {};
384     hidl_caps->version = legacy_caps.version;
385     hidl_caps->maxLength = legacy_caps.max_len;
386     return true;
387 }
388 
convertHidlGscanReportEventFlagToLegacy(StaBackgroundScanBucketEventReportSchemeMask hidl_flag)389 uint8_t convertHidlGscanReportEventFlagToLegacy(
390     StaBackgroundScanBucketEventReportSchemeMask hidl_flag) {
391     using HidlFlag = StaBackgroundScanBucketEventReportSchemeMask;
392     switch (hidl_flag) {
393         case HidlFlag::EACH_SCAN:
394             return REPORT_EVENTS_EACH_SCAN;
395         case HidlFlag::FULL_RESULTS:
396             return REPORT_EVENTS_FULL_RESULTS;
397         case HidlFlag::NO_BATCH:
398             return REPORT_EVENTS_NO_BATCH;
399     };
400     CHECK(false);
401 }
402 
convertLegacyGscanDataFlagToHidl(uint8_t legacy_flag)403 StaScanDataFlagMask convertLegacyGscanDataFlagToHidl(uint8_t legacy_flag) {
404     switch (legacy_flag) {
405         case legacy_hal::WIFI_SCAN_FLAG_INTERRUPTED:
406             return StaScanDataFlagMask::INTERRUPTED;
407     };
408     CHECK(false) << "Unknown legacy flag: " << legacy_flag;
409     // To silence the compiler warning about reaching the end of non-void
410     // function.
411     return {};
412 }
413 
convertLegacyGscanCapabilitiesToHidl(const legacy_hal::wifi_gscan_capabilities & legacy_caps,StaBackgroundScanCapabilities * hidl_caps)414 bool convertLegacyGscanCapabilitiesToHidl(
415     const legacy_hal::wifi_gscan_capabilities& legacy_caps,
416     StaBackgroundScanCapabilities* hidl_caps) {
417     if (!hidl_caps) {
418         return false;
419     }
420     *hidl_caps = {};
421     hidl_caps->maxCacheSize = legacy_caps.max_scan_cache_size;
422     hidl_caps->maxBuckets = legacy_caps.max_scan_buckets;
423     hidl_caps->maxApCachePerScan = legacy_caps.max_ap_cache_per_scan;
424     hidl_caps->maxReportingThreshold = legacy_caps.max_scan_reporting_threshold;
425     return true;
426 }
427 
convertHidlWifiBandToLegacy(WifiBand band)428 legacy_hal::wifi_band convertHidlWifiBandToLegacy(WifiBand band) {
429     switch (band) {
430         case WifiBand::BAND_UNSPECIFIED:
431             return legacy_hal::WIFI_BAND_UNSPECIFIED;
432         case WifiBand::BAND_24GHZ:
433             return legacy_hal::WIFI_BAND_BG;
434         case WifiBand::BAND_5GHZ:
435             return legacy_hal::WIFI_BAND_A;
436         case WifiBand::BAND_5GHZ_DFS:
437             return legacy_hal::WIFI_BAND_A_DFS;
438         case WifiBand::BAND_5GHZ_WITH_DFS:
439             return legacy_hal::WIFI_BAND_A_WITH_DFS;
440         case WifiBand::BAND_24GHZ_5GHZ:
441             return legacy_hal::WIFI_BAND_ABG;
442         case WifiBand::BAND_24GHZ_5GHZ_WITH_DFS:
443             return legacy_hal::WIFI_BAND_ABG_WITH_DFS;
444     };
445     CHECK(false);
446 }
447 
convertHidlGscanParamsToLegacy(const StaBackgroundScanParameters & hidl_scan_params,legacy_hal::wifi_scan_cmd_params * legacy_scan_params)448 bool convertHidlGscanParamsToLegacy(
449     const StaBackgroundScanParameters& hidl_scan_params,
450     legacy_hal::wifi_scan_cmd_params* legacy_scan_params) {
451     if (!legacy_scan_params) {
452         return false;
453     }
454     *legacy_scan_params = {};
455     legacy_scan_params->base_period = hidl_scan_params.basePeriodInMs;
456     legacy_scan_params->max_ap_per_scan = hidl_scan_params.maxApPerScan;
457     legacy_scan_params->report_threshold_percent =
458         hidl_scan_params.reportThresholdPercent;
459     legacy_scan_params->report_threshold_num_scans =
460         hidl_scan_params.reportThresholdNumScans;
461     if (hidl_scan_params.buckets.size() > MAX_BUCKETS) {
462         return false;
463     }
464     legacy_scan_params->num_buckets = hidl_scan_params.buckets.size();
465     for (uint32_t bucket_idx = 0; bucket_idx < hidl_scan_params.buckets.size();
466          bucket_idx++) {
467         const StaBackgroundScanBucketParameters& hidl_bucket_spec =
468             hidl_scan_params.buckets[bucket_idx];
469         legacy_hal::wifi_scan_bucket_spec& legacy_bucket_spec =
470             legacy_scan_params->buckets[bucket_idx];
471         if (hidl_bucket_spec.bucketIdx >= MAX_BUCKETS) {
472             return false;
473         }
474         legacy_bucket_spec.bucket = hidl_bucket_spec.bucketIdx;
475         legacy_bucket_spec.band =
476             convertHidlWifiBandToLegacy(hidl_bucket_spec.band);
477         legacy_bucket_spec.period = hidl_bucket_spec.periodInMs;
478         legacy_bucket_spec.max_period =
479             hidl_bucket_spec.exponentialMaxPeriodInMs;
480         legacy_bucket_spec.base = hidl_bucket_spec.exponentialBase;
481         legacy_bucket_spec.step_count = hidl_bucket_spec.exponentialStepCount;
482         legacy_bucket_spec.report_events = 0;
483         using HidlFlag = StaBackgroundScanBucketEventReportSchemeMask;
484         for (const auto flag : {HidlFlag::EACH_SCAN, HidlFlag::FULL_RESULTS,
485                                 HidlFlag::NO_BATCH}) {
486             if (hidl_bucket_spec.eventReportScheme &
487                 static_cast<std::underlying_type<HidlFlag>::type>(flag)) {
488                 legacy_bucket_spec.report_events |=
489                     convertHidlGscanReportEventFlagToLegacy(flag);
490             }
491         }
492         if (hidl_bucket_spec.frequencies.size() > MAX_CHANNELS) {
493             return false;
494         }
495         legacy_bucket_spec.num_channels = hidl_bucket_spec.frequencies.size();
496         for (uint32_t freq_idx = 0;
497              freq_idx < hidl_bucket_spec.frequencies.size(); freq_idx++) {
498             legacy_bucket_spec.channels[freq_idx].channel =
499                 hidl_bucket_spec.frequencies[freq_idx];
500         }
501     }
502     return true;
503 }
504 
convertLegacyIeToHidl(const legacy_hal::wifi_information_element & legacy_ie,WifiInformationElement * hidl_ie)505 bool convertLegacyIeToHidl(
506     const legacy_hal::wifi_information_element& legacy_ie,
507     WifiInformationElement* hidl_ie) {
508     if (!hidl_ie) {
509         return false;
510     }
511     *hidl_ie = {};
512     hidl_ie->id = legacy_ie.id;
513     hidl_ie->data =
514         std::vector<uint8_t>(legacy_ie.data, legacy_ie.data + legacy_ie.len);
515     return true;
516 }
517 
convertLegacyIeBlobToHidl(const uint8_t * ie_blob,uint32_t ie_blob_len,std::vector<WifiInformationElement> * hidl_ies)518 bool convertLegacyIeBlobToHidl(const uint8_t* ie_blob, uint32_t ie_blob_len,
519                                std::vector<WifiInformationElement>* hidl_ies) {
520     if (!ie_blob || !hidl_ies) {
521         return false;
522     }
523     *hidl_ies = {};
524     const uint8_t* ies_begin = ie_blob;
525     const uint8_t* ies_end = ie_blob + ie_blob_len;
526     const uint8_t* next_ie = ies_begin;
527     using wifi_ie = legacy_hal::wifi_information_element;
528     constexpr size_t kIeHeaderLen = sizeof(wifi_ie);
529     // Each IE should atleast have the header (i.e |id| & |len| fields).
530     while (next_ie + kIeHeaderLen <= ies_end) {
531         const wifi_ie& legacy_ie = (*reinterpret_cast<const wifi_ie*>(next_ie));
532         uint32_t curr_ie_len = kIeHeaderLen + legacy_ie.len;
533         if (next_ie + curr_ie_len > ies_end) {
534             LOG(ERROR) << "Error parsing IE blob. Next IE: " << (void*)next_ie
535                        << ", Curr IE len: " << curr_ie_len
536                        << ", IEs End: " << (void*)ies_end;
537             break;
538         }
539         WifiInformationElement hidl_ie;
540         if (!convertLegacyIeToHidl(legacy_ie, &hidl_ie)) {
541             LOG(ERROR) << "Error converting IE. Id: " << legacy_ie.id
542                        << ", len: " << legacy_ie.len;
543             break;
544         }
545         hidl_ies->push_back(std::move(hidl_ie));
546         next_ie += curr_ie_len;
547     }
548     // Check if the blob has been fully consumed.
549     if (next_ie != ies_end) {
550         LOG(ERROR) << "Failed to fully parse IE blob. Next IE: "
551                    << (void*)next_ie << ", IEs End: " << (void*)ies_end;
552     }
553     return true;
554 }
555 
convertLegacyGscanResultToHidl(const legacy_hal::wifi_scan_result & legacy_scan_result,bool has_ie_data,StaScanResult * hidl_scan_result)556 bool convertLegacyGscanResultToHidl(
557     const legacy_hal::wifi_scan_result& legacy_scan_result, bool has_ie_data,
558     StaScanResult* hidl_scan_result) {
559     if (!hidl_scan_result) {
560         return false;
561     }
562     *hidl_scan_result = {};
563     hidl_scan_result->timeStampInUs = legacy_scan_result.ts;
564     hidl_scan_result->ssid = std::vector<uint8_t>(
565         legacy_scan_result.ssid,
566         legacy_scan_result.ssid + strnlen(legacy_scan_result.ssid,
567                                           sizeof(legacy_scan_result.ssid) - 1));
568     memcpy(hidl_scan_result->bssid.data(), legacy_scan_result.bssid,
569            hidl_scan_result->bssid.size());
570     hidl_scan_result->frequency = legacy_scan_result.channel;
571     hidl_scan_result->rssi = legacy_scan_result.rssi;
572     hidl_scan_result->beaconPeriodInMs = legacy_scan_result.beacon_period;
573     hidl_scan_result->capability = legacy_scan_result.capability;
574     if (has_ie_data) {
575         std::vector<WifiInformationElement> ies;
576         if (!convertLegacyIeBlobToHidl(
577                 reinterpret_cast<const uint8_t*>(legacy_scan_result.ie_data),
578                 legacy_scan_result.ie_length, &ies)) {
579             return false;
580         }
581         hidl_scan_result->informationElements = std::move(ies);
582     }
583     return true;
584 }
585 
convertLegacyCachedGscanResultsToHidl(const legacy_hal::wifi_cached_scan_results & legacy_cached_scan_result,StaScanData * hidl_scan_data)586 bool convertLegacyCachedGscanResultsToHidl(
587     const legacy_hal::wifi_cached_scan_results& legacy_cached_scan_result,
588     StaScanData* hidl_scan_data) {
589     if (!hidl_scan_data) {
590         return false;
591     }
592     *hidl_scan_data = {};
593     hidl_scan_data->flags = 0;
594     for (const auto flag : {legacy_hal::WIFI_SCAN_FLAG_INTERRUPTED}) {
595         if (legacy_cached_scan_result.flags & flag) {
596             hidl_scan_data->flags |=
597                 static_cast<std::underlying_type<StaScanDataFlagMask>::type>(
598                     convertLegacyGscanDataFlagToHidl(flag));
599         }
600     }
601     hidl_scan_data->bucketsScanned = legacy_cached_scan_result.buckets_scanned;
602 
603     CHECK(legacy_cached_scan_result.num_results >= 0 &&
604           legacy_cached_scan_result.num_results <= MAX_AP_CACHE_PER_SCAN);
605     std::vector<StaScanResult> hidl_scan_results;
606     for (int32_t result_idx = 0;
607          result_idx < legacy_cached_scan_result.num_results; result_idx++) {
608         StaScanResult hidl_scan_result;
609         if (!convertLegacyGscanResultToHidl(
610                 legacy_cached_scan_result.results[result_idx], false,
611                 &hidl_scan_result)) {
612             return false;
613         }
614         hidl_scan_results.push_back(hidl_scan_result);
615     }
616     hidl_scan_data->results = std::move(hidl_scan_results);
617     return true;
618 }
619 
convertLegacyVectorOfCachedGscanResultsToHidl(const std::vector<legacy_hal::wifi_cached_scan_results> & legacy_cached_scan_results,std::vector<StaScanData> * hidl_scan_datas)620 bool convertLegacyVectorOfCachedGscanResultsToHidl(
621     const std::vector<legacy_hal::wifi_cached_scan_results>&
622         legacy_cached_scan_results,
623     std::vector<StaScanData>* hidl_scan_datas) {
624     if (!hidl_scan_datas) {
625         return false;
626     }
627     *hidl_scan_datas = {};
628     for (const auto& legacy_cached_scan_result : legacy_cached_scan_results) {
629         StaScanData hidl_scan_data;
630         if (!convertLegacyCachedGscanResultsToHidl(legacy_cached_scan_result,
631                                                    &hidl_scan_data)) {
632             return false;
633         }
634         hidl_scan_datas->push_back(hidl_scan_data);
635     }
636     return true;
637 }
638 
convertLegacyDebugTxPacketFateToHidl(legacy_hal::wifi_tx_packet_fate fate)639 WifiDebugTxPacketFate convertLegacyDebugTxPacketFateToHidl(
640     legacy_hal::wifi_tx_packet_fate fate) {
641     switch (fate) {
642         case legacy_hal::TX_PKT_FATE_ACKED:
643             return WifiDebugTxPacketFate::ACKED;
644         case legacy_hal::TX_PKT_FATE_SENT:
645             return WifiDebugTxPacketFate::SENT;
646         case legacy_hal::TX_PKT_FATE_FW_QUEUED:
647             return WifiDebugTxPacketFate::FW_QUEUED;
648         case legacy_hal::TX_PKT_FATE_FW_DROP_INVALID:
649             return WifiDebugTxPacketFate::FW_DROP_INVALID;
650         case legacy_hal::TX_PKT_FATE_FW_DROP_NOBUFS:
651             return WifiDebugTxPacketFate::FW_DROP_NOBUFS;
652         case legacy_hal::TX_PKT_FATE_FW_DROP_OTHER:
653             return WifiDebugTxPacketFate::FW_DROP_OTHER;
654         case legacy_hal::TX_PKT_FATE_DRV_QUEUED:
655             return WifiDebugTxPacketFate::DRV_QUEUED;
656         case legacy_hal::TX_PKT_FATE_DRV_DROP_INVALID:
657             return WifiDebugTxPacketFate::DRV_DROP_INVALID;
658         case legacy_hal::TX_PKT_FATE_DRV_DROP_NOBUFS:
659             return WifiDebugTxPacketFate::DRV_DROP_NOBUFS;
660         case legacy_hal::TX_PKT_FATE_DRV_DROP_OTHER:
661             return WifiDebugTxPacketFate::DRV_DROP_OTHER;
662     };
663     CHECK(false) << "Unknown legacy fate type: " << fate;
664 }
665 
convertLegacyDebugRxPacketFateToHidl(legacy_hal::wifi_rx_packet_fate fate)666 WifiDebugRxPacketFate convertLegacyDebugRxPacketFateToHidl(
667     legacy_hal::wifi_rx_packet_fate fate) {
668     switch (fate) {
669         case legacy_hal::RX_PKT_FATE_SUCCESS:
670             return WifiDebugRxPacketFate::SUCCESS;
671         case legacy_hal::RX_PKT_FATE_FW_QUEUED:
672             return WifiDebugRxPacketFate::FW_QUEUED;
673         case legacy_hal::RX_PKT_FATE_FW_DROP_FILTER:
674             return WifiDebugRxPacketFate::FW_DROP_FILTER;
675         case legacy_hal::RX_PKT_FATE_FW_DROP_INVALID:
676             return WifiDebugRxPacketFate::FW_DROP_INVALID;
677         case legacy_hal::RX_PKT_FATE_FW_DROP_NOBUFS:
678             return WifiDebugRxPacketFate::FW_DROP_NOBUFS;
679         case legacy_hal::RX_PKT_FATE_FW_DROP_OTHER:
680             return WifiDebugRxPacketFate::FW_DROP_OTHER;
681         case legacy_hal::RX_PKT_FATE_DRV_QUEUED:
682             return WifiDebugRxPacketFate::DRV_QUEUED;
683         case legacy_hal::RX_PKT_FATE_DRV_DROP_FILTER:
684             return WifiDebugRxPacketFate::DRV_DROP_FILTER;
685         case legacy_hal::RX_PKT_FATE_DRV_DROP_INVALID:
686             return WifiDebugRxPacketFate::DRV_DROP_INVALID;
687         case legacy_hal::RX_PKT_FATE_DRV_DROP_NOBUFS:
688             return WifiDebugRxPacketFate::DRV_DROP_NOBUFS;
689         case legacy_hal::RX_PKT_FATE_DRV_DROP_OTHER:
690             return WifiDebugRxPacketFate::DRV_DROP_OTHER;
691     };
692     CHECK(false) << "Unknown legacy fate type: " << fate;
693 }
694 
convertLegacyDebugPacketFateFrameTypeToHidl(legacy_hal::frame_type type)695 WifiDebugPacketFateFrameType convertLegacyDebugPacketFateFrameTypeToHidl(
696     legacy_hal::frame_type type) {
697     switch (type) {
698         case legacy_hal::FRAME_TYPE_UNKNOWN:
699             return WifiDebugPacketFateFrameType::UNKNOWN;
700         case legacy_hal::FRAME_TYPE_ETHERNET_II:
701             return WifiDebugPacketFateFrameType::ETHERNET_II;
702         case legacy_hal::FRAME_TYPE_80211_MGMT:
703             return WifiDebugPacketFateFrameType::MGMT_80211;
704     };
705     CHECK(false) << "Unknown legacy frame type: " << type;
706 }
707 
convertLegacyDebugPacketFateFrameToHidl(const legacy_hal::frame_info & legacy_frame,WifiDebugPacketFateFrameInfo * hidl_frame)708 bool convertLegacyDebugPacketFateFrameToHidl(
709     const legacy_hal::frame_info& legacy_frame,
710     WifiDebugPacketFateFrameInfo* hidl_frame) {
711     if (!hidl_frame) {
712         return false;
713     }
714     *hidl_frame = {};
715     hidl_frame->frameType =
716         convertLegacyDebugPacketFateFrameTypeToHidl(legacy_frame.payload_type);
717     hidl_frame->frameLen = legacy_frame.frame_len;
718     hidl_frame->driverTimestampUsec = legacy_frame.driver_timestamp_usec;
719     hidl_frame->firmwareTimestampUsec = legacy_frame.firmware_timestamp_usec;
720     const uint8_t* frame_begin = reinterpret_cast<const uint8_t*>(
721         legacy_frame.frame_content.ethernet_ii_bytes);
722     hidl_frame->frameContent =
723         std::vector<uint8_t>(frame_begin, frame_begin + legacy_frame.frame_len);
724     return true;
725 }
726 
convertLegacyDebugTxPacketFateToHidl(const legacy_hal::wifi_tx_report & legacy_fate,WifiDebugTxPacketFateReport * hidl_fate)727 bool convertLegacyDebugTxPacketFateToHidl(
728     const legacy_hal::wifi_tx_report& legacy_fate,
729     WifiDebugTxPacketFateReport* hidl_fate) {
730     if (!hidl_fate) {
731         return false;
732     }
733     *hidl_fate = {};
734     hidl_fate->fate = convertLegacyDebugTxPacketFateToHidl(legacy_fate.fate);
735     return convertLegacyDebugPacketFateFrameToHidl(legacy_fate.frame_inf,
736                                                    &hidl_fate->frameInfo);
737 }
738 
convertLegacyVectorOfDebugTxPacketFateToHidl(const std::vector<legacy_hal::wifi_tx_report> & legacy_fates,std::vector<WifiDebugTxPacketFateReport> * hidl_fates)739 bool convertLegacyVectorOfDebugTxPacketFateToHidl(
740     const std::vector<legacy_hal::wifi_tx_report>& legacy_fates,
741     std::vector<WifiDebugTxPacketFateReport>* hidl_fates) {
742     if (!hidl_fates) {
743         return false;
744     }
745     *hidl_fates = {};
746     for (const auto& legacy_fate : legacy_fates) {
747         WifiDebugTxPacketFateReport hidl_fate;
748         if (!convertLegacyDebugTxPacketFateToHidl(legacy_fate, &hidl_fate)) {
749             return false;
750         }
751         hidl_fates->push_back(hidl_fate);
752     }
753     return true;
754 }
755 
convertLegacyDebugRxPacketFateToHidl(const legacy_hal::wifi_rx_report & legacy_fate,WifiDebugRxPacketFateReport * hidl_fate)756 bool convertLegacyDebugRxPacketFateToHidl(
757     const legacy_hal::wifi_rx_report& legacy_fate,
758     WifiDebugRxPacketFateReport* hidl_fate) {
759     if (!hidl_fate) {
760         return false;
761     }
762     *hidl_fate = {};
763     hidl_fate->fate = convertLegacyDebugRxPacketFateToHidl(legacy_fate.fate);
764     return convertLegacyDebugPacketFateFrameToHidl(legacy_fate.frame_inf,
765                                                    &hidl_fate->frameInfo);
766 }
767 
convertLegacyVectorOfDebugRxPacketFateToHidl(const std::vector<legacy_hal::wifi_rx_report> & legacy_fates,std::vector<WifiDebugRxPacketFateReport> * hidl_fates)768 bool convertLegacyVectorOfDebugRxPacketFateToHidl(
769     const std::vector<legacy_hal::wifi_rx_report>& legacy_fates,
770     std::vector<WifiDebugRxPacketFateReport>* hidl_fates) {
771     if (!hidl_fates) {
772         return false;
773     }
774     *hidl_fates = {};
775     for (const auto& legacy_fate : legacy_fates) {
776         WifiDebugRxPacketFateReport hidl_fate;
777         if (!convertLegacyDebugRxPacketFateToHidl(legacy_fate, &hidl_fate)) {
778             return false;
779         }
780         hidl_fates->push_back(hidl_fate);
781     }
782     return true;
783 }
784 
convertLegacyLinkLayerStatsToHidl(const legacy_hal::LinkLayerStats & legacy_stats,StaLinkLayerStats * hidl_stats)785 bool convertLegacyLinkLayerStatsToHidl(
786     const legacy_hal::LinkLayerStats& legacy_stats,
787     StaLinkLayerStats* hidl_stats) {
788     if (!hidl_stats) {
789         return false;
790     }
791     *hidl_stats = {};
792     // iface legacy_stats conversion.
793     hidl_stats->iface.beaconRx = legacy_stats.iface.beacon_rx;
794     hidl_stats->iface.avgRssiMgmt = legacy_stats.iface.rssi_mgmt;
795     hidl_stats->iface.wmeBePktStats.rxMpdu =
796         legacy_stats.iface.ac[legacy_hal::WIFI_AC_BE].rx_mpdu;
797     hidl_stats->iface.wmeBePktStats.txMpdu =
798         legacy_stats.iface.ac[legacy_hal::WIFI_AC_BE].tx_mpdu;
799     hidl_stats->iface.wmeBePktStats.lostMpdu =
800         legacy_stats.iface.ac[legacy_hal::WIFI_AC_BE].mpdu_lost;
801     hidl_stats->iface.wmeBePktStats.retries =
802         legacy_stats.iface.ac[legacy_hal::WIFI_AC_BE].retries;
803     hidl_stats->iface.wmeBkPktStats.rxMpdu =
804         legacy_stats.iface.ac[legacy_hal::WIFI_AC_BK].rx_mpdu;
805     hidl_stats->iface.wmeBkPktStats.txMpdu =
806         legacy_stats.iface.ac[legacy_hal::WIFI_AC_BK].tx_mpdu;
807     hidl_stats->iface.wmeBkPktStats.lostMpdu =
808         legacy_stats.iface.ac[legacy_hal::WIFI_AC_BK].mpdu_lost;
809     hidl_stats->iface.wmeBkPktStats.retries =
810         legacy_stats.iface.ac[legacy_hal::WIFI_AC_BK].retries;
811     hidl_stats->iface.wmeViPktStats.rxMpdu =
812         legacy_stats.iface.ac[legacy_hal::WIFI_AC_VI].rx_mpdu;
813     hidl_stats->iface.wmeViPktStats.txMpdu =
814         legacy_stats.iface.ac[legacy_hal::WIFI_AC_VI].tx_mpdu;
815     hidl_stats->iface.wmeViPktStats.lostMpdu =
816         legacy_stats.iface.ac[legacy_hal::WIFI_AC_VI].mpdu_lost;
817     hidl_stats->iface.wmeViPktStats.retries =
818         legacy_stats.iface.ac[legacy_hal::WIFI_AC_VI].retries;
819     hidl_stats->iface.wmeVoPktStats.rxMpdu =
820         legacy_stats.iface.ac[legacy_hal::WIFI_AC_VO].rx_mpdu;
821     hidl_stats->iface.wmeVoPktStats.txMpdu =
822         legacy_stats.iface.ac[legacy_hal::WIFI_AC_VO].tx_mpdu;
823     hidl_stats->iface.wmeVoPktStats.lostMpdu =
824         legacy_stats.iface.ac[legacy_hal::WIFI_AC_VO].mpdu_lost;
825     hidl_stats->iface.wmeVoPktStats.retries =
826         legacy_stats.iface.ac[legacy_hal::WIFI_AC_VO].retries;
827     // radio legacy_stats conversion.
828     std::vector<StaLinkLayerRadioStats> hidl_radios_stats;
829     for (const auto& legacy_radio_stats : legacy_stats.radios) {
830         StaLinkLayerRadioStats hidl_radio_stats;
831         hidl_radio_stats.onTimeInMs = legacy_radio_stats.stats.on_time;
832         hidl_radio_stats.txTimeInMs = legacy_radio_stats.stats.tx_time;
833         hidl_radio_stats.rxTimeInMs = legacy_radio_stats.stats.rx_time;
834         hidl_radio_stats.onTimeInMsForScan =
835             legacy_radio_stats.stats.on_time_scan;
836         hidl_radio_stats.txTimeInMsPerLevel =
837             legacy_radio_stats.tx_time_per_levels;
838         hidl_radios_stats.push_back(hidl_radio_stats);
839     }
840     hidl_stats->radios = hidl_radios_stats;
841     // Timestamp in the HAL wrapper here since it's not provided in the legacy
842     // HAL API.
843     hidl_stats->timeStampInMs = uptimeMillis();
844     return true;
845 }
846 
convertLegacyRoamingCapabilitiesToHidl(const legacy_hal::wifi_roaming_capabilities & legacy_caps,StaRoamingCapabilities * hidl_caps)847 bool convertLegacyRoamingCapabilitiesToHidl(
848     const legacy_hal::wifi_roaming_capabilities& legacy_caps,
849     StaRoamingCapabilities* hidl_caps) {
850     if (!hidl_caps) {
851         return false;
852     }
853     *hidl_caps = {};
854     hidl_caps->maxBlacklistSize = legacy_caps.max_blacklist_size;
855     hidl_caps->maxWhitelistSize = legacy_caps.max_whitelist_size;
856     return true;
857 }
858 
convertHidlRoamingConfigToLegacy(const StaRoamingConfig & hidl_config,legacy_hal::wifi_roaming_config * legacy_config)859 bool convertHidlRoamingConfigToLegacy(
860     const StaRoamingConfig& hidl_config,
861     legacy_hal::wifi_roaming_config* legacy_config) {
862     if (!legacy_config) {
863         return false;
864     }
865     *legacy_config = {};
866     if (hidl_config.bssidBlacklist.size() > MAX_BLACKLIST_BSSID ||
867         hidl_config.ssidWhitelist.size() > MAX_WHITELIST_SSID) {
868         return false;
869     }
870     legacy_config->num_blacklist_bssid = hidl_config.bssidBlacklist.size();
871     uint32_t i = 0;
872     for (const auto& bssid : hidl_config.bssidBlacklist) {
873         CHECK(bssid.size() == sizeof(legacy_hal::mac_addr));
874         memcpy(legacy_config->blacklist_bssid[i++], bssid.data(), bssid.size());
875     }
876     legacy_config->num_whitelist_ssid = hidl_config.ssidWhitelist.size();
877     i = 0;
878     for (const auto& ssid : hidl_config.ssidWhitelist) {
879         CHECK(ssid.size() <= sizeof(legacy_hal::ssid_t::ssid_str));
880         legacy_config->whitelist_ssid[i].length = ssid.size();
881         memcpy(legacy_config->whitelist_ssid[i].ssid_str, ssid.data(),
882                ssid.size());
883         i++;
884     }
885     return true;
886 }
887 
convertHidlRoamingStateToLegacy(StaRoamingState state)888 legacy_hal::fw_roaming_state_t convertHidlRoamingStateToLegacy(
889     StaRoamingState state) {
890     switch (state) {
891         case StaRoamingState::ENABLED:
892             return legacy_hal::ROAMING_ENABLE;
893         case StaRoamingState::DISABLED:
894             return legacy_hal::ROAMING_DISABLE;
895     };
896     CHECK(false);
897 }
898 
convertHidlNanMatchAlgToLegacy(NanMatchAlg type)899 legacy_hal::NanMatchAlg convertHidlNanMatchAlgToLegacy(NanMatchAlg type) {
900     switch (type) {
901         case NanMatchAlg::MATCH_ONCE:
902             return legacy_hal::NAN_MATCH_ALG_MATCH_ONCE;
903         case NanMatchAlg::MATCH_CONTINUOUS:
904             return legacy_hal::NAN_MATCH_ALG_MATCH_CONTINUOUS;
905         case NanMatchAlg::MATCH_NEVER:
906             return legacy_hal::NAN_MATCH_ALG_MATCH_NEVER;
907     }
908     CHECK(false);
909 }
910 
convertHidlNanPublishTypeToLegacy(NanPublishType type)911 legacy_hal::NanPublishType convertHidlNanPublishTypeToLegacy(
912     NanPublishType type) {
913     switch (type) {
914         case NanPublishType::UNSOLICITED:
915             return legacy_hal::NAN_PUBLISH_TYPE_UNSOLICITED;
916         case NanPublishType::SOLICITED:
917             return legacy_hal::NAN_PUBLISH_TYPE_SOLICITED;
918         case NanPublishType::UNSOLICITED_SOLICITED:
919             return legacy_hal::NAN_PUBLISH_TYPE_UNSOLICITED_SOLICITED;
920     }
921     CHECK(false);
922 }
923 
convertHidlNanTxTypeToLegacy(NanTxType type)924 legacy_hal::NanTxType convertHidlNanTxTypeToLegacy(NanTxType type) {
925     switch (type) {
926         case NanTxType::BROADCAST:
927             return legacy_hal::NAN_TX_TYPE_BROADCAST;
928         case NanTxType::UNICAST:
929             return legacy_hal::NAN_TX_TYPE_UNICAST;
930     }
931     CHECK(false);
932 }
933 
convertHidlNanSubscribeTypeToLegacy(NanSubscribeType type)934 legacy_hal::NanSubscribeType convertHidlNanSubscribeTypeToLegacy(
935     NanSubscribeType type) {
936     switch (type) {
937         case NanSubscribeType::PASSIVE:
938             return legacy_hal::NAN_SUBSCRIBE_TYPE_PASSIVE;
939         case NanSubscribeType::ACTIVE:
940             return legacy_hal::NAN_SUBSCRIBE_TYPE_ACTIVE;
941     }
942     CHECK(false);
943 }
944 
convertHidlNanSrfTypeToLegacy(NanSrfType type)945 legacy_hal::NanSRFType convertHidlNanSrfTypeToLegacy(NanSrfType type) {
946     switch (type) {
947         case NanSrfType::BLOOM_FILTER:
948             return legacy_hal::NAN_SRF_ATTR_BLOOM_FILTER;
949         case NanSrfType::PARTIAL_MAC_ADDR:
950             return legacy_hal::NAN_SRF_ATTR_PARTIAL_MAC_ADDR;
951     }
952     CHECK(false);
953 }
954 
convertHidlNanDataPathChannelCfgToLegacy(NanDataPathChannelCfg type)955 legacy_hal::NanDataPathChannelCfg convertHidlNanDataPathChannelCfgToLegacy(
956     NanDataPathChannelCfg type) {
957     switch (type) {
958         case NanDataPathChannelCfg::CHANNEL_NOT_REQUESTED:
959             return legacy_hal::NAN_DP_CHANNEL_NOT_REQUESTED;
960         case NanDataPathChannelCfg::REQUEST_CHANNEL_SETUP:
961             return legacy_hal::NAN_DP_REQUEST_CHANNEL_SETUP;
962         case NanDataPathChannelCfg::FORCE_CHANNEL_SETUP:
963             return legacy_hal::NAN_DP_FORCE_CHANNEL_SETUP;
964     }
965     CHECK(false);
966 }
967 
convertLegacyNanStatusTypeToHidl(legacy_hal::NanStatusType type)968 NanStatusType convertLegacyNanStatusTypeToHidl(legacy_hal::NanStatusType type) {
969     switch (type) {
970         case legacy_hal::NAN_STATUS_SUCCESS:
971             return NanStatusType::SUCCESS;
972         case legacy_hal::NAN_STATUS_INTERNAL_FAILURE:
973             return NanStatusType::INTERNAL_FAILURE;
974         case legacy_hal::NAN_STATUS_PROTOCOL_FAILURE:
975             return NanStatusType::PROTOCOL_FAILURE;
976         case legacy_hal::NAN_STATUS_INVALID_PUBLISH_SUBSCRIBE_ID:
977             return NanStatusType::INVALID_SESSION_ID;
978         case legacy_hal::NAN_STATUS_NO_RESOURCE_AVAILABLE:
979             return NanStatusType::NO_RESOURCES_AVAILABLE;
980         case legacy_hal::NAN_STATUS_INVALID_PARAM:
981             return NanStatusType::INVALID_ARGS;
982         case legacy_hal::NAN_STATUS_INVALID_REQUESTOR_INSTANCE_ID:
983             return NanStatusType::INVALID_PEER_ID;
984         case legacy_hal::NAN_STATUS_INVALID_NDP_ID:
985             return NanStatusType::INVALID_NDP_ID;
986         case legacy_hal::NAN_STATUS_NAN_NOT_ALLOWED:
987             return NanStatusType::NAN_NOT_ALLOWED;
988         case legacy_hal::NAN_STATUS_NO_OTA_ACK:
989             return NanStatusType::NO_OTA_ACK;
990         case legacy_hal::NAN_STATUS_ALREADY_ENABLED:
991             return NanStatusType::ALREADY_ENABLED;
992         case legacy_hal::NAN_STATUS_FOLLOWUP_QUEUE_FULL:
993             return NanStatusType::FOLLOWUP_TX_QUEUE_FULL;
994         case legacy_hal::NAN_STATUS_UNSUPPORTED_CONCURRENCY_NAN_DISABLED:
995             return NanStatusType::UNSUPPORTED_CONCURRENCY_NAN_DISABLED;
996     }
997     CHECK(false);
998 }
999 
convertToWifiNanStatus(legacy_hal::NanStatusType type,const char * str,size_t max_len,WifiNanStatus * wifiNanStatus)1000 void convertToWifiNanStatus(legacy_hal::NanStatusType type, const char* str,
1001                             size_t max_len, WifiNanStatus* wifiNanStatus) {
1002     wifiNanStatus->status = convertLegacyNanStatusTypeToHidl(type);
1003     wifiNanStatus->description = safeConvertChar(str, max_len);
1004 }
1005 
convertHidlNanEnableRequestToLegacy(const NanEnableRequest & hidl_request,legacy_hal::NanEnableRequest * legacy_request)1006 bool convertHidlNanEnableRequestToLegacy(
1007     const NanEnableRequest& hidl_request,
1008     legacy_hal::NanEnableRequest* legacy_request) {
1009     if (!legacy_request) {
1010         LOG(ERROR)
1011             << "convertHidlNanEnableRequestToLegacy: null legacy_request";
1012         return false;
1013     }
1014     *legacy_request = {};
1015 
1016     legacy_request->config_2dot4g_support = 1;
1017     legacy_request->support_2dot4g_val =
1018         hidl_request.operateInBand[(size_t)NanBandIndex::NAN_BAND_24GHZ];
1019     legacy_request->config_support_5g = 1;
1020     legacy_request->support_5g_val =
1021         hidl_request.operateInBand[(size_t)NanBandIndex::NAN_BAND_5GHZ];
1022     legacy_request->config_hop_count_limit = 1;
1023     legacy_request->hop_count_limit_val = hidl_request.hopCountMax;
1024     legacy_request->master_pref = hidl_request.configParams.masterPref;
1025     legacy_request->discovery_indication_cfg = 0;
1026     legacy_request->discovery_indication_cfg |=
1027         hidl_request.configParams.disableDiscoveryAddressChangeIndication ? 0x1
1028                                                                           : 0x0;
1029     legacy_request->discovery_indication_cfg |=
1030         hidl_request.configParams.disableStartedClusterIndication ? 0x2 : 0x0;
1031     legacy_request->discovery_indication_cfg |=
1032         hidl_request.configParams.disableJoinedClusterIndication ? 0x4 : 0x0;
1033     legacy_request->config_sid_beacon = 1;
1034     if (hidl_request.configParams.numberOfPublishServiceIdsInBeacon > 127) {
1035         LOG(ERROR) << "convertHidlNanEnableRequestToLegacy: "
1036                       "numberOfPublishServiceIdsInBeacon > 127";
1037         return false;
1038     }
1039     legacy_request->sid_beacon_val =
1040         (hidl_request.configParams.includePublishServiceIdsInBeacon ? 0x1
1041                                                                     : 0x0) |
1042         (hidl_request.configParams.numberOfPublishServiceIdsInBeacon << 1);
1043     legacy_request->config_subscribe_sid_beacon = 1;
1044     if (hidl_request.configParams.numberOfSubscribeServiceIdsInBeacon > 127) {
1045         LOG(ERROR) << "convertHidlNanEnableRequestToLegacy: "
1046                       "numberOfSubscribeServiceIdsInBeacon > 127";
1047         return false;
1048     }
1049     legacy_request->subscribe_sid_beacon_val =
1050         (hidl_request.configParams.includeSubscribeServiceIdsInBeacon ? 0x1
1051                                                                       : 0x0) |
1052         (hidl_request.configParams.numberOfSubscribeServiceIdsInBeacon << 1);
1053     legacy_request->config_rssi_window_size = 1;
1054     legacy_request->rssi_window_size_val =
1055         hidl_request.configParams.rssiWindowSize;
1056     legacy_request->config_disc_mac_addr_randomization = 1;
1057     legacy_request->disc_mac_addr_rand_interval_sec =
1058         hidl_request.configParams.macAddressRandomizationIntervalSec;
1059     legacy_request->config_2dot4g_rssi_close = 1;
1060     if (hidl_request.configParams.bandSpecificConfig.size() != 2) {
1061         LOG(ERROR) << "convertHidlNanEnableRequestToLegacy: "
1062                       "bandSpecificConfig.size() != 2";
1063         return false;
1064     }
1065     legacy_request->rssi_close_2dot4g_val =
1066         hidl_request.configParams
1067             .bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
1068             .rssiClose;
1069     legacy_request->config_2dot4g_rssi_middle = 1;
1070     legacy_request->rssi_middle_2dot4g_val =
1071         hidl_request.configParams
1072             .bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
1073             .rssiMiddle;
1074     legacy_request->config_2dot4g_rssi_proximity = 1;
1075     legacy_request->rssi_proximity_2dot4g_val =
1076         hidl_request.configParams
1077             .bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
1078             .rssiCloseProximity;
1079     legacy_request->config_scan_params = 1;
1080     legacy_request->scan_params_val
1081         .dwell_time[legacy_hal::NAN_CHANNEL_24G_BAND] =
1082         hidl_request.configParams
1083             .bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
1084             .dwellTimeMs;
1085     legacy_request->scan_params_val
1086         .scan_period[legacy_hal::NAN_CHANNEL_24G_BAND] =
1087         hidl_request.configParams
1088             .bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
1089             .scanPeriodSec;
1090     legacy_request->config_dw.config_2dot4g_dw_band =
1091         hidl_request.configParams
1092             .bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
1093             .validDiscoveryWindowIntervalVal;
1094     legacy_request->config_dw.dw_2dot4g_interval_val =
1095         hidl_request.configParams
1096             .bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
1097             .discoveryWindowIntervalVal;
1098     legacy_request->config_5g_rssi_close = 1;
1099     legacy_request->rssi_close_5g_val =
1100         hidl_request.configParams
1101             .bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
1102             .rssiClose;
1103     legacy_request->config_5g_rssi_middle = 1;
1104     legacy_request->rssi_middle_5g_val =
1105         hidl_request.configParams
1106             .bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
1107             .rssiMiddle;
1108     legacy_request->config_5g_rssi_close_proximity = 1;
1109     legacy_request->rssi_close_proximity_5g_val =
1110         hidl_request.configParams
1111             .bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
1112             .rssiCloseProximity;
1113     legacy_request->scan_params_val
1114         .dwell_time[legacy_hal::NAN_CHANNEL_5G_BAND_LOW] =
1115         hidl_request.configParams
1116             .bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
1117             .dwellTimeMs;
1118     legacy_request->scan_params_val
1119         .scan_period[legacy_hal::NAN_CHANNEL_5G_BAND_LOW] =
1120         hidl_request.configParams
1121             .bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
1122             .scanPeriodSec;
1123     legacy_request->scan_params_val
1124         .dwell_time[legacy_hal::NAN_CHANNEL_5G_BAND_HIGH] =
1125         hidl_request.configParams
1126             .bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
1127             .dwellTimeMs;
1128     legacy_request->scan_params_val
1129         .scan_period[legacy_hal::NAN_CHANNEL_5G_BAND_HIGH] =
1130         hidl_request.configParams
1131             .bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
1132             .scanPeriodSec;
1133     legacy_request->config_dw.config_5g_dw_band =
1134         hidl_request.configParams
1135             .bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
1136             .validDiscoveryWindowIntervalVal;
1137     legacy_request->config_dw.dw_5g_interval_val =
1138         hidl_request.configParams
1139             .bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
1140             .discoveryWindowIntervalVal;
1141     if (hidl_request.debugConfigs.validClusterIdVals) {
1142         legacy_request->cluster_low =
1143             hidl_request.debugConfigs.clusterIdBottomRangeVal;
1144         legacy_request->cluster_high =
1145             hidl_request.debugConfigs.clusterIdTopRangeVal;
1146     } else {  // need 'else' since not configurable in legacy HAL
1147         legacy_request->cluster_low = 0x0000;
1148         legacy_request->cluster_high = 0xFFFF;
1149     }
1150     legacy_request->config_intf_addr =
1151         hidl_request.debugConfigs.validIntfAddrVal;
1152     memcpy(legacy_request->intf_addr_val,
1153            hidl_request.debugConfigs.intfAddrVal.data(), 6);
1154     legacy_request->config_oui = hidl_request.debugConfigs.validOuiVal;
1155     legacy_request->oui_val = hidl_request.debugConfigs.ouiVal;
1156     legacy_request->config_random_factor_force =
1157         hidl_request.debugConfigs.validRandomFactorForceVal;
1158     legacy_request->random_factor_force_val =
1159         hidl_request.debugConfigs.randomFactorForceVal;
1160     legacy_request->config_hop_count_force =
1161         hidl_request.debugConfigs.validHopCountForceVal;
1162     legacy_request->hop_count_force_val =
1163         hidl_request.debugConfigs.hopCountForceVal;
1164     legacy_request->config_24g_channel =
1165         hidl_request.debugConfigs.validDiscoveryChannelVal;
1166     legacy_request->channel_24g_val =
1167         hidl_request.debugConfigs
1168             .discoveryChannelMhzVal[(size_t)NanBandIndex::NAN_BAND_24GHZ];
1169     legacy_request->config_5g_channel =
1170         hidl_request.debugConfigs.validDiscoveryChannelVal;
1171     legacy_request->channel_5g_val =
1172         hidl_request.debugConfigs
1173             .discoveryChannelMhzVal[(size_t)NanBandIndex::NAN_BAND_5GHZ];
1174     legacy_request->config_2dot4g_beacons =
1175         hidl_request.debugConfigs.validUseBeaconsInBandVal;
1176     legacy_request->beacon_2dot4g_val =
1177         hidl_request.debugConfigs
1178             .useBeaconsInBandVal[(size_t)NanBandIndex::NAN_BAND_24GHZ];
1179     legacy_request->config_5g_beacons =
1180         hidl_request.debugConfigs.validUseBeaconsInBandVal;
1181     legacy_request->beacon_5g_val =
1182         hidl_request.debugConfigs
1183             .useBeaconsInBandVal[(size_t)NanBandIndex::NAN_BAND_5GHZ];
1184     legacy_request->config_2dot4g_sdf =
1185         hidl_request.debugConfigs.validUseSdfInBandVal;
1186     legacy_request->sdf_2dot4g_val =
1187         hidl_request.debugConfigs
1188             .useSdfInBandVal[(size_t)NanBandIndex::NAN_BAND_24GHZ];
1189     legacy_request->config_5g_sdf =
1190         hidl_request.debugConfigs.validUseSdfInBandVal;
1191     legacy_request->sdf_5g_val =
1192         hidl_request.debugConfigs
1193             .useSdfInBandVal[(size_t)NanBandIndex::NAN_BAND_5GHZ];
1194 
1195     return true;
1196 }
1197 
convertHidlNanEnableRequest_1_2ToLegacy(const NanEnableRequest & hidl_request1,const NanConfigRequestSupplemental & hidl_request2,legacy_hal::NanEnableRequest * legacy_request)1198 bool convertHidlNanEnableRequest_1_2ToLegacy(
1199     const NanEnableRequest& hidl_request1,
1200     const NanConfigRequestSupplemental& hidl_request2,
1201     legacy_hal::NanEnableRequest* legacy_request) {
1202     if (!legacy_request) {
1203         LOG(ERROR)
1204             << "convertHidlNanEnableRequest_1_2ToLegacy: null legacy_request";
1205         return false;
1206     }
1207 
1208     *legacy_request = {};
1209     if (!convertHidlNanEnableRequestToLegacy(hidl_request1, legacy_request)) {
1210         return false;
1211     }
1212 
1213     legacy_request->config_discovery_beacon_int = 1;
1214     legacy_request->discovery_beacon_interval =
1215         hidl_request2.discoveryBeaconIntervalMs;
1216     legacy_request->config_nss = 1;
1217     legacy_request->nss = hidl_request2.numberOfSpatialStreamsInDiscovery;
1218     legacy_request->config_dw_early_termination = 1;
1219     legacy_request->enable_dw_termination =
1220         hidl_request2.enableDiscoveryWindowEarlyTermination;
1221     legacy_request->config_enable_ranging = 1;
1222     legacy_request->enable_ranging = hidl_request2.enableRanging;
1223 
1224     return true;
1225 }
1226 
convertHidlNanPublishRequestToLegacy(const NanPublishRequest & hidl_request,legacy_hal::NanPublishRequest * legacy_request)1227 bool convertHidlNanPublishRequestToLegacy(
1228     const NanPublishRequest& hidl_request,
1229     legacy_hal::NanPublishRequest* legacy_request) {
1230     if (!legacy_request) {
1231         LOG(ERROR)
1232             << "convertHidlNanPublishRequestToLegacy: null legacy_request";
1233         return false;
1234     }
1235     *legacy_request = {};
1236 
1237     legacy_request->publish_id = hidl_request.baseConfigs.sessionId;
1238     legacy_request->ttl = hidl_request.baseConfigs.ttlSec;
1239     legacy_request->period = hidl_request.baseConfigs.discoveryWindowPeriod;
1240     legacy_request->publish_count = hidl_request.baseConfigs.discoveryCount;
1241     legacy_request->service_name_len =
1242         hidl_request.baseConfigs.serviceName.size();
1243     if (legacy_request->service_name_len > NAN_MAX_SERVICE_NAME_LEN) {
1244         LOG(ERROR) << "convertHidlNanPublishRequestToLegacy: service_name_len "
1245                       "too large";
1246         return false;
1247     }
1248     memcpy(legacy_request->service_name,
1249            hidl_request.baseConfigs.serviceName.data(),
1250            legacy_request->service_name_len);
1251     legacy_request->publish_match_indicator = convertHidlNanMatchAlgToLegacy(
1252         hidl_request.baseConfigs.discoveryMatchIndicator);
1253     legacy_request->service_specific_info_len =
1254         hidl_request.baseConfigs.serviceSpecificInfo.size();
1255     if (legacy_request->service_specific_info_len >
1256         NAN_MAX_SERVICE_SPECIFIC_INFO_LEN) {
1257         LOG(ERROR) << "convertHidlNanPublishRequestToLegacy: "
1258                       "service_specific_info_len too large";
1259         return false;
1260     }
1261     memcpy(legacy_request->service_specific_info,
1262            hidl_request.baseConfigs.serviceSpecificInfo.data(),
1263            legacy_request->service_specific_info_len);
1264     legacy_request->sdea_service_specific_info_len =
1265         hidl_request.baseConfigs.extendedServiceSpecificInfo.size();
1266     if (legacy_request->sdea_service_specific_info_len >
1267         NAN_MAX_SDEA_SERVICE_SPECIFIC_INFO_LEN) {
1268         LOG(ERROR) << "convertHidlNanPublishRequestToLegacy: "
1269                       "sdea_service_specific_info_len too large";
1270         return false;
1271     }
1272     memcpy(legacy_request->sdea_service_specific_info,
1273            hidl_request.baseConfigs.extendedServiceSpecificInfo.data(),
1274            legacy_request->sdea_service_specific_info_len);
1275     legacy_request->rx_match_filter_len =
1276         hidl_request.baseConfigs.rxMatchFilter.size();
1277     if (legacy_request->rx_match_filter_len > NAN_MAX_MATCH_FILTER_LEN) {
1278         LOG(ERROR) << "convertHidlNanPublishRequestToLegacy: "
1279                       "rx_match_filter_len too large";
1280         return false;
1281     }
1282     memcpy(legacy_request->rx_match_filter,
1283            hidl_request.baseConfigs.rxMatchFilter.data(),
1284            legacy_request->rx_match_filter_len);
1285     legacy_request->tx_match_filter_len =
1286         hidl_request.baseConfigs.txMatchFilter.size();
1287     if (legacy_request->tx_match_filter_len > NAN_MAX_MATCH_FILTER_LEN) {
1288         LOG(ERROR) << "convertHidlNanPublishRequestToLegacy: "
1289                       "tx_match_filter_len too large";
1290         return false;
1291     }
1292     memcpy(legacy_request->tx_match_filter,
1293            hidl_request.baseConfigs.txMatchFilter.data(),
1294            legacy_request->tx_match_filter_len);
1295     legacy_request->rssi_threshold_flag =
1296         hidl_request.baseConfigs.useRssiThreshold;
1297     legacy_request->recv_indication_cfg = 0;
1298     legacy_request->recv_indication_cfg |=
1299         hidl_request.baseConfigs.disableDiscoveryTerminationIndication ? 0x1
1300                                                                        : 0x0;
1301     legacy_request->recv_indication_cfg |=
1302         hidl_request.baseConfigs.disableMatchExpirationIndication ? 0x2 : 0x0;
1303     legacy_request->recv_indication_cfg |=
1304         hidl_request.baseConfigs.disableFollowupReceivedIndication ? 0x4 : 0x0;
1305     legacy_request->recv_indication_cfg |= 0x8;
1306     legacy_request->cipher_type =
1307         (unsigned int)hidl_request.baseConfigs.securityConfig.cipherType;
1308     if (hidl_request.baseConfigs.securityConfig.securityType ==
1309         NanDataPathSecurityType::PMK) {
1310         legacy_request->key_info.key_type =
1311             legacy_hal::NAN_SECURITY_KEY_INPUT_PMK;
1312         legacy_request->key_info.body.pmk_info.pmk_len =
1313             hidl_request.baseConfigs.securityConfig.pmk.size();
1314         if (legacy_request->key_info.body.pmk_info.pmk_len !=
1315             NAN_PMK_INFO_LEN) {
1316             LOG(ERROR)
1317                 << "convertHidlNanPublishRequestToLegacy: invalid pmk_len";
1318             return false;
1319         }
1320         memcpy(legacy_request->key_info.body.pmk_info.pmk,
1321                hidl_request.baseConfigs.securityConfig.pmk.data(),
1322                legacy_request->key_info.body.pmk_info.pmk_len);
1323     }
1324     if (hidl_request.baseConfigs.securityConfig.securityType ==
1325         NanDataPathSecurityType::PASSPHRASE) {
1326         legacy_request->key_info.key_type =
1327             legacy_hal::NAN_SECURITY_KEY_INPUT_PASSPHRASE;
1328         legacy_request->key_info.body.passphrase_info.passphrase_len =
1329             hidl_request.baseConfigs.securityConfig.passphrase.size();
1330         if (legacy_request->key_info.body.passphrase_info.passphrase_len <
1331             NAN_SECURITY_MIN_PASSPHRASE_LEN) {
1332             LOG(ERROR) << "convertHidlNanPublishRequestToLegacy: "
1333                           "passphrase_len too small";
1334             return false;
1335         }
1336         if (legacy_request->key_info.body.passphrase_info.passphrase_len >
1337             NAN_SECURITY_MAX_PASSPHRASE_LEN) {
1338             LOG(ERROR) << "convertHidlNanPublishRequestToLegacy: "
1339                           "passphrase_len too large";
1340             return false;
1341         }
1342         memcpy(legacy_request->key_info.body.passphrase_info.passphrase,
1343                hidl_request.baseConfigs.securityConfig.passphrase.data(),
1344                legacy_request->key_info.body.passphrase_info.passphrase_len);
1345     }
1346     legacy_request->sdea_params.security_cfg =
1347         (hidl_request.baseConfigs.securityConfig.securityType !=
1348          NanDataPathSecurityType::OPEN)
1349             ? legacy_hal::NAN_DP_CONFIG_SECURITY
1350             : legacy_hal::NAN_DP_CONFIG_NO_SECURITY;
1351     legacy_request->sdea_params.ranging_state =
1352         hidl_request.baseConfigs.rangingRequired
1353             ? legacy_hal::NAN_RANGING_ENABLE
1354             : legacy_hal::NAN_RANGING_DISABLE;
1355     legacy_request->ranging_cfg.ranging_interval_msec =
1356         hidl_request.baseConfigs.rangingIntervalMsec;
1357     legacy_request->ranging_cfg.config_ranging_indications =
1358         hidl_request.baseConfigs.configRangingIndications;
1359     legacy_request->ranging_cfg.distance_ingress_mm =
1360         hidl_request.baseConfigs.distanceIngressCm * 10;
1361     legacy_request->ranging_cfg.distance_egress_mm =
1362         hidl_request.baseConfigs.distanceEgressCm * 10;
1363     legacy_request->ranging_auto_response =
1364         hidl_request.baseConfigs.rangingRequired
1365             ? legacy_hal::NAN_RANGING_AUTO_RESPONSE_ENABLE
1366             : legacy_hal::NAN_RANGING_AUTO_RESPONSE_DISABLE;
1367     legacy_request->sdea_params.range_report =
1368         legacy_hal::NAN_DISABLE_RANGE_REPORT;
1369     legacy_request->publish_type =
1370         convertHidlNanPublishTypeToLegacy(hidl_request.publishType);
1371     legacy_request->tx_type = convertHidlNanTxTypeToLegacy(hidl_request.txType);
1372     legacy_request->service_responder_policy =
1373         hidl_request.autoAcceptDataPathRequests
1374             ? legacy_hal::NAN_SERVICE_ACCEPT_POLICY_ALL
1375             : legacy_hal::NAN_SERVICE_ACCEPT_POLICY_NONE;
1376 
1377     return true;
1378 }
1379 
convertHidlNanSubscribeRequestToLegacy(const NanSubscribeRequest & hidl_request,legacy_hal::NanSubscribeRequest * legacy_request)1380 bool convertHidlNanSubscribeRequestToLegacy(
1381     const NanSubscribeRequest& hidl_request,
1382     legacy_hal::NanSubscribeRequest* legacy_request) {
1383     if (!legacy_request) {
1384         LOG(ERROR)
1385             << "convertHidlNanSubscribeRequestToLegacy: legacy_request is null";
1386         return false;
1387     }
1388     *legacy_request = {};
1389 
1390     legacy_request->subscribe_id = hidl_request.baseConfigs.sessionId;
1391     legacy_request->ttl = hidl_request.baseConfigs.ttlSec;
1392     legacy_request->period = hidl_request.baseConfigs.discoveryWindowPeriod;
1393     legacy_request->subscribe_count = hidl_request.baseConfigs.discoveryCount;
1394     legacy_request->service_name_len =
1395         hidl_request.baseConfigs.serviceName.size();
1396     if (legacy_request->service_name_len > NAN_MAX_SERVICE_NAME_LEN) {
1397         LOG(ERROR) << "convertHidlNanSubscribeRequestToLegacy: "
1398                       "service_name_len too large";
1399         return false;
1400     }
1401     memcpy(legacy_request->service_name,
1402            hidl_request.baseConfigs.serviceName.data(),
1403            legacy_request->service_name_len);
1404     legacy_request->subscribe_match_indicator = convertHidlNanMatchAlgToLegacy(
1405         hidl_request.baseConfigs.discoveryMatchIndicator);
1406     legacy_request->service_specific_info_len =
1407         hidl_request.baseConfigs.serviceSpecificInfo.size();
1408     if (legacy_request->service_specific_info_len >
1409         NAN_MAX_SERVICE_SPECIFIC_INFO_LEN) {
1410         LOG(ERROR) << "convertHidlNanSubscribeRequestToLegacy: "
1411                       "service_specific_info_len too large";
1412         return false;
1413     }
1414     memcpy(legacy_request->service_specific_info,
1415            hidl_request.baseConfigs.serviceSpecificInfo.data(),
1416            legacy_request->service_specific_info_len);
1417     legacy_request->sdea_service_specific_info_len =
1418         hidl_request.baseConfigs.extendedServiceSpecificInfo.size();
1419     if (legacy_request->sdea_service_specific_info_len >
1420         NAN_MAX_SDEA_SERVICE_SPECIFIC_INFO_LEN) {
1421         LOG(ERROR) << "convertHidlNanSubscribeRequestToLegacy: "
1422                       "sdea_service_specific_info_len too large";
1423         return false;
1424     }
1425     memcpy(legacy_request->sdea_service_specific_info,
1426            hidl_request.baseConfigs.extendedServiceSpecificInfo.data(),
1427            legacy_request->sdea_service_specific_info_len);
1428     legacy_request->rx_match_filter_len =
1429         hidl_request.baseConfigs.rxMatchFilter.size();
1430     if (legacy_request->rx_match_filter_len > NAN_MAX_MATCH_FILTER_LEN) {
1431         LOG(ERROR) << "convertHidlNanSubscribeRequestToLegacy: "
1432                       "rx_match_filter_len too large";
1433         return false;
1434     }
1435     memcpy(legacy_request->rx_match_filter,
1436            hidl_request.baseConfigs.rxMatchFilter.data(),
1437            legacy_request->rx_match_filter_len);
1438     legacy_request->tx_match_filter_len =
1439         hidl_request.baseConfigs.txMatchFilter.size();
1440     if (legacy_request->tx_match_filter_len > NAN_MAX_MATCH_FILTER_LEN) {
1441         LOG(ERROR) << "convertHidlNanSubscribeRequestToLegacy: "
1442                       "tx_match_filter_len too large";
1443         return false;
1444     }
1445     memcpy(legacy_request->tx_match_filter,
1446            hidl_request.baseConfigs.txMatchFilter.data(),
1447            legacy_request->tx_match_filter_len);
1448     legacy_request->rssi_threshold_flag =
1449         hidl_request.baseConfigs.useRssiThreshold;
1450     legacy_request->recv_indication_cfg = 0;
1451     legacy_request->recv_indication_cfg |=
1452         hidl_request.baseConfigs.disableDiscoveryTerminationIndication ? 0x1
1453                                                                        : 0x0;
1454     legacy_request->recv_indication_cfg |=
1455         hidl_request.baseConfigs.disableMatchExpirationIndication ? 0x2 : 0x0;
1456     legacy_request->recv_indication_cfg |=
1457         hidl_request.baseConfigs.disableFollowupReceivedIndication ? 0x4 : 0x0;
1458     legacy_request->cipher_type =
1459         (unsigned int)hidl_request.baseConfigs.securityConfig.cipherType;
1460     if (hidl_request.baseConfigs.securityConfig.securityType ==
1461         NanDataPathSecurityType::PMK) {
1462         legacy_request->key_info.key_type =
1463             legacy_hal::NAN_SECURITY_KEY_INPUT_PMK;
1464         legacy_request->key_info.body.pmk_info.pmk_len =
1465             hidl_request.baseConfigs.securityConfig.pmk.size();
1466         if (legacy_request->key_info.body.pmk_info.pmk_len !=
1467             NAN_PMK_INFO_LEN) {
1468             LOG(ERROR)
1469                 << "convertHidlNanSubscribeRequestToLegacy: invalid pmk_len";
1470             return false;
1471         }
1472         memcpy(legacy_request->key_info.body.pmk_info.pmk,
1473                hidl_request.baseConfigs.securityConfig.pmk.data(),
1474                legacy_request->key_info.body.pmk_info.pmk_len);
1475     }
1476     if (hidl_request.baseConfigs.securityConfig.securityType ==
1477         NanDataPathSecurityType::PASSPHRASE) {
1478         legacy_request->key_info.key_type =
1479             legacy_hal::NAN_SECURITY_KEY_INPUT_PASSPHRASE;
1480         legacy_request->key_info.body.passphrase_info.passphrase_len =
1481             hidl_request.baseConfigs.securityConfig.passphrase.size();
1482         if (legacy_request->key_info.body.passphrase_info.passphrase_len <
1483             NAN_SECURITY_MIN_PASSPHRASE_LEN) {
1484             LOG(ERROR) << "convertHidlNanSubscribeRequestToLegacy: "
1485                           "passphrase_len too small";
1486             return false;
1487         }
1488         if (legacy_request->key_info.body.passphrase_info.passphrase_len >
1489             NAN_SECURITY_MAX_PASSPHRASE_LEN) {
1490             LOG(ERROR) << "convertHidlNanSubscribeRequestToLegacy: "
1491                           "passphrase_len too large";
1492             return false;
1493         }
1494         memcpy(legacy_request->key_info.body.passphrase_info.passphrase,
1495                hidl_request.baseConfigs.securityConfig.passphrase.data(),
1496                legacy_request->key_info.body.passphrase_info.passphrase_len);
1497     }
1498     legacy_request->sdea_params.security_cfg =
1499         (hidl_request.baseConfigs.securityConfig.securityType !=
1500          NanDataPathSecurityType::OPEN)
1501             ? legacy_hal::NAN_DP_CONFIG_SECURITY
1502             : legacy_hal::NAN_DP_CONFIG_NO_SECURITY;
1503     legacy_request->sdea_params.ranging_state =
1504         hidl_request.baseConfigs.rangingRequired
1505             ? legacy_hal::NAN_RANGING_ENABLE
1506             : legacy_hal::NAN_RANGING_DISABLE;
1507     legacy_request->ranging_cfg.ranging_interval_msec =
1508         hidl_request.baseConfigs.rangingIntervalMsec;
1509     legacy_request->ranging_cfg.config_ranging_indications =
1510         hidl_request.baseConfigs.configRangingIndications;
1511     legacy_request->ranging_cfg.distance_ingress_mm =
1512         hidl_request.baseConfigs.distanceIngressCm * 10;
1513     legacy_request->ranging_cfg.distance_egress_mm =
1514         hidl_request.baseConfigs.distanceEgressCm * 10;
1515     legacy_request->ranging_auto_response =
1516         hidl_request.baseConfigs.rangingRequired
1517             ? legacy_hal::NAN_RANGING_AUTO_RESPONSE_ENABLE
1518             : legacy_hal::NAN_RANGING_AUTO_RESPONSE_DISABLE;
1519     legacy_request->sdea_params.range_report =
1520         legacy_hal::NAN_DISABLE_RANGE_REPORT;
1521     legacy_request->subscribe_type =
1522         convertHidlNanSubscribeTypeToLegacy(hidl_request.subscribeType);
1523     legacy_request->serviceResponseFilter =
1524         convertHidlNanSrfTypeToLegacy(hidl_request.srfType);
1525     legacy_request->serviceResponseInclude =
1526         hidl_request.srfRespondIfInAddressSet
1527             ? legacy_hal::NAN_SRF_INCLUDE_RESPOND
1528             : legacy_hal::NAN_SRF_INCLUDE_DO_NOT_RESPOND;
1529     legacy_request->useServiceResponseFilter =
1530         hidl_request.shouldUseSrf ? legacy_hal::NAN_USE_SRF
1531                                   : legacy_hal::NAN_DO_NOT_USE_SRF;
1532     legacy_request->ssiRequiredForMatchIndication =
1533         hidl_request.isSsiRequiredForMatch
1534             ? legacy_hal::NAN_SSI_REQUIRED_IN_MATCH_IND
1535             : legacy_hal::NAN_SSI_NOT_REQUIRED_IN_MATCH_IND;
1536     legacy_request->num_intf_addr_present = hidl_request.intfAddr.size();
1537     if (legacy_request->num_intf_addr_present > NAN_MAX_SUBSCRIBE_MAX_ADDRESS) {
1538         LOG(ERROR) << "convertHidlNanSubscribeRequestToLegacy: "
1539                       "num_intf_addr_present - too many";
1540         return false;
1541     }
1542     for (int i = 0; i < legacy_request->num_intf_addr_present; i++) {
1543         memcpy(legacy_request->intf_addr[i], hidl_request.intfAddr[i].data(),
1544                6);
1545     }
1546 
1547     return true;
1548 }
1549 
convertHidlNanTransmitFollowupRequestToLegacy(const NanTransmitFollowupRequest & hidl_request,legacy_hal::NanTransmitFollowupRequest * legacy_request)1550 bool convertHidlNanTransmitFollowupRequestToLegacy(
1551     const NanTransmitFollowupRequest& hidl_request,
1552     legacy_hal::NanTransmitFollowupRequest* legacy_request) {
1553     if (!legacy_request) {
1554         LOG(ERROR) << "convertHidlNanTransmitFollowupRequestToLegacy: "
1555                       "legacy_request is null";
1556         return false;
1557     }
1558     *legacy_request = {};
1559 
1560     legacy_request->publish_subscribe_id = hidl_request.discoverySessionId;
1561     legacy_request->requestor_instance_id = hidl_request.peerId;
1562     memcpy(legacy_request->addr, hidl_request.addr.data(), 6);
1563     legacy_request->priority = hidl_request.isHighPriority
1564                                    ? legacy_hal::NAN_TX_PRIORITY_HIGH
1565                                    : legacy_hal::NAN_TX_PRIORITY_NORMAL;
1566     legacy_request->dw_or_faw = hidl_request.shouldUseDiscoveryWindow
1567                                     ? legacy_hal::NAN_TRANSMIT_IN_DW
1568                                     : legacy_hal::NAN_TRANSMIT_IN_FAW;
1569     legacy_request->service_specific_info_len =
1570         hidl_request.serviceSpecificInfo.size();
1571     if (legacy_request->service_specific_info_len >
1572         NAN_MAX_SERVICE_SPECIFIC_INFO_LEN) {
1573         LOG(ERROR) << "convertHidlNanTransmitFollowupRequestToLegacy: "
1574                       "service_specific_info_len too large";
1575         return false;
1576     }
1577     memcpy(legacy_request->service_specific_info,
1578            hidl_request.serviceSpecificInfo.data(),
1579            legacy_request->service_specific_info_len);
1580     legacy_request->sdea_service_specific_info_len =
1581         hidl_request.extendedServiceSpecificInfo.size();
1582     if (legacy_request->sdea_service_specific_info_len >
1583         NAN_MAX_SDEA_SERVICE_SPECIFIC_INFO_LEN) {
1584         LOG(ERROR) << "convertHidlNanTransmitFollowupRequestToLegacy: "
1585                       "sdea_service_specific_info_len too large";
1586         return false;
1587     }
1588     memcpy(legacy_request->sdea_service_specific_info,
1589            hidl_request.extendedServiceSpecificInfo.data(),
1590            legacy_request->sdea_service_specific_info_len);
1591     legacy_request->recv_indication_cfg =
1592         hidl_request.disableFollowupResultIndication ? 0x1 : 0x0;
1593 
1594     return true;
1595 }
1596 
convertHidlNanConfigRequestToLegacy(const NanConfigRequest & hidl_request,legacy_hal::NanConfigRequest * legacy_request)1597 bool convertHidlNanConfigRequestToLegacy(
1598     const NanConfigRequest& hidl_request,
1599     legacy_hal::NanConfigRequest* legacy_request) {
1600     if (!legacy_request) {
1601         LOG(ERROR)
1602             << "convertHidlNanConfigRequestToLegacy: legacy_request is null";
1603         return false;
1604     }
1605     *legacy_request = {};
1606 
1607     // TODO: b/34059183 tracks missing configurations in legacy HAL or uknown
1608     // defaults
1609     legacy_request->master_pref = hidl_request.masterPref;
1610     legacy_request->discovery_indication_cfg = 0;
1611     legacy_request->discovery_indication_cfg |=
1612         hidl_request.disableDiscoveryAddressChangeIndication ? 0x1 : 0x0;
1613     legacy_request->discovery_indication_cfg |=
1614         hidl_request.disableStartedClusterIndication ? 0x2 : 0x0;
1615     legacy_request->discovery_indication_cfg |=
1616         hidl_request.disableJoinedClusterIndication ? 0x4 : 0x0;
1617     legacy_request->config_sid_beacon = 1;
1618     if (hidl_request.numberOfPublishServiceIdsInBeacon > 127) {
1619         LOG(ERROR) << "convertHidlNanConfigRequestToLegacy: "
1620                       "numberOfPublishServiceIdsInBeacon > 127";
1621         return false;
1622     }
1623     legacy_request->sid_beacon =
1624         (hidl_request.includePublishServiceIdsInBeacon ? 0x1 : 0x0) |
1625         (hidl_request.numberOfPublishServiceIdsInBeacon << 1);
1626     legacy_request->config_subscribe_sid_beacon = 1;
1627     if (hidl_request.numberOfSubscribeServiceIdsInBeacon > 127) {
1628         LOG(ERROR) << "convertHidlNanConfigRequestToLegacy: "
1629                       "numberOfSubscribeServiceIdsInBeacon > 127";
1630         return false;
1631     }
1632     legacy_request->subscribe_sid_beacon_val =
1633         (hidl_request.includeSubscribeServiceIdsInBeacon ? 0x1 : 0x0) |
1634         (hidl_request.numberOfSubscribeServiceIdsInBeacon << 1);
1635     legacy_request->config_rssi_window_size = 1;
1636     legacy_request->rssi_window_size_val = hidl_request.rssiWindowSize;
1637     legacy_request->config_disc_mac_addr_randomization = 1;
1638     legacy_request->disc_mac_addr_rand_interval_sec =
1639         hidl_request.macAddressRandomizationIntervalSec;
1640     /* TODO : missing
1641     legacy_request->config_2dot4g_rssi_close = 1;
1642     legacy_request->rssi_close_2dot4g_val =
1643           hidl_request.bandSpecificConfig[
1644               (size_t) NanBandIndex::NAN_BAND_24GHZ].rssiClose;
1645     legacy_request->config_2dot4g_rssi_middle = 1;
1646     legacy_request->rssi_middle_2dot4g_val =
1647           hidl_request.bandSpecificConfig[
1648               (size_t) NanBandIndex::NAN_BAND_24GHZ].rssiMiddle;
1649     legacy_request->config_2dot4g_rssi_proximity = 1;
1650     legacy_request->rssi_proximity_2dot4g_val =
1651           hidl_request.bandSpecificConfig[
1652               (size_t) NanBandIndex::NAN_BAND_24GHZ].rssiCloseProximity;
1653     */
1654     legacy_request->config_scan_params = 1;
1655     legacy_request->scan_params_val
1656         .dwell_time[legacy_hal::NAN_CHANNEL_24G_BAND] =
1657         hidl_request.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
1658             .dwellTimeMs;
1659     legacy_request->scan_params_val
1660         .scan_period[legacy_hal::NAN_CHANNEL_24G_BAND] =
1661         hidl_request.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
1662             .scanPeriodSec;
1663     legacy_request->config_dw.config_2dot4g_dw_band =
1664         hidl_request.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
1665             .validDiscoveryWindowIntervalVal;
1666     legacy_request->config_dw.dw_2dot4g_interval_val =
1667         hidl_request.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
1668             .discoveryWindowIntervalVal;
1669     /* TODO: missing
1670     legacy_request->config_5g_rssi_close = 1;
1671     legacy_request->rssi_close_5g_val =
1672           hidl_request.bandSpecificConfig[
1673               (size_t) NanBandIndex::NAN_BAND_5GHZ].rssiClose;
1674     legacy_request->config_5g_rssi_middle = 1;
1675     legacy_request->rssi_middle_5g_val =
1676           hidl_request.bandSpecificConfig[
1677               (size_t) NanBandIndex::NAN_BAND_5GHZ].rssiMiddle;
1678     */
1679     legacy_request->config_5g_rssi_close_proximity = 1;
1680     legacy_request->rssi_close_proximity_5g_val =
1681         hidl_request.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
1682             .rssiCloseProximity;
1683     legacy_request->scan_params_val
1684         .dwell_time[legacy_hal::NAN_CHANNEL_5G_BAND_LOW] =
1685         hidl_request.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
1686             .dwellTimeMs;
1687     legacy_request->scan_params_val
1688         .scan_period[legacy_hal::NAN_CHANNEL_5G_BAND_LOW] =
1689         hidl_request.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
1690             .scanPeriodSec;
1691     legacy_request->scan_params_val
1692         .dwell_time[legacy_hal::NAN_CHANNEL_5G_BAND_HIGH] =
1693         hidl_request.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
1694             .dwellTimeMs;
1695     legacy_request->scan_params_val
1696         .scan_period[legacy_hal::NAN_CHANNEL_5G_BAND_HIGH] =
1697         hidl_request.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
1698             .scanPeriodSec;
1699     legacy_request->config_dw.config_5g_dw_band =
1700         hidl_request.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
1701             .validDiscoveryWindowIntervalVal;
1702     legacy_request->config_dw.dw_5g_interval_val =
1703         hidl_request.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
1704             .discoveryWindowIntervalVal;
1705 
1706     return true;
1707 }
1708 
convertHidlNanConfigRequest_1_2ToLegacy(const NanConfigRequest & hidl_request1,const NanConfigRequestSupplemental & hidl_request2,legacy_hal::NanConfigRequest * legacy_request)1709 bool convertHidlNanConfigRequest_1_2ToLegacy(
1710     const NanConfigRequest& hidl_request1,
1711     const NanConfigRequestSupplemental& hidl_request2,
1712     legacy_hal::NanConfigRequest* legacy_request) {
1713     if (!legacy_request) {
1714         LOG(ERROR) << "convertHidlNanConfigRequest_1_2ToLegacy: legacy_request "
1715                       "is null";
1716         return false;
1717     }
1718 
1719     *legacy_request = {};
1720     if (!convertHidlNanConfigRequestToLegacy(hidl_request1, legacy_request)) {
1721         return false;
1722     }
1723 
1724     legacy_request->config_discovery_beacon_int = 1;
1725     legacy_request->discovery_beacon_interval =
1726         hidl_request2.discoveryBeaconIntervalMs;
1727     legacy_request->config_nss = 1;
1728     legacy_request->nss = hidl_request2.numberOfSpatialStreamsInDiscovery;
1729     legacy_request->config_dw_early_termination = 1;
1730     legacy_request->enable_dw_termination =
1731         hidl_request2.enableDiscoveryWindowEarlyTermination;
1732     legacy_request->config_enable_ranging = 1;
1733     legacy_request->enable_ranging = hidl_request2.enableRanging;
1734 
1735     return true;
1736 }
1737 
convertHidlNanDataPathInitiatorRequestToLegacy(const NanInitiateDataPathRequest & hidl_request,legacy_hal::NanDataPathInitiatorRequest * legacy_request)1738 bool convertHidlNanDataPathInitiatorRequestToLegacy(
1739     const NanInitiateDataPathRequest& hidl_request,
1740     legacy_hal::NanDataPathInitiatorRequest* legacy_request) {
1741     if (!legacy_request) {
1742         LOG(ERROR) << "convertHidlNanDataPathInitiatorRequestToLegacy: "
1743                       "legacy_request is null";
1744         return false;
1745     }
1746     *legacy_request = {};
1747 
1748     legacy_request->requestor_instance_id = hidl_request.peerId;
1749     memcpy(legacy_request->peer_disc_mac_addr,
1750            hidl_request.peerDiscMacAddr.data(), 6);
1751     legacy_request->channel_request_type =
1752         convertHidlNanDataPathChannelCfgToLegacy(
1753             hidl_request.channelRequestType);
1754     legacy_request->channel = hidl_request.channel;
1755     strcpy(legacy_request->ndp_iface, hidl_request.ifaceName.c_str());
1756     legacy_request->ndp_cfg.security_cfg =
1757         (hidl_request.securityConfig.securityType !=
1758          NanDataPathSecurityType::OPEN)
1759             ? legacy_hal::NAN_DP_CONFIG_SECURITY
1760             : legacy_hal::NAN_DP_CONFIG_NO_SECURITY;
1761     legacy_request->app_info.ndp_app_info_len = hidl_request.appInfo.size();
1762     if (legacy_request->app_info.ndp_app_info_len > NAN_DP_MAX_APP_INFO_LEN) {
1763         LOG(ERROR) << "convertHidlNanDataPathInitiatorRequestToLegacy: "
1764                       "ndp_app_info_len too large";
1765         return false;
1766     }
1767     memcpy(legacy_request->app_info.ndp_app_info, hidl_request.appInfo.data(),
1768            legacy_request->app_info.ndp_app_info_len);
1769     legacy_request->cipher_type =
1770         (unsigned int)hidl_request.securityConfig.cipherType;
1771     if (hidl_request.securityConfig.securityType ==
1772         NanDataPathSecurityType::PMK) {
1773         legacy_request->key_info.key_type =
1774             legacy_hal::NAN_SECURITY_KEY_INPUT_PMK;
1775         legacy_request->key_info.body.pmk_info.pmk_len =
1776             hidl_request.securityConfig.pmk.size();
1777         if (legacy_request->key_info.body.pmk_info.pmk_len !=
1778             NAN_PMK_INFO_LEN) {
1779             LOG(ERROR) << "convertHidlNanDataPathInitiatorRequestToLegacy: "
1780                           "invalid pmk_len";
1781             return false;
1782         }
1783         memcpy(legacy_request->key_info.body.pmk_info.pmk,
1784                hidl_request.securityConfig.pmk.data(),
1785                legacy_request->key_info.body.pmk_info.pmk_len);
1786     }
1787     if (hidl_request.securityConfig.securityType ==
1788         NanDataPathSecurityType::PASSPHRASE) {
1789         legacy_request->key_info.key_type =
1790             legacy_hal::NAN_SECURITY_KEY_INPUT_PASSPHRASE;
1791         legacy_request->key_info.body.passphrase_info.passphrase_len =
1792             hidl_request.securityConfig.passphrase.size();
1793         if (legacy_request->key_info.body.passphrase_info.passphrase_len <
1794             NAN_SECURITY_MIN_PASSPHRASE_LEN) {
1795             LOG(ERROR) << "convertHidlNanDataPathInitiatorRequestToLegacy: "
1796                           "passphrase_len too small";
1797             return false;
1798         }
1799         if (legacy_request->key_info.body.passphrase_info.passphrase_len >
1800             NAN_SECURITY_MAX_PASSPHRASE_LEN) {
1801             LOG(ERROR) << "convertHidlNanDataPathInitiatorRequestToLegacy: "
1802                           "passphrase_len too large";
1803             return false;
1804         }
1805         memcpy(legacy_request->key_info.body.passphrase_info.passphrase,
1806                hidl_request.securityConfig.passphrase.data(),
1807                legacy_request->key_info.body.passphrase_info.passphrase_len);
1808     }
1809     legacy_request->service_name_len = hidl_request.serviceNameOutOfBand.size();
1810     if (legacy_request->service_name_len > NAN_MAX_SERVICE_NAME_LEN) {
1811         LOG(ERROR) << "convertHidlNanDataPathInitiatorRequestToLegacy: "
1812                       "service_name_len too large";
1813         return false;
1814     }
1815     memcpy(legacy_request->service_name,
1816            hidl_request.serviceNameOutOfBand.data(),
1817            legacy_request->service_name_len);
1818 
1819     return true;
1820 }
1821 
convertHidlNanDataPathIndicationResponseToLegacy(const NanRespondToDataPathIndicationRequest & hidl_request,legacy_hal::NanDataPathIndicationResponse * legacy_request)1822 bool convertHidlNanDataPathIndicationResponseToLegacy(
1823     const NanRespondToDataPathIndicationRequest& hidl_request,
1824     legacy_hal::NanDataPathIndicationResponse* legacy_request) {
1825     if (!legacy_request) {
1826         LOG(ERROR) << "convertHidlNanDataPathIndicationResponseToLegacy: "
1827                       "legacy_request is null";
1828         return false;
1829     }
1830     *legacy_request = {};
1831 
1832     legacy_request->rsp_code = hidl_request.acceptRequest
1833                                    ? legacy_hal::NAN_DP_REQUEST_ACCEPT
1834                                    : legacy_hal::NAN_DP_REQUEST_REJECT;
1835     legacy_request->ndp_instance_id = hidl_request.ndpInstanceId;
1836     strcpy(legacy_request->ndp_iface, hidl_request.ifaceName.c_str());
1837     legacy_request->ndp_cfg.security_cfg =
1838         (hidl_request.securityConfig.securityType !=
1839          NanDataPathSecurityType::OPEN)
1840             ? legacy_hal::NAN_DP_CONFIG_SECURITY
1841             : legacy_hal::NAN_DP_CONFIG_NO_SECURITY;
1842     legacy_request->app_info.ndp_app_info_len = hidl_request.appInfo.size();
1843     if (legacy_request->app_info.ndp_app_info_len > NAN_DP_MAX_APP_INFO_LEN) {
1844         LOG(ERROR) << "convertHidlNanDataPathIndicationResponseToLegacy: "
1845                       "ndp_app_info_len too large";
1846         return false;
1847     }
1848     memcpy(legacy_request->app_info.ndp_app_info, hidl_request.appInfo.data(),
1849            legacy_request->app_info.ndp_app_info_len);
1850     legacy_request->cipher_type =
1851         (unsigned int)hidl_request.securityConfig.cipherType;
1852     if (hidl_request.securityConfig.securityType ==
1853         NanDataPathSecurityType::PMK) {
1854         legacy_request->key_info.key_type =
1855             legacy_hal::NAN_SECURITY_KEY_INPUT_PMK;
1856         legacy_request->key_info.body.pmk_info.pmk_len =
1857             hidl_request.securityConfig.pmk.size();
1858         if (legacy_request->key_info.body.pmk_info.pmk_len !=
1859             NAN_PMK_INFO_LEN) {
1860             LOG(ERROR) << "convertHidlNanDataPathIndicationResponseToLegacy: "
1861                           "invalid pmk_len";
1862             return false;
1863         }
1864         memcpy(legacy_request->key_info.body.pmk_info.pmk,
1865                hidl_request.securityConfig.pmk.data(),
1866                legacy_request->key_info.body.pmk_info.pmk_len);
1867     }
1868     if (hidl_request.securityConfig.securityType ==
1869         NanDataPathSecurityType::PASSPHRASE) {
1870         legacy_request->key_info.key_type =
1871             legacy_hal::NAN_SECURITY_KEY_INPUT_PASSPHRASE;
1872         legacy_request->key_info.body.passphrase_info.passphrase_len =
1873             hidl_request.securityConfig.passphrase.size();
1874         if (legacy_request->key_info.body.passphrase_info.passphrase_len <
1875             NAN_SECURITY_MIN_PASSPHRASE_LEN) {
1876             LOG(ERROR) << "convertHidlNanDataPathIndicationResponseToLegacy: "
1877                           "passphrase_len too small";
1878             return false;
1879         }
1880         if (legacy_request->key_info.body.passphrase_info.passphrase_len >
1881             NAN_SECURITY_MAX_PASSPHRASE_LEN) {
1882             LOG(ERROR) << "convertHidlNanDataPathIndicationResponseToLegacy: "
1883                           "passphrase_len too large";
1884             return false;
1885         }
1886         memcpy(legacy_request->key_info.body.passphrase_info.passphrase,
1887                hidl_request.securityConfig.passphrase.data(),
1888                legacy_request->key_info.body.passphrase_info.passphrase_len);
1889     }
1890     legacy_request->service_name_len = hidl_request.serviceNameOutOfBand.size();
1891     if (legacy_request->service_name_len > NAN_MAX_SERVICE_NAME_LEN) {
1892         LOG(ERROR) << "convertHidlNanDataPathIndicationResponseToLegacy: "
1893                       "service_name_len too large";
1894         return false;
1895     }
1896     memcpy(legacy_request->service_name,
1897            hidl_request.serviceNameOutOfBand.data(),
1898            legacy_request->service_name_len);
1899 
1900     return true;
1901 }
1902 
convertLegacyNanResponseHeaderToHidl(const legacy_hal::NanResponseMsg & legacy_response,WifiNanStatus * wifiNanStatus)1903 bool convertLegacyNanResponseHeaderToHidl(
1904     const legacy_hal::NanResponseMsg& legacy_response,
1905     WifiNanStatus* wifiNanStatus) {
1906     if (!wifiNanStatus) {
1907         LOG(ERROR)
1908             << "convertLegacyNanResponseHeaderToHidl: wifiNanStatus is null";
1909         return false;
1910     }
1911     *wifiNanStatus = {};
1912 
1913     convertToWifiNanStatus(legacy_response.status, legacy_response.nan_error,
1914                            sizeof(legacy_response.nan_error), wifiNanStatus);
1915     return true;
1916 }
1917 
convertLegacyNanCapabilitiesResponseToHidl(const legacy_hal::NanCapabilities & legacy_response,NanCapabilities * hidl_response)1918 bool convertLegacyNanCapabilitiesResponseToHidl(
1919     const legacy_hal::NanCapabilities& legacy_response,
1920     NanCapabilities* hidl_response) {
1921     if (!hidl_response) {
1922         LOG(ERROR) << "convertLegacyNanCapabilitiesResponseToHidl: "
1923                       "hidl_response is null";
1924         return false;
1925     }
1926     *hidl_response = {};
1927 
1928     hidl_response->maxConcurrentClusters =
1929         legacy_response.max_concurrent_nan_clusters;
1930     hidl_response->maxPublishes = legacy_response.max_publishes;
1931     hidl_response->maxSubscribes = legacy_response.max_subscribes;
1932     hidl_response->maxServiceNameLen = legacy_response.max_service_name_len;
1933     hidl_response->maxMatchFilterLen = legacy_response.max_match_filter_len;
1934     hidl_response->maxTotalMatchFilterLen =
1935         legacy_response.max_total_match_filter_len;
1936     hidl_response->maxServiceSpecificInfoLen =
1937         legacy_response.max_service_specific_info_len;
1938     hidl_response->maxExtendedServiceSpecificInfoLen =
1939         legacy_response.max_sdea_service_specific_info_len;
1940     hidl_response->maxNdiInterfaces = legacy_response.max_ndi_interfaces;
1941     hidl_response->maxNdpSessions = legacy_response.max_ndp_sessions;
1942     hidl_response->maxAppInfoLen = legacy_response.max_app_info_len;
1943     hidl_response->maxQueuedTransmitFollowupMsgs =
1944         legacy_response.max_queued_transmit_followup_msgs;
1945     hidl_response->maxSubscribeInterfaceAddresses =
1946         legacy_response.max_subscribe_address;
1947     hidl_response->supportedCipherSuites =
1948         legacy_response.cipher_suites_supported;
1949 
1950     return true;
1951 }
1952 
convertLegacyNanMatchIndToHidl(const legacy_hal::NanMatchInd & legacy_ind,NanMatchInd * hidl_ind)1953 bool convertLegacyNanMatchIndToHidl(const legacy_hal::NanMatchInd& legacy_ind,
1954                                     NanMatchInd* hidl_ind) {
1955     if (!hidl_ind) {
1956         LOG(ERROR) << "convertLegacyNanMatchIndToHidl: hidl_ind is null";
1957         return false;
1958     }
1959     *hidl_ind = {};
1960 
1961     hidl_ind->discoverySessionId = legacy_ind.publish_subscribe_id;
1962     hidl_ind->peerId = legacy_ind.requestor_instance_id;
1963     hidl_ind->addr = hidl_array<uint8_t, 6>(legacy_ind.addr);
1964     hidl_ind->serviceSpecificInfo =
1965         std::vector<uint8_t>(legacy_ind.service_specific_info,
1966                              legacy_ind.service_specific_info +
1967                                  legacy_ind.service_specific_info_len);
1968     hidl_ind->extendedServiceSpecificInfo =
1969         std::vector<uint8_t>(legacy_ind.sdea_service_specific_info,
1970                              legacy_ind.sdea_service_specific_info +
1971                                  legacy_ind.sdea_service_specific_info_len);
1972     hidl_ind->matchFilter = std::vector<uint8_t>(
1973         legacy_ind.sdf_match_filter,
1974         legacy_ind.sdf_match_filter + legacy_ind.sdf_match_filter_len);
1975     hidl_ind->matchOccuredInBeaconFlag = legacy_ind.match_occured_flag == 1;
1976     hidl_ind->outOfResourceFlag = legacy_ind.out_of_resource_flag == 1;
1977     hidl_ind->rssiValue = legacy_ind.rssi_value;
1978     hidl_ind->peerCipherType = (NanCipherSuiteType)legacy_ind.peer_cipher_type;
1979     hidl_ind->peerRequiresSecurityEnabledInNdp =
1980         legacy_ind.peer_sdea_params.security_cfg ==
1981         legacy_hal::NAN_DP_CONFIG_SECURITY;
1982     hidl_ind->peerRequiresRanging = legacy_ind.peer_sdea_params.ranging_state ==
1983                                     legacy_hal::NAN_RANGING_ENABLE;
1984     hidl_ind->rangingMeasurementInCm =
1985         legacy_ind.range_info.range_measurement_mm / 10;
1986     hidl_ind->rangingIndicationType = legacy_ind.range_info.ranging_event_type;
1987 
1988     return true;
1989 }
1990 
convertLegacyNanFollowupIndToHidl(const legacy_hal::NanFollowupInd & legacy_ind,NanFollowupReceivedInd * hidl_ind)1991 bool convertLegacyNanFollowupIndToHidl(
1992     const legacy_hal::NanFollowupInd& legacy_ind,
1993     NanFollowupReceivedInd* hidl_ind) {
1994     if (!hidl_ind) {
1995         LOG(ERROR) << "convertLegacyNanFollowupIndToHidl: hidl_ind is null";
1996         return false;
1997     }
1998     *hidl_ind = {};
1999 
2000     hidl_ind->discoverySessionId = legacy_ind.publish_subscribe_id;
2001     hidl_ind->peerId = legacy_ind.requestor_instance_id;
2002     hidl_ind->addr = hidl_array<uint8_t, 6>(legacy_ind.addr);
2003     hidl_ind->receivedInFaw = legacy_ind.dw_or_faw == 1;
2004     hidl_ind->serviceSpecificInfo =
2005         std::vector<uint8_t>(legacy_ind.service_specific_info,
2006                              legacy_ind.service_specific_info +
2007                                  legacy_ind.service_specific_info_len);
2008     hidl_ind->extendedServiceSpecificInfo =
2009         std::vector<uint8_t>(legacy_ind.sdea_service_specific_info,
2010                              legacy_ind.sdea_service_specific_info +
2011                                  legacy_ind.sdea_service_specific_info_len);
2012 
2013     return true;
2014 }
2015 
convertLegacyNanDataPathRequestIndToHidl(const legacy_hal::NanDataPathRequestInd & legacy_ind,NanDataPathRequestInd * hidl_ind)2016 bool convertLegacyNanDataPathRequestIndToHidl(
2017     const legacy_hal::NanDataPathRequestInd& legacy_ind,
2018     NanDataPathRequestInd* hidl_ind) {
2019     if (!hidl_ind) {
2020         LOG(ERROR)
2021             << "convertLegacyNanDataPathRequestIndToHidl: hidl_ind is null";
2022         return false;
2023     }
2024     *hidl_ind = {};
2025 
2026     hidl_ind->discoverySessionId = legacy_ind.service_instance_id;
2027     hidl_ind->peerDiscMacAddr =
2028         hidl_array<uint8_t, 6>(legacy_ind.peer_disc_mac_addr);
2029     hidl_ind->ndpInstanceId = legacy_ind.ndp_instance_id;
2030     hidl_ind->securityRequired =
2031         legacy_ind.ndp_cfg.security_cfg == legacy_hal::NAN_DP_CONFIG_SECURITY;
2032     hidl_ind->appInfo =
2033         std::vector<uint8_t>(legacy_ind.app_info.ndp_app_info,
2034                              legacy_ind.app_info.ndp_app_info +
2035                                  legacy_ind.app_info.ndp_app_info_len);
2036 
2037     return true;
2038 }
2039 
convertLegacyNdpChannelInfoToHidl(const legacy_hal::NanChannelInfo & legacy_struct,NanDataPathChannelInfo * hidl_struct)2040 bool convertLegacyNdpChannelInfoToHidl(
2041     const legacy_hal::NanChannelInfo& legacy_struct,
2042     NanDataPathChannelInfo* hidl_struct) {
2043     if (!hidl_struct) {
2044         LOG(ERROR) << "convertLegacyNdpChannelInfoToHidl: hidl_struct is null";
2045         return false;
2046     }
2047     *hidl_struct = {};
2048 
2049     hidl_struct->channelFreq = legacy_struct.channel;
2050     hidl_struct->channelBandwidth = convertLegacyWifiChannelWidthToHidl(
2051         (legacy_hal::wifi_channel_width)legacy_struct.bandwidth);
2052     hidl_struct->numSpatialStreams = legacy_struct.nss;
2053 
2054     return true;
2055 }
2056 
convertLegacyNanDataPathConfirmIndToHidl(const legacy_hal::NanDataPathConfirmInd & legacy_ind,NanDataPathConfirmInd * hidl_ind)2057 bool convertLegacyNanDataPathConfirmIndToHidl(
2058     const legacy_hal::NanDataPathConfirmInd& legacy_ind,
2059     NanDataPathConfirmInd* hidl_ind) {
2060     if (!hidl_ind) {
2061         LOG(ERROR)
2062             << "convertLegacyNanDataPathConfirmIndToHidl: hidl_ind is null";
2063         return false;
2064     }
2065     *hidl_ind = {};
2066 
2067     hidl_ind->V1_0.ndpInstanceId = legacy_ind.ndp_instance_id;
2068     hidl_ind->V1_0.dataPathSetupSuccess =
2069         legacy_ind.rsp_code == legacy_hal::NAN_DP_REQUEST_ACCEPT;
2070     hidl_ind->V1_0.peerNdiMacAddr =
2071         hidl_array<uint8_t, 6>(legacy_ind.peer_ndi_mac_addr);
2072     hidl_ind->V1_0.appInfo =
2073         std::vector<uint8_t>(legacy_ind.app_info.ndp_app_info,
2074                              legacy_ind.app_info.ndp_app_info +
2075                                  legacy_ind.app_info.ndp_app_info_len);
2076     hidl_ind->V1_0.status.status =
2077         convertLegacyNanStatusTypeToHidl(legacy_ind.reason_code);
2078     hidl_ind->V1_0.status.description = "";  // TODO: b/34059183
2079 
2080     std::vector<NanDataPathChannelInfo> channelInfo;
2081     for (unsigned int i = 0; i < legacy_ind.num_channels; ++i) {
2082         NanDataPathChannelInfo hidl_struct;
2083         if (!convertLegacyNdpChannelInfoToHidl(legacy_ind.channel_info[i],
2084                                                &hidl_struct)) {
2085             return false;
2086         }
2087         channelInfo.push_back(hidl_struct);
2088     }
2089     hidl_ind->channelInfo = channelInfo;
2090 
2091     return true;
2092 }
2093 
convertLegacyNanDataPathScheduleUpdateIndToHidl(const legacy_hal::NanDataPathScheduleUpdateInd & legacy_ind,NanDataPathScheduleUpdateInd * hidl_ind)2094 bool convertLegacyNanDataPathScheduleUpdateIndToHidl(
2095     const legacy_hal::NanDataPathScheduleUpdateInd& legacy_ind,
2096     NanDataPathScheduleUpdateInd* hidl_ind) {
2097     if (!hidl_ind) {
2098         LOG(ERROR) << "convertLegacyNanDataPathScheduleUpdateIndToHidl: "
2099                       "hidl_ind is null";
2100         return false;
2101     }
2102     *hidl_ind = {};
2103 
2104     hidl_ind->peerDiscoveryAddress =
2105         hidl_array<uint8_t, 6>(legacy_ind.peer_mac_addr);
2106     std::vector<NanDataPathChannelInfo> channelInfo;
2107     for (unsigned int i = 0; i < legacy_ind.num_channels; ++i) {
2108         NanDataPathChannelInfo hidl_struct;
2109         if (!convertLegacyNdpChannelInfoToHidl(legacy_ind.channel_info[i],
2110                                                &hidl_struct)) {
2111             return false;
2112         }
2113         channelInfo.push_back(hidl_struct);
2114     }
2115     hidl_ind->channelInfo = channelInfo;
2116     std::vector<uint32_t> ndpInstanceIds;
2117     for (unsigned int i = 0; i < legacy_ind.num_ndp_instances; ++i) {
2118         ndpInstanceIds.push_back(legacy_ind.ndp_instance_id[i]);
2119     }
2120     hidl_ind->ndpInstanceIds = ndpInstanceIds;
2121 
2122     return true;
2123 }
2124 
convertHidlRttTypeToLegacy(RttType type)2125 legacy_hal::wifi_rtt_type convertHidlRttTypeToLegacy(RttType type) {
2126     switch (type) {
2127         case RttType::ONE_SIDED:
2128             return legacy_hal::RTT_TYPE_1_SIDED;
2129         case RttType::TWO_SIDED:
2130             return legacy_hal::RTT_TYPE_2_SIDED;
2131     };
2132     CHECK(false);
2133 }
2134 
convertLegacyRttTypeToHidl(legacy_hal::wifi_rtt_type type)2135 RttType convertLegacyRttTypeToHidl(legacy_hal::wifi_rtt_type type) {
2136     switch (type) {
2137         case legacy_hal::RTT_TYPE_1_SIDED:
2138             return RttType::ONE_SIDED;
2139         case legacy_hal::RTT_TYPE_2_SIDED:
2140             return RttType::TWO_SIDED;
2141     };
2142     CHECK(false) << "Unknown legacy type: " << type;
2143 }
2144 
convertHidlRttPeerTypeToLegacy(RttPeerType type)2145 legacy_hal::rtt_peer_type convertHidlRttPeerTypeToLegacy(RttPeerType type) {
2146     switch (type) {
2147         case RttPeerType::AP:
2148             return legacy_hal::RTT_PEER_AP;
2149         case RttPeerType::STA:
2150             return legacy_hal::RTT_PEER_STA;
2151         case RttPeerType::P2P_GO:
2152             return legacy_hal::RTT_PEER_P2P_GO;
2153         case RttPeerType::P2P_CLIENT:
2154             return legacy_hal::RTT_PEER_P2P_CLIENT;
2155         case RttPeerType::NAN:
2156             return legacy_hal::RTT_PEER_NAN;
2157     };
2158     CHECK(false);
2159 }
2160 
convertHidlWifiChannelWidthToLegacy(WifiChannelWidthInMhz type)2161 legacy_hal::wifi_channel_width convertHidlWifiChannelWidthToLegacy(
2162     WifiChannelWidthInMhz type) {
2163     switch (type) {
2164         case WifiChannelWidthInMhz::WIDTH_20:
2165             return legacy_hal::WIFI_CHAN_WIDTH_20;
2166         case WifiChannelWidthInMhz::WIDTH_40:
2167             return legacy_hal::WIFI_CHAN_WIDTH_40;
2168         case WifiChannelWidthInMhz::WIDTH_80:
2169             return legacy_hal::WIFI_CHAN_WIDTH_80;
2170         case WifiChannelWidthInMhz::WIDTH_160:
2171             return legacy_hal::WIFI_CHAN_WIDTH_160;
2172         case WifiChannelWidthInMhz::WIDTH_80P80:
2173             return legacy_hal::WIFI_CHAN_WIDTH_80P80;
2174         case WifiChannelWidthInMhz::WIDTH_5:
2175             return legacy_hal::WIFI_CHAN_WIDTH_5;
2176         case WifiChannelWidthInMhz::WIDTH_10:
2177             return legacy_hal::WIFI_CHAN_WIDTH_10;
2178         case WifiChannelWidthInMhz::WIDTH_INVALID:
2179             return legacy_hal::WIFI_CHAN_WIDTH_INVALID;
2180     };
2181     CHECK(false);
2182 }
2183 
convertLegacyWifiChannelWidthToHidl(legacy_hal::wifi_channel_width type)2184 WifiChannelWidthInMhz convertLegacyWifiChannelWidthToHidl(
2185     legacy_hal::wifi_channel_width type) {
2186     switch (type) {
2187         case legacy_hal::WIFI_CHAN_WIDTH_20:
2188             return WifiChannelWidthInMhz::WIDTH_20;
2189         case legacy_hal::WIFI_CHAN_WIDTH_40:
2190             return WifiChannelWidthInMhz::WIDTH_40;
2191         case legacy_hal::WIFI_CHAN_WIDTH_80:
2192             return WifiChannelWidthInMhz::WIDTH_80;
2193         case legacy_hal::WIFI_CHAN_WIDTH_160:
2194             return WifiChannelWidthInMhz::WIDTH_160;
2195         case legacy_hal::WIFI_CHAN_WIDTH_80P80:
2196             return WifiChannelWidthInMhz::WIDTH_80P80;
2197         case legacy_hal::WIFI_CHAN_WIDTH_5:
2198             return WifiChannelWidthInMhz::WIDTH_5;
2199         case legacy_hal::WIFI_CHAN_WIDTH_10:
2200             return WifiChannelWidthInMhz::WIDTH_10;
2201         case legacy_hal::WIFI_CHAN_WIDTH_INVALID:
2202             return WifiChannelWidthInMhz::WIDTH_INVALID;
2203     };
2204     CHECK(false) << "Unknown legacy type: " << type;
2205 }
2206 
convertHidlRttPreambleToLegacy(RttPreamble type)2207 legacy_hal::wifi_rtt_preamble convertHidlRttPreambleToLegacy(RttPreamble type) {
2208     switch (type) {
2209         case RttPreamble::LEGACY:
2210             return legacy_hal::WIFI_RTT_PREAMBLE_LEGACY;
2211         case RttPreamble::HT:
2212             return legacy_hal::WIFI_RTT_PREAMBLE_HT;
2213         case RttPreamble::VHT:
2214             return legacy_hal::WIFI_RTT_PREAMBLE_VHT;
2215     };
2216     CHECK(false);
2217 }
2218 
convertLegacyRttPreambleToHidl(legacy_hal::wifi_rtt_preamble type)2219 RttPreamble convertLegacyRttPreambleToHidl(legacy_hal::wifi_rtt_preamble type) {
2220     switch (type) {
2221         case legacy_hal::WIFI_RTT_PREAMBLE_LEGACY:
2222             return RttPreamble::LEGACY;
2223         case legacy_hal::WIFI_RTT_PREAMBLE_HT:
2224             return RttPreamble::HT;
2225         case legacy_hal::WIFI_RTT_PREAMBLE_VHT:
2226             return RttPreamble::VHT;
2227     };
2228     CHECK(false) << "Unknown legacy type: " << type;
2229 }
2230 
convertHidlRttBwToLegacy(RttBw type)2231 legacy_hal::wifi_rtt_bw convertHidlRttBwToLegacy(RttBw type) {
2232     switch (type) {
2233         case RttBw::BW_5MHZ:
2234             return legacy_hal::WIFI_RTT_BW_5;
2235         case RttBw::BW_10MHZ:
2236             return legacy_hal::WIFI_RTT_BW_10;
2237         case RttBw::BW_20MHZ:
2238             return legacy_hal::WIFI_RTT_BW_20;
2239         case RttBw::BW_40MHZ:
2240             return legacy_hal::WIFI_RTT_BW_40;
2241         case RttBw::BW_80MHZ:
2242             return legacy_hal::WIFI_RTT_BW_80;
2243         case RttBw::BW_160MHZ:
2244             return legacy_hal::WIFI_RTT_BW_160;
2245     };
2246     CHECK(false);
2247 }
2248 
convertLegacyRttBwToHidl(legacy_hal::wifi_rtt_bw type)2249 RttBw convertLegacyRttBwToHidl(legacy_hal::wifi_rtt_bw type) {
2250     switch (type) {
2251         case legacy_hal::WIFI_RTT_BW_5:
2252             return RttBw::BW_5MHZ;
2253         case legacy_hal::WIFI_RTT_BW_10:
2254             return RttBw::BW_10MHZ;
2255         case legacy_hal::WIFI_RTT_BW_20:
2256             return RttBw::BW_20MHZ;
2257         case legacy_hal::WIFI_RTT_BW_40:
2258             return RttBw::BW_40MHZ;
2259         case legacy_hal::WIFI_RTT_BW_80:
2260             return RttBw::BW_80MHZ;
2261         case legacy_hal::WIFI_RTT_BW_160:
2262             return RttBw::BW_160MHZ;
2263     };
2264     CHECK(false) << "Unknown legacy type: " << type;
2265 }
2266 
convertHidlRttMotionPatternToLegacy(RttMotionPattern type)2267 legacy_hal::wifi_motion_pattern convertHidlRttMotionPatternToLegacy(
2268     RttMotionPattern type) {
2269     switch (type) {
2270         case RttMotionPattern::NOT_EXPECTED:
2271             return legacy_hal::WIFI_MOTION_NOT_EXPECTED;
2272         case RttMotionPattern::EXPECTED:
2273             return legacy_hal::WIFI_MOTION_EXPECTED;
2274         case RttMotionPattern::UNKNOWN:
2275             return legacy_hal::WIFI_MOTION_UNKNOWN;
2276     };
2277     CHECK(false);
2278 }
2279 
convertLegacyWifiRatePreambleToHidl(uint8_t preamble)2280 WifiRatePreamble convertLegacyWifiRatePreambleToHidl(uint8_t preamble) {
2281     switch (preamble) {
2282         case 0:
2283             return WifiRatePreamble::OFDM;
2284         case 1:
2285             return WifiRatePreamble::CCK;
2286         case 2:
2287             return WifiRatePreamble::HT;
2288         case 3:
2289             return WifiRatePreamble::VHT;
2290         default:
2291             return WifiRatePreamble::RESERVED;
2292     };
2293     CHECK(false) << "Unknown legacy preamble: " << preamble;
2294 }
2295 
convertLegacyWifiRateNssToHidl(uint8_t nss)2296 WifiRateNss convertLegacyWifiRateNssToHidl(uint8_t nss) {
2297     switch (nss) {
2298         case 0:
2299             return WifiRateNss::NSS_1x1;
2300         case 1:
2301             return WifiRateNss::NSS_2x2;
2302         case 2:
2303             return WifiRateNss::NSS_3x3;
2304         case 3:
2305             return WifiRateNss::NSS_4x4;
2306     };
2307     CHECK(false) << "Unknown legacy nss: " << nss;
2308     return {};
2309 }
2310 
convertLegacyRttStatusToHidl(legacy_hal::wifi_rtt_status status)2311 RttStatus convertLegacyRttStatusToHidl(legacy_hal::wifi_rtt_status status) {
2312     switch (status) {
2313         case legacy_hal::RTT_STATUS_SUCCESS:
2314             return RttStatus::SUCCESS;
2315         case legacy_hal::RTT_STATUS_FAILURE:
2316             return RttStatus::FAILURE;
2317         case legacy_hal::RTT_STATUS_FAIL_NO_RSP:
2318             return RttStatus::FAIL_NO_RSP;
2319         case legacy_hal::RTT_STATUS_FAIL_REJECTED:
2320             return RttStatus::FAIL_REJECTED;
2321         case legacy_hal::RTT_STATUS_FAIL_NOT_SCHEDULED_YET:
2322             return RttStatus::FAIL_NOT_SCHEDULED_YET;
2323         case legacy_hal::RTT_STATUS_FAIL_TM_TIMEOUT:
2324             return RttStatus::FAIL_TM_TIMEOUT;
2325         case legacy_hal::RTT_STATUS_FAIL_AP_ON_DIFF_CHANNEL:
2326             return RttStatus::FAIL_AP_ON_DIFF_CHANNEL;
2327         case legacy_hal::RTT_STATUS_FAIL_NO_CAPABILITY:
2328             return RttStatus::FAIL_NO_CAPABILITY;
2329         case legacy_hal::RTT_STATUS_ABORTED:
2330             return RttStatus::ABORTED;
2331         case legacy_hal::RTT_STATUS_FAIL_INVALID_TS:
2332             return RttStatus::FAIL_INVALID_TS;
2333         case legacy_hal::RTT_STATUS_FAIL_PROTOCOL:
2334             return RttStatus::FAIL_PROTOCOL;
2335         case legacy_hal::RTT_STATUS_FAIL_SCHEDULE:
2336             return RttStatus::FAIL_SCHEDULE;
2337         case legacy_hal::RTT_STATUS_FAIL_BUSY_TRY_LATER:
2338             return RttStatus::FAIL_BUSY_TRY_LATER;
2339         case legacy_hal::RTT_STATUS_INVALID_REQ:
2340             return RttStatus::INVALID_REQ;
2341         case legacy_hal::RTT_STATUS_NO_WIFI:
2342             return RttStatus::NO_WIFI;
2343         case legacy_hal::RTT_STATUS_FAIL_FTM_PARAM_OVERRIDE:
2344             return RttStatus::FAIL_FTM_PARAM_OVERRIDE;
2345         case legacy_hal::RTT_STATUS_NAN_RANGING_PROTOCOL_FAILURE:
2346             return RttStatus::FAILURE;  // TODO: add HIDL enumeration
2347         case legacy_hal::RTT_STATUS_NAN_RANGING_CONCURRENCY_NOT_SUPPORTED:
2348             return RttStatus::FAILURE;  // TODO: add HIDL enumeration
2349     };
2350     CHECK(false) << "Unknown legacy status: " << status;
2351 }
2352 
convertHidlWifiChannelInfoToLegacy(const WifiChannelInfo & hidl_info,legacy_hal::wifi_channel_info * legacy_info)2353 bool convertHidlWifiChannelInfoToLegacy(
2354     const WifiChannelInfo& hidl_info,
2355     legacy_hal::wifi_channel_info* legacy_info) {
2356     if (!legacy_info) {
2357         return false;
2358     }
2359     *legacy_info = {};
2360     legacy_info->width = convertHidlWifiChannelWidthToLegacy(hidl_info.width);
2361     legacy_info->center_freq = hidl_info.centerFreq;
2362     legacy_info->center_freq0 = hidl_info.centerFreq0;
2363     legacy_info->center_freq1 = hidl_info.centerFreq1;
2364     return true;
2365 }
2366 
convertLegacyWifiChannelInfoToHidl(const legacy_hal::wifi_channel_info & legacy_info,WifiChannelInfo * hidl_info)2367 bool convertLegacyWifiChannelInfoToHidl(
2368     const legacy_hal::wifi_channel_info& legacy_info,
2369     WifiChannelInfo* hidl_info) {
2370     if (!hidl_info) {
2371         return false;
2372     }
2373     *hidl_info = {};
2374     hidl_info->width = convertLegacyWifiChannelWidthToHidl(legacy_info.width);
2375     hidl_info->centerFreq = legacy_info.center_freq;
2376     hidl_info->centerFreq0 = legacy_info.center_freq0;
2377     hidl_info->centerFreq1 = legacy_info.center_freq1;
2378     return true;
2379 }
2380 
convertHidlRttConfigToLegacy(const RttConfig & hidl_config,legacy_hal::wifi_rtt_config * legacy_config)2381 bool convertHidlRttConfigToLegacy(const RttConfig& hidl_config,
2382                                   legacy_hal::wifi_rtt_config* legacy_config) {
2383     if (!legacy_config) {
2384         return false;
2385     }
2386     *legacy_config = {};
2387     CHECK(hidl_config.addr.size() == sizeof(legacy_config->addr));
2388     memcpy(legacy_config->addr, hidl_config.addr.data(),
2389            hidl_config.addr.size());
2390     legacy_config->type = convertHidlRttTypeToLegacy(hidl_config.type);
2391     legacy_config->peer = convertHidlRttPeerTypeToLegacy(hidl_config.peer);
2392     if (!convertHidlWifiChannelInfoToLegacy(hidl_config.channel,
2393                                             &legacy_config->channel)) {
2394         return false;
2395     }
2396     legacy_config->burst_period = hidl_config.burstPeriod;
2397     legacy_config->num_burst = hidl_config.numBurst;
2398     legacy_config->num_frames_per_burst = hidl_config.numFramesPerBurst;
2399     legacy_config->num_retries_per_rtt_frame =
2400         hidl_config.numRetriesPerRttFrame;
2401     legacy_config->num_retries_per_ftmr = hidl_config.numRetriesPerFtmr;
2402     legacy_config->LCI_request = hidl_config.mustRequestLci;
2403     legacy_config->LCR_request = hidl_config.mustRequestLcr;
2404     legacy_config->burst_duration = hidl_config.burstDuration;
2405     legacy_config->preamble =
2406         convertHidlRttPreambleToLegacy(hidl_config.preamble);
2407     legacy_config->bw = convertHidlRttBwToLegacy(hidl_config.bw);
2408     return true;
2409 }
2410 
convertHidlVectorOfRttConfigToLegacy(const std::vector<RttConfig> & hidl_configs,std::vector<legacy_hal::wifi_rtt_config> * legacy_configs)2411 bool convertHidlVectorOfRttConfigToLegacy(
2412     const std::vector<RttConfig>& hidl_configs,
2413     std::vector<legacy_hal::wifi_rtt_config>* legacy_configs) {
2414     if (!legacy_configs) {
2415         return false;
2416     }
2417     *legacy_configs = {};
2418     for (const auto& hidl_config : hidl_configs) {
2419         legacy_hal::wifi_rtt_config legacy_config;
2420         if (!convertHidlRttConfigToLegacy(hidl_config, &legacy_config)) {
2421             return false;
2422         }
2423         legacy_configs->push_back(legacy_config);
2424     }
2425     return true;
2426 }
2427 
convertHidlRttLciInformationToLegacy(const RttLciInformation & hidl_info,legacy_hal::wifi_lci_information * legacy_info)2428 bool convertHidlRttLciInformationToLegacy(
2429     const RttLciInformation& hidl_info,
2430     legacy_hal::wifi_lci_information* legacy_info) {
2431     if (!legacy_info) {
2432         return false;
2433     }
2434     *legacy_info = {};
2435     legacy_info->latitude = hidl_info.latitude;
2436     legacy_info->longitude = hidl_info.longitude;
2437     legacy_info->altitude = hidl_info.altitude;
2438     legacy_info->latitude_unc = hidl_info.latitudeUnc;
2439     legacy_info->longitude_unc = hidl_info.longitudeUnc;
2440     legacy_info->altitude_unc = hidl_info.altitudeUnc;
2441     legacy_info->motion_pattern =
2442         convertHidlRttMotionPatternToLegacy(hidl_info.motionPattern);
2443     legacy_info->floor = hidl_info.floor;
2444     legacy_info->height_above_floor = hidl_info.heightAboveFloor;
2445     legacy_info->height_unc = hidl_info.heightUnc;
2446     return true;
2447 }
2448 
convertHidlRttLcrInformationToLegacy(const RttLcrInformation & hidl_info,legacy_hal::wifi_lcr_information * legacy_info)2449 bool convertHidlRttLcrInformationToLegacy(
2450     const RttLcrInformation& hidl_info,
2451     legacy_hal::wifi_lcr_information* legacy_info) {
2452     if (!legacy_info) {
2453         return false;
2454     }
2455     *legacy_info = {};
2456     CHECK(hidl_info.countryCode.size() == sizeof(legacy_info->country_code));
2457     memcpy(legacy_info->country_code, hidl_info.countryCode.data(),
2458            hidl_info.countryCode.size());
2459     if (hidl_info.civicInfo.size() > sizeof(legacy_info->civic_info)) {
2460         return false;
2461     }
2462     legacy_info->length = hidl_info.civicInfo.size();
2463     memcpy(legacy_info->civic_info, hidl_info.civicInfo.c_str(),
2464            hidl_info.civicInfo.size());
2465     return true;
2466 }
2467 
convertHidlRttResponderToLegacy(const RttResponder & hidl_responder,legacy_hal::wifi_rtt_responder * legacy_responder)2468 bool convertHidlRttResponderToLegacy(
2469     const RttResponder& hidl_responder,
2470     legacy_hal::wifi_rtt_responder* legacy_responder) {
2471     if (!legacy_responder) {
2472         return false;
2473     }
2474     *legacy_responder = {};
2475     if (!convertHidlWifiChannelInfoToLegacy(hidl_responder.channel,
2476                                             &legacy_responder->channel)) {
2477         return false;
2478     }
2479     legacy_responder->preamble =
2480         convertHidlRttPreambleToLegacy(hidl_responder.preamble);
2481     return true;
2482 }
2483 
convertLegacyRttResponderToHidl(const legacy_hal::wifi_rtt_responder & legacy_responder,RttResponder * hidl_responder)2484 bool convertLegacyRttResponderToHidl(
2485     const legacy_hal::wifi_rtt_responder& legacy_responder,
2486     RttResponder* hidl_responder) {
2487     if (!hidl_responder) {
2488         return false;
2489     }
2490     *hidl_responder = {};
2491     if (!convertLegacyWifiChannelInfoToHidl(legacy_responder.channel,
2492                                             &hidl_responder->channel)) {
2493         return false;
2494     }
2495     hidl_responder->preamble =
2496         convertLegacyRttPreambleToHidl(legacy_responder.preamble);
2497     return true;
2498 }
2499 
convertLegacyRttCapabilitiesToHidl(const legacy_hal::wifi_rtt_capabilities & legacy_capabilities,RttCapabilities * hidl_capabilities)2500 bool convertLegacyRttCapabilitiesToHidl(
2501     const legacy_hal::wifi_rtt_capabilities& legacy_capabilities,
2502     RttCapabilities* hidl_capabilities) {
2503     if (!hidl_capabilities) {
2504         return false;
2505     }
2506     *hidl_capabilities = {};
2507     hidl_capabilities->rttOneSidedSupported =
2508         legacy_capabilities.rtt_one_sided_supported;
2509     hidl_capabilities->rttFtmSupported = legacy_capabilities.rtt_ftm_supported;
2510     hidl_capabilities->lciSupported = legacy_capabilities.lci_support;
2511     hidl_capabilities->lcrSupported = legacy_capabilities.lcr_support;
2512     hidl_capabilities->responderSupported =
2513         legacy_capabilities.responder_supported;
2514     hidl_capabilities->preambleSupport = 0;
2515     for (const auto flag : {legacy_hal::WIFI_RTT_PREAMBLE_LEGACY,
2516                             legacy_hal::WIFI_RTT_PREAMBLE_HT,
2517                             legacy_hal::WIFI_RTT_PREAMBLE_VHT}) {
2518         if (legacy_capabilities.preamble_support & flag) {
2519             hidl_capabilities->preambleSupport |=
2520                 static_cast<std::underlying_type<RttPreamble>::type>(
2521                     convertLegacyRttPreambleToHidl(flag));
2522         }
2523     }
2524     hidl_capabilities->bwSupport = 0;
2525     for (const auto flag :
2526          {legacy_hal::WIFI_RTT_BW_5, legacy_hal::WIFI_RTT_BW_10,
2527           legacy_hal::WIFI_RTT_BW_20, legacy_hal::WIFI_RTT_BW_40,
2528           legacy_hal::WIFI_RTT_BW_80, legacy_hal::WIFI_RTT_BW_160}) {
2529         if (legacy_capabilities.bw_support & flag) {
2530             hidl_capabilities->bwSupport |=
2531                 static_cast<std::underlying_type<RttBw>::type>(
2532                     convertLegacyRttBwToHidl(flag));
2533         }
2534     }
2535     hidl_capabilities->mcVersion = legacy_capabilities.mc_version;
2536     return true;
2537 }
2538 
convertLegacyWifiRateInfoToHidl(const legacy_hal::wifi_rate & legacy_rate,WifiRateInfo * hidl_rate)2539 bool convertLegacyWifiRateInfoToHidl(const legacy_hal::wifi_rate& legacy_rate,
2540                                      WifiRateInfo* hidl_rate) {
2541     if (!hidl_rate) {
2542         return false;
2543     }
2544     *hidl_rate = {};
2545     hidl_rate->preamble =
2546         convertLegacyWifiRatePreambleToHidl(legacy_rate.preamble);
2547     hidl_rate->nss = convertLegacyWifiRateNssToHidl(legacy_rate.nss);
2548     hidl_rate->bw = convertLegacyWifiChannelWidthToHidl(
2549         static_cast<legacy_hal::wifi_channel_width>(legacy_rate.bw));
2550     hidl_rate->rateMcsIdx = legacy_rate.rateMcsIdx;
2551     hidl_rate->bitRateInKbps = legacy_rate.bitrate;
2552     return true;
2553 }
2554 
convertLegacyRttResultToHidl(const legacy_hal::wifi_rtt_result & legacy_result,RttResult * hidl_result)2555 bool convertLegacyRttResultToHidl(
2556     const legacy_hal::wifi_rtt_result& legacy_result, RttResult* hidl_result) {
2557     if (!hidl_result) {
2558         return false;
2559     }
2560     *hidl_result = {};
2561     CHECK(sizeof(legacy_result.addr) == hidl_result->addr.size());
2562     memcpy(hidl_result->addr.data(), legacy_result.addr,
2563            sizeof(legacy_result.addr));
2564     hidl_result->burstNum = legacy_result.burst_num;
2565     hidl_result->measurementNumber = legacy_result.measurement_number;
2566     hidl_result->successNumber = legacy_result.success_number;
2567     hidl_result->numberPerBurstPeer = legacy_result.number_per_burst_peer;
2568     hidl_result->status = convertLegacyRttStatusToHidl(legacy_result.status);
2569     hidl_result->retryAfterDuration = legacy_result.retry_after_duration;
2570     hidl_result->type = convertLegacyRttTypeToHidl(legacy_result.type);
2571     hidl_result->rssi = legacy_result.rssi;
2572     hidl_result->rssiSpread = legacy_result.rssi_spread;
2573     if (!convertLegacyWifiRateInfoToHidl(legacy_result.tx_rate,
2574                                          &hidl_result->txRate)) {
2575         return false;
2576     }
2577     if (!convertLegacyWifiRateInfoToHidl(legacy_result.rx_rate,
2578                                          &hidl_result->rxRate)) {
2579         return false;
2580     }
2581     hidl_result->rtt = legacy_result.rtt;
2582     hidl_result->rttSd = legacy_result.rtt_sd;
2583     hidl_result->rttSpread = legacy_result.rtt_spread;
2584     hidl_result->distanceInMm = legacy_result.distance_mm;
2585     hidl_result->distanceSdInMm = legacy_result.distance_sd_mm;
2586     hidl_result->distanceSpreadInMm = legacy_result.distance_spread_mm;
2587     hidl_result->timeStampInUs = legacy_result.ts;
2588     hidl_result->burstDurationInMs = legacy_result.burst_duration;
2589     hidl_result->negotiatedBurstNum = legacy_result.negotiated_burst_num;
2590     if (legacy_result.LCI &&
2591         !convertLegacyIeToHidl(*legacy_result.LCI, &hidl_result->lci)) {
2592         return false;
2593     }
2594     if (legacy_result.LCR &&
2595         !convertLegacyIeToHidl(*legacy_result.LCR, &hidl_result->lcr)) {
2596         return false;
2597     }
2598     return true;
2599 }
2600 
convertLegacyVectorOfRttResultToHidl(const std::vector<const legacy_hal::wifi_rtt_result * > & legacy_results,std::vector<RttResult> * hidl_results)2601 bool convertLegacyVectorOfRttResultToHidl(
2602     const std::vector<const legacy_hal::wifi_rtt_result*>& legacy_results,
2603     std::vector<RttResult>* hidl_results) {
2604     if (!hidl_results) {
2605         return false;
2606     }
2607     *hidl_results = {};
2608     for (const auto legacy_result : legacy_results) {
2609         RttResult hidl_result;
2610         if (!convertLegacyRttResultToHidl(*legacy_result, &hidl_result)) {
2611             return false;
2612         }
2613         hidl_results->push_back(hidl_result);
2614     }
2615     return true;
2616 }
2617 }  // namespace hidl_struct_util
2618 }  // namespace implementation
2619 }  // namespace V1_2
2620 }  // namespace wifi
2621 }  // namespace hardware
2622 }  // namespace android
2623