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