• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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     strcpy(legacy_request->ndp_iface, hidl_request.ifaceName.c_str());
1823     legacy_request->ndp_cfg.security_cfg =
1824         (hidl_request.securityConfig.securityType !=
1825          NanDataPathSecurityType::OPEN)
1826             ? legacy_hal::NAN_DP_CONFIG_SECURITY
1827             : legacy_hal::NAN_DP_CONFIG_NO_SECURITY;
1828     legacy_request->app_info.ndp_app_info_len = hidl_request.appInfo.size();
1829     if (legacy_request->app_info.ndp_app_info_len > NAN_DP_MAX_APP_INFO_LEN) {
1830         LOG(ERROR) << "convertHidlNanDataPathInitiatorRequestToLegacy: "
1831                       "ndp_app_info_len too large";
1832         return false;
1833     }
1834     memcpy(legacy_request->app_info.ndp_app_info, hidl_request.appInfo.data(),
1835            legacy_request->app_info.ndp_app_info_len);
1836     legacy_request->cipher_type =
1837         (unsigned int)hidl_request.securityConfig.cipherType;
1838     if (hidl_request.securityConfig.securityType ==
1839         NanDataPathSecurityType::PMK) {
1840         legacy_request->key_info.key_type =
1841             legacy_hal::NAN_SECURITY_KEY_INPUT_PMK;
1842         legacy_request->key_info.body.pmk_info.pmk_len =
1843             hidl_request.securityConfig.pmk.size();
1844         if (legacy_request->key_info.body.pmk_info.pmk_len !=
1845             NAN_PMK_INFO_LEN) {
1846             LOG(ERROR) << "convertHidlNanDataPathInitiatorRequestToLegacy: "
1847                           "invalid pmk_len";
1848             return false;
1849         }
1850         memcpy(legacy_request->key_info.body.pmk_info.pmk,
1851                hidl_request.securityConfig.pmk.data(),
1852                legacy_request->key_info.body.pmk_info.pmk_len);
1853     }
1854     if (hidl_request.securityConfig.securityType ==
1855         NanDataPathSecurityType::PASSPHRASE) {
1856         legacy_request->key_info.key_type =
1857             legacy_hal::NAN_SECURITY_KEY_INPUT_PASSPHRASE;
1858         legacy_request->key_info.body.passphrase_info.passphrase_len =
1859             hidl_request.securityConfig.passphrase.size();
1860         if (legacy_request->key_info.body.passphrase_info.passphrase_len <
1861             NAN_SECURITY_MIN_PASSPHRASE_LEN) {
1862             LOG(ERROR) << "convertHidlNanDataPathInitiatorRequestToLegacy: "
1863                           "passphrase_len too small";
1864             return false;
1865         }
1866         if (legacy_request->key_info.body.passphrase_info.passphrase_len >
1867             NAN_SECURITY_MAX_PASSPHRASE_LEN) {
1868             LOG(ERROR) << "convertHidlNanDataPathInitiatorRequestToLegacy: "
1869                           "passphrase_len too large";
1870             return false;
1871         }
1872         memcpy(legacy_request->key_info.body.passphrase_info.passphrase,
1873                hidl_request.securityConfig.passphrase.data(),
1874                legacy_request->key_info.body.passphrase_info.passphrase_len);
1875     }
1876     legacy_request->service_name_len = hidl_request.serviceNameOutOfBand.size();
1877     if (legacy_request->service_name_len > NAN_MAX_SERVICE_NAME_LEN) {
1878         LOG(ERROR) << "convertHidlNanDataPathInitiatorRequestToLegacy: "
1879                       "service_name_len too large";
1880         return false;
1881     }
1882     memcpy(legacy_request->service_name,
1883            hidl_request.serviceNameOutOfBand.data(),
1884            legacy_request->service_name_len);
1885 
1886     return true;
1887 }
1888 
convertHidlNanDataPathIndicationResponseToLegacy(const NanRespondToDataPathIndicationRequest & hidl_request,legacy_hal::NanDataPathIndicationResponse * legacy_request)1889 bool convertHidlNanDataPathIndicationResponseToLegacy(
1890     const NanRespondToDataPathIndicationRequest& hidl_request,
1891     legacy_hal::NanDataPathIndicationResponse* legacy_request) {
1892     if (!legacy_request) {
1893         LOG(ERROR) << "convertHidlNanDataPathIndicationResponseToLegacy: "
1894                       "legacy_request is null";
1895         return false;
1896     }
1897     *legacy_request = {};
1898 
1899     legacy_request->rsp_code = hidl_request.acceptRequest
1900                                    ? legacy_hal::NAN_DP_REQUEST_ACCEPT
1901                                    : legacy_hal::NAN_DP_REQUEST_REJECT;
1902     legacy_request->ndp_instance_id = hidl_request.ndpInstanceId;
1903     strcpy(legacy_request->ndp_iface, hidl_request.ifaceName.c_str());
1904     legacy_request->ndp_cfg.security_cfg =
1905         (hidl_request.securityConfig.securityType !=
1906          NanDataPathSecurityType::OPEN)
1907             ? legacy_hal::NAN_DP_CONFIG_SECURITY
1908             : legacy_hal::NAN_DP_CONFIG_NO_SECURITY;
1909     legacy_request->app_info.ndp_app_info_len = hidl_request.appInfo.size();
1910     if (legacy_request->app_info.ndp_app_info_len > NAN_DP_MAX_APP_INFO_LEN) {
1911         LOG(ERROR) << "convertHidlNanDataPathIndicationResponseToLegacy: "
1912                       "ndp_app_info_len too large";
1913         return false;
1914     }
1915     memcpy(legacy_request->app_info.ndp_app_info, hidl_request.appInfo.data(),
1916            legacy_request->app_info.ndp_app_info_len);
1917     legacy_request->cipher_type =
1918         (unsigned int)hidl_request.securityConfig.cipherType;
1919     if (hidl_request.securityConfig.securityType ==
1920         NanDataPathSecurityType::PMK) {
1921         legacy_request->key_info.key_type =
1922             legacy_hal::NAN_SECURITY_KEY_INPUT_PMK;
1923         legacy_request->key_info.body.pmk_info.pmk_len =
1924             hidl_request.securityConfig.pmk.size();
1925         if (legacy_request->key_info.body.pmk_info.pmk_len !=
1926             NAN_PMK_INFO_LEN) {
1927             LOG(ERROR) << "convertHidlNanDataPathIndicationResponseToLegacy: "
1928                           "invalid pmk_len";
1929             return false;
1930         }
1931         memcpy(legacy_request->key_info.body.pmk_info.pmk,
1932                hidl_request.securityConfig.pmk.data(),
1933                legacy_request->key_info.body.pmk_info.pmk_len);
1934     }
1935     if (hidl_request.securityConfig.securityType ==
1936         NanDataPathSecurityType::PASSPHRASE) {
1937         legacy_request->key_info.key_type =
1938             legacy_hal::NAN_SECURITY_KEY_INPUT_PASSPHRASE;
1939         legacy_request->key_info.body.passphrase_info.passphrase_len =
1940             hidl_request.securityConfig.passphrase.size();
1941         if (legacy_request->key_info.body.passphrase_info.passphrase_len <
1942             NAN_SECURITY_MIN_PASSPHRASE_LEN) {
1943             LOG(ERROR) << "convertHidlNanDataPathIndicationResponseToLegacy: "
1944                           "passphrase_len too small";
1945             return false;
1946         }
1947         if (legacy_request->key_info.body.passphrase_info.passphrase_len >
1948             NAN_SECURITY_MAX_PASSPHRASE_LEN) {
1949             LOG(ERROR) << "convertHidlNanDataPathIndicationResponseToLegacy: "
1950                           "passphrase_len too large";
1951             return false;
1952         }
1953         memcpy(legacy_request->key_info.body.passphrase_info.passphrase,
1954                hidl_request.securityConfig.passphrase.data(),
1955                legacy_request->key_info.body.passphrase_info.passphrase_len);
1956     }
1957     legacy_request->service_name_len = hidl_request.serviceNameOutOfBand.size();
1958     if (legacy_request->service_name_len > NAN_MAX_SERVICE_NAME_LEN) {
1959         LOG(ERROR) << "convertHidlNanDataPathIndicationResponseToLegacy: "
1960                       "service_name_len too large";
1961         return false;
1962     }
1963     memcpy(legacy_request->service_name,
1964            hidl_request.serviceNameOutOfBand.data(),
1965            legacy_request->service_name_len);
1966 
1967     return true;
1968 }
1969 
convertLegacyNanResponseHeaderToHidl(const legacy_hal::NanResponseMsg & legacy_response,WifiNanStatus * wifiNanStatus)1970 bool convertLegacyNanResponseHeaderToHidl(
1971     const legacy_hal::NanResponseMsg& legacy_response,
1972     WifiNanStatus* wifiNanStatus) {
1973     if (!wifiNanStatus) {
1974         LOG(ERROR)
1975             << "convertLegacyNanResponseHeaderToHidl: wifiNanStatus is null";
1976         return false;
1977     }
1978     *wifiNanStatus = {};
1979 
1980     convertToWifiNanStatus(legacy_response.status, legacy_response.nan_error,
1981                            sizeof(legacy_response.nan_error), wifiNanStatus);
1982     return true;
1983 }
1984 
convertLegacyNanCapabilitiesResponseToHidl(const legacy_hal::NanCapabilities & legacy_response,NanCapabilities * hidl_response)1985 bool convertLegacyNanCapabilitiesResponseToHidl(
1986     const legacy_hal::NanCapabilities& legacy_response,
1987     NanCapabilities* hidl_response) {
1988     if (!hidl_response) {
1989         LOG(ERROR) << "convertLegacyNanCapabilitiesResponseToHidl: "
1990                       "hidl_response is null";
1991         return false;
1992     }
1993     *hidl_response = {};
1994 
1995     hidl_response->maxConcurrentClusters =
1996         legacy_response.max_concurrent_nan_clusters;
1997     hidl_response->maxPublishes = legacy_response.max_publishes;
1998     hidl_response->maxSubscribes = legacy_response.max_subscribes;
1999     hidl_response->maxServiceNameLen = legacy_response.max_service_name_len;
2000     hidl_response->maxMatchFilterLen = legacy_response.max_match_filter_len;
2001     hidl_response->maxTotalMatchFilterLen =
2002         legacy_response.max_total_match_filter_len;
2003     hidl_response->maxServiceSpecificInfoLen =
2004         legacy_response.max_service_specific_info_len;
2005     hidl_response->maxExtendedServiceSpecificInfoLen =
2006         legacy_response.max_sdea_service_specific_info_len;
2007     hidl_response->maxNdiInterfaces = legacy_response.max_ndi_interfaces;
2008     hidl_response->maxNdpSessions = legacy_response.max_ndp_sessions;
2009     hidl_response->maxAppInfoLen = legacy_response.max_app_info_len;
2010     hidl_response->maxQueuedTransmitFollowupMsgs =
2011         legacy_response.max_queued_transmit_followup_msgs;
2012     hidl_response->maxSubscribeInterfaceAddresses =
2013         legacy_response.max_subscribe_address;
2014     hidl_response->supportedCipherSuites =
2015         legacy_response.cipher_suites_supported;
2016 
2017     return true;
2018 }
2019 
convertLegacyNanMatchIndToHidl(const legacy_hal::NanMatchInd & legacy_ind,NanMatchInd * hidl_ind)2020 bool convertLegacyNanMatchIndToHidl(const legacy_hal::NanMatchInd& legacy_ind,
2021                                     NanMatchInd* hidl_ind) {
2022     if (!hidl_ind) {
2023         LOG(ERROR) << "convertLegacyNanMatchIndToHidl: hidl_ind is null";
2024         return false;
2025     }
2026     *hidl_ind = {};
2027 
2028     hidl_ind->discoverySessionId = legacy_ind.publish_subscribe_id;
2029     hidl_ind->peerId = legacy_ind.requestor_instance_id;
2030     hidl_ind->addr = hidl_array<uint8_t, 6>(legacy_ind.addr);
2031     hidl_ind->serviceSpecificInfo =
2032         std::vector<uint8_t>(legacy_ind.service_specific_info,
2033                              legacy_ind.service_specific_info +
2034                                  legacy_ind.service_specific_info_len);
2035     hidl_ind->extendedServiceSpecificInfo =
2036         std::vector<uint8_t>(legacy_ind.sdea_service_specific_info,
2037                              legacy_ind.sdea_service_specific_info +
2038                                  legacy_ind.sdea_service_specific_info_len);
2039     hidl_ind->matchFilter = std::vector<uint8_t>(
2040         legacy_ind.sdf_match_filter,
2041         legacy_ind.sdf_match_filter + legacy_ind.sdf_match_filter_len);
2042     hidl_ind->matchOccuredInBeaconFlag = legacy_ind.match_occured_flag == 1;
2043     hidl_ind->outOfResourceFlag = legacy_ind.out_of_resource_flag == 1;
2044     hidl_ind->rssiValue = legacy_ind.rssi_value;
2045     hidl_ind->peerCipherType = (NanCipherSuiteType)legacy_ind.peer_cipher_type;
2046     hidl_ind->peerRequiresSecurityEnabledInNdp =
2047         legacy_ind.peer_sdea_params.security_cfg ==
2048         legacy_hal::NAN_DP_CONFIG_SECURITY;
2049     hidl_ind->peerRequiresRanging = legacy_ind.peer_sdea_params.ranging_state ==
2050                                     legacy_hal::NAN_RANGING_ENABLE;
2051     hidl_ind->rangingMeasurementInCm =
2052         legacy_ind.range_info.range_measurement_mm / 10;
2053     hidl_ind->rangingIndicationType = legacy_ind.range_info.ranging_event_type;
2054 
2055     return true;
2056 }
2057 
convertLegacyNanFollowupIndToHidl(const legacy_hal::NanFollowupInd & legacy_ind,NanFollowupReceivedInd * hidl_ind)2058 bool convertLegacyNanFollowupIndToHidl(
2059     const legacy_hal::NanFollowupInd& legacy_ind,
2060     NanFollowupReceivedInd* hidl_ind) {
2061     if (!hidl_ind) {
2062         LOG(ERROR) << "convertLegacyNanFollowupIndToHidl: hidl_ind is null";
2063         return false;
2064     }
2065     *hidl_ind = {};
2066 
2067     hidl_ind->discoverySessionId = legacy_ind.publish_subscribe_id;
2068     hidl_ind->peerId = legacy_ind.requestor_instance_id;
2069     hidl_ind->addr = hidl_array<uint8_t, 6>(legacy_ind.addr);
2070     hidl_ind->receivedInFaw = legacy_ind.dw_or_faw == 1;
2071     hidl_ind->serviceSpecificInfo =
2072         std::vector<uint8_t>(legacy_ind.service_specific_info,
2073                              legacy_ind.service_specific_info +
2074                                  legacy_ind.service_specific_info_len);
2075     hidl_ind->extendedServiceSpecificInfo =
2076         std::vector<uint8_t>(legacy_ind.sdea_service_specific_info,
2077                              legacy_ind.sdea_service_specific_info +
2078                                  legacy_ind.sdea_service_specific_info_len);
2079 
2080     return true;
2081 }
2082 
convertLegacyNanDataPathRequestIndToHidl(const legacy_hal::NanDataPathRequestInd & legacy_ind,NanDataPathRequestInd * hidl_ind)2083 bool convertLegacyNanDataPathRequestIndToHidl(
2084     const legacy_hal::NanDataPathRequestInd& legacy_ind,
2085     NanDataPathRequestInd* hidl_ind) {
2086     if (!hidl_ind) {
2087         LOG(ERROR)
2088             << "convertLegacyNanDataPathRequestIndToHidl: hidl_ind is null";
2089         return false;
2090     }
2091     *hidl_ind = {};
2092 
2093     hidl_ind->discoverySessionId = legacy_ind.service_instance_id;
2094     hidl_ind->peerDiscMacAddr =
2095         hidl_array<uint8_t, 6>(legacy_ind.peer_disc_mac_addr);
2096     hidl_ind->ndpInstanceId = legacy_ind.ndp_instance_id;
2097     hidl_ind->securityRequired =
2098         legacy_ind.ndp_cfg.security_cfg == legacy_hal::NAN_DP_CONFIG_SECURITY;
2099     hidl_ind->appInfo =
2100         std::vector<uint8_t>(legacy_ind.app_info.ndp_app_info,
2101                              legacy_ind.app_info.ndp_app_info +
2102                                  legacy_ind.app_info.ndp_app_info_len);
2103 
2104     return true;
2105 }
2106 
convertLegacyNdpChannelInfoToHidl(const legacy_hal::NanChannelInfo & legacy_struct,V1_2::NanDataPathChannelInfo * hidl_struct)2107 bool convertLegacyNdpChannelInfoToHidl(
2108     const legacy_hal::NanChannelInfo& legacy_struct,
2109     V1_2::NanDataPathChannelInfo* hidl_struct) {
2110     if (!hidl_struct) {
2111         LOG(ERROR) << "convertLegacyNdpChannelInfoToHidl: hidl_struct is null";
2112         return false;
2113     }
2114     *hidl_struct = {};
2115 
2116     hidl_struct->channelFreq = legacy_struct.channel;
2117     hidl_struct->channelBandwidth = convertLegacyWifiChannelWidthToHidl(
2118         (legacy_hal::wifi_channel_width)legacy_struct.bandwidth);
2119     hidl_struct->numSpatialStreams = legacy_struct.nss;
2120 
2121     return true;
2122 }
2123 
convertLegacyNanDataPathConfirmIndToHidl(const legacy_hal::NanDataPathConfirmInd & legacy_ind,V1_2::NanDataPathConfirmInd * hidl_ind)2124 bool convertLegacyNanDataPathConfirmIndToHidl(
2125     const legacy_hal::NanDataPathConfirmInd& legacy_ind,
2126     V1_2::NanDataPathConfirmInd* hidl_ind) {
2127     if (!hidl_ind) {
2128         LOG(ERROR)
2129             << "convertLegacyNanDataPathConfirmIndToHidl: hidl_ind is null";
2130         return false;
2131     }
2132     *hidl_ind = {};
2133 
2134     hidl_ind->V1_0.ndpInstanceId = legacy_ind.ndp_instance_id;
2135     hidl_ind->V1_0.dataPathSetupSuccess =
2136         legacy_ind.rsp_code == legacy_hal::NAN_DP_REQUEST_ACCEPT;
2137     hidl_ind->V1_0.peerNdiMacAddr =
2138         hidl_array<uint8_t, 6>(legacy_ind.peer_ndi_mac_addr);
2139     hidl_ind->V1_0.appInfo =
2140         std::vector<uint8_t>(legacy_ind.app_info.ndp_app_info,
2141                              legacy_ind.app_info.ndp_app_info +
2142                                  legacy_ind.app_info.ndp_app_info_len);
2143     hidl_ind->V1_0.status.status =
2144         convertLegacyNanStatusTypeToHidl(legacy_ind.reason_code);
2145     hidl_ind->V1_0.status.description = "";  // TODO: b/34059183
2146 
2147     std::vector<V1_2::NanDataPathChannelInfo> channelInfo;
2148     for (unsigned int i = 0; i < legacy_ind.num_channels; ++i) {
2149         V1_2::NanDataPathChannelInfo hidl_struct;
2150         if (!convertLegacyNdpChannelInfoToHidl(legacy_ind.channel_info[i],
2151                                                &hidl_struct)) {
2152             return false;
2153         }
2154         channelInfo.push_back(hidl_struct);
2155     }
2156     hidl_ind->channelInfo = channelInfo;
2157 
2158     return true;
2159 }
2160 
convertLegacyNanDataPathScheduleUpdateIndToHidl(const legacy_hal::NanDataPathScheduleUpdateInd & legacy_ind,V1_2::NanDataPathScheduleUpdateInd * hidl_ind)2161 bool convertLegacyNanDataPathScheduleUpdateIndToHidl(
2162     const legacy_hal::NanDataPathScheduleUpdateInd& legacy_ind,
2163     V1_2::NanDataPathScheduleUpdateInd* hidl_ind) {
2164     if (!hidl_ind) {
2165         LOG(ERROR) << "convertLegacyNanDataPathScheduleUpdateIndToHidl: "
2166                       "hidl_ind is null";
2167         return false;
2168     }
2169     *hidl_ind = {};
2170 
2171     hidl_ind->peerDiscoveryAddress =
2172         hidl_array<uint8_t, 6>(legacy_ind.peer_mac_addr);
2173     std::vector<V1_2::NanDataPathChannelInfo> channelInfo;
2174     for (unsigned int i = 0; i < legacy_ind.num_channels; ++i) {
2175         V1_2::NanDataPathChannelInfo hidl_struct;
2176         if (!convertLegacyNdpChannelInfoToHidl(legacy_ind.channel_info[i],
2177                                                &hidl_struct)) {
2178             return false;
2179         }
2180         channelInfo.push_back(hidl_struct);
2181     }
2182     hidl_ind->channelInfo = channelInfo;
2183     std::vector<uint32_t> ndpInstanceIds;
2184     for (unsigned int i = 0; i < legacy_ind.num_ndp_instances; ++i) {
2185         ndpInstanceIds.push_back(legacy_ind.ndp_instance_id[i]);
2186     }
2187     hidl_ind->ndpInstanceIds = ndpInstanceIds;
2188 
2189     return true;
2190 }
2191 
convertHidlRttTypeToLegacy(RttType type)2192 legacy_hal::wifi_rtt_type convertHidlRttTypeToLegacy(RttType type) {
2193     switch (type) {
2194         case RttType::ONE_SIDED:
2195             return legacy_hal::RTT_TYPE_1_SIDED;
2196         case RttType::TWO_SIDED:
2197             return legacy_hal::RTT_TYPE_2_SIDED;
2198     };
2199     CHECK(false);
2200 }
2201 
convertLegacyRttTypeToHidl(legacy_hal::wifi_rtt_type type)2202 RttType convertLegacyRttTypeToHidl(legacy_hal::wifi_rtt_type type) {
2203     switch (type) {
2204         case legacy_hal::RTT_TYPE_1_SIDED:
2205             return RttType::ONE_SIDED;
2206         case legacy_hal::RTT_TYPE_2_SIDED:
2207             return RttType::TWO_SIDED;
2208     };
2209     CHECK(false) << "Unknown legacy type: " << type;
2210 }
2211 
convertHidlRttPeerTypeToLegacy(RttPeerType type)2212 legacy_hal::rtt_peer_type convertHidlRttPeerTypeToLegacy(RttPeerType type) {
2213     switch (type) {
2214         case RttPeerType::AP:
2215             return legacy_hal::RTT_PEER_AP;
2216         case RttPeerType::STA:
2217             return legacy_hal::RTT_PEER_STA;
2218         case RttPeerType::P2P_GO:
2219             return legacy_hal::RTT_PEER_P2P_GO;
2220         case RttPeerType::P2P_CLIENT:
2221             return legacy_hal::RTT_PEER_P2P_CLIENT;
2222         case RttPeerType::NAN:
2223             return legacy_hal::RTT_PEER_NAN;
2224     };
2225     CHECK(false);
2226 }
2227 
convertHidlWifiChannelWidthToLegacy(WifiChannelWidthInMhz type)2228 legacy_hal::wifi_channel_width convertHidlWifiChannelWidthToLegacy(
2229     WifiChannelWidthInMhz type) {
2230     switch (type) {
2231         case WifiChannelWidthInMhz::WIDTH_20:
2232             return legacy_hal::WIFI_CHAN_WIDTH_20;
2233         case WifiChannelWidthInMhz::WIDTH_40:
2234             return legacy_hal::WIFI_CHAN_WIDTH_40;
2235         case WifiChannelWidthInMhz::WIDTH_80:
2236             return legacy_hal::WIFI_CHAN_WIDTH_80;
2237         case WifiChannelWidthInMhz::WIDTH_160:
2238             return legacy_hal::WIFI_CHAN_WIDTH_160;
2239         case WifiChannelWidthInMhz::WIDTH_80P80:
2240             return legacy_hal::WIFI_CHAN_WIDTH_80P80;
2241         case WifiChannelWidthInMhz::WIDTH_5:
2242             return legacy_hal::WIFI_CHAN_WIDTH_5;
2243         case WifiChannelWidthInMhz::WIDTH_10:
2244             return legacy_hal::WIFI_CHAN_WIDTH_10;
2245         case WifiChannelWidthInMhz::WIDTH_INVALID:
2246             return legacy_hal::WIFI_CHAN_WIDTH_INVALID;
2247     };
2248     CHECK(false);
2249 }
2250 
convertLegacyWifiChannelWidthToHidl(legacy_hal::wifi_channel_width type)2251 WifiChannelWidthInMhz convertLegacyWifiChannelWidthToHidl(
2252     legacy_hal::wifi_channel_width type) {
2253     switch (type) {
2254         case legacy_hal::WIFI_CHAN_WIDTH_20:
2255             return WifiChannelWidthInMhz::WIDTH_20;
2256         case legacy_hal::WIFI_CHAN_WIDTH_40:
2257             return WifiChannelWidthInMhz::WIDTH_40;
2258         case legacy_hal::WIFI_CHAN_WIDTH_80:
2259             return WifiChannelWidthInMhz::WIDTH_80;
2260         case legacy_hal::WIFI_CHAN_WIDTH_160:
2261             return WifiChannelWidthInMhz::WIDTH_160;
2262         case legacy_hal::WIFI_CHAN_WIDTH_80P80:
2263             return WifiChannelWidthInMhz::WIDTH_80P80;
2264         case legacy_hal::WIFI_CHAN_WIDTH_5:
2265             return WifiChannelWidthInMhz::WIDTH_5;
2266         case legacy_hal::WIFI_CHAN_WIDTH_10:
2267             return WifiChannelWidthInMhz::WIDTH_10;
2268         case legacy_hal::WIFI_CHAN_WIDTH_INVALID:
2269             return WifiChannelWidthInMhz::WIDTH_INVALID;
2270     };
2271     CHECK(false) << "Unknown legacy type: " << type;
2272 }
2273 
convertHidlRttPreambleToLegacy(RttPreamble type)2274 legacy_hal::wifi_rtt_preamble convertHidlRttPreambleToLegacy(RttPreamble type) {
2275     switch (type) {
2276         case RttPreamble::LEGACY:
2277             return legacy_hal::WIFI_RTT_PREAMBLE_LEGACY;
2278         case RttPreamble::HT:
2279             return legacy_hal::WIFI_RTT_PREAMBLE_HT;
2280         case RttPreamble::VHT:
2281             return legacy_hal::WIFI_RTT_PREAMBLE_VHT;
2282     };
2283     CHECK(false);
2284 }
2285 
convertLegacyRttPreambleToHidl(legacy_hal::wifi_rtt_preamble type)2286 RttPreamble convertLegacyRttPreambleToHidl(legacy_hal::wifi_rtt_preamble type) {
2287     switch (type) {
2288         case legacy_hal::WIFI_RTT_PREAMBLE_LEGACY:
2289             return RttPreamble::LEGACY;
2290         case legacy_hal::WIFI_RTT_PREAMBLE_HT:
2291             return RttPreamble::HT;
2292         case legacy_hal::WIFI_RTT_PREAMBLE_VHT:
2293             return RttPreamble::VHT;
2294     };
2295     CHECK(false) << "Unknown legacy type: " << type;
2296 }
2297 
convertHidlRttBwToLegacy(RttBw type)2298 legacy_hal::wifi_rtt_bw convertHidlRttBwToLegacy(RttBw type) {
2299     switch (type) {
2300         case RttBw::BW_5MHZ:
2301             return legacy_hal::WIFI_RTT_BW_5;
2302         case RttBw::BW_10MHZ:
2303             return legacy_hal::WIFI_RTT_BW_10;
2304         case RttBw::BW_20MHZ:
2305             return legacy_hal::WIFI_RTT_BW_20;
2306         case RttBw::BW_40MHZ:
2307             return legacy_hal::WIFI_RTT_BW_40;
2308         case RttBw::BW_80MHZ:
2309             return legacy_hal::WIFI_RTT_BW_80;
2310         case RttBw::BW_160MHZ:
2311             return legacy_hal::WIFI_RTT_BW_160;
2312     };
2313     CHECK(false);
2314 }
2315 
convertLegacyRttBwToHidl(legacy_hal::wifi_rtt_bw type)2316 RttBw convertLegacyRttBwToHidl(legacy_hal::wifi_rtt_bw type) {
2317     switch (type) {
2318         case legacy_hal::WIFI_RTT_BW_5:
2319             return RttBw::BW_5MHZ;
2320         case legacy_hal::WIFI_RTT_BW_10:
2321             return RttBw::BW_10MHZ;
2322         case legacy_hal::WIFI_RTT_BW_20:
2323             return RttBw::BW_20MHZ;
2324         case legacy_hal::WIFI_RTT_BW_40:
2325             return RttBw::BW_40MHZ;
2326         case legacy_hal::WIFI_RTT_BW_80:
2327             return RttBw::BW_80MHZ;
2328         case legacy_hal::WIFI_RTT_BW_160:
2329             return RttBw::BW_160MHZ;
2330     };
2331     CHECK(false) << "Unknown legacy type: " << type;
2332 }
2333 
convertHidlRttMotionPatternToLegacy(RttMotionPattern type)2334 legacy_hal::wifi_motion_pattern convertHidlRttMotionPatternToLegacy(
2335     RttMotionPattern type) {
2336     switch (type) {
2337         case RttMotionPattern::NOT_EXPECTED:
2338             return legacy_hal::WIFI_MOTION_NOT_EXPECTED;
2339         case RttMotionPattern::EXPECTED:
2340             return legacy_hal::WIFI_MOTION_EXPECTED;
2341         case RttMotionPattern::UNKNOWN:
2342             return legacy_hal::WIFI_MOTION_UNKNOWN;
2343     };
2344     CHECK(false);
2345 }
2346 
convertLegacyWifiRatePreambleToHidl(uint8_t preamble)2347 WifiRatePreamble convertLegacyWifiRatePreambleToHidl(uint8_t preamble) {
2348     switch (preamble) {
2349         case 0:
2350             return WifiRatePreamble::OFDM;
2351         case 1:
2352             return WifiRatePreamble::CCK;
2353         case 2:
2354             return WifiRatePreamble::HT;
2355         case 3:
2356             return WifiRatePreamble::VHT;
2357         default:
2358             return WifiRatePreamble::RESERVED;
2359     };
2360     CHECK(false) << "Unknown legacy preamble: " << preamble;
2361 }
2362 
convertLegacyWifiRateNssToHidl(uint8_t nss)2363 WifiRateNss convertLegacyWifiRateNssToHidl(uint8_t nss) {
2364     switch (nss) {
2365         case 0:
2366             return WifiRateNss::NSS_1x1;
2367         case 1:
2368             return WifiRateNss::NSS_2x2;
2369         case 2:
2370             return WifiRateNss::NSS_3x3;
2371         case 3:
2372             return WifiRateNss::NSS_4x4;
2373     };
2374     CHECK(false) << "Unknown legacy nss: " << nss;
2375     return {};
2376 }
2377 
convertLegacyRttStatusToHidl(legacy_hal::wifi_rtt_status status)2378 RttStatus convertLegacyRttStatusToHidl(legacy_hal::wifi_rtt_status status) {
2379     switch (status) {
2380         case legacy_hal::RTT_STATUS_SUCCESS:
2381             return RttStatus::SUCCESS;
2382         case legacy_hal::RTT_STATUS_FAILURE:
2383             return RttStatus::FAILURE;
2384         case legacy_hal::RTT_STATUS_FAIL_NO_RSP:
2385             return RttStatus::FAIL_NO_RSP;
2386         case legacy_hal::RTT_STATUS_FAIL_REJECTED:
2387             return RttStatus::FAIL_REJECTED;
2388         case legacy_hal::RTT_STATUS_FAIL_NOT_SCHEDULED_YET:
2389             return RttStatus::FAIL_NOT_SCHEDULED_YET;
2390         case legacy_hal::RTT_STATUS_FAIL_TM_TIMEOUT:
2391             return RttStatus::FAIL_TM_TIMEOUT;
2392         case legacy_hal::RTT_STATUS_FAIL_AP_ON_DIFF_CHANNEL:
2393             return RttStatus::FAIL_AP_ON_DIFF_CHANNEL;
2394         case legacy_hal::RTT_STATUS_FAIL_NO_CAPABILITY:
2395             return RttStatus::FAIL_NO_CAPABILITY;
2396         case legacy_hal::RTT_STATUS_ABORTED:
2397             return RttStatus::ABORTED;
2398         case legacy_hal::RTT_STATUS_FAIL_INVALID_TS:
2399             return RttStatus::FAIL_INVALID_TS;
2400         case legacy_hal::RTT_STATUS_FAIL_PROTOCOL:
2401             return RttStatus::FAIL_PROTOCOL;
2402         case legacy_hal::RTT_STATUS_FAIL_SCHEDULE:
2403             return RttStatus::FAIL_SCHEDULE;
2404         case legacy_hal::RTT_STATUS_FAIL_BUSY_TRY_LATER:
2405             return RttStatus::FAIL_BUSY_TRY_LATER;
2406         case legacy_hal::RTT_STATUS_INVALID_REQ:
2407             return RttStatus::INVALID_REQ;
2408         case legacy_hal::RTT_STATUS_NO_WIFI:
2409             return RttStatus::NO_WIFI;
2410         case legacy_hal::RTT_STATUS_FAIL_FTM_PARAM_OVERRIDE:
2411             return RttStatus::FAIL_FTM_PARAM_OVERRIDE;
2412         case legacy_hal::RTT_STATUS_NAN_RANGING_PROTOCOL_FAILURE:
2413             return RttStatus::FAILURE;  // TODO: add HIDL enumeration
2414         case legacy_hal::RTT_STATUS_NAN_RANGING_CONCURRENCY_NOT_SUPPORTED:
2415             return RttStatus::FAILURE;  // TODO: add HIDL enumeration
2416     };
2417     CHECK(false) << "Unknown legacy status: " << status;
2418 }
2419 
convertHidlWifiChannelInfoToLegacy(const WifiChannelInfo & hidl_info,legacy_hal::wifi_channel_info * legacy_info)2420 bool convertHidlWifiChannelInfoToLegacy(
2421     const WifiChannelInfo& hidl_info,
2422     legacy_hal::wifi_channel_info* legacy_info) {
2423     if (!legacy_info) {
2424         return false;
2425     }
2426     *legacy_info = {};
2427     legacy_info->width = convertHidlWifiChannelWidthToLegacy(hidl_info.width);
2428     legacy_info->center_freq = hidl_info.centerFreq;
2429     legacy_info->center_freq0 = hidl_info.centerFreq0;
2430     legacy_info->center_freq1 = hidl_info.centerFreq1;
2431     return true;
2432 }
2433 
convertLegacyWifiChannelInfoToHidl(const legacy_hal::wifi_channel_info & legacy_info,WifiChannelInfo * hidl_info)2434 bool convertLegacyWifiChannelInfoToHidl(
2435     const legacy_hal::wifi_channel_info& legacy_info,
2436     WifiChannelInfo* hidl_info) {
2437     if (!hidl_info) {
2438         return false;
2439     }
2440     *hidl_info = {};
2441     hidl_info->width = convertLegacyWifiChannelWidthToHidl(legacy_info.width);
2442     hidl_info->centerFreq = legacy_info.center_freq;
2443     hidl_info->centerFreq0 = legacy_info.center_freq0;
2444     hidl_info->centerFreq1 = legacy_info.center_freq1;
2445     return true;
2446 }
2447 
convertHidlRttConfigToLegacy(const RttConfig & hidl_config,legacy_hal::wifi_rtt_config * legacy_config)2448 bool convertHidlRttConfigToLegacy(const RttConfig& hidl_config,
2449                                   legacy_hal::wifi_rtt_config* legacy_config) {
2450     if (!legacy_config) {
2451         return false;
2452     }
2453     *legacy_config = {};
2454     CHECK(hidl_config.addr.size() == sizeof(legacy_config->addr));
2455     memcpy(legacy_config->addr, hidl_config.addr.data(),
2456            hidl_config.addr.size());
2457     legacy_config->type = convertHidlRttTypeToLegacy(hidl_config.type);
2458     legacy_config->peer = convertHidlRttPeerTypeToLegacy(hidl_config.peer);
2459     if (!convertHidlWifiChannelInfoToLegacy(hidl_config.channel,
2460                                             &legacy_config->channel)) {
2461         return false;
2462     }
2463     legacy_config->burst_period = hidl_config.burstPeriod;
2464     legacy_config->num_burst = hidl_config.numBurst;
2465     legacy_config->num_frames_per_burst = hidl_config.numFramesPerBurst;
2466     legacy_config->num_retries_per_rtt_frame =
2467         hidl_config.numRetriesPerRttFrame;
2468     legacy_config->num_retries_per_ftmr = hidl_config.numRetriesPerFtmr;
2469     legacy_config->LCI_request = hidl_config.mustRequestLci;
2470     legacy_config->LCR_request = hidl_config.mustRequestLcr;
2471     legacy_config->burst_duration = hidl_config.burstDuration;
2472     legacy_config->preamble =
2473         convertHidlRttPreambleToLegacy(hidl_config.preamble);
2474     legacy_config->bw = convertHidlRttBwToLegacy(hidl_config.bw);
2475     return true;
2476 }
2477 
convertHidlVectorOfRttConfigToLegacy(const std::vector<RttConfig> & hidl_configs,std::vector<legacy_hal::wifi_rtt_config> * legacy_configs)2478 bool convertHidlVectorOfRttConfigToLegacy(
2479     const std::vector<RttConfig>& hidl_configs,
2480     std::vector<legacy_hal::wifi_rtt_config>* legacy_configs) {
2481     if (!legacy_configs) {
2482         return false;
2483     }
2484     *legacy_configs = {};
2485     for (const auto& hidl_config : hidl_configs) {
2486         legacy_hal::wifi_rtt_config legacy_config;
2487         if (!convertHidlRttConfigToLegacy(hidl_config, &legacy_config)) {
2488             return false;
2489         }
2490         legacy_configs->push_back(legacy_config);
2491     }
2492     return true;
2493 }
2494 
convertHidlRttLciInformationToLegacy(const RttLciInformation & hidl_info,legacy_hal::wifi_lci_information * legacy_info)2495 bool convertHidlRttLciInformationToLegacy(
2496     const RttLciInformation& hidl_info,
2497     legacy_hal::wifi_lci_information* legacy_info) {
2498     if (!legacy_info) {
2499         return false;
2500     }
2501     *legacy_info = {};
2502     legacy_info->latitude = hidl_info.latitude;
2503     legacy_info->longitude = hidl_info.longitude;
2504     legacy_info->altitude = hidl_info.altitude;
2505     legacy_info->latitude_unc = hidl_info.latitudeUnc;
2506     legacy_info->longitude_unc = hidl_info.longitudeUnc;
2507     legacy_info->altitude_unc = hidl_info.altitudeUnc;
2508     legacy_info->motion_pattern =
2509         convertHidlRttMotionPatternToLegacy(hidl_info.motionPattern);
2510     legacy_info->floor = hidl_info.floor;
2511     legacy_info->height_above_floor = hidl_info.heightAboveFloor;
2512     legacy_info->height_unc = hidl_info.heightUnc;
2513     return true;
2514 }
2515 
convertHidlRttLcrInformationToLegacy(const RttLcrInformation & hidl_info,legacy_hal::wifi_lcr_information * legacy_info)2516 bool convertHidlRttLcrInformationToLegacy(
2517     const RttLcrInformation& hidl_info,
2518     legacy_hal::wifi_lcr_information* legacy_info) {
2519     if (!legacy_info) {
2520         return false;
2521     }
2522     *legacy_info = {};
2523     CHECK(hidl_info.countryCode.size() == sizeof(legacy_info->country_code));
2524     memcpy(legacy_info->country_code, hidl_info.countryCode.data(),
2525            hidl_info.countryCode.size());
2526     if (hidl_info.civicInfo.size() > sizeof(legacy_info->civic_info)) {
2527         return false;
2528     }
2529     legacy_info->length = hidl_info.civicInfo.size();
2530     memcpy(legacy_info->civic_info, hidl_info.civicInfo.c_str(),
2531            hidl_info.civicInfo.size());
2532     return true;
2533 }
2534 
convertHidlRttResponderToLegacy(const RttResponder & hidl_responder,legacy_hal::wifi_rtt_responder * legacy_responder)2535 bool convertHidlRttResponderToLegacy(
2536     const RttResponder& hidl_responder,
2537     legacy_hal::wifi_rtt_responder* legacy_responder) {
2538     if (!legacy_responder) {
2539         return false;
2540     }
2541     *legacy_responder = {};
2542     if (!convertHidlWifiChannelInfoToLegacy(hidl_responder.channel,
2543                                             &legacy_responder->channel)) {
2544         return false;
2545     }
2546     legacy_responder->preamble =
2547         convertHidlRttPreambleToLegacy(hidl_responder.preamble);
2548     return true;
2549 }
2550 
convertLegacyRttResponderToHidl(const legacy_hal::wifi_rtt_responder & legacy_responder,RttResponder * hidl_responder)2551 bool convertLegacyRttResponderToHidl(
2552     const legacy_hal::wifi_rtt_responder& legacy_responder,
2553     RttResponder* hidl_responder) {
2554     if (!hidl_responder) {
2555         return false;
2556     }
2557     *hidl_responder = {};
2558     if (!convertLegacyWifiChannelInfoToHidl(legacy_responder.channel,
2559                                             &hidl_responder->channel)) {
2560         return false;
2561     }
2562     hidl_responder->preamble =
2563         convertLegacyRttPreambleToHidl(legacy_responder.preamble);
2564     return true;
2565 }
2566 
convertLegacyRttCapabilitiesToHidl(const legacy_hal::wifi_rtt_capabilities & legacy_capabilities,RttCapabilities * hidl_capabilities)2567 bool convertLegacyRttCapabilitiesToHidl(
2568     const legacy_hal::wifi_rtt_capabilities& legacy_capabilities,
2569     RttCapabilities* hidl_capabilities) {
2570     if (!hidl_capabilities) {
2571         return false;
2572     }
2573     *hidl_capabilities = {};
2574     hidl_capabilities->rttOneSidedSupported =
2575         legacy_capabilities.rtt_one_sided_supported;
2576     hidl_capabilities->rttFtmSupported = legacy_capabilities.rtt_ftm_supported;
2577     hidl_capabilities->lciSupported = legacy_capabilities.lci_support;
2578     hidl_capabilities->lcrSupported = legacy_capabilities.lcr_support;
2579     hidl_capabilities->responderSupported =
2580         legacy_capabilities.responder_supported;
2581     hidl_capabilities->preambleSupport = 0;
2582     for (const auto flag : {legacy_hal::WIFI_RTT_PREAMBLE_LEGACY,
2583                             legacy_hal::WIFI_RTT_PREAMBLE_HT,
2584                             legacy_hal::WIFI_RTT_PREAMBLE_VHT}) {
2585         if (legacy_capabilities.preamble_support & flag) {
2586             hidl_capabilities->preambleSupport |=
2587                 static_cast<std::underlying_type<RttPreamble>::type>(
2588                     convertLegacyRttPreambleToHidl(flag));
2589         }
2590     }
2591     hidl_capabilities->bwSupport = 0;
2592     for (const auto flag :
2593          {legacy_hal::WIFI_RTT_BW_5, legacy_hal::WIFI_RTT_BW_10,
2594           legacy_hal::WIFI_RTT_BW_20, legacy_hal::WIFI_RTT_BW_40,
2595           legacy_hal::WIFI_RTT_BW_80, legacy_hal::WIFI_RTT_BW_160}) {
2596         if (legacy_capabilities.bw_support & flag) {
2597             hidl_capabilities->bwSupport |=
2598                 static_cast<std::underlying_type<RttBw>::type>(
2599                     convertLegacyRttBwToHidl(flag));
2600         }
2601     }
2602     hidl_capabilities->mcVersion = legacy_capabilities.mc_version;
2603     return true;
2604 }
2605 
convertLegacyWifiRateInfoToHidl(const legacy_hal::wifi_rate & legacy_rate,WifiRateInfo * hidl_rate)2606 bool convertLegacyWifiRateInfoToHidl(const legacy_hal::wifi_rate& legacy_rate,
2607                                      WifiRateInfo* hidl_rate) {
2608     if (!hidl_rate) {
2609         return false;
2610     }
2611     *hidl_rate = {};
2612     hidl_rate->preamble =
2613         convertLegacyWifiRatePreambleToHidl(legacy_rate.preamble);
2614     hidl_rate->nss = convertLegacyWifiRateNssToHidl(legacy_rate.nss);
2615     hidl_rate->bw = convertLegacyWifiChannelWidthToHidl(
2616         static_cast<legacy_hal::wifi_channel_width>(legacy_rate.bw));
2617     hidl_rate->rateMcsIdx = legacy_rate.rateMcsIdx;
2618     hidl_rate->bitRateInKbps = legacy_rate.bitrate;
2619     return true;
2620 }
2621 
convertLegacyRttResultToHidl(const legacy_hal::wifi_rtt_result & legacy_result,RttResult * hidl_result)2622 bool convertLegacyRttResultToHidl(
2623     const legacy_hal::wifi_rtt_result& legacy_result, RttResult* hidl_result) {
2624     if (!hidl_result) {
2625         return false;
2626     }
2627     *hidl_result = {};
2628     CHECK(sizeof(legacy_result.addr) == hidl_result->addr.size());
2629     memcpy(hidl_result->addr.data(), legacy_result.addr,
2630            sizeof(legacy_result.addr));
2631     hidl_result->burstNum = legacy_result.burst_num;
2632     hidl_result->measurementNumber = legacy_result.measurement_number;
2633     hidl_result->successNumber = legacy_result.success_number;
2634     hidl_result->numberPerBurstPeer = legacy_result.number_per_burst_peer;
2635     hidl_result->status = convertLegacyRttStatusToHidl(legacy_result.status);
2636     hidl_result->retryAfterDuration = legacy_result.retry_after_duration;
2637     hidl_result->type = convertLegacyRttTypeToHidl(legacy_result.type);
2638     hidl_result->rssi = legacy_result.rssi;
2639     hidl_result->rssiSpread = legacy_result.rssi_spread;
2640     if (!convertLegacyWifiRateInfoToHidl(legacy_result.tx_rate,
2641                                          &hidl_result->txRate)) {
2642         return false;
2643     }
2644     if (!convertLegacyWifiRateInfoToHidl(legacy_result.rx_rate,
2645                                          &hidl_result->rxRate)) {
2646         return false;
2647     }
2648     hidl_result->rtt = legacy_result.rtt;
2649     hidl_result->rttSd = legacy_result.rtt_sd;
2650     hidl_result->rttSpread = legacy_result.rtt_spread;
2651     hidl_result->distanceInMm = legacy_result.distance_mm;
2652     hidl_result->distanceSdInMm = legacy_result.distance_sd_mm;
2653     hidl_result->distanceSpreadInMm = legacy_result.distance_spread_mm;
2654     hidl_result->timeStampInUs = legacy_result.ts;
2655     hidl_result->burstDurationInMs = legacy_result.burst_duration;
2656     hidl_result->negotiatedBurstNum = legacy_result.negotiated_burst_num;
2657     if (legacy_result.LCI &&
2658         !convertLegacyIeToHidl(*legacy_result.LCI, &hidl_result->lci)) {
2659         return false;
2660     }
2661     if (legacy_result.LCR &&
2662         !convertLegacyIeToHidl(*legacy_result.LCR, &hidl_result->lcr)) {
2663         return false;
2664     }
2665     return true;
2666 }
2667 
convertLegacyVectorOfRttResultToHidl(const std::vector<const legacy_hal::wifi_rtt_result * > & legacy_results,std::vector<RttResult> * hidl_results)2668 bool convertLegacyVectorOfRttResultToHidl(
2669     const std::vector<const legacy_hal::wifi_rtt_result*>& legacy_results,
2670     std::vector<RttResult>* hidl_results) {
2671     if (!hidl_results) {
2672         return false;
2673     }
2674     *hidl_results = {};
2675     for (const auto legacy_result : legacy_results) {
2676         RttResult hidl_result;
2677         if (!convertLegacyRttResultToHidl(*legacy_result, &hidl_result)) {
2678             return false;
2679         }
2680         hidl_results->push_back(hidl_result);
2681     }
2682     return true;
2683 }
2684 }  // namespace hidl_struct_util
2685 }  // namespace implementation
2686 }  // namespace V1_3
2687 }  // namespace wifi
2688 }  // namespace hardware
2689 }  // namespace android
2690