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