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