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