• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2022 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 "aidl_struct_util.h"
21 
22 namespace aidl {
23 namespace android {
24 namespace hardware {
25 namespace wifi {
26 namespace aidl_struct_util {
27 
28 WifiChannelWidthInMhz convertLegacyWifiChannelWidthToAidl(legacy_hal::wifi_channel_width type);
29 bool convertAidlWifiChannelInfoToLegacy(const WifiChannelInfo& aidl_info,
30                                         legacy_hal::wifi_channel_info* legacy_info);
31 RttBw convertLegacyRttBwToAidl(legacy_hal::wifi_rtt_bw type);
32 
safeConvertChar(const char * str,size_t max_len)33 std::string safeConvertChar(const char* str, size_t max_len) {
34     const char* c = str;
35     size_t size = 0;
36     while (*c && (unsigned char)*c < 128 && size < max_len) {
37         ++size;
38         ++c;
39     }
40     return std::string(str, size);
41 }
42 
uintToIntVec(const std::vector<uint32_t> & in)43 inline std::vector<int32_t> uintToIntVec(const std::vector<uint32_t>& in) {
44     return std::vector<int32_t>(in.begin(), in.end());
45 }
46 
convertLegacyChipFeatureToAidl(uint64_t feature)47 IWifiChip::FeatureSetMask convertLegacyChipFeatureToAidl(uint64_t feature) {
48     switch (feature) {
49         case WIFI_FEATURE_SET_TX_POWER_LIMIT:
50             return IWifiChip::FeatureSetMask::SET_TX_POWER_LIMIT;
51         case WIFI_FEATURE_USE_BODY_HEAD_SAR:
52             return IWifiChip::FeatureSetMask::USE_BODY_HEAD_SAR;
53         case WIFI_FEATURE_D2D_RTT:
54             return IWifiChip::FeatureSetMask::D2D_RTT;
55         case WIFI_FEATURE_D2AP_RTT:
56             return IWifiChip::FeatureSetMask::D2AP_RTT;
57         case WIFI_FEATURE_INFRA_60G:
58             return IWifiChip::FeatureSetMask::WIGIG;
59         case WIFI_FEATURE_SET_LATENCY_MODE:
60             return IWifiChip::FeatureSetMask::SET_LATENCY_MODE;
61         case WIFI_FEATURE_P2P_RAND_MAC:
62             return IWifiChip::FeatureSetMask::P2P_RAND_MAC;
63         case WIFI_FEATURE_AFC_CHANNEL:
64             return IWifiChip::FeatureSetMask::SET_AFC_CHANNEL_ALLOWANCE;
65         case WIFI_FEATURE_SET_VOIP_MODE:
66             return IWifiChip::FeatureSetMask::SET_VOIP_MODE;
67         case WIFI_FEATURE_MLO_SAP:
68             return IWifiChip::FeatureSetMask::MLO_SAP;
69         case WIFI_FEATURE_MULTIPLE_MLD_ON_SAP:
70             return IWifiChip::FeatureSetMask::MULTIPLE_MLD_ON_SAP;
71     };
72     CHECK(false) << "Unknown legacy feature: " << feature;
73     return {};
74 }
75 
convertLegacyStaIfaceFeatureToAidl(uint64_t feature)76 IWifiStaIface::FeatureSetMask convertLegacyStaIfaceFeatureToAidl(uint64_t feature) {
77     switch (feature) {
78         case WIFI_FEATURE_GSCAN:
79             return IWifiStaIface::FeatureSetMask::BACKGROUND_SCAN;
80         case WIFI_FEATURE_LINK_LAYER_STATS:
81             return IWifiStaIface::FeatureSetMask::LINK_LAYER_STATS;
82         case WIFI_FEATURE_RSSI_MONITOR:
83             return IWifiStaIface::FeatureSetMask::RSSI_MONITOR;
84         case WIFI_FEATURE_CONTROL_ROAMING:
85             return IWifiStaIface::FeatureSetMask::CONTROL_ROAMING;
86         case WIFI_FEATURE_IE_WHITELIST:
87             return IWifiStaIface::FeatureSetMask::PROBE_IE_ALLOWLIST;
88         case WIFI_FEATURE_SCAN_RAND:
89             return IWifiStaIface::FeatureSetMask::SCAN_RAND;
90         case WIFI_FEATURE_INFRA_5G:
91             return IWifiStaIface::FeatureSetMask::STA_5G;
92         case WIFI_FEATURE_HOTSPOT:
93             return IWifiStaIface::FeatureSetMask::HOTSPOT;
94         case WIFI_FEATURE_PNO:
95             return IWifiStaIface::FeatureSetMask::PNO;
96         case WIFI_FEATURE_TDLS:
97             return IWifiStaIface::FeatureSetMask::TDLS;
98         case WIFI_FEATURE_TDLS_OFFCHANNEL:
99             return IWifiStaIface::FeatureSetMask::TDLS_OFFCHANNEL;
100         case WIFI_FEATURE_CONFIG_NDO:
101             return IWifiStaIface::FeatureSetMask::ND_OFFLOAD;
102         case WIFI_FEATURE_MKEEP_ALIVE:
103             return IWifiStaIface::FeatureSetMask::KEEP_ALIVE;
104         case WIFI_FEATURE_ROAMING_MODE_CONTROL:
105             return IWifiStaIface::FeatureSetMask::ROAMING_MODE_CONTROL;
106         case WIFI_FEATURE_CACHED_SCAN_RESULTS:
107             return IWifiStaIface::FeatureSetMask::CACHED_SCAN_DATA;
108     };
109     CHECK(false) << "Unknown legacy feature: " << feature;
110     return {};
111 }
112 
convertLegacyChipFeaturesToAidl(uint64_t legacy_feature_set,uint32_t * aidl_feature_set)113 bool convertLegacyChipFeaturesToAidl(uint64_t legacy_feature_set, uint32_t* aidl_feature_set) {
114     if (!aidl_feature_set) {
115         return false;
116     }
117     *aidl_feature_set = 0;
118     std::vector<uint64_t> features = {WIFI_FEATURE_SET_TX_POWER_LIMIT,
119                                       WIFI_FEATURE_USE_BODY_HEAD_SAR,
120                                       WIFI_FEATURE_D2D_RTT,
121                                       WIFI_FEATURE_D2AP_RTT,
122                                       WIFI_FEATURE_INFRA_60G,
123                                       WIFI_FEATURE_SET_LATENCY_MODE,
124                                       WIFI_FEATURE_P2P_RAND_MAC,
125                                       WIFI_FEATURE_AFC_CHANNEL,
126                                       WIFI_FEATURE_SET_VOIP_MODE,
127                                       WIFI_FEATURE_MLO_SAP,
128                                       WIFI_FEATURE_MULTIPLE_MLD_ON_SAP};
129     for (const auto feature : features) {
130         if (feature & legacy_feature_set) {
131             *aidl_feature_set |= static_cast<uint32_t>(convertLegacyChipFeatureToAidl(feature));
132         }
133     }
134 
135     return true;
136 }
137 
convertLegacyDebugRingBufferFlagsToAidl(uint32_t flag)138 WifiDebugRingBufferFlags convertLegacyDebugRingBufferFlagsToAidl(uint32_t flag) {
139     switch (flag) {
140         case WIFI_RING_BUFFER_FLAG_HAS_BINARY_ENTRIES:
141             return WifiDebugRingBufferFlags::HAS_BINARY_ENTRIES;
142         case WIFI_RING_BUFFER_FLAG_HAS_ASCII_ENTRIES:
143             return WifiDebugRingBufferFlags::HAS_ASCII_ENTRIES;
144     };
145     CHECK(false) << "Unknown legacy flag: " << flag;
146     return {};
147 }
148 
convertLegacyDebugRingBufferStatusToAidl(const legacy_hal::wifi_ring_buffer_status & legacy_status,WifiDebugRingBufferStatus * aidl_status)149 bool convertLegacyDebugRingBufferStatusToAidl(
150         const legacy_hal::wifi_ring_buffer_status& legacy_status,
151         WifiDebugRingBufferStatus* aidl_status) {
152     if (!aidl_status) {
153         return false;
154     }
155     *aidl_status = {};
156     aidl_status->ringName = safeConvertChar(reinterpret_cast<const char*>(legacy_status.name),
157                                             sizeof(legacy_status.name));
158     aidl_status->flags = 0;
159     for (const auto flag :
160          {WIFI_RING_BUFFER_FLAG_HAS_BINARY_ENTRIES, WIFI_RING_BUFFER_FLAG_HAS_ASCII_ENTRIES}) {
161         if (flag & legacy_status.flags) {
162             aidl_status->flags |= static_cast<std::underlying_type<WifiDebugRingBufferFlags>::type>(
163                     convertLegacyDebugRingBufferFlagsToAidl(flag));
164         }
165     }
166     aidl_status->ringId = legacy_status.ring_id;
167     aidl_status->sizeInBytes = legacy_status.ring_buffer_byte_size;
168     // Calculate free size of the ring the buffer. We don't need to send the
169     // exact read/write pointers that were there in the legacy HAL interface.
170     if (legacy_status.written_bytes >= legacy_status.read_bytes) {
171         aidl_status->freeSizeInBytes = legacy_status.ring_buffer_byte_size -
172                                        (legacy_status.written_bytes - legacy_status.read_bytes);
173     } else {
174         aidl_status->freeSizeInBytes = legacy_status.read_bytes - legacy_status.written_bytes;
175     }
176     aidl_status->verboseLevel = legacy_status.verbose_level;
177     return true;
178 }
179 
convertLegacyVectorOfDebugRingBufferStatusToAidl(const std::vector<legacy_hal::wifi_ring_buffer_status> & legacy_status_vec,std::vector<WifiDebugRingBufferStatus> * aidl_status_vec)180 bool convertLegacyVectorOfDebugRingBufferStatusToAidl(
181         const std::vector<legacy_hal::wifi_ring_buffer_status>& legacy_status_vec,
182         std::vector<WifiDebugRingBufferStatus>* aidl_status_vec) {
183     if (!aidl_status_vec) {
184         return false;
185     }
186     *aidl_status_vec = {};
187     for (const auto& legacy_status : legacy_status_vec) {
188         WifiDebugRingBufferStatus aidl_status;
189         if (!convertLegacyDebugRingBufferStatusToAidl(legacy_status, &aidl_status)) {
190             return false;
191         }
192         aidl_status_vec->push_back(aidl_status);
193     }
194     return true;
195 }
196 
convertLegacyWakeReasonStatsToAidl(const legacy_hal::WakeReasonStats & legacy_stats,WifiDebugHostWakeReasonStats * aidl_stats)197 bool convertLegacyWakeReasonStatsToAidl(const legacy_hal::WakeReasonStats& legacy_stats,
198                                         WifiDebugHostWakeReasonStats* aidl_stats) {
199     if (!aidl_stats) {
200         return false;
201     }
202     *aidl_stats = {};
203     aidl_stats->totalCmdEventWakeCnt = legacy_stats.wake_reason_cnt.total_cmd_event_wake;
204     aidl_stats->cmdEventWakeCntPerType = uintToIntVec(legacy_stats.cmd_event_wake_cnt);
205     aidl_stats->totalDriverFwLocalWakeCnt = legacy_stats.wake_reason_cnt.total_driver_fw_local_wake;
206     aidl_stats->driverFwLocalWakeCntPerType = uintToIntVec(legacy_stats.driver_fw_local_wake_cnt);
207     aidl_stats->totalRxPacketWakeCnt = legacy_stats.wake_reason_cnt.total_rx_data_wake;
208     aidl_stats->rxPktWakeDetails.rxUnicastCnt =
209             legacy_stats.wake_reason_cnt.rx_wake_details.rx_unicast_cnt;
210     aidl_stats->rxPktWakeDetails.rxMulticastCnt =
211             legacy_stats.wake_reason_cnt.rx_wake_details.rx_multicast_cnt;
212     aidl_stats->rxPktWakeDetails.rxBroadcastCnt =
213             legacy_stats.wake_reason_cnt.rx_wake_details.rx_broadcast_cnt;
214     aidl_stats->rxMulticastPkWakeDetails.ipv4RxMulticastAddrCnt =
215             legacy_stats.wake_reason_cnt.rx_multicast_wake_pkt_info.ipv4_rx_multicast_addr_cnt;
216     aidl_stats->rxMulticastPkWakeDetails.ipv6RxMulticastAddrCnt =
217             legacy_stats.wake_reason_cnt.rx_multicast_wake_pkt_info.ipv6_rx_multicast_addr_cnt;
218     aidl_stats->rxMulticastPkWakeDetails.otherRxMulticastAddrCnt =
219             legacy_stats.wake_reason_cnt.rx_multicast_wake_pkt_info.other_rx_multicast_addr_cnt;
220     aidl_stats->rxIcmpPkWakeDetails.icmpPkt =
221             legacy_stats.wake_reason_cnt.rx_wake_pkt_classification_info.icmp_pkt;
222     aidl_stats->rxIcmpPkWakeDetails.icmp6Pkt =
223             legacy_stats.wake_reason_cnt.rx_wake_pkt_classification_info.icmp6_pkt;
224     aidl_stats->rxIcmpPkWakeDetails.icmp6Ra =
225             legacy_stats.wake_reason_cnt.rx_wake_pkt_classification_info.icmp6_ra;
226     aidl_stats->rxIcmpPkWakeDetails.icmp6Na =
227             legacy_stats.wake_reason_cnt.rx_wake_pkt_classification_info.icmp6_na;
228     aidl_stats->rxIcmpPkWakeDetails.icmp6Ns =
229             legacy_stats.wake_reason_cnt.rx_wake_pkt_classification_info.icmp6_ns;
230     return true;
231 }
232 
convertAidlTxPowerScenarioToLegacy(IWifiChip::TxPowerScenario aidl_scenario)233 legacy_hal::wifi_power_scenario convertAidlTxPowerScenarioToLegacy(
234         IWifiChip::TxPowerScenario aidl_scenario) {
235     switch (aidl_scenario) {
236         case IWifiChip::TxPowerScenario::VOICE_CALL:
237             return legacy_hal::WIFI_POWER_SCENARIO_VOICE_CALL;
238         case IWifiChip::TxPowerScenario::ON_HEAD_CELL_OFF:
239             return legacy_hal::WIFI_POWER_SCENARIO_ON_HEAD_CELL_OFF;
240         case IWifiChip::TxPowerScenario::ON_HEAD_CELL_ON:
241             return legacy_hal::WIFI_POWER_SCENARIO_ON_HEAD_CELL_ON;
242         case IWifiChip::TxPowerScenario::ON_BODY_CELL_OFF:
243             return legacy_hal::WIFI_POWER_SCENARIO_ON_BODY_CELL_OFF;
244         case IWifiChip::TxPowerScenario::ON_BODY_CELL_ON:
245             return legacy_hal::WIFI_POWER_SCENARIO_ON_BODY_CELL_ON;
246     };
247     CHECK(false);
248 }
249 
convertAidlLatencyModeToLegacy(IWifiChip::LatencyMode aidl_latency_mode)250 legacy_hal::wifi_latency_mode convertAidlLatencyModeToLegacy(
251         IWifiChip::LatencyMode aidl_latency_mode) {
252     switch (aidl_latency_mode) {
253         case IWifiChip::LatencyMode::NORMAL:
254             return legacy_hal::WIFI_LATENCY_MODE_NORMAL;
255         case IWifiChip::LatencyMode::LOW:
256             return legacy_hal::WIFI_LATENCY_MODE_LOW;
257     }
258     CHECK(false);
259 }
260 
convertLegacyWifiMacInfoToAidl(const legacy_hal::WifiMacInfo & legacy_mac_info,IWifiChipEventCallback::RadioModeInfo * aidl_radio_mode_info)261 bool convertLegacyWifiMacInfoToAidl(const legacy_hal::WifiMacInfo& legacy_mac_info,
262                                     IWifiChipEventCallback::RadioModeInfo* aidl_radio_mode_info) {
263     if (!aidl_radio_mode_info) {
264         return false;
265     }
266     *aidl_radio_mode_info = {};
267 
268     aidl_radio_mode_info->radioId = legacy_mac_info.wlan_mac_id;
269     // Convert from bitmask of bands in the legacy HAL to enum value in
270     // the AIDL interface.
271     if (legacy_mac_info.mac_band & legacy_hal::WLAN_MAC_6_0_BAND &&
272         legacy_mac_info.mac_band & legacy_hal::WLAN_MAC_5_0_BAND &&
273         legacy_mac_info.mac_band & legacy_hal::WLAN_MAC_2_4_BAND) {
274         aidl_radio_mode_info->bandInfo = WifiBand::BAND_24GHZ_5GHZ_6GHZ;
275     } else if (legacy_mac_info.mac_band & legacy_hal::WLAN_MAC_6_0_BAND &&
276                legacy_mac_info.mac_band & legacy_hal::WLAN_MAC_5_0_BAND) {
277         aidl_radio_mode_info->bandInfo = WifiBand::BAND_5GHZ_6GHZ;
278     } else if (legacy_mac_info.mac_band & legacy_hal::WLAN_MAC_6_0_BAND) {
279         aidl_radio_mode_info->bandInfo = WifiBand::BAND_6GHZ;
280     } else if (legacy_mac_info.mac_band & legacy_hal::WLAN_MAC_2_4_BAND &&
281                legacy_mac_info.mac_band & legacy_hal::WLAN_MAC_5_0_BAND) {
282         aidl_radio_mode_info->bandInfo = WifiBand::BAND_24GHZ_5GHZ;
283     } else if (legacy_mac_info.mac_band & legacy_hal::WLAN_MAC_2_4_BAND) {
284         aidl_radio_mode_info->bandInfo = WifiBand::BAND_24GHZ;
285     } else if (legacy_mac_info.mac_band & legacy_hal::WLAN_MAC_5_0_BAND) {
286         aidl_radio_mode_info->bandInfo = WifiBand::BAND_5GHZ;
287     } else {
288         aidl_radio_mode_info->bandInfo = WifiBand::BAND_UNSPECIFIED;
289     }
290     std::vector<IWifiChipEventCallback::IfaceInfo> iface_info_vec;
291     for (const auto& legacy_iface_info : legacy_mac_info.iface_infos) {
292         IWifiChipEventCallback::IfaceInfo iface_info;
293         iface_info.name = legacy_iface_info.name;
294         iface_info.channel = legacy_iface_info.channel;
295         iface_info_vec.push_back(iface_info);
296     }
297     aidl_radio_mode_info->ifaceInfos = iface_info_vec;
298     return true;
299 }
300 
convertAidlWifiBandToLegacyMacBand(WifiBand aidl_band)301 uint32_t convertAidlWifiBandToLegacyMacBand(WifiBand aidl_band) {
302     switch (aidl_band) {
303         case WifiBand::BAND_24GHZ:
304             return legacy_hal::WLAN_MAC_2_4_BAND;
305         case WifiBand::BAND_5GHZ:
306         case WifiBand::BAND_5GHZ_DFS:
307         case WifiBand::BAND_5GHZ_WITH_DFS:
308             return legacy_hal::WLAN_MAC_5_0_BAND;
309         case WifiBand::BAND_24GHZ_5GHZ:
310         case WifiBand::BAND_24GHZ_5GHZ_WITH_DFS:
311             return (legacy_hal::WLAN_MAC_2_4_BAND | legacy_hal::WLAN_MAC_5_0_BAND);
312         case WifiBand::BAND_6GHZ:
313             return legacy_hal::WLAN_MAC_6_0_BAND;
314         case WifiBand::BAND_5GHZ_6GHZ:
315             return (legacy_hal::WLAN_MAC_5_0_BAND | legacy_hal::WLAN_MAC_6_0_BAND);
316         case WifiBand::BAND_24GHZ_5GHZ_6GHZ:
317         case WifiBand::BAND_24GHZ_5GHZ_WITH_DFS_6GHZ:
318             return (legacy_hal::WLAN_MAC_2_4_BAND | legacy_hal::WLAN_MAC_5_0_BAND |
319                     legacy_hal::WLAN_MAC_6_0_BAND);
320         case WifiBand::BAND_60GHZ:
321             return legacy_hal::WLAN_MAC_60_0_BAND;
322         default:
323             return (legacy_hal::WLAN_MAC_2_4_BAND | legacy_hal::WLAN_MAC_5_0_BAND |
324                     legacy_hal::WLAN_MAC_6_0_BAND | legacy_hal::WLAN_MAC_60_0_BAND);
325     }
326 }
327 
convertLegacyMacBandToAidlWifiBand(uint32_t band)328 WifiBand convertLegacyMacBandToAidlWifiBand(uint32_t band) {
329     switch (band) {
330         case legacy_hal::WLAN_MAC_2_4_BAND:
331             return WifiBand::BAND_24GHZ;
332         case legacy_hal::WLAN_MAC_5_0_BAND:
333             return WifiBand::BAND_5GHZ;
334         case legacy_hal::WLAN_MAC_6_0_BAND:
335             return WifiBand::BAND_6GHZ;
336         case legacy_hal::WLAN_MAC_60_0_BAND:
337             return WifiBand::BAND_60GHZ;
338         default:
339             return WifiBand::BAND_UNSPECIFIED;
340     }
341 }
342 
convertAidlWifiIfaceModeToLegacy(uint32_t aidl_iface_mask)343 uint32_t convertAidlWifiIfaceModeToLegacy(uint32_t aidl_iface_mask) {
344     uint32_t legacy_iface_mask = 0;
345     if (aidl_iface_mask & static_cast<int32_t>(WifiIfaceMode::IFACE_MODE_STA)) {
346         legacy_iface_mask |= (1 << legacy_hal::WIFI_INTERFACE_STA);
347     }
348     if (aidl_iface_mask & static_cast<int32_t>(WifiIfaceMode::IFACE_MODE_SOFTAP)) {
349         legacy_iface_mask |= (1 << legacy_hal::WIFI_INTERFACE_SOFTAP);
350     }
351     if (aidl_iface_mask & static_cast<int32_t>(WifiIfaceMode::IFACE_MODE_P2P_CLIENT)) {
352         legacy_iface_mask |= (1 << legacy_hal::WIFI_INTERFACE_P2P_CLIENT);
353     }
354     if (aidl_iface_mask & static_cast<int32_t>(WifiIfaceMode::IFACE_MODE_P2P_GO)) {
355         legacy_iface_mask |= (1 << legacy_hal::WIFI_INTERFACE_P2P_GO);
356     }
357     if (aidl_iface_mask & static_cast<int32_t>(WifiIfaceMode::IFACE_MODE_NAN)) {
358         legacy_iface_mask |= (1 << legacy_hal::WIFI_INTERFACE_NAN);
359     }
360     if (aidl_iface_mask & static_cast<int32_t>(WifiIfaceMode::IFACE_MODE_TDLS)) {
361         legacy_iface_mask |= (1 << legacy_hal::WIFI_INTERFACE_TDLS);
362     }
363     if (aidl_iface_mask & static_cast<int32_t>(WifiIfaceMode::IFACE_MODE_MESH)) {
364         legacy_iface_mask |= (1 << legacy_hal::WIFI_INTERFACE_MESH);
365     }
366     if (aidl_iface_mask & static_cast<int32_t>(WifiIfaceMode::IFACE_MODE_IBSS)) {
367         legacy_iface_mask |= (1 << legacy_hal::WIFI_INTERFACE_IBSS);
368     }
369     return legacy_iface_mask;
370 }
371 
convertLegacyWifiInterfaceModeToAidl(uint32_t legacy_iface_mask)372 uint32_t convertLegacyWifiInterfaceModeToAidl(uint32_t legacy_iface_mask) {
373     uint32_t aidl_iface_mask = 0;
374     if (legacy_iface_mask & (1 << legacy_hal::WIFI_INTERFACE_STA)) {
375         aidl_iface_mask |= static_cast<int32_t>(WifiIfaceMode::IFACE_MODE_STA);
376     }
377     if (legacy_iface_mask & (1 << legacy_hal::WIFI_INTERFACE_SOFTAP)) {
378         aidl_iface_mask |= static_cast<int32_t>(WifiIfaceMode::IFACE_MODE_SOFTAP);
379     }
380     if (legacy_iface_mask & (1 << legacy_hal::WIFI_INTERFACE_P2P_CLIENT)) {
381         aidl_iface_mask |= static_cast<int32_t>(WifiIfaceMode::IFACE_MODE_P2P_CLIENT);
382     }
383     if (legacy_iface_mask & (1 << legacy_hal::WIFI_INTERFACE_P2P_GO)) {
384         aidl_iface_mask |= static_cast<int32_t>(WifiIfaceMode::IFACE_MODE_P2P_GO);
385     }
386     if (legacy_iface_mask & (1 << legacy_hal::WIFI_INTERFACE_NAN)) {
387         aidl_iface_mask |= static_cast<int32_t>(WifiIfaceMode::IFACE_MODE_NAN);
388     }
389     if (legacy_iface_mask & (1 << legacy_hal::WIFI_INTERFACE_TDLS)) {
390         aidl_iface_mask |= static_cast<int32_t>(WifiIfaceMode::IFACE_MODE_TDLS);
391     }
392     if (legacy_iface_mask & (1 << legacy_hal::WIFI_INTERFACE_MESH)) {
393         aidl_iface_mask |= static_cast<int32_t>(WifiIfaceMode::IFACE_MODE_MESH);
394     }
395     if (legacy_iface_mask & (1 << legacy_hal::WIFI_INTERFACE_IBSS)) {
396         aidl_iface_mask |= static_cast<int32_t>(WifiIfaceMode::IFACE_MODE_IBSS);
397     }
398     return aidl_iface_mask;
399 }
400 
convertAidlUsableChannelFilterToLegacy(uint32_t aidl_filter_mask)401 uint32_t convertAidlUsableChannelFilterToLegacy(uint32_t aidl_filter_mask) {
402     uint32_t legacy_filter_mask = 0;
403     if (aidl_filter_mask &
404         static_cast<int32_t>(IWifiChip::UsableChannelFilter::CELLULAR_COEXISTENCE)) {
405         legacy_filter_mask |= legacy_hal::WIFI_USABLE_CHANNEL_FILTER_CELLULAR_COEXISTENCE;
406     }
407     if (aidl_filter_mask & static_cast<int32_t>(IWifiChip::UsableChannelFilter::CONCURRENCY)) {
408         legacy_filter_mask |= legacy_hal::WIFI_USABLE_CHANNEL_FILTER_CONCURRENCY;
409     }
410     if (aidl_filter_mask & static_cast<int32_t>(IWifiChip::UsableChannelFilter::NAN_INSTANT_MODE)) {
411         legacy_filter_mask |= WIFI_USABLE_CHANNEL_FILTER_NAN_INSTANT_MODE;
412     }
413     return legacy_filter_mask;
414 }
415 
convertLegacyWifiUsableChannelToAidl(const legacy_hal::wifi_usable_channel & legacy_usable_channel,WifiUsableChannel * aidl_usable_channel)416 bool convertLegacyWifiUsableChannelToAidl(
417         const legacy_hal::wifi_usable_channel& legacy_usable_channel,
418         WifiUsableChannel* aidl_usable_channel) {
419     if (!aidl_usable_channel) {
420         return false;
421     }
422     *aidl_usable_channel = {};
423     aidl_usable_channel->channel = legacy_usable_channel.freq;
424     aidl_usable_channel->channelBandwidth =
425             convertLegacyWifiChannelWidthToAidl(legacy_usable_channel.width);
426     aidl_usable_channel->ifaceModeMask =
427             convertLegacyWifiInterfaceModeToAidl(legacy_usable_channel.iface_mode_mask);
428 
429     return true;
430 }
431 
convertLegacyWifiUsableChannelsToAidl(const std::vector<legacy_hal::wifi_usable_channel> & legacy_usable_channels,std::vector<WifiUsableChannel> * aidl_usable_channels)432 bool convertLegacyWifiUsableChannelsToAidl(
433         const std::vector<legacy_hal::wifi_usable_channel>& legacy_usable_channels,
434         std::vector<WifiUsableChannel>* aidl_usable_channels) {
435     if (!aidl_usable_channels) {
436         return false;
437     }
438     *aidl_usable_channels = {};
439     for (const auto& legacy_usable_channel : legacy_usable_channels) {
440         WifiUsableChannel aidl_usable_channel;
441         if (!convertLegacyWifiUsableChannelToAidl(legacy_usable_channel, &aidl_usable_channel)) {
442             return false;
443         }
444         aidl_usable_channels->push_back(aidl_usable_channel);
445     }
446     return true;
447 }
448 
convertLegacyWifiMacInfosToAidl(const std::vector<legacy_hal::WifiMacInfo> & legacy_mac_infos,std::vector<IWifiChipEventCallback::RadioModeInfo> * aidl_radio_mode_infos)449 bool convertLegacyWifiMacInfosToAidl(
450         const std::vector<legacy_hal::WifiMacInfo>& legacy_mac_infos,
451         std::vector<IWifiChipEventCallback::RadioModeInfo>* aidl_radio_mode_infos) {
452     if (!aidl_radio_mode_infos) {
453         return false;
454     }
455     *aidl_radio_mode_infos = {};
456 
457     for (const auto& legacy_mac_info : legacy_mac_infos) {
458         IWifiChipEventCallback::RadioModeInfo aidl_radio_mode_info;
459         if (!convertLegacyWifiMacInfoToAidl(legacy_mac_info, &aidl_radio_mode_info)) {
460             return false;
461         }
462         aidl_radio_mode_infos->push_back(aidl_radio_mode_info);
463     }
464     return true;
465 }
466 
convertLegacyStaIfaceFeaturesToAidl(uint64_t legacy_feature_set,uint32_t * aidl_feature_set)467 bool convertLegacyStaIfaceFeaturesToAidl(uint64_t legacy_feature_set, uint32_t* aidl_feature_set) {
468     if (!aidl_feature_set) {
469         return false;
470     }
471     *aidl_feature_set = 0;
472     for (const auto feature :
473          {WIFI_FEATURE_GSCAN, WIFI_FEATURE_LINK_LAYER_STATS, WIFI_FEATURE_RSSI_MONITOR,
474           WIFI_FEATURE_CONTROL_ROAMING, WIFI_FEATURE_IE_WHITELIST, WIFI_FEATURE_SCAN_RAND,
475           WIFI_FEATURE_INFRA_5G, WIFI_FEATURE_HOTSPOT, WIFI_FEATURE_PNO, WIFI_FEATURE_TDLS,
476           WIFI_FEATURE_TDLS_OFFCHANNEL, WIFI_FEATURE_CONFIG_NDO, WIFI_FEATURE_MKEEP_ALIVE,
477           WIFI_FEATURE_ROAMING_MODE_CONTROL, WIFI_FEATURE_CACHED_SCAN_RESULTS}) {
478         if (feature & legacy_feature_set) {
479             *aidl_feature_set |= static_cast<uint32_t>(convertLegacyStaIfaceFeatureToAidl(feature));
480         }
481     }
482     // There is no flag for this one in the legacy feature set. Adding it to the
483     // set because all the current devices support it.
484     *aidl_feature_set |= static_cast<uint32_t>(IWifiStaIface::FeatureSetMask::APF);
485     return true;
486 }
487 
convertLegacyApfCapabilitiesToAidl(const legacy_hal::PacketFilterCapabilities & legacy_caps,StaApfPacketFilterCapabilities * aidl_caps)488 bool convertLegacyApfCapabilitiesToAidl(const legacy_hal::PacketFilterCapabilities& legacy_caps,
489                                         StaApfPacketFilterCapabilities* aidl_caps) {
490     if (!aidl_caps) {
491         return false;
492     }
493     *aidl_caps = {};
494     aidl_caps->version = legacy_caps.version;
495     aidl_caps->maxLength = legacy_caps.max_len;
496     return true;
497 }
498 
convertAidlGscanReportEventFlagToLegacy(StaBackgroundScanBucketEventReportSchemeMask aidl_flag)499 uint8_t convertAidlGscanReportEventFlagToLegacy(
500         StaBackgroundScanBucketEventReportSchemeMask aidl_flag) {
501     using AidlFlag = StaBackgroundScanBucketEventReportSchemeMask;
502     switch (aidl_flag) {
503         case AidlFlag::EACH_SCAN:
504             return REPORT_EVENTS_EACH_SCAN;
505         case AidlFlag::FULL_RESULTS:
506             return REPORT_EVENTS_FULL_RESULTS;
507         case AidlFlag::NO_BATCH:
508             return REPORT_EVENTS_NO_BATCH;
509     };
510     CHECK(false);
511 }
512 
convertLegacyGscanDataFlagToAidl(uint8_t legacy_flag)513 StaScanDataFlagMask convertLegacyGscanDataFlagToAidl(uint8_t legacy_flag) {
514     switch (legacy_flag) {
515         case legacy_hal::WIFI_SCAN_FLAG_INTERRUPTED:
516             return StaScanDataFlagMask::INTERRUPTED;
517     };
518     CHECK(false) << "Unknown legacy flag: " << legacy_flag;
519     // To silence the compiler warning about reaching the end of non-void
520     // function.
521     return {};
522 }
523 
convertLegacyGscanCapabilitiesToAidl(const legacy_hal::wifi_gscan_capabilities & legacy_caps,StaBackgroundScanCapabilities * aidl_caps)524 bool convertLegacyGscanCapabilitiesToAidl(const legacy_hal::wifi_gscan_capabilities& legacy_caps,
525                                           StaBackgroundScanCapabilities* aidl_caps) {
526     if (!aidl_caps) {
527         return false;
528     }
529     *aidl_caps = {};
530     aidl_caps->maxCacheSize = legacy_caps.max_scan_cache_size;
531     aidl_caps->maxBuckets = legacy_caps.max_scan_buckets;
532     aidl_caps->maxApCachePerScan = legacy_caps.max_ap_cache_per_scan;
533     aidl_caps->maxReportingThreshold = legacy_caps.max_scan_reporting_threshold;
534     return true;
535 }
536 
537 // Only use to prepare parameters for Gscan.
convertAidlWifiBandToLegacy(WifiBand band)538 legacy_hal::wifi_band convertAidlWifiBandToLegacy(WifiBand band) {
539     switch (band) {
540         case WifiBand::BAND_UNSPECIFIED:
541             return legacy_hal::WIFI_BAND_UNSPECIFIED;
542         case WifiBand::BAND_24GHZ:
543             return legacy_hal::WIFI_BAND_BG;
544         case WifiBand::BAND_5GHZ:
545             return legacy_hal::WIFI_BAND_A;
546         case WifiBand::BAND_5GHZ_DFS:
547             return legacy_hal::WIFI_BAND_A_DFS;
548         case WifiBand::BAND_5GHZ_WITH_DFS:
549             return legacy_hal::WIFI_BAND_A_WITH_DFS;
550         case WifiBand::BAND_24GHZ_5GHZ:
551             return legacy_hal::WIFI_BAND_ABG;
552         case WifiBand::BAND_24GHZ_5GHZ_WITH_DFS:
553             return legacy_hal::WIFI_BAND_ABG_WITH_DFS;
554         case WifiBand::BAND_6GHZ:
555         case WifiBand::BAND_60GHZ:
556         case WifiBand::BAND_5GHZ_6GHZ:
557         case WifiBand::BAND_24GHZ_5GHZ_6GHZ:
558         case WifiBand::BAND_24GHZ_5GHZ_6GHZ_60GHZ:
559         case WifiBand::BAND_24GHZ_5GHZ_WITH_DFS_6GHZ:
560         case WifiBand::BAND_24GHZ_5GHZ_WITH_DFS_6GHZ_60GHZ:
561             LOG(INFO) << "WifiBand mapping may be incorrect, since 6GHz is not supported by legacy";
562             return legacy_hal::WIFI_BAND_UNSPECIFIED;
563         default:
564             CHECK(false);
565             return {};
566     };
567 }
568 
convertAidlGscanParamsToLegacy(const StaBackgroundScanParameters & aidl_scan_params,legacy_hal::wifi_scan_cmd_params * legacy_scan_params)569 bool convertAidlGscanParamsToLegacy(const StaBackgroundScanParameters& aidl_scan_params,
570                                     legacy_hal::wifi_scan_cmd_params* legacy_scan_params) {
571     if (!legacy_scan_params) {
572         return false;
573     }
574     *legacy_scan_params = {};
575     legacy_scan_params->base_period = aidl_scan_params.basePeriodInMs;
576     legacy_scan_params->max_ap_per_scan = aidl_scan_params.maxApPerScan;
577     legacy_scan_params->report_threshold_percent = aidl_scan_params.reportThresholdPercent;
578     legacy_scan_params->report_threshold_num_scans = aidl_scan_params.reportThresholdNumScans;
579     if (aidl_scan_params.buckets.size() > MAX_BUCKETS) {
580         return false;
581     }
582     legacy_scan_params->num_buckets = aidl_scan_params.buckets.size();
583     for (uint32_t bucket_idx = 0; bucket_idx < aidl_scan_params.buckets.size(); bucket_idx++) {
584         const StaBackgroundScanBucketParameters& aidl_bucket_spec =
585                 aidl_scan_params.buckets[bucket_idx];
586         legacy_hal::wifi_scan_bucket_spec& legacy_bucket_spec =
587                 legacy_scan_params->buckets[bucket_idx];
588         if (aidl_bucket_spec.bucketIdx >= MAX_BUCKETS) {
589             return false;
590         }
591         legacy_bucket_spec.bucket = aidl_bucket_spec.bucketIdx;
592         legacy_bucket_spec.band = convertAidlWifiBandToLegacy(aidl_bucket_spec.band);
593         legacy_bucket_spec.period = aidl_bucket_spec.periodInMs;
594         legacy_bucket_spec.max_period = aidl_bucket_spec.exponentialMaxPeriodInMs;
595         legacy_bucket_spec.base = aidl_bucket_spec.exponentialBase;
596         legacy_bucket_spec.step_count = aidl_bucket_spec.exponentialStepCount;
597         legacy_bucket_spec.report_events = 0;
598         using AidlFlag = StaBackgroundScanBucketEventReportSchemeMask;
599         for (const auto flag : {AidlFlag::EACH_SCAN, AidlFlag::FULL_RESULTS, AidlFlag::NO_BATCH}) {
600             if (aidl_bucket_spec.eventReportScheme &
601                 static_cast<std::underlying_type<AidlFlag>::type>(flag)) {
602                 legacy_bucket_spec.report_events |= convertAidlGscanReportEventFlagToLegacy(flag);
603             }
604         }
605         if (aidl_bucket_spec.frequencies.size() > MAX_CHANNELS) {
606             return false;
607         }
608         legacy_bucket_spec.num_channels = aidl_bucket_spec.frequencies.size();
609         for (uint32_t freq_idx = 0; freq_idx < aidl_bucket_spec.frequencies.size(); freq_idx++) {
610             legacy_bucket_spec.channels[freq_idx].channel = aidl_bucket_spec.frequencies[freq_idx];
611         }
612     }
613     return true;
614 }
615 
convertLegacyIeToAidl(const legacy_hal::wifi_information_element & legacy_ie,WifiInformationElement * aidl_ie)616 bool convertLegacyIeToAidl(const legacy_hal::wifi_information_element& legacy_ie,
617                            WifiInformationElement* aidl_ie) {
618     if (!aidl_ie) {
619         return false;
620     }
621     *aidl_ie = {};
622     aidl_ie->id = legacy_ie.id;
623     aidl_ie->data = std::vector<uint8_t>(legacy_ie.data, legacy_ie.data + legacy_ie.len);
624     return true;
625 }
626 
convertLegacyIeBlobToAidl(const uint8_t * ie_blob,uint32_t ie_blob_len,std::vector<WifiInformationElement> * aidl_ies)627 bool convertLegacyIeBlobToAidl(const uint8_t* ie_blob, uint32_t ie_blob_len,
628                                std::vector<WifiInformationElement>* aidl_ies) {
629     if (!ie_blob || !aidl_ies) {
630         return false;
631     }
632     *aidl_ies = {};
633     const uint8_t* ies_begin = ie_blob;
634     const uint8_t* ies_end = ie_blob + ie_blob_len;
635     const uint8_t* next_ie = ies_begin;
636     using wifi_ie = legacy_hal::wifi_information_element;
637     constexpr size_t kIeHeaderLen = sizeof(wifi_ie);
638     // Each IE should at least have the header (i.e |id| & |len| fields).
639     while (next_ie + kIeHeaderLen <= ies_end) {
640         const wifi_ie& legacy_ie = (*reinterpret_cast<const wifi_ie*>(next_ie));
641         uint32_t curr_ie_len = kIeHeaderLen + legacy_ie.len;
642         if (next_ie + curr_ie_len > ies_end) {
643             LOG(ERROR) << "Error parsing IE blob. Next IE: " << (void*)next_ie
644                        << ", Curr IE len: " << curr_ie_len << ", IEs End: " << (void*)ies_end;
645             break;
646         }
647         WifiInformationElement aidl_ie;
648         if (!convertLegacyIeToAidl(legacy_ie, &aidl_ie)) {
649             LOG(ERROR) << "Error converting IE. Id: " << legacy_ie.id << ", len: " << legacy_ie.len;
650             break;
651         }
652         aidl_ies->push_back(std::move(aidl_ie));
653         next_ie += curr_ie_len;
654     }
655     // Check if the blob has been fully consumed.
656     if (next_ie != ies_end) {
657         LOG(ERROR) << "Failed to fully parse IE blob. Next IE: " << (void*)next_ie
658                    << ", IEs End: " << (void*)ies_end;
659     }
660     return true;
661 }
662 
convertLegacyGscanResultToAidl(const legacy_hal::wifi_scan_result & legacy_scan_result,bool has_ie_data,StaScanResult * aidl_scan_result)663 bool convertLegacyGscanResultToAidl(const legacy_hal::wifi_scan_result& legacy_scan_result,
664                                     bool has_ie_data, StaScanResult* aidl_scan_result) {
665     if (!aidl_scan_result) {
666         return false;
667     }
668     *aidl_scan_result = {};
669     aidl_scan_result->timeStampInUs = legacy_scan_result.ts;
670     aidl_scan_result->ssid = std::vector<uint8_t>(
671             legacy_scan_result.ssid,
672             legacy_scan_result.ssid +
673                     strnlen(legacy_scan_result.ssid, sizeof(legacy_scan_result.ssid) - 1));
674     aidl_scan_result->bssid = std::array<uint8_t, 6>();
675     std::copy(legacy_scan_result.bssid, legacy_scan_result.bssid + 6,
676               std::begin(aidl_scan_result->bssid));
677     aidl_scan_result->frequency = legacy_scan_result.channel;
678     aidl_scan_result->rssi = legacy_scan_result.rssi;
679     aidl_scan_result->beaconPeriodInMs = legacy_scan_result.beacon_period;
680     aidl_scan_result->capability = legacy_scan_result.capability;
681     if (has_ie_data) {
682         std::vector<WifiInformationElement> ies;
683         if (!convertLegacyIeBlobToAidl(reinterpret_cast<const uint8_t*>(legacy_scan_result.ie_data),
684                                        legacy_scan_result.ie_length, &ies)) {
685             return false;
686         }
687         aidl_scan_result->informationElements = std::move(ies);
688     }
689     return true;
690 }
691 
convertLegacyCachedGscanResultsToAidl(const legacy_hal::wifi_cached_scan_results & legacy_cached_scan_result,StaScanData * aidl_scan_data)692 bool convertLegacyCachedGscanResultsToAidl(
693         const legacy_hal::wifi_cached_scan_results& legacy_cached_scan_result,
694         StaScanData* aidl_scan_data) {
695     if (!aidl_scan_data) {
696         return false;
697     }
698     *aidl_scan_data = {};
699     int32_t flags = 0;
700     for (const auto flag : {legacy_hal::WIFI_SCAN_FLAG_INTERRUPTED}) {
701         if (legacy_cached_scan_result.flags & flag) {
702             flags |= static_cast<std::underlying_type<StaScanDataFlagMask>::type>(
703                     convertLegacyGscanDataFlagToAidl(flag));
704         }
705     }
706     aidl_scan_data->flags = flags;
707     aidl_scan_data->bucketsScanned = legacy_cached_scan_result.buckets_scanned;
708 
709     CHECK(legacy_cached_scan_result.num_results >= 0 &&
710           legacy_cached_scan_result.num_results <= MAX_AP_CACHE_PER_SCAN);
711     std::vector<StaScanResult> aidl_scan_results;
712     for (int32_t result_idx = 0; result_idx < legacy_cached_scan_result.num_results; result_idx++) {
713         StaScanResult aidl_scan_result;
714         if (!convertLegacyGscanResultToAidl(legacy_cached_scan_result.results[result_idx], false,
715                                             &aidl_scan_result)) {
716             return false;
717         }
718         aidl_scan_results.push_back(aidl_scan_result);
719     }
720     aidl_scan_data->results = std::move(aidl_scan_results);
721     return true;
722 }
723 
convertLegacyVectorOfCachedGscanResultsToAidl(const std::vector<legacy_hal::wifi_cached_scan_results> & legacy_cached_scan_results,std::vector<StaScanData> * aidl_scan_datas)724 bool convertLegacyVectorOfCachedGscanResultsToAidl(
725         const std::vector<legacy_hal::wifi_cached_scan_results>& legacy_cached_scan_results,
726         std::vector<StaScanData>* aidl_scan_datas) {
727     if (!aidl_scan_datas) {
728         return false;
729     }
730     *aidl_scan_datas = {};
731     for (const auto& legacy_cached_scan_result : legacy_cached_scan_results) {
732         StaScanData aidl_scan_data;
733         if (!convertLegacyCachedGscanResultsToAidl(legacy_cached_scan_result, &aidl_scan_data)) {
734             return false;
735         }
736         aidl_scan_datas->push_back(aidl_scan_data);
737     }
738     return true;
739 }
740 
convertLegacyDebugTxPacketFateToAidl(legacy_hal::wifi_tx_packet_fate fate)741 WifiDebugTxPacketFate convertLegacyDebugTxPacketFateToAidl(legacy_hal::wifi_tx_packet_fate fate) {
742     switch (fate) {
743         case legacy_hal::TX_PKT_FATE_ACKED:
744             return WifiDebugTxPacketFate::ACKED;
745         case legacy_hal::TX_PKT_FATE_SENT:
746             return WifiDebugTxPacketFate::SENT;
747         case legacy_hal::TX_PKT_FATE_FW_QUEUED:
748             return WifiDebugTxPacketFate::FW_QUEUED;
749         case legacy_hal::TX_PKT_FATE_FW_DROP_INVALID:
750             return WifiDebugTxPacketFate::FW_DROP_INVALID;
751         case legacy_hal::TX_PKT_FATE_FW_DROP_NOBUFS:
752             return WifiDebugTxPacketFate::FW_DROP_NOBUFS;
753         case legacy_hal::TX_PKT_FATE_FW_DROP_OTHER:
754             return WifiDebugTxPacketFate::FW_DROP_OTHER;
755         case legacy_hal::TX_PKT_FATE_DRV_QUEUED:
756             return WifiDebugTxPacketFate::DRV_QUEUED;
757         case legacy_hal::TX_PKT_FATE_DRV_DROP_INVALID:
758             return WifiDebugTxPacketFate::DRV_DROP_INVALID;
759         case legacy_hal::TX_PKT_FATE_DRV_DROP_NOBUFS:
760             return WifiDebugTxPacketFate::DRV_DROP_NOBUFS;
761         case legacy_hal::TX_PKT_FATE_DRV_DROP_OTHER:
762             return WifiDebugTxPacketFate::DRV_DROP_OTHER;
763     };
764     CHECK(false) << "Unknown legacy fate type: " << fate;
765 }
766 
convertLegacyDebugRxPacketFateToAidl(legacy_hal::wifi_rx_packet_fate fate)767 WifiDebugRxPacketFate convertLegacyDebugRxPacketFateToAidl(legacy_hal::wifi_rx_packet_fate fate) {
768     switch (fate) {
769         case legacy_hal::RX_PKT_FATE_SUCCESS:
770             return WifiDebugRxPacketFate::SUCCESS;
771         case legacy_hal::RX_PKT_FATE_FW_QUEUED:
772             return WifiDebugRxPacketFate::FW_QUEUED;
773         case legacy_hal::RX_PKT_FATE_FW_DROP_FILTER:
774             return WifiDebugRxPacketFate::FW_DROP_FILTER;
775         case legacy_hal::RX_PKT_FATE_FW_DROP_INVALID:
776             return WifiDebugRxPacketFate::FW_DROP_INVALID;
777         case legacy_hal::RX_PKT_FATE_FW_DROP_NOBUFS:
778             return WifiDebugRxPacketFate::FW_DROP_NOBUFS;
779         case legacy_hal::RX_PKT_FATE_FW_DROP_OTHER:
780             return WifiDebugRxPacketFate::FW_DROP_OTHER;
781         case legacy_hal::RX_PKT_FATE_DRV_QUEUED:
782             return WifiDebugRxPacketFate::DRV_QUEUED;
783         case legacy_hal::RX_PKT_FATE_DRV_DROP_FILTER:
784             return WifiDebugRxPacketFate::DRV_DROP_FILTER;
785         case legacy_hal::RX_PKT_FATE_DRV_DROP_INVALID:
786             return WifiDebugRxPacketFate::DRV_DROP_INVALID;
787         case legacy_hal::RX_PKT_FATE_DRV_DROP_NOBUFS:
788             return WifiDebugRxPacketFate::DRV_DROP_NOBUFS;
789         case legacy_hal::RX_PKT_FATE_DRV_DROP_OTHER:
790             return WifiDebugRxPacketFate::DRV_DROP_OTHER;
791     };
792     CHECK(false) << "Unknown legacy fate type: " << fate;
793 }
794 
convertLegacyDebugPacketFateFrameTypeToAidl(legacy_hal::frame_type type)795 WifiDebugPacketFateFrameType convertLegacyDebugPacketFateFrameTypeToAidl(
796         legacy_hal::frame_type type) {
797     switch (type) {
798         case legacy_hal::FRAME_TYPE_UNKNOWN:
799             return WifiDebugPacketFateFrameType::UNKNOWN;
800         case legacy_hal::FRAME_TYPE_ETHERNET_II:
801             return WifiDebugPacketFateFrameType::ETHERNET_II;
802         case legacy_hal::FRAME_TYPE_80211_MGMT:
803             return WifiDebugPacketFateFrameType::MGMT_80211;
804     };
805     CHECK(false) << "Unknown legacy frame type: " << type;
806 }
807 
convertLegacyDebugPacketFateFrameToAidl(const legacy_hal::frame_info & legacy_frame,WifiDebugPacketFateFrameInfo * aidl_frame)808 bool convertLegacyDebugPacketFateFrameToAidl(const legacy_hal::frame_info& legacy_frame,
809                                              WifiDebugPacketFateFrameInfo* aidl_frame) {
810     if (!aidl_frame) {
811         return false;
812     }
813     *aidl_frame = {};
814     aidl_frame->frameType = convertLegacyDebugPacketFateFrameTypeToAidl(legacy_frame.payload_type);
815     aidl_frame->frameLen = legacy_frame.frame_len;
816     aidl_frame->driverTimestampUsec = legacy_frame.driver_timestamp_usec;
817     aidl_frame->firmwareTimestampUsec = legacy_frame.firmware_timestamp_usec;
818     const uint8_t* frame_begin =
819             reinterpret_cast<const uint8_t*>(legacy_frame.frame_content.ethernet_ii_bytes);
820     aidl_frame->frameContent =
821             std::vector<uint8_t>(frame_begin, frame_begin + legacy_frame.frame_len);
822     return true;
823 }
824 
convertLegacyDebugTxPacketFateToAidl(const legacy_hal::wifi_tx_report & legacy_fate,WifiDebugTxPacketFateReport * aidl_fate)825 bool convertLegacyDebugTxPacketFateToAidl(const legacy_hal::wifi_tx_report& legacy_fate,
826                                           WifiDebugTxPacketFateReport* aidl_fate) {
827     if (!aidl_fate) {
828         return false;
829     }
830     *aidl_fate = {};
831     aidl_fate->fate = convertLegacyDebugTxPacketFateToAidl(legacy_fate.fate);
832     return convertLegacyDebugPacketFateFrameToAidl(legacy_fate.frame_inf, &aidl_fate->frameInfo);
833 }
834 
convertLegacyVectorOfDebugTxPacketFateToAidl(const std::vector<legacy_hal::wifi_tx_report> & legacy_fates,std::vector<WifiDebugTxPacketFateReport> * aidl_fates)835 bool convertLegacyVectorOfDebugTxPacketFateToAidl(
836         const std::vector<legacy_hal::wifi_tx_report>& legacy_fates,
837         std::vector<WifiDebugTxPacketFateReport>* aidl_fates) {
838     if (!aidl_fates) {
839         return false;
840     }
841     *aidl_fates = {};
842     for (const auto& legacy_fate : legacy_fates) {
843         WifiDebugTxPacketFateReport aidl_fate;
844         if (!convertLegacyDebugTxPacketFateToAidl(legacy_fate, &aidl_fate)) {
845             return false;
846         }
847         aidl_fates->push_back(aidl_fate);
848     }
849     return true;
850 }
851 
convertLegacyDebugRxPacketFateToAidl(const legacy_hal::wifi_rx_report & legacy_fate,WifiDebugRxPacketFateReport * aidl_fate)852 bool convertLegacyDebugRxPacketFateToAidl(const legacy_hal::wifi_rx_report& legacy_fate,
853                                           WifiDebugRxPacketFateReport* aidl_fate) {
854     if (!aidl_fate) {
855         return false;
856     }
857     *aidl_fate = {};
858     aidl_fate->fate = convertLegacyDebugRxPacketFateToAidl(legacy_fate.fate);
859     return convertLegacyDebugPacketFateFrameToAidl(legacy_fate.frame_inf, &aidl_fate->frameInfo);
860 }
861 
convertLegacyVectorOfDebugRxPacketFateToAidl(const std::vector<legacy_hal::wifi_rx_report> & legacy_fates,std::vector<WifiDebugRxPacketFateReport> * aidl_fates)862 bool convertLegacyVectorOfDebugRxPacketFateToAidl(
863         const std::vector<legacy_hal::wifi_rx_report>& legacy_fates,
864         std::vector<WifiDebugRxPacketFateReport>* aidl_fates) {
865     if (!aidl_fates) {
866         return false;
867     }
868     *aidl_fates = {};
869     for (const auto& legacy_fate : legacy_fates) {
870         WifiDebugRxPacketFateReport aidl_fate;
871         if (!convertLegacyDebugRxPacketFateToAidl(legacy_fate, &aidl_fate)) {
872             return false;
873         }
874         aidl_fates->push_back(aidl_fate);
875     }
876     return true;
877 }
878 
convertLegacyLinkLayerRadioStatsToAidl(const legacy_hal::LinkLayerRadioStats & legacy_radio_stat,StaLinkLayerRadioStats * aidl_radio_stat)879 bool convertLegacyLinkLayerRadioStatsToAidl(
880         const legacy_hal::LinkLayerRadioStats& legacy_radio_stat,
881         StaLinkLayerRadioStats* aidl_radio_stat) {
882     if (!aidl_radio_stat) {
883         return false;
884     }
885     *aidl_radio_stat = {};
886 
887     aidl_radio_stat->radioId = legacy_radio_stat.stats.radio;
888     aidl_radio_stat->onTimeInMs = legacy_radio_stat.stats.on_time;
889     aidl_radio_stat->txTimeInMs = legacy_radio_stat.stats.tx_time;
890     aidl_radio_stat->rxTimeInMs = legacy_radio_stat.stats.rx_time;
891     aidl_radio_stat->onTimeInMsForScan = legacy_radio_stat.stats.on_time_scan;
892     aidl_radio_stat->txTimeInMsPerLevel = uintToIntVec(legacy_radio_stat.tx_time_per_levels);
893     aidl_radio_stat->onTimeInMsForNanScan = legacy_radio_stat.stats.on_time_nbd;
894     aidl_radio_stat->onTimeInMsForBgScan = legacy_radio_stat.stats.on_time_gscan;
895     aidl_radio_stat->onTimeInMsForRoamScan = legacy_radio_stat.stats.on_time_roam_scan;
896     aidl_radio_stat->onTimeInMsForPnoScan = legacy_radio_stat.stats.on_time_pno_scan;
897     aidl_radio_stat->onTimeInMsForHs20Scan = legacy_radio_stat.stats.on_time_hs20;
898 
899     std::vector<WifiChannelStats> aidl_channel_stats;
900 
901     for (const auto& channel_stat : legacy_radio_stat.channel_stats) {
902         WifiChannelStats aidl_channel_stat;
903         aidl_channel_stat.onTimeInMs = channel_stat.on_time;
904         aidl_channel_stat.ccaBusyTimeInMs = channel_stat.cca_busy_time;
905         aidl_channel_stat.channel.width = WifiChannelWidthInMhz::WIDTH_20;
906         aidl_channel_stat.channel.centerFreq = channel_stat.channel.center_freq;
907         aidl_channel_stat.channel.centerFreq0 = channel_stat.channel.center_freq0;
908         aidl_channel_stat.channel.centerFreq1 = channel_stat.channel.center_freq1;
909         aidl_channel_stats.push_back(aidl_channel_stat);
910     }
911 
912     aidl_radio_stat->channelStats = aidl_channel_stats;
913 
914     return true;
915 }
916 
convertLegacyMlLinkStateToAidl(wifi_link_state state)917 StaLinkLayerLinkStats::StaLinkState convertLegacyMlLinkStateToAidl(wifi_link_state state) {
918     if (state == wifi_link_state::WIFI_LINK_STATE_NOT_IN_USE) {
919         return StaLinkLayerLinkStats::StaLinkState::NOT_IN_USE;
920     } else if (state == wifi_link_state::WIFI_LINK_STATE_IN_USE) {
921         return StaLinkLayerLinkStats::StaLinkState::IN_USE;
922     }
923     return StaLinkLayerLinkStats::StaLinkState::UNKNOWN;
924 }
925 
convertLegacyLinkLayerMlStatsToAidl(const legacy_hal::LinkLayerMlStats & legacy_ml_stats,StaLinkLayerStats * aidl_stats)926 bool convertLegacyLinkLayerMlStatsToAidl(const legacy_hal::LinkLayerMlStats& legacy_ml_stats,
927                                          StaLinkLayerStats* aidl_stats) {
928     if (!aidl_stats) {
929         return false;
930     }
931     *aidl_stats = {};
932     std::vector<StaLinkLayerLinkStats> links;
933     // Iterate over each links
934     for (const auto& link : legacy_ml_stats.links) {
935         StaLinkLayerLinkStats linkStats = {};
936         linkStats.linkId = link.stat.link_id;
937         linkStats.state = convertLegacyMlLinkStateToAidl(link.stat.state);
938         linkStats.radioId = link.stat.radio;
939         linkStats.frequencyMhz = link.stat.frequency;
940         linkStats.beaconRx = link.stat.beacon_rx;
941         linkStats.avgRssiMgmt = link.stat.rssi_mgmt;
942         linkStats.wmeBePktStats.rxMpdu = link.stat.ac[legacy_hal::WIFI_AC_BE].rx_mpdu;
943         linkStats.wmeBePktStats.txMpdu = link.stat.ac[legacy_hal::WIFI_AC_BE].tx_mpdu;
944         linkStats.wmeBePktStats.lostMpdu = link.stat.ac[legacy_hal::WIFI_AC_BE].mpdu_lost;
945         linkStats.wmeBePktStats.retries = link.stat.ac[legacy_hal::WIFI_AC_BE].retries;
946         linkStats.wmeBeContentionTimeStats.contentionTimeMinInUsec =
947                 link.stat.ac[legacy_hal::WIFI_AC_BE].contention_time_min;
948         linkStats.wmeBeContentionTimeStats.contentionTimeMaxInUsec =
949                 link.stat.ac[legacy_hal::WIFI_AC_BE].contention_time_max;
950         linkStats.wmeBeContentionTimeStats.contentionTimeAvgInUsec =
951                 link.stat.ac[legacy_hal::WIFI_AC_BE].contention_time_avg;
952         linkStats.wmeBeContentionTimeStats.contentionNumSamples =
953                 link.stat.ac[legacy_hal::WIFI_AC_BE].contention_num_samples;
954         linkStats.wmeBkPktStats.rxMpdu = link.stat.ac[legacy_hal::WIFI_AC_BK].rx_mpdu;
955         linkStats.wmeBkPktStats.txMpdu = link.stat.ac[legacy_hal::WIFI_AC_BK].tx_mpdu;
956         linkStats.wmeBkPktStats.lostMpdu = link.stat.ac[legacy_hal::WIFI_AC_BK].mpdu_lost;
957         linkStats.wmeBkPktStats.retries = link.stat.ac[legacy_hal::WIFI_AC_BK].retries;
958         linkStats.wmeBkContentionTimeStats.contentionTimeMinInUsec =
959                 link.stat.ac[legacy_hal::WIFI_AC_BK].contention_time_min;
960         linkStats.wmeBkContentionTimeStats.contentionTimeMaxInUsec =
961                 link.stat.ac[legacy_hal::WIFI_AC_BK].contention_time_max;
962         linkStats.wmeBkContentionTimeStats.contentionTimeAvgInUsec =
963                 link.stat.ac[legacy_hal::WIFI_AC_BK].contention_time_avg;
964         linkStats.wmeBkContentionTimeStats.contentionNumSamples =
965                 link.stat.ac[legacy_hal::WIFI_AC_BK].contention_num_samples;
966         linkStats.wmeViPktStats.rxMpdu = link.stat.ac[legacy_hal::WIFI_AC_VI].rx_mpdu;
967         linkStats.wmeViPktStats.txMpdu = link.stat.ac[legacy_hal::WIFI_AC_VI].tx_mpdu;
968         linkStats.wmeViPktStats.lostMpdu = link.stat.ac[legacy_hal::WIFI_AC_VI].mpdu_lost;
969         linkStats.wmeViPktStats.retries = link.stat.ac[legacy_hal::WIFI_AC_VI].retries;
970         linkStats.wmeViContentionTimeStats.contentionTimeMinInUsec =
971                 link.stat.ac[legacy_hal::WIFI_AC_VI].contention_time_min;
972         linkStats.wmeViContentionTimeStats.contentionTimeMaxInUsec =
973                 link.stat.ac[legacy_hal::WIFI_AC_VI].contention_time_max;
974         linkStats.wmeViContentionTimeStats.contentionTimeAvgInUsec =
975                 link.stat.ac[legacy_hal::WIFI_AC_VI].contention_time_avg;
976         linkStats.wmeViContentionTimeStats.contentionNumSamples =
977                 link.stat.ac[legacy_hal::WIFI_AC_VI].contention_num_samples;
978         linkStats.wmeVoPktStats.rxMpdu = link.stat.ac[legacy_hal::WIFI_AC_VO].rx_mpdu;
979         linkStats.wmeVoPktStats.txMpdu = link.stat.ac[legacy_hal::WIFI_AC_VO].tx_mpdu;
980         linkStats.wmeVoPktStats.lostMpdu = link.stat.ac[legacy_hal::WIFI_AC_VO].mpdu_lost;
981         linkStats.wmeVoPktStats.retries = link.stat.ac[legacy_hal::WIFI_AC_VO].retries;
982         linkStats.wmeVoContentionTimeStats.contentionTimeMinInUsec =
983                 link.stat.ac[legacy_hal::WIFI_AC_VO].contention_time_min;
984         linkStats.wmeVoContentionTimeStats.contentionTimeMaxInUsec =
985                 link.stat.ac[legacy_hal::WIFI_AC_VO].contention_time_max;
986         linkStats.wmeVoContentionTimeStats.contentionTimeAvgInUsec =
987                 link.stat.ac[legacy_hal::WIFI_AC_VO].contention_time_avg;
988         linkStats.wmeVoContentionTimeStats.contentionNumSamples =
989                 link.stat.ac[legacy_hal::WIFI_AC_VO].contention_num_samples;
990         linkStats.timeSliceDutyCycleInPercent = link.stat.time_slicing_duty_cycle_percent;
991         // peer info legacy_stats conversion.
992         std::vector<StaPeerInfo> aidl_peers_info_stats;
993         for (const auto& legacy_peer_info_stats : link.peers) {
994             StaPeerInfo aidl_peer_info_stats;
995             if (!convertLegacyPeerInfoStatsToAidl(legacy_peer_info_stats, &aidl_peer_info_stats)) {
996                 return false;
997             }
998             aidl_peers_info_stats.push_back(aidl_peer_info_stats);
999         }
1000         linkStats.peers = aidl_peers_info_stats;
1001         // Push link stats to aidl stats.
1002         links.push_back(linkStats);
1003     }
1004     aidl_stats->iface.links = links;
1005     // radio legacy_stats conversion.
1006     std::vector<StaLinkLayerRadioStats> aidl_radios_stats;
1007     for (const auto& legacy_radio_stats : legacy_ml_stats.radios) {
1008         StaLinkLayerRadioStats aidl_radio_stats;
1009         if (!convertLegacyLinkLayerRadioStatsToAidl(legacy_radio_stats, &aidl_radio_stats)) {
1010             return false;
1011         }
1012         aidl_radios_stats.push_back(aidl_radio_stats);
1013     }
1014     aidl_stats->radios = aidl_radios_stats;
1015     aidl_stats->timeStampInMs = ::android::uptimeMillis();
1016 
1017     return true;
1018 }
1019 
convertLegacyLinkLayerStatsToAidl(const legacy_hal::LinkLayerStats & legacy_stats,StaLinkLayerStats * aidl_stats)1020 bool convertLegacyLinkLayerStatsToAidl(const legacy_hal::LinkLayerStats& legacy_stats,
1021                                        StaLinkLayerStats* aidl_stats) {
1022     if (!aidl_stats) {
1023         return false;
1024     }
1025     *aidl_stats = {};
1026     std::vector<StaLinkLayerLinkStats> links;
1027     StaLinkLayerLinkStats linkStats = {};
1028     // iface legacy_stats conversion.
1029     linkStats.linkId = 0;
1030     linkStats.beaconRx = legacy_stats.iface.beacon_rx;
1031     linkStats.avgRssiMgmt = legacy_stats.iface.rssi_mgmt;
1032     linkStats.wmeBePktStats.rxMpdu = legacy_stats.iface.ac[legacy_hal::WIFI_AC_BE].rx_mpdu;
1033     linkStats.wmeBePktStats.txMpdu = legacy_stats.iface.ac[legacy_hal::WIFI_AC_BE].tx_mpdu;
1034     linkStats.wmeBePktStats.lostMpdu = legacy_stats.iface.ac[legacy_hal::WIFI_AC_BE].mpdu_lost;
1035     linkStats.wmeBePktStats.retries = legacy_stats.iface.ac[legacy_hal::WIFI_AC_BE].retries;
1036     linkStats.wmeBeContentionTimeStats.contentionTimeMinInUsec =
1037             legacy_stats.iface.ac[legacy_hal::WIFI_AC_BE].contention_time_min;
1038     linkStats.wmeBeContentionTimeStats.contentionTimeMaxInUsec =
1039             legacy_stats.iface.ac[legacy_hal::WIFI_AC_BE].contention_time_max;
1040     linkStats.wmeBeContentionTimeStats.contentionTimeAvgInUsec =
1041             legacy_stats.iface.ac[legacy_hal::WIFI_AC_BE].contention_time_avg;
1042     linkStats.wmeBeContentionTimeStats.contentionNumSamples =
1043             legacy_stats.iface.ac[legacy_hal::WIFI_AC_BE].contention_num_samples;
1044     linkStats.wmeBkPktStats.rxMpdu = legacy_stats.iface.ac[legacy_hal::WIFI_AC_BK].rx_mpdu;
1045     linkStats.wmeBkPktStats.txMpdu = legacy_stats.iface.ac[legacy_hal::WIFI_AC_BK].tx_mpdu;
1046     linkStats.wmeBkPktStats.lostMpdu = legacy_stats.iface.ac[legacy_hal::WIFI_AC_BK].mpdu_lost;
1047     linkStats.wmeBkPktStats.retries = legacy_stats.iface.ac[legacy_hal::WIFI_AC_BK].retries;
1048     linkStats.wmeBkContentionTimeStats.contentionTimeMinInUsec =
1049             legacy_stats.iface.ac[legacy_hal::WIFI_AC_BK].contention_time_min;
1050     linkStats.wmeBkContentionTimeStats.contentionTimeMaxInUsec =
1051             legacy_stats.iface.ac[legacy_hal::WIFI_AC_BK].contention_time_max;
1052     linkStats.wmeBkContentionTimeStats.contentionTimeAvgInUsec =
1053             legacy_stats.iface.ac[legacy_hal::WIFI_AC_BK].contention_time_avg;
1054     linkStats.wmeBkContentionTimeStats.contentionNumSamples =
1055             legacy_stats.iface.ac[legacy_hal::WIFI_AC_BK].contention_num_samples;
1056     linkStats.wmeViPktStats.rxMpdu = legacy_stats.iface.ac[legacy_hal::WIFI_AC_VI].rx_mpdu;
1057     linkStats.wmeViPktStats.txMpdu = legacy_stats.iface.ac[legacy_hal::WIFI_AC_VI].tx_mpdu;
1058     linkStats.wmeViPktStats.lostMpdu = legacy_stats.iface.ac[legacy_hal::WIFI_AC_VI].mpdu_lost;
1059     linkStats.wmeViPktStats.retries = legacy_stats.iface.ac[legacy_hal::WIFI_AC_VI].retries;
1060     linkStats.wmeViContentionTimeStats.contentionTimeMinInUsec =
1061             legacy_stats.iface.ac[legacy_hal::WIFI_AC_VI].contention_time_min;
1062     linkStats.wmeViContentionTimeStats.contentionTimeMaxInUsec =
1063             legacy_stats.iface.ac[legacy_hal::WIFI_AC_VI].contention_time_max;
1064     linkStats.wmeViContentionTimeStats.contentionTimeAvgInUsec =
1065             legacy_stats.iface.ac[legacy_hal::WIFI_AC_VI].contention_time_avg;
1066     linkStats.wmeViContentionTimeStats.contentionNumSamples =
1067             legacy_stats.iface.ac[legacy_hal::WIFI_AC_VI].contention_num_samples;
1068     linkStats.wmeVoPktStats.rxMpdu = legacy_stats.iface.ac[legacy_hal::WIFI_AC_VO].rx_mpdu;
1069     linkStats.wmeVoPktStats.txMpdu = legacy_stats.iface.ac[legacy_hal::WIFI_AC_VO].tx_mpdu;
1070     linkStats.wmeVoPktStats.lostMpdu = legacy_stats.iface.ac[legacy_hal::WIFI_AC_VO].mpdu_lost;
1071     linkStats.wmeVoPktStats.retries = legacy_stats.iface.ac[legacy_hal::WIFI_AC_VO].retries;
1072     linkStats.wmeVoContentionTimeStats.contentionTimeMinInUsec =
1073             legacy_stats.iface.ac[legacy_hal::WIFI_AC_VO].contention_time_min;
1074     linkStats.wmeVoContentionTimeStats.contentionTimeMaxInUsec =
1075             legacy_stats.iface.ac[legacy_hal::WIFI_AC_VO].contention_time_max;
1076     linkStats.wmeVoContentionTimeStats.contentionTimeAvgInUsec =
1077             legacy_stats.iface.ac[legacy_hal::WIFI_AC_VO].contention_time_avg;
1078     linkStats.wmeVoContentionTimeStats.contentionNumSamples =
1079             legacy_stats.iface.ac[legacy_hal::WIFI_AC_VO].contention_num_samples;
1080     linkStats.timeSliceDutyCycleInPercent = legacy_stats.iface.info.time_slicing_duty_cycle_percent;
1081     // peer info legacy_stats conversion.
1082     std::vector<StaPeerInfo> aidl_peers_info_stats;
1083     for (const auto& legacy_peer_info_stats : legacy_stats.peers) {
1084         StaPeerInfo aidl_peer_info_stats;
1085         if (!convertLegacyPeerInfoStatsToAidl(legacy_peer_info_stats, &aidl_peer_info_stats)) {
1086             return false;
1087         }
1088         aidl_peers_info_stats.push_back(aidl_peer_info_stats);
1089     }
1090     linkStats.peers = aidl_peers_info_stats;
1091     links.push_back(linkStats);
1092     aidl_stats->iface.links = links;
1093     // radio legacy_stats conversion.
1094     std::vector<StaLinkLayerRadioStats> aidl_radios_stats;
1095     for (const auto& legacy_radio_stats : legacy_stats.radios) {
1096         StaLinkLayerRadioStats aidl_radio_stats;
1097         if (!convertLegacyLinkLayerRadioStatsToAidl(legacy_radio_stats, &aidl_radio_stats)) {
1098             return false;
1099         }
1100         aidl_radios_stats.push_back(aidl_radio_stats);
1101     }
1102     aidl_stats->radios = aidl_radios_stats;
1103     aidl_stats->timeStampInMs = ::android::uptimeMillis();
1104     return true;
1105 }
1106 
1107 // TODO (b/324519882): Remove logs after validating the structure size.
logAidlLinkLayerStatsSize(StaLinkLayerStats & aidl_stats)1108 void logAidlLinkLayerStatsSize(StaLinkLayerStats& aidl_stats) {
1109     unsigned long expectedMaxRadios = 5;
1110     unsigned long expectedMaxLinks = 5;
1111     unsigned long expectedMaxChannelStats = 512;
1112     unsigned long expectedMaxPeers = 3;
1113     unsigned long expectedMaxRateStats = 1024;
1114 
1115     unsigned long maxChannelStats = 0, maxPeers = 0, maxRateStats = 0;
1116     for (size_t i = 0; i < aidl_stats.radios.size(); i++) {
1117         maxChannelStats =
1118                 std::max(maxChannelStats, (unsigned long)aidl_stats.radios[i].channelStats.size());
1119     }
1120     for (size_t i = 0; i < aidl_stats.iface.links.size(); i++) {
1121         maxPeers = std::max(maxPeers, (unsigned long)aidl_stats.iface.links[i].peers.size());
1122         for (size_t j = 0; j < aidl_stats.iface.links[i].peers.size(); j++) {
1123             maxRateStats =
1124                     std::max(maxRateStats,
1125                              (unsigned long)aidl_stats.iface.links[i].peers[j].rateStats.size());
1126         }
1127     }
1128 
1129     if (aidl_stats.radios.size() > expectedMaxRadios ||
1130         aidl_stats.iface.links.size() > expectedMaxLinks ||
1131         maxChannelStats > expectedMaxChannelStats || maxPeers > expectedMaxPeers ||
1132         maxRateStats > expectedMaxRateStats) {
1133         LOG(INFO) << "StaLinkLayerStats exceeds expected vector size";
1134         LOG(INFO) << "  numRadios: " << aidl_stats.radios.size();
1135         LOG(INFO) << "  numLinks: " << aidl_stats.iface.links.size();
1136         LOG(INFO) << "  maxChannelStats: " << maxChannelStats;
1137         LOG(INFO) << "  maxPeers: " << maxPeers;
1138         LOG(INFO) << "  maxRateStats: " << maxRateStats;
1139     }
1140 }
1141 
convertLegacyPeerInfoStatsToAidl(const legacy_hal::WifiPeerInfo & legacy_peer_info_stats,StaPeerInfo * aidl_peer_info_stats)1142 bool convertLegacyPeerInfoStatsToAidl(const legacy_hal::WifiPeerInfo& legacy_peer_info_stats,
1143                                       StaPeerInfo* aidl_peer_info_stats) {
1144     if (!aidl_peer_info_stats) {
1145         return false;
1146     }
1147     *aidl_peer_info_stats = {};
1148     aidl_peer_info_stats->staCount = legacy_peer_info_stats.peer_info.bssload.sta_count;
1149     aidl_peer_info_stats->chanUtil = legacy_peer_info_stats.peer_info.bssload.chan_util;
1150 
1151     std::vector<StaRateStat> aidlRateStats;
1152     for (const auto& legacy_rate_stats : legacy_peer_info_stats.rate_stats) {
1153         StaRateStat rateStat;
1154         if (!convertLegacyWifiRateInfoToAidl(legacy_rate_stats.rate, &rateStat.rateInfo)) {
1155             return false;
1156         }
1157         rateStat.txMpdu = legacy_rate_stats.tx_mpdu;
1158         rateStat.rxMpdu = legacy_rate_stats.rx_mpdu;
1159         rateStat.mpduLost = legacy_rate_stats.mpdu_lost;
1160         rateStat.retries = legacy_rate_stats.retries;
1161         aidlRateStats.push_back(rateStat);
1162     }
1163     aidl_peer_info_stats->rateStats = aidlRateStats;
1164     return true;
1165 }
1166 
convertLegacyRoamingCapabilitiesToAidl(const legacy_hal::wifi_roaming_capabilities & legacy_caps,StaRoamingCapabilities * aidl_caps)1167 bool convertLegacyRoamingCapabilitiesToAidl(
1168         const legacy_hal::wifi_roaming_capabilities& legacy_caps,
1169         StaRoamingCapabilities* aidl_caps) {
1170     if (!aidl_caps) {
1171         return false;
1172     }
1173     *aidl_caps = {};
1174     aidl_caps->maxBlocklistSize = legacy_caps.max_blacklist_size;
1175     aidl_caps->maxAllowlistSize = legacy_caps.max_whitelist_size;
1176     return true;
1177 }
1178 
convertAidlRoamingConfigToLegacy(const StaRoamingConfig & aidl_config,legacy_hal::wifi_roaming_config * legacy_config)1179 bool convertAidlRoamingConfigToLegacy(const StaRoamingConfig& aidl_config,
1180                                       legacy_hal::wifi_roaming_config* legacy_config) {
1181     if (!legacy_config) {
1182         return false;
1183     }
1184     *legacy_config = {};
1185     if (aidl_config.bssidBlocklist.size() > MAX_BLACKLIST_BSSID ||
1186         aidl_config.ssidAllowlist.size() > MAX_WHITELIST_SSID) {
1187         return false;
1188     }
1189     legacy_config->num_blacklist_bssid = aidl_config.bssidBlocklist.size();
1190     uint32_t i = 0;
1191     for (const auto& bssid : aidl_config.bssidBlocklist) {
1192         CHECK(bssid.data.size() == sizeof(legacy_hal::mac_addr));
1193         memcpy(legacy_config->blacklist_bssid[i++], bssid.data.data(), bssid.data.size());
1194     }
1195     legacy_config->num_whitelist_ssid = aidl_config.ssidAllowlist.size();
1196     i = 0;
1197     for (const auto& ssid : aidl_config.ssidAllowlist) {
1198         CHECK(ssid.data.size() <= sizeof(legacy_hal::ssid_t::ssid_str));
1199         legacy_config->whitelist_ssid[i].length = ssid.data.size();
1200         memcpy(legacy_config->whitelist_ssid[i].ssid_str, ssid.data.data(), ssid.data.size());
1201         i++;
1202     }
1203     return true;
1204 }
1205 
convertAidlRoamingStateToLegacy(StaRoamingState state)1206 legacy_hal::fw_roaming_state_t convertAidlRoamingStateToLegacy(StaRoamingState state) {
1207     switch (state) {
1208         case StaRoamingState::ENABLED:
1209             return legacy_hal::ROAMING_ENABLE;
1210         case StaRoamingState::DISABLED:
1211             return legacy_hal::ROAMING_DISABLE;
1212         case StaRoamingState::AGGRESSIVE:
1213             return legacy_hal::ROAMING_AGGRESSIVE;
1214     };
1215     CHECK(false);
1216 }
1217 
convertAidlNanMatchAlgToLegacy(NanMatchAlg type)1218 legacy_hal::NanMatchAlg convertAidlNanMatchAlgToLegacy(NanMatchAlg type) {
1219     switch (type) {
1220         case NanMatchAlg::MATCH_ONCE:
1221             return legacy_hal::NAN_MATCH_ALG_MATCH_ONCE;
1222         case NanMatchAlg::MATCH_CONTINUOUS:
1223             return legacy_hal::NAN_MATCH_ALG_MATCH_CONTINUOUS;
1224         case NanMatchAlg::MATCH_NEVER:
1225             return legacy_hal::NAN_MATCH_ALG_MATCH_NEVER;
1226     }
1227     CHECK(false);
1228 }
1229 
convertAidlNanPublishTypeToLegacy(NanPublishType type)1230 legacy_hal::NanPublishType convertAidlNanPublishTypeToLegacy(NanPublishType type) {
1231     switch (type) {
1232         case NanPublishType::UNSOLICITED:
1233             return legacy_hal::NAN_PUBLISH_TYPE_UNSOLICITED;
1234         case NanPublishType::SOLICITED:
1235             return legacy_hal::NAN_PUBLISH_TYPE_SOLICITED;
1236         case NanPublishType::UNSOLICITED_SOLICITED:
1237             return legacy_hal::NAN_PUBLISH_TYPE_UNSOLICITED_SOLICITED;
1238     }
1239     CHECK(false);
1240 }
1241 
convertAidlNanTxTypeToLegacy(NanTxType type)1242 legacy_hal::NanTxType convertAidlNanTxTypeToLegacy(NanTxType type) {
1243     switch (type) {
1244         case NanTxType::BROADCAST:
1245             return legacy_hal::NAN_TX_TYPE_BROADCAST;
1246         case NanTxType::UNICAST:
1247             return legacy_hal::NAN_TX_TYPE_UNICAST;
1248     }
1249     CHECK(false);
1250 }
1251 
convertAidlNanSubscribeTypeToLegacy(NanSubscribeType type)1252 legacy_hal::NanSubscribeType convertAidlNanSubscribeTypeToLegacy(NanSubscribeType type) {
1253     switch (type) {
1254         case NanSubscribeType::PASSIVE:
1255             return legacy_hal::NAN_SUBSCRIBE_TYPE_PASSIVE;
1256         case NanSubscribeType::ACTIVE:
1257             return legacy_hal::NAN_SUBSCRIBE_TYPE_ACTIVE;
1258     }
1259     CHECK(false);
1260 }
1261 
convertAidlNanSrfTypeToLegacy(NanSrfType type)1262 legacy_hal::NanSRFType convertAidlNanSrfTypeToLegacy(NanSrfType type) {
1263     switch (type) {
1264         case NanSrfType::BLOOM_FILTER:
1265             return legacy_hal::NAN_SRF_ATTR_BLOOM_FILTER;
1266         case NanSrfType::PARTIAL_MAC_ADDR:
1267             return legacy_hal::NAN_SRF_ATTR_PARTIAL_MAC_ADDR;
1268     }
1269     CHECK(false);
1270 }
1271 
convertAidlNanDataPathChannelCfgToLegacy(NanDataPathChannelCfg type)1272 legacy_hal::NanDataPathChannelCfg convertAidlNanDataPathChannelCfgToLegacy(
1273         NanDataPathChannelCfg type) {
1274     switch (type) {
1275         case NanDataPathChannelCfg::CHANNEL_NOT_REQUESTED:
1276             return legacy_hal::NAN_DP_CHANNEL_NOT_REQUESTED;
1277         case NanDataPathChannelCfg::REQUEST_CHANNEL_SETUP:
1278             return legacy_hal::NAN_DP_REQUEST_CHANNEL_SETUP;
1279         case NanDataPathChannelCfg::FORCE_CHANNEL_SETUP:
1280             return legacy_hal::NAN_DP_FORCE_CHANNEL_SETUP;
1281     }
1282     CHECK(false);
1283 }
1284 
convertAidlNanPairingRequestTypeToLegacy(NanPairingRequestType type)1285 legacy_hal::NanPairingRequestType convertAidlNanPairingRequestTypeToLegacy(
1286         NanPairingRequestType type) {
1287     switch (type) {
1288         case NanPairingRequestType::NAN_PAIRING_SETUP:
1289             return legacy_hal::NAN_PAIRING_SETUP;
1290         case NanPairingRequestType::NAN_PAIRING_VERIFICATION:
1291             return legacy_hal::NAN_PAIRING_VERIFICATION;
1292     }
1293     LOG(FATAL);
1294 }
1295 
convertLegacyNanPairingRequestTypeToAidl(legacy_hal::NanPairingRequestType type)1296 NanPairingRequestType convertLegacyNanPairingRequestTypeToAidl(
1297         legacy_hal::NanPairingRequestType type) {
1298     switch (type) {
1299         case legacy_hal::NAN_PAIRING_SETUP:
1300             return NanPairingRequestType::NAN_PAIRING_SETUP;
1301         case legacy_hal::NAN_PAIRING_VERIFICATION:
1302             return NanPairingRequestType::NAN_PAIRING_VERIFICATION;
1303     }
1304     LOG(FATAL);
1305 }
1306 
convertAidlAkmTypeToLegacy(NanPairingAkm type)1307 legacy_hal::NanAkm convertAidlAkmTypeToLegacy(NanPairingAkm type) {
1308     switch (type) {
1309         case NanPairingAkm::SAE:
1310             return legacy_hal::SAE;
1311         case NanPairingAkm::PASN:
1312             return legacy_hal::PASN;
1313     }
1314     LOG(FATAL);
1315 }
1316 
convertLegacyAkmTypeToAidl(legacy_hal::NanAkm type)1317 NanPairingAkm convertLegacyAkmTypeToAidl(legacy_hal::NanAkm type) {
1318     switch (type) {
1319         case legacy_hal::SAE:
1320             return NanPairingAkm::SAE;
1321         case legacy_hal::PASN:
1322             return NanPairingAkm::PASN;
1323     }
1324     LOG(FATAL);
1325 }
1326 
convertAidlBootstrappingMethodToLegacy(NanBootstrappingMethod type)1327 uint16_t convertAidlBootstrappingMethodToLegacy(NanBootstrappingMethod type) {
1328     switch (type) {
1329         case NanBootstrappingMethod::BOOTSTRAPPING_OPPORTUNISTIC_MASK:
1330             return NAN_PAIRING_BOOTSTRAPPING_OPPORTUNISTIC_MASK;
1331         case NanBootstrappingMethod::BOOTSTRAPPING_PIN_CODE_DISPLAY_MASK:
1332             return NAN_PAIRING_BOOTSTRAPPING_PIN_CODE_DISPLAY_MASK;
1333         case NanBootstrappingMethod::BOOTSTRAPPING_PASSPHRASE_DISPLAY_MASK:
1334             return NAN_PAIRING_BOOTSTRAPPING_PASSPHRASE_DISPLAY_MASK;
1335         case NanBootstrappingMethod::BOOTSTRAPPING_QR_DISPLAY_MASK:
1336             return NAN_PAIRING_BOOTSTRAPPING_QR_DISPLAY_MASK;
1337         case NanBootstrappingMethod::BOOTSTRAPPING_NFC_TAG_MASK:
1338             return NAN_PAIRING_BOOTSTRAPPING_NFC_TAG_MASK;
1339         case NanBootstrappingMethod::BOOTSTRAPPING_PIN_CODE_KEYPAD_MASK:
1340             return NAN_PAIRING_BOOTSTRAPPING_PIN_CODE_KEYPAD_MASK;
1341         case NanBootstrappingMethod::BOOTSTRAPPING_PASSPHRASE_KEYPAD_MASK:
1342             return NAN_PAIRING_BOOTSTRAPPING_PASSPHRASE_KEYPAD_MASK;
1343         case NanBootstrappingMethod::BOOTSTRAPPING_QR_SCAN_MASK:
1344             return NAN_PAIRING_BOOTSTRAPPING_QR_SCAN_MASK;
1345         case NanBootstrappingMethod::BOOTSTRAPPING_NFC_READER_MASK:
1346             return NAN_PAIRING_BOOTSTRAPPING_NFC_READER_MASK;
1347         case NanBootstrappingMethod::BOOTSTRAPPING_SERVICE_MANAGED_MASK:
1348             return NAN_PAIRING_BOOTSTRAPPING_SERVICE_MANAGED_MASK;
1349         case NanBootstrappingMethod::BOOTSTRAPPING_HANDSHAKE_SHIP_MASK:
1350             return NAN_PAIRING_BOOTSTRAPPING_HANDSHAKE_SHIP_MASK;
1351     }
1352     LOG(FATAL);
1353 }
1354 
convertLegacyBootstrappingMethodToAidl(uint16_t type)1355 NanBootstrappingMethod convertLegacyBootstrappingMethodToAidl(uint16_t type) {
1356     switch (type) {
1357         case NAN_PAIRING_BOOTSTRAPPING_OPPORTUNISTIC_MASK:
1358             return NanBootstrappingMethod::BOOTSTRAPPING_OPPORTUNISTIC_MASK;
1359         case NAN_PAIRING_BOOTSTRAPPING_PIN_CODE_DISPLAY_MASK:
1360             return NanBootstrappingMethod::BOOTSTRAPPING_PIN_CODE_DISPLAY_MASK;
1361         case NAN_PAIRING_BOOTSTRAPPING_PASSPHRASE_DISPLAY_MASK:
1362             return NanBootstrappingMethod::BOOTSTRAPPING_PASSPHRASE_DISPLAY_MASK;
1363         case NAN_PAIRING_BOOTSTRAPPING_QR_DISPLAY_MASK:
1364             return NanBootstrappingMethod::BOOTSTRAPPING_QR_DISPLAY_MASK;
1365         case NAN_PAIRING_BOOTSTRAPPING_NFC_TAG_MASK:
1366             return NanBootstrappingMethod::BOOTSTRAPPING_NFC_TAG_MASK;
1367         case NAN_PAIRING_BOOTSTRAPPING_PIN_CODE_KEYPAD_MASK:
1368             return NanBootstrappingMethod::BOOTSTRAPPING_PIN_CODE_KEYPAD_MASK;
1369         case NAN_PAIRING_BOOTSTRAPPING_PASSPHRASE_KEYPAD_MASK:
1370             return NanBootstrappingMethod::BOOTSTRAPPING_PASSPHRASE_KEYPAD_MASK;
1371         case NAN_PAIRING_BOOTSTRAPPING_QR_SCAN_MASK:
1372             return NanBootstrappingMethod::BOOTSTRAPPING_QR_SCAN_MASK;
1373         case NAN_PAIRING_BOOTSTRAPPING_NFC_READER_MASK:
1374             return NanBootstrappingMethod::BOOTSTRAPPING_NFC_READER_MASK;
1375         case NAN_PAIRING_BOOTSTRAPPING_SERVICE_MANAGED_MASK:
1376             return NanBootstrappingMethod::BOOTSTRAPPING_SERVICE_MANAGED_MASK;
1377         case NAN_PAIRING_BOOTSTRAPPING_HANDSHAKE_SHIP_MASK:
1378             return NanBootstrappingMethod::BOOTSTRAPPING_HANDSHAKE_SHIP_MASK;
1379     }
1380     LOG(FATAL);
1381     return {};
1382 }
1383 
covertAidlPairingConfigToLegacy(const NanPairingConfig & aidl_config,legacy_hal::NanPairingConfig * legacy_config)1384 bool covertAidlPairingConfigToLegacy(const NanPairingConfig& aidl_config,
1385                                      legacy_hal::NanPairingConfig* legacy_config) {
1386     if (!legacy_config) {
1387         LOG(ERROR) << "covertAidlPairingConfigToLegacy: legacy_config is null";
1388         return false;
1389     }
1390     legacy_config->enable_pairing_setup = aidl_config.enablePairingSetup ? 0x1 : 0x0;
1391     legacy_config->enable_pairing_cache = aidl_config.enablePairingCache ? 0x1 : 0x0;
1392     legacy_config->enable_pairing_verification = aidl_config.enablePairingVerification ? 0x1 : 0x0;
1393     legacy_config->supported_bootstrapping_methods = aidl_config.supportedBootstrappingMethods;
1394     return true;
1395 }
1396 
convertLegacyPairingConfigToAidl(const legacy_hal::NanPairingConfig & legacy_config,NanPairingConfig * aidl_config)1397 bool convertLegacyPairingConfigToAidl(const legacy_hal::NanPairingConfig& legacy_config,
1398                                       NanPairingConfig* aidl_config) {
1399     if (!aidl_config) {
1400         LOG(ERROR) << "convertLegacyPairingConfigToAidl: aidl_nira is null";
1401         return false;
1402     }
1403     *aidl_config = {};
1404     aidl_config->enablePairingSetup = legacy_config.enable_pairing_setup == 0x1;
1405     aidl_config->enablePairingCache = legacy_config.enable_pairing_cache == 0x1;
1406     aidl_config->enablePairingVerification = legacy_config.enable_pairing_verification == 0x1;
1407     aidl_config->supportedBootstrappingMethods = legacy_config.supported_bootstrapping_methods;
1408     return true;
1409 }
1410 
convertLegacyNiraToAidl(const legacy_hal::NanIdentityResolutionAttribute & legacy_nira,NanIdentityResolutionAttribute * aidl_nira)1411 bool convertLegacyNiraToAidl(const legacy_hal::NanIdentityResolutionAttribute& legacy_nira,
1412                              NanIdentityResolutionAttribute* aidl_nira) {
1413     if (!aidl_nira) {
1414         LOG(ERROR) << "convertLegacyNiraToAidl: aidl_nira is null";
1415         return false;
1416     }
1417     *aidl_nira = {};
1418     aidl_nira->nonce = std::array<uint8_t, 8>();
1419     std::copy(legacy_nira.nonce, legacy_nira.nonce + 8, std::begin(aidl_nira->nonce));
1420     aidl_nira->tag = std::array<uint8_t, 8>();
1421     std::copy(legacy_nira.tag, legacy_nira.tag + 8, std::begin(aidl_nira->tag));
1422     return true;
1423 }
1424 
convertLegacyNpsaToAidl(const legacy_hal::NpkSecurityAssociation & legacy_npsa,NpkSecurityAssociation * aidl_npsa)1425 bool convertLegacyNpsaToAidl(const legacy_hal::NpkSecurityAssociation& legacy_npsa,
1426                              NpkSecurityAssociation* aidl_npsa) {
1427     if (!aidl_npsa) {
1428         LOG(ERROR) << "convertLegacyNiraToAidl: aidl_nira is null";
1429         return false;
1430     }
1431     *aidl_npsa = {};
1432     aidl_npsa->peerNanIdentityKey = std::array<uint8_t, 16>();
1433     std::copy(legacy_npsa.peer_nan_identity_key, legacy_npsa.peer_nan_identity_key + 16,
1434               std::begin(aidl_npsa->peerNanIdentityKey));
1435     aidl_npsa->localNanIdentityKey = std::array<uint8_t, 16>();
1436     std::copy(legacy_npsa.local_nan_identity_key, legacy_npsa.local_nan_identity_key + 16,
1437               std::begin(aidl_npsa->localNanIdentityKey));
1438     aidl_npsa->npk = std::array<uint8_t, 32>();
1439     std::copy(legacy_npsa.npk.pmk, legacy_npsa.npk.pmk + 32, std::begin(aidl_npsa->npk));
1440     aidl_npsa->akm = convertLegacyAkmTypeToAidl(legacy_npsa.akm);
1441     aidl_npsa->cipherType = (NanCipherSuiteType)legacy_npsa.cipher_type;
1442     return true;
1443 }
1444 
convertLegacyNanStatusTypeToAidl(legacy_hal::NanStatusType type)1445 NanStatusCode convertLegacyNanStatusTypeToAidl(legacy_hal::NanStatusType type) {
1446     switch (type) {
1447         case legacy_hal::NAN_STATUS_SUCCESS:
1448             return NanStatusCode::SUCCESS;
1449         case legacy_hal::NAN_STATUS_INTERNAL_FAILURE:
1450             return NanStatusCode::INTERNAL_FAILURE;
1451         case legacy_hal::NAN_STATUS_PROTOCOL_FAILURE:
1452             return NanStatusCode::PROTOCOL_FAILURE;
1453         case legacy_hal::NAN_STATUS_INVALID_PUBLISH_SUBSCRIBE_ID:
1454             return NanStatusCode::INVALID_SESSION_ID;
1455         case legacy_hal::NAN_STATUS_NO_RESOURCE_AVAILABLE:
1456             return NanStatusCode::NO_RESOURCES_AVAILABLE;
1457         case legacy_hal::NAN_STATUS_INVALID_PARAM:
1458             return NanStatusCode::INVALID_ARGS;
1459         case legacy_hal::NAN_STATUS_INVALID_REQUESTOR_INSTANCE_ID:
1460             return NanStatusCode::INVALID_PEER_ID;
1461         case legacy_hal::NAN_STATUS_INVALID_NDP_ID:
1462             return NanStatusCode::INVALID_NDP_ID;
1463         case legacy_hal::NAN_STATUS_NAN_NOT_ALLOWED:
1464             return NanStatusCode::NAN_NOT_ALLOWED;
1465         case legacy_hal::NAN_STATUS_NO_OTA_ACK:
1466             return NanStatusCode::NO_OTA_ACK;
1467         case legacy_hal::NAN_STATUS_ALREADY_ENABLED:
1468             return NanStatusCode::ALREADY_ENABLED;
1469         case legacy_hal::NAN_STATUS_FOLLOWUP_QUEUE_FULL:
1470             return NanStatusCode::FOLLOWUP_TX_QUEUE_FULL;
1471         case legacy_hal::NAN_STATUS_UNSUPPORTED_CONCURRENCY_NAN_DISABLED:
1472             return NanStatusCode::UNSUPPORTED_CONCURRENCY_NAN_DISABLED;
1473         case legacy_hal::NAN_STATUS_INVALID_PAIRING_ID:
1474             return NanStatusCode::INVALID_PAIRING_ID;
1475         case legacy_hal::NAN_STATUS_INVALID_BOOTSTRAPPING_ID:
1476             return NanStatusCode::INVALID_BOOTSTRAPPING_ID;
1477         case legacy_hal::NAN_STATUS_REDUNDANT_REQUEST:
1478             return NanStatusCode::REDUNDANT_REQUEST;
1479         case legacy_hal::NAN_STATUS_NOT_SUPPORTED:
1480             return NanStatusCode::NOT_SUPPORTED;
1481         case legacy_hal::NAN_STATUS_NO_CONNECTION:
1482             return NanStatusCode::NO_CONNECTION;
1483     }
1484     CHECK(false);
1485 }
1486 
convertToNanStatus(legacy_hal::NanStatusType type,const char * str,size_t max_len,NanStatus * nanStatus)1487 void convertToNanStatus(legacy_hal::NanStatusType type, const char* str, size_t max_len,
1488                         NanStatus* nanStatus) {
1489     nanStatus->status = convertLegacyNanStatusTypeToAidl(type);
1490     nanStatus->description = safeConvertChar(str, max_len);
1491 }
1492 
convertAidlNanEnableRequestToLegacy(const NanEnableRequest & aidl_request1,const NanConfigRequestSupplemental & aidl_request2,legacy_hal::NanEnableRequest * legacy_request)1493 bool convertAidlNanEnableRequestToLegacy(const NanEnableRequest& aidl_request1,
1494                                          const NanConfigRequestSupplemental& aidl_request2,
1495                                          legacy_hal::NanEnableRequest* legacy_request) {
1496     if (!legacy_request) {
1497         LOG(ERROR) << "convertAidlNanEnableRequestToLegacy: null legacy_request";
1498         return false;
1499     }
1500     *legacy_request = {};
1501 
1502     legacy_request->config_2dot4g_support = 1;
1503     legacy_request->support_2dot4g_val =
1504             aidl_request1.operateInBand[(size_t)NanBandIndex::NAN_BAND_24GHZ];
1505     legacy_request->config_support_5g = 1;
1506     legacy_request->support_5g_val =
1507             aidl_request1.operateInBand[(size_t)NanBandIndex::NAN_BAND_5GHZ];
1508     legacy_request->config_hop_count_limit = 1;
1509     legacy_request->hop_count_limit_val = aidl_request1.hopCountMax;
1510     legacy_request->master_pref = aidl_request1.configParams.masterPref;
1511     legacy_request->discovery_indication_cfg = 0;
1512     legacy_request->discovery_indication_cfg |=
1513             aidl_request1.configParams.disableDiscoveryAddressChangeIndication ? 0x1 : 0x0;
1514     legacy_request->discovery_indication_cfg |=
1515             aidl_request1.configParams.disableStartedClusterIndication ? 0x2 : 0x0;
1516     legacy_request->discovery_indication_cfg |=
1517             aidl_request1.configParams.disableJoinedClusterIndication ? 0x4 : 0x0;
1518     legacy_request->config_sid_beacon = 1;
1519     if (aidl_request1.configParams.numberOfPublishServiceIdsInBeacon < 0) {
1520         LOG(ERROR) << "convertAidlNanEnableRequestToLegacy: "
1521                       "numberOfPublishServiceIdsInBeacon < 0";
1522         return false;
1523     }
1524     legacy_request->sid_beacon_val =
1525             (aidl_request1.configParams.includePublishServiceIdsInBeacon ? 0x1 : 0x0) |
1526             (aidl_request1.configParams.numberOfPublishServiceIdsInBeacon << 1);
1527     legacy_request->config_subscribe_sid_beacon = 1;
1528     if (aidl_request1.configParams.numberOfSubscribeServiceIdsInBeacon < 0) {
1529         LOG(ERROR) << "convertAidlNanEnableRequestToLegacy: "
1530                       "numberOfSubscribeServiceIdsInBeacon < 0";
1531         return false;
1532     }
1533     legacy_request->subscribe_sid_beacon_val =
1534             (aidl_request1.configParams.includeSubscribeServiceIdsInBeacon ? 0x1 : 0x0) |
1535             (aidl_request1.configParams.numberOfSubscribeServiceIdsInBeacon << 1);
1536     legacy_request->config_rssi_window_size = 1;
1537     legacy_request->rssi_window_size_val = aidl_request1.configParams.rssiWindowSize;
1538     legacy_request->config_disc_mac_addr_randomization = 1;
1539     legacy_request->disc_mac_addr_rand_interval_sec =
1540             aidl_request1.configParams.macAddressRandomizationIntervalSec;
1541     legacy_request->config_2dot4g_rssi_close = 1;
1542     if (aidl_request1.configParams.bandSpecificConfig.size() != 3) {
1543         LOG(ERROR) << "convertAidlNanEnableRequestToLegacy: "
1544                       "bandSpecificConfig.size() != 3";
1545         return false;
1546     }
1547     legacy_request->rssi_close_2dot4g_val =
1548             aidl_request1.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
1549                     .rssiClose;
1550     legacy_request->config_2dot4g_rssi_middle = 1;
1551     legacy_request->rssi_middle_2dot4g_val =
1552             aidl_request1.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
1553                     .rssiMiddle;
1554     legacy_request->config_2dot4g_rssi_proximity = 1;
1555     legacy_request->rssi_proximity_2dot4g_val =
1556             aidl_request1.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
1557                     .rssiCloseProximity;
1558     legacy_request->config_scan_params = 1;
1559     legacy_request->scan_params_val.dwell_time[legacy_hal::NAN_CHANNEL_24G_BAND] =
1560             aidl_request1.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
1561                     .dwellTimeMs;
1562     legacy_request->scan_params_val.scan_period[legacy_hal::NAN_CHANNEL_24G_BAND] =
1563             aidl_request1.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
1564                     .scanPeriodSec;
1565     legacy_request->config_dw.config_2dot4g_dw_band =
1566             aidl_request1.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
1567                     .validDiscoveryWindowIntervalVal;
1568     legacy_request->config_dw.dw_2dot4g_interval_val =
1569             aidl_request1.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
1570                     .discoveryWindowIntervalVal;
1571     legacy_request->config_5g_rssi_close = 1;
1572     legacy_request->rssi_close_5g_val =
1573             aidl_request1.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
1574                     .rssiClose;
1575     legacy_request->config_5g_rssi_middle = 1;
1576     legacy_request->rssi_middle_5g_val =
1577             aidl_request1.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
1578                     .rssiMiddle;
1579     legacy_request->config_5g_rssi_close_proximity = 1;
1580     legacy_request->rssi_close_proximity_5g_val =
1581             aidl_request1.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
1582                     .rssiCloseProximity;
1583     legacy_request->scan_params_val.dwell_time[legacy_hal::NAN_CHANNEL_5G_BAND_LOW] =
1584             aidl_request1.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
1585                     .dwellTimeMs;
1586     legacy_request->scan_params_val.scan_period[legacy_hal::NAN_CHANNEL_5G_BAND_LOW] =
1587             aidl_request1.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
1588                     .scanPeriodSec;
1589     legacy_request->scan_params_val.dwell_time[legacy_hal::NAN_CHANNEL_5G_BAND_HIGH] =
1590             aidl_request1.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
1591                     .dwellTimeMs;
1592     legacy_request->scan_params_val.scan_period[legacy_hal::NAN_CHANNEL_5G_BAND_HIGH] =
1593             aidl_request1.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
1594                     .scanPeriodSec;
1595     legacy_request->config_dw.config_5g_dw_band =
1596             aidl_request1.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
1597                     .validDiscoveryWindowIntervalVal;
1598     legacy_request->config_dw.dw_5g_interval_val =
1599             aidl_request1.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
1600                     .discoveryWindowIntervalVal;
1601     if (aidl_request1.debugConfigs.validClusterIdVals) {
1602         legacy_request->cluster_low = aidl_request1.debugConfigs.clusterIdBottomRangeVal;
1603         legacy_request->cluster_high = aidl_request1.debugConfigs.clusterIdTopRangeVal;
1604     } else {  // need 'else' since not configurable in legacy HAL
1605         legacy_request->cluster_low = 0x0000;
1606         legacy_request->cluster_high = 0xFFFF;
1607     }
1608     legacy_request->config_intf_addr = aidl_request1.debugConfigs.validIntfAddrVal;
1609     memcpy(legacy_request->intf_addr_val, aidl_request1.debugConfigs.intfAddrVal.data(), 6);
1610     legacy_request->config_oui = aidl_request1.debugConfigs.validOuiVal;
1611     legacy_request->oui_val = aidl_request1.debugConfigs.ouiVal;
1612     legacy_request->config_random_factor_force =
1613             aidl_request1.debugConfigs.validRandomFactorForceVal;
1614     legacy_request->random_factor_force_val = aidl_request1.debugConfigs.randomFactorForceVal;
1615     legacy_request->config_hop_count_force = aidl_request1.debugConfigs.validHopCountForceVal;
1616     legacy_request->hop_count_force_val = aidl_request1.debugConfigs.hopCountForceVal;
1617     legacy_request->config_24g_channel = aidl_request1.debugConfigs.validDiscoveryChannelVal;
1618     legacy_request->channel_24g_val =
1619             aidl_request1.debugConfigs.discoveryChannelMhzVal[(size_t)NanBandIndex::NAN_BAND_24GHZ];
1620     legacy_request->config_5g_channel = aidl_request1.debugConfigs.validDiscoveryChannelVal;
1621     legacy_request->channel_5g_val =
1622             aidl_request1.debugConfigs.discoveryChannelMhzVal[(size_t)NanBandIndex::NAN_BAND_5GHZ];
1623     legacy_request->config_2dot4g_beacons = aidl_request1.debugConfigs.validUseBeaconsInBandVal;
1624     legacy_request->beacon_2dot4g_val =
1625             aidl_request1.debugConfigs.useBeaconsInBandVal[(size_t)NanBandIndex::NAN_BAND_24GHZ];
1626     legacy_request->config_5g_beacons = aidl_request1.debugConfigs.validUseBeaconsInBandVal;
1627     legacy_request->beacon_5g_val =
1628             aidl_request1.debugConfigs.useBeaconsInBandVal[(size_t)NanBandIndex::NAN_BAND_5GHZ];
1629     legacy_request->config_2dot4g_sdf = aidl_request1.debugConfigs.validUseSdfInBandVal;
1630     legacy_request->sdf_2dot4g_val =
1631             aidl_request1.debugConfigs.useSdfInBandVal[(size_t)NanBandIndex::NAN_BAND_24GHZ];
1632     legacy_request->config_5g_sdf = aidl_request1.debugConfigs.validUseSdfInBandVal;
1633     legacy_request->sdf_5g_val =
1634             aidl_request1.debugConfigs.useSdfInBandVal[(size_t)NanBandIndex::NAN_BAND_5GHZ];
1635 
1636     legacy_request->config_discovery_beacon_int = 1;
1637     legacy_request->discovery_beacon_interval = aidl_request2.discoveryBeaconIntervalMs;
1638     legacy_request->config_nss = 1;
1639     legacy_request->nss = aidl_request2.numberOfSpatialStreamsInDiscovery;
1640     legacy_request->config_dw_early_termination = 1;
1641     legacy_request->enable_dw_termination = aidl_request2.enableDiscoveryWindowEarlyTermination;
1642     legacy_request->config_enable_ranging = 1;
1643     legacy_request->enable_ranging = aidl_request2.enableRanging;
1644 
1645     legacy_request->config_enable_instant_mode = 1;
1646     legacy_request->enable_instant_mode = aidl_request2.enableInstantCommunicationMode;
1647     legacy_request->config_instant_mode_channel = 1;
1648     legacy_request->instant_mode_channel = aidl_request2.instantModeChannel;
1649 
1650     return true;
1651 }
1652 
convertAidlNanConfigRequestToLegacy(const NanConfigRequest & aidl_request1,const NanConfigRequestSupplemental & aidl_request2,legacy_hal::NanConfigRequest * legacy_request)1653 bool convertAidlNanConfigRequestToLegacy(const NanConfigRequest& aidl_request1,
1654                                          const NanConfigRequestSupplemental& aidl_request2,
1655                                          legacy_hal::NanConfigRequest* legacy_request) {
1656     if (!legacy_request) {
1657         LOG(ERROR) << "convertAidlNanConfigRequestToLegacy: null legacy_request";
1658         return false;
1659     }
1660     *legacy_request = {};
1661 
1662     legacy_request->master_pref = aidl_request1.masterPref;
1663     legacy_request->discovery_indication_cfg = 0;
1664     legacy_request->discovery_indication_cfg |=
1665             aidl_request1.disableDiscoveryAddressChangeIndication ? 0x1 : 0x0;
1666     legacy_request->discovery_indication_cfg |=
1667             aidl_request1.disableStartedClusterIndication ? 0x2 : 0x0;
1668     legacy_request->discovery_indication_cfg |=
1669             aidl_request1.disableJoinedClusterIndication ? 0x4 : 0x0;
1670     legacy_request->config_sid_beacon = 1;
1671     if (aidl_request1.numberOfPublishServiceIdsInBeacon < 0) {
1672         LOG(ERROR) << "convertAidlNanConfigRequestToLegacy: "
1673                       "numberOfPublishServiceIdsInBeacon < 0";
1674         return false;
1675     }
1676     legacy_request->sid_beacon = (aidl_request1.includePublishServiceIdsInBeacon ? 0x1 : 0x0) |
1677                                  (aidl_request1.numberOfPublishServiceIdsInBeacon << 1);
1678     legacy_request->config_subscribe_sid_beacon = 1;
1679     if (aidl_request1.numberOfSubscribeServiceIdsInBeacon < 0) {
1680         LOG(ERROR) << "convertAidlNanConfigRequestToLegacy: "
1681                       "numberOfSubscribeServiceIdsInBeacon < 0";
1682         return false;
1683     }
1684     legacy_request->subscribe_sid_beacon_val =
1685             (aidl_request1.includeSubscribeServiceIdsInBeacon ? 0x1 : 0x0) |
1686             (aidl_request1.numberOfSubscribeServiceIdsInBeacon << 1);
1687     legacy_request->config_rssi_window_size = 1;
1688     legacy_request->rssi_window_size_val = aidl_request1.rssiWindowSize;
1689     legacy_request->config_disc_mac_addr_randomization = 1;
1690     legacy_request->disc_mac_addr_rand_interval_sec =
1691             aidl_request1.macAddressRandomizationIntervalSec;
1692 
1693     legacy_request->config_scan_params = 1;
1694     legacy_request->scan_params_val.dwell_time[legacy_hal::NAN_CHANNEL_24G_BAND] =
1695             aidl_request1.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ].dwellTimeMs;
1696     legacy_request->scan_params_val.scan_period[legacy_hal::NAN_CHANNEL_24G_BAND] =
1697             aidl_request1.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ].scanPeriodSec;
1698     legacy_request->config_dw.config_2dot4g_dw_band =
1699             aidl_request1.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
1700                     .validDiscoveryWindowIntervalVal;
1701     legacy_request->config_dw.dw_2dot4g_interval_val =
1702             aidl_request1.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
1703                     .discoveryWindowIntervalVal;
1704 
1705     legacy_request->config_5g_rssi_close_proximity = 1;
1706     legacy_request->rssi_close_proximity_5g_val =
1707             aidl_request1.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
1708                     .rssiCloseProximity;
1709     legacy_request->scan_params_val.dwell_time[legacy_hal::NAN_CHANNEL_5G_BAND_LOW] =
1710             aidl_request1.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ].dwellTimeMs;
1711     legacy_request->scan_params_val.scan_period[legacy_hal::NAN_CHANNEL_5G_BAND_LOW] =
1712             aidl_request1.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ].scanPeriodSec;
1713     legacy_request->scan_params_val.dwell_time[legacy_hal::NAN_CHANNEL_5G_BAND_HIGH] =
1714             aidl_request1.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ].dwellTimeMs;
1715     legacy_request->scan_params_val.scan_period[legacy_hal::NAN_CHANNEL_5G_BAND_HIGH] =
1716             aidl_request1.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ].scanPeriodSec;
1717     legacy_request->config_dw.config_5g_dw_band =
1718             aidl_request1.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
1719                     .validDiscoveryWindowIntervalVal;
1720     legacy_request->config_dw.dw_5g_interval_val =
1721             aidl_request1.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
1722                     .discoveryWindowIntervalVal;
1723 
1724     legacy_request->config_discovery_beacon_int = 1;
1725     legacy_request->discovery_beacon_interval = aidl_request2.discoveryBeaconIntervalMs;
1726     legacy_request->config_nss = 1;
1727     legacy_request->nss = aidl_request2.numberOfSpatialStreamsInDiscovery;
1728     legacy_request->config_dw_early_termination = 1;
1729     legacy_request->enable_dw_termination = aidl_request2.enableDiscoveryWindowEarlyTermination;
1730     legacy_request->config_enable_ranging = 1;
1731     legacy_request->enable_ranging = aidl_request2.enableRanging;
1732 
1733     legacy_request->config_enable_instant_mode = 1;
1734     legacy_request->enable_instant_mode = aidl_request2.enableInstantCommunicationMode;
1735     legacy_request->config_instant_mode_channel = 1;
1736     legacy_request->instant_mode_channel = aidl_request2.instantModeChannel;
1737     legacy_request->config_cluster_id = 1;
1738     legacy_request->cluster_id_val = aidl_request2.clusterId;
1739 
1740     return true;
1741 }
1742 
convertAidlNanPublishRequestToLegacy(const NanPublishRequest & aidl_request,legacy_hal::NanPublishRequest * legacy_request)1743 bool convertAidlNanPublishRequestToLegacy(const NanPublishRequest& aidl_request,
1744                                           legacy_hal::NanPublishRequest* legacy_request) {
1745     if (!legacy_request) {
1746         LOG(ERROR) << "convertAidlNanPublishRequestToLegacy: null legacy_request";
1747         return false;
1748     }
1749     *legacy_request = {};
1750 
1751     legacy_request->publish_id = static_cast<uint8_t>(aidl_request.baseConfigs.sessionId);
1752     legacy_request->ttl = aidl_request.baseConfigs.ttlSec;
1753     legacy_request->period = aidl_request.baseConfigs.discoveryWindowPeriod;
1754     legacy_request->publish_count = aidl_request.baseConfigs.discoveryCount;
1755     legacy_request->service_name_len = aidl_request.baseConfigs.serviceName.size();
1756     if (legacy_request->service_name_len > NAN_MAX_SERVICE_NAME_LEN) {
1757         LOG(ERROR) << "convertAidlNanPublishRequestToLegacy: service_name_len "
1758                       "too large";
1759         return false;
1760     }
1761     memcpy(legacy_request->service_name, aidl_request.baseConfigs.serviceName.data(),
1762            legacy_request->service_name_len);
1763     legacy_request->publish_match_indicator =
1764             convertAidlNanMatchAlgToLegacy(aidl_request.baseConfigs.discoveryMatchIndicator);
1765     legacy_request->service_specific_info_len = aidl_request.baseConfigs.serviceSpecificInfo.size();
1766     if (legacy_request->service_specific_info_len > NAN_MAX_SERVICE_SPECIFIC_INFO_LEN) {
1767         LOG(ERROR) << "convertAidlNanPublishRequestToLegacy: "
1768                       "service_specific_info_len too large";
1769         return false;
1770     }
1771     memcpy(legacy_request->service_specific_info,
1772            aidl_request.baseConfigs.serviceSpecificInfo.data(),
1773            legacy_request->service_specific_info_len);
1774     legacy_request->sdea_service_specific_info_len =
1775             aidl_request.baseConfigs.extendedServiceSpecificInfo.size();
1776     if (legacy_request->sdea_service_specific_info_len > NAN_MAX_SDEA_SERVICE_SPECIFIC_INFO_LEN) {
1777         LOG(ERROR) << "convertAidlNanPublishRequestToLegacy: "
1778                       "sdea_service_specific_info_len too large";
1779         return false;
1780     }
1781     memcpy(legacy_request->sdea_service_specific_info,
1782            aidl_request.baseConfigs.extendedServiceSpecificInfo.data(),
1783            legacy_request->sdea_service_specific_info_len);
1784     legacy_request->rx_match_filter_len = aidl_request.baseConfigs.rxMatchFilter.size();
1785     if (legacy_request->rx_match_filter_len > NAN_MAX_MATCH_FILTER_LEN) {
1786         LOG(ERROR) << "convertAidlNanPublishRequestToLegacy: "
1787                       "rx_match_filter_len too large";
1788         return false;
1789     }
1790     memcpy(legacy_request->rx_match_filter, aidl_request.baseConfigs.rxMatchFilter.data(),
1791            legacy_request->rx_match_filter_len);
1792     legacy_request->tx_match_filter_len = aidl_request.baseConfigs.txMatchFilter.size();
1793     if (legacy_request->tx_match_filter_len > NAN_MAX_MATCH_FILTER_LEN) {
1794         LOG(ERROR) << "convertAidlNanPublishRequestToLegacy: "
1795                       "tx_match_filter_len too large";
1796         return false;
1797     }
1798     memcpy(legacy_request->tx_match_filter, aidl_request.baseConfigs.txMatchFilter.data(),
1799            legacy_request->tx_match_filter_len);
1800     legacy_request->rssi_threshold_flag = aidl_request.baseConfigs.useRssiThreshold;
1801     legacy_request->recv_indication_cfg = 0;
1802     legacy_request->recv_indication_cfg |=
1803             aidl_request.baseConfigs.disableDiscoveryTerminationIndication ? 0x1 : 0x0;
1804     legacy_request->recv_indication_cfg |=
1805             aidl_request.baseConfigs.disableMatchExpirationIndication ? 0x2 : 0x0;
1806     legacy_request->recv_indication_cfg |=
1807             aidl_request.baseConfigs.disableFollowupReceivedIndication ? 0x4 : 0x0;
1808     legacy_request->recv_indication_cfg |= 0x8;
1809     legacy_request->cipher_type = (unsigned int)aidl_request.baseConfigs.securityConfig.cipherType;
1810 
1811     legacy_request->scid_len = aidl_request.baseConfigs.securityConfig.scid.size();
1812     if (legacy_request->scid_len > NAN_MAX_SCID_BUF_LEN) {
1813         LOG(ERROR) << "convertAidlNanPublishRequestToLegacy: scid_len too large";
1814         return false;
1815     }
1816     memcpy(legacy_request->scid, aidl_request.baseConfigs.securityConfig.scid.data(),
1817            legacy_request->scid_len);
1818 
1819     if (aidl_request.baseConfigs.securityConfig.securityType == NanDataPathSecurityType::PMK) {
1820         legacy_request->key_info.key_type = legacy_hal::NAN_SECURITY_KEY_INPUT_PMK;
1821         legacy_request->key_info.body.pmk_info.pmk_len =
1822                 aidl_request.baseConfigs.securityConfig.pmk.size();
1823         if (legacy_request->key_info.body.pmk_info.pmk_len != NAN_PMK_INFO_LEN) {
1824             LOG(ERROR) << "convertAidlNanPublishRequestToLegacy: invalid pmk_len";
1825             return false;
1826         }
1827         memcpy(legacy_request->key_info.body.pmk_info.pmk,
1828                aidl_request.baseConfigs.securityConfig.pmk.data(),
1829                legacy_request->key_info.body.pmk_info.pmk_len);
1830     }
1831     if (aidl_request.baseConfigs.securityConfig.securityType ==
1832         NanDataPathSecurityType::PASSPHRASE) {
1833         legacy_request->key_info.key_type = legacy_hal::NAN_SECURITY_KEY_INPUT_PASSPHRASE;
1834         legacy_request->key_info.body.passphrase_info.passphrase_len =
1835                 aidl_request.baseConfigs.securityConfig.passphrase.size();
1836         if (legacy_request->key_info.body.passphrase_info.passphrase_len <
1837             NAN_SECURITY_MIN_PASSPHRASE_LEN) {
1838             LOG(ERROR) << "convertAidlNanPublishRequestToLegacy: "
1839                           "passphrase_len too small";
1840             return false;
1841         }
1842         if (legacy_request->key_info.body.passphrase_info.passphrase_len >
1843             NAN_SECURITY_MAX_PASSPHRASE_LEN) {
1844             LOG(ERROR) << "convertAidlNanPublishRequestToLegacy: "
1845                           "passphrase_len too large";
1846             return false;
1847         }
1848         memcpy(legacy_request->key_info.body.passphrase_info.passphrase,
1849                aidl_request.baseConfigs.securityConfig.passphrase.data(),
1850                legacy_request->key_info.body.passphrase_info.passphrase_len);
1851     }
1852     legacy_request->sdea_params.security_cfg =
1853             (aidl_request.baseConfigs.securityConfig.securityType != NanDataPathSecurityType::OPEN)
1854                     ? legacy_hal::NAN_DP_CONFIG_SECURITY
1855                     : legacy_hal::NAN_DP_CONFIG_NO_SECURITY;
1856 
1857     legacy_request->sdea_params.ranging_state = aidl_request.baseConfigs.rangingRequired
1858                                                         ? legacy_hal::NAN_RANGING_ENABLE
1859                                                         : legacy_hal::NAN_RANGING_DISABLE;
1860     legacy_request->ranging_cfg.ranging_interval_msec = aidl_request.baseConfigs.rangingIntervalMs;
1861     legacy_request->ranging_cfg.config_ranging_indications =
1862             aidl_request.baseConfigs.configRangingIndications;
1863     legacy_request->ranging_cfg.distance_ingress_mm =
1864             aidl_request.baseConfigs.distanceIngressCm * 10;
1865     legacy_request->ranging_cfg.distance_egress_mm = aidl_request.baseConfigs.distanceEgressCm * 10;
1866     legacy_request->ranging_auto_response = aidl_request.baseConfigs.rangingRequired
1867                                                     ? legacy_hal::NAN_RANGING_AUTO_RESPONSE_ENABLE
1868                                                     : legacy_hal::NAN_RANGING_AUTO_RESPONSE_DISABLE;
1869     legacy_request->sdea_params.range_report = aidl_request.rangingResultsRequired
1870                                                        ? legacy_hal::NAN_ENABLE_RANGE_REPORT
1871                                                        : legacy_hal::NAN_DISABLE_RANGE_REPORT;
1872     legacy_request->publish_type = convertAidlNanPublishTypeToLegacy(aidl_request.publishType);
1873     legacy_request->tx_type = convertAidlNanTxTypeToLegacy(aidl_request.txType);
1874     legacy_request->service_responder_policy = aidl_request.autoAcceptDataPathRequests
1875                                                        ? legacy_hal::NAN_SERVICE_ACCEPT_POLICY_ALL
1876                                                        : legacy_hal::NAN_SERVICE_ACCEPT_POLICY_NONE;
1877     memcpy(legacy_request->nan_identity_key, aidl_request.identityKey.data(), NAN_IDENTITY_KEY_LEN);
1878     if (!covertAidlPairingConfigToLegacy(aidl_request.pairingConfig,
1879                                          &legacy_request->nan_pairing_config)) {
1880         LOG(ERROR) << "convertAidlNanPublishRequestToLegacy: invalid pairing config";
1881         return false;
1882     }
1883     legacy_request->enable_suspendability = aidl_request.baseConfigs.enableSessionSuspendability;
1884 
1885     return true;
1886 }
1887 
convertAidlNanSubscribeRequestToLegacy(const NanSubscribeRequest & aidl_request,legacy_hal::NanSubscribeRequest * legacy_request)1888 bool convertAidlNanSubscribeRequestToLegacy(const NanSubscribeRequest& aidl_request,
1889                                             legacy_hal::NanSubscribeRequest* legacy_request) {
1890     if (!legacy_request) {
1891         LOG(ERROR) << "convertAidlNanSubscribeRequestToLegacy: legacy_request is null";
1892         return false;
1893     }
1894     *legacy_request = {};
1895 
1896     legacy_request->subscribe_id = static_cast<uint8_t>(aidl_request.baseConfigs.sessionId);
1897     legacy_request->ttl = aidl_request.baseConfigs.ttlSec;
1898     legacy_request->period = aidl_request.baseConfigs.discoveryWindowPeriod;
1899     legacy_request->subscribe_count = aidl_request.baseConfigs.discoveryCount;
1900     legacy_request->service_name_len = aidl_request.baseConfigs.serviceName.size();
1901     if (legacy_request->service_name_len > NAN_MAX_SERVICE_NAME_LEN) {
1902         LOG(ERROR) << "convertAidlNanSubscribeRequestToLegacy: "
1903                       "service_name_len too large";
1904         return false;
1905     }
1906     memcpy(legacy_request->service_name, aidl_request.baseConfigs.serviceName.data(),
1907            legacy_request->service_name_len);
1908     legacy_request->subscribe_match_indicator =
1909             convertAidlNanMatchAlgToLegacy(aidl_request.baseConfigs.discoveryMatchIndicator);
1910     legacy_request->service_specific_info_len = aidl_request.baseConfigs.serviceSpecificInfo.size();
1911     if (legacy_request->service_specific_info_len > NAN_MAX_SERVICE_SPECIFIC_INFO_LEN) {
1912         LOG(ERROR) << "convertAidlNanSubscribeRequestToLegacy: "
1913                       "service_specific_info_len too large";
1914         return false;
1915     }
1916     memcpy(legacy_request->service_specific_info,
1917            aidl_request.baseConfigs.serviceSpecificInfo.data(),
1918            legacy_request->service_specific_info_len);
1919     legacy_request->sdea_service_specific_info_len =
1920             aidl_request.baseConfigs.extendedServiceSpecificInfo.size();
1921     if (legacy_request->sdea_service_specific_info_len > NAN_MAX_SDEA_SERVICE_SPECIFIC_INFO_LEN) {
1922         LOG(ERROR) << "convertAidlNanSubscribeRequestToLegacy: "
1923                       "sdea_service_specific_info_len too large";
1924         return false;
1925     }
1926     memcpy(legacy_request->sdea_service_specific_info,
1927            aidl_request.baseConfigs.extendedServiceSpecificInfo.data(),
1928            legacy_request->sdea_service_specific_info_len);
1929     legacy_request->rx_match_filter_len = aidl_request.baseConfigs.rxMatchFilter.size();
1930     if (legacy_request->rx_match_filter_len > NAN_MAX_MATCH_FILTER_LEN) {
1931         LOG(ERROR) << "convertAidlNanSubscribeRequestToLegacy: "
1932                       "rx_match_filter_len too large";
1933         return false;
1934     }
1935     memcpy(legacy_request->rx_match_filter, aidl_request.baseConfigs.rxMatchFilter.data(),
1936            legacy_request->rx_match_filter_len);
1937     legacy_request->tx_match_filter_len = aidl_request.baseConfigs.txMatchFilter.size();
1938     if (legacy_request->tx_match_filter_len > NAN_MAX_MATCH_FILTER_LEN) {
1939         LOG(ERROR) << "convertAidlNanSubscribeRequestToLegacy: "
1940                       "tx_match_filter_len too large";
1941         return false;
1942     }
1943     memcpy(legacy_request->tx_match_filter, aidl_request.baseConfigs.txMatchFilter.data(),
1944            legacy_request->tx_match_filter_len);
1945     legacy_request->rssi_threshold_flag = aidl_request.baseConfigs.useRssiThreshold;
1946     legacy_request->recv_indication_cfg = 0;
1947     legacy_request->recv_indication_cfg |=
1948             aidl_request.baseConfigs.disableDiscoveryTerminationIndication ? 0x1 : 0x0;
1949     legacy_request->recv_indication_cfg |=
1950             aidl_request.baseConfigs.disableMatchExpirationIndication ? 0x2 : 0x0;
1951     legacy_request->recv_indication_cfg |=
1952             aidl_request.baseConfigs.disableFollowupReceivedIndication ? 0x4 : 0x0;
1953     legacy_request->cipher_type = (unsigned int)aidl_request.baseConfigs.securityConfig.cipherType;
1954     if (aidl_request.baseConfigs.securityConfig.securityType == NanDataPathSecurityType::PMK) {
1955         legacy_request->key_info.key_type = legacy_hal::NAN_SECURITY_KEY_INPUT_PMK;
1956         legacy_request->key_info.body.pmk_info.pmk_len =
1957                 aidl_request.baseConfigs.securityConfig.pmk.size();
1958         if (legacy_request->key_info.body.pmk_info.pmk_len != NAN_PMK_INFO_LEN) {
1959             LOG(ERROR) << "convertAidlNanSubscribeRequestToLegacy: invalid pmk_len";
1960             return false;
1961         }
1962         memcpy(legacy_request->key_info.body.pmk_info.pmk,
1963                aidl_request.baseConfigs.securityConfig.pmk.data(),
1964                legacy_request->key_info.body.pmk_info.pmk_len);
1965     }
1966     if (aidl_request.baseConfigs.securityConfig.securityType ==
1967         NanDataPathSecurityType::PASSPHRASE) {
1968         legacy_request->key_info.key_type = legacy_hal::NAN_SECURITY_KEY_INPUT_PASSPHRASE;
1969         legacy_request->key_info.body.passphrase_info.passphrase_len =
1970                 aidl_request.baseConfigs.securityConfig.passphrase.size();
1971         if (legacy_request->key_info.body.passphrase_info.passphrase_len <
1972             NAN_SECURITY_MIN_PASSPHRASE_LEN) {
1973             LOG(ERROR) << "convertAidlNanSubscribeRequestToLegacy: "
1974                           "passphrase_len too small";
1975             return false;
1976         }
1977         if (legacy_request->key_info.body.passphrase_info.passphrase_len >
1978             NAN_SECURITY_MAX_PASSPHRASE_LEN) {
1979             LOG(ERROR) << "convertAidlNanSubscribeRequestToLegacy: "
1980                           "passphrase_len too large";
1981             return false;
1982         }
1983         memcpy(legacy_request->key_info.body.passphrase_info.passphrase,
1984                aidl_request.baseConfigs.securityConfig.passphrase.data(),
1985                legacy_request->key_info.body.passphrase_info.passphrase_len);
1986     }
1987     legacy_request->sdea_params.security_cfg =
1988             (aidl_request.baseConfigs.securityConfig.securityType != NanDataPathSecurityType::OPEN)
1989                     ? legacy_hal::NAN_DP_CONFIG_SECURITY
1990                     : legacy_hal::NAN_DP_CONFIG_NO_SECURITY;
1991     legacy_request->sdea_params.ranging_state = aidl_request.baseConfigs.rangingRequired
1992                                                         ? legacy_hal::NAN_RANGING_ENABLE
1993                                                         : legacy_hal::NAN_RANGING_DISABLE;
1994     legacy_request->ranging_cfg.ranging_interval_msec = aidl_request.baseConfigs.rangingIntervalMs;
1995     legacy_request->ranging_cfg.config_ranging_indications =
1996             aidl_request.baseConfigs.configRangingIndications;
1997     legacy_request->ranging_cfg.distance_ingress_mm =
1998             aidl_request.baseConfigs.distanceIngressCm * 10;
1999     legacy_request->ranging_cfg.distance_egress_mm = aidl_request.baseConfigs.distanceEgressCm * 10;
2000     legacy_request->ranging_cfg.rtt_burst_size = aidl_request.baseConfigs.rttBurstSize;
2001     legacy_request->ranging_cfg.preamble =
2002             convertAidlRttPreambleToLegacy(aidl_request.baseConfigs.preamble);
2003     if (aidl_request.baseConfigs.channelInfo.has_value()) {
2004         if (!convertAidlWifiChannelInfoToLegacy(aidl_request.baseConfigs.channelInfo.value(),
2005                                                 &legacy_request->ranging_cfg.channel_info)) {
2006             LOG(ERROR) << "convertAidlNanSubscribeRequestToLegacy: "
2007                           "Unable to convert aidl channel info to legacy";
2008             return false;
2009         }
2010     }
2011     legacy_request->ranging_auto_response = aidl_request.baseConfigs.rangingRequired
2012                                                     ? legacy_hal::NAN_RANGING_AUTO_RESPONSE_ENABLE
2013                                                     : legacy_hal::NAN_RANGING_AUTO_RESPONSE_DISABLE;
2014     legacy_request->sdea_params.range_report = legacy_hal::NAN_DISABLE_RANGE_REPORT;
2015     legacy_request->subscribe_type =
2016             convertAidlNanSubscribeTypeToLegacy(aidl_request.subscribeType);
2017     legacy_request->serviceResponseFilter = convertAidlNanSrfTypeToLegacy(aidl_request.srfType);
2018     legacy_request->serviceResponseInclude = aidl_request.srfRespondIfInAddressSet
2019                                                      ? legacy_hal::NAN_SRF_INCLUDE_RESPOND
2020                                                      : legacy_hal::NAN_SRF_INCLUDE_DO_NOT_RESPOND;
2021     legacy_request->useServiceResponseFilter =
2022             aidl_request.shouldUseSrf ? legacy_hal::NAN_USE_SRF : legacy_hal::NAN_DO_NOT_USE_SRF;
2023     legacy_request->ssiRequiredForMatchIndication =
2024             aidl_request.isSsiRequiredForMatch ? legacy_hal::NAN_SSI_REQUIRED_IN_MATCH_IND
2025                                                : legacy_hal::NAN_SSI_NOT_REQUIRED_IN_MATCH_IND;
2026     legacy_request->num_intf_addr_present = aidl_request.intfAddr.size();
2027     if (legacy_request->num_intf_addr_present > NAN_MAX_SUBSCRIBE_MAX_ADDRESS) {
2028         LOG(ERROR) << "convertAidlNanSubscribeRequestToLegacy: "
2029                       "num_intf_addr_present - too many";
2030         return false;
2031     }
2032     for (int i = 0; i < legacy_request->num_intf_addr_present; i++) {
2033         memcpy(legacy_request->intf_addr[i], aidl_request.intfAddr[i].data.data(), 6);
2034     }
2035     memcpy(legacy_request->nan_identity_key, aidl_request.identityKey.data(), NAN_IDENTITY_KEY_LEN);
2036     if (!covertAidlPairingConfigToLegacy(aidl_request.pairingConfig,
2037                                          &legacy_request->nan_pairing_config)) {
2038         LOG(ERROR) << "convertAidlNanSubscribeRequestToLegacy: invalid pairing config";
2039         return false;
2040     }
2041     legacy_request->enable_suspendability = aidl_request.baseConfigs.enableSessionSuspendability;
2042 
2043     return true;
2044 }
2045 
convertAidlNanTransmitFollowupRequestToLegacy(const NanTransmitFollowupRequest & aidl_request,legacy_hal::NanTransmitFollowupRequest * legacy_request)2046 bool convertAidlNanTransmitFollowupRequestToLegacy(
2047         const NanTransmitFollowupRequest& aidl_request,
2048         legacy_hal::NanTransmitFollowupRequest* legacy_request) {
2049     if (!legacy_request) {
2050         LOG(ERROR) << "convertAidlNanTransmitFollowupRequestToLegacy: "
2051                       "legacy_request is null";
2052         return false;
2053     }
2054     *legacy_request = {};
2055 
2056     legacy_request->publish_subscribe_id = static_cast<uint8_t>(aidl_request.discoverySessionId);
2057     legacy_request->requestor_instance_id = aidl_request.peerId;
2058     memcpy(legacy_request->addr, aidl_request.addr.data(), 6);
2059     legacy_request->priority = aidl_request.isHighPriority ? legacy_hal::NAN_TX_PRIORITY_HIGH
2060                                                            : legacy_hal::NAN_TX_PRIORITY_NORMAL;
2061     legacy_request->dw_or_faw = aidl_request.shouldUseDiscoveryWindow
2062                                         ? legacy_hal::NAN_TRANSMIT_IN_DW
2063                                         : legacy_hal::NAN_TRANSMIT_IN_FAW;
2064     legacy_request->service_specific_info_len = aidl_request.serviceSpecificInfo.size();
2065     if (legacy_request->service_specific_info_len > NAN_MAX_SERVICE_SPECIFIC_INFO_LEN) {
2066         LOG(ERROR) << "convertAidlNanTransmitFollowupRequestToLegacy: "
2067                       "service_specific_info_len too large";
2068         return false;
2069     }
2070     memcpy(legacy_request->service_specific_info, aidl_request.serviceSpecificInfo.data(),
2071            legacy_request->service_specific_info_len);
2072     legacy_request->sdea_service_specific_info_len =
2073             aidl_request.extendedServiceSpecificInfo.size();
2074     if (legacy_request->sdea_service_specific_info_len > NAN_MAX_SDEA_SERVICE_SPECIFIC_INFO_LEN) {
2075         LOG(ERROR) << "convertAidlNanTransmitFollowupRequestToLegacy: "
2076                       "sdea_service_specific_info_len too large";
2077         return false;
2078     }
2079     memcpy(legacy_request->sdea_service_specific_info,
2080            aidl_request.extendedServiceSpecificInfo.data(),
2081            legacy_request->sdea_service_specific_info_len);
2082     legacy_request->recv_indication_cfg = aidl_request.disableFollowupResultIndication ? 0x1 : 0x0;
2083 
2084     return true;
2085 }
2086 
convertAidlNanDataPathInitiatorRequestToLegacy(const NanInitiateDataPathRequest & aidl_request,legacy_hal::NanDataPathInitiatorRequest * legacy_request)2087 bool convertAidlNanDataPathInitiatorRequestToLegacy(
2088         const NanInitiateDataPathRequest& aidl_request,
2089         legacy_hal::NanDataPathInitiatorRequest* legacy_request) {
2090     if (!legacy_request) {
2091         LOG(ERROR) << "convertAidlNanDataPathInitiatorRequestToLegacy: "
2092                       "legacy_request is null";
2093         return false;
2094     }
2095     *legacy_request = {};
2096 
2097     legacy_request->requestor_instance_id = aidl_request.peerId;
2098     memcpy(legacy_request->peer_disc_mac_addr, aidl_request.peerDiscMacAddr.data(), 6);
2099     legacy_request->channel_request_type =
2100             convertAidlNanDataPathChannelCfgToLegacy(aidl_request.channelRequestType);
2101     legacy_request->channel = aidl_request.channel;
2102     if (strnlen(aidl_request.ifaceName.c_str(), IFNAMSIZ + 1) == IFNAMSIZ + 1) {
2103         LOG(ERROR) << "convertAidlNanDataPathInitiatorRequestToLegacy: "
2104                       "ifaceName too long";
2105         return false;
2106     }
2107     strlcpy(legacy_request->ndp_iface, aidl_request.ifaceName.c_str(), IFNAMSIZ + 1);
2108     legacy_request->ndp_cfg.security_cfg =
2109             (aidl_request.securityConfig.securityType != NanDataPathSecurityType::OPEN)
2110                     ? legacy_hal::NAN_DP_CONFIG_SECURITY
2111                     : legacy_hal::NAN_DP_CONFIG_NO_SECURITY;
2112     legacy_request->app_info.ndp_app_info_len = aidl_request.appInfo.size();
2113     if (legacy_request->app_info.ndp_app_info_len > NAN_DP_MAX_APP_INFO_LEN) {
2114         LOG(ERROR) << "convertAidlNanDataPathInitiatorRequestToLegacy: "
2115                       "ndp_app_info_len too large";
2116         return false;
2117     }
2118     memcpy(legacy_request->app_info.ndp_app_info, aidl_request.appInfo.data(),
2119            legacy_request->app_info.ndp_app_info_len);
2120     legacy_request->cipher_type = (unsigned int)aidl_request.securityConfig.cipherType;
2121     if (aidl_request.securityConfig.securityType == NanDataPathSecurityType::PMK) {
2122         legacy_request->key_info.key_type = legacy_hal::NAN_SECURITY_KEY_INPUT_PMK;
2123         legacy_request->key_info.body.pmk_info.pmk_len = aidl_request.securityConfig.pmk.size();
2124         if (legacy_request->key_info.body.pmk_info.pmk_len != NAN_PMK_INFO_LEN) {
2125             LOG(ERROR) << "convertAidlNanDataPathInitiatorRequestToLegacy: "
2126                           "invalid pmk_len";
2127             return false;
2128         }
2129         memcpy(legacy_request->key_info.body.pmk_info.pmk, aidl_request.securityConfig.pmk.data(),
2130                legacy_request->key_info.body.pmk_info.pmk_len);
2131     }
2132     if (aidl_request.securityConfig.securityType == NanDataPathSecurityType::PASSPHRASE) {
2133         legacy_request->key_info.key_type = legacy_hal::NAN_SECURITY_KEY_INPUT_PASSPHRASE;
2134         legacy_request->key_info.body.passphrase_info.passphrase_len =
2135                 aidl_request.securityConfig.passphrase.size();
2136         if (legacy_request->key_info.body.passphrase_info.passphrase_len <
2137             NAN_SECURITY_MIN_PASSPHRASE_LEN) {
2138             LOG(ERROR) << "convertAidlNanDataPathInitiatorRequestToLegacy: "
2139                           "passphrase_len too small";
2140             return false;
2141         }
2142         if (legacy_request->key_info.body.passphrase_info.passphrase_len >
2143             NAN_SECURITY_MAX_PASSPHRASE_LEN) {
2144             LOG(ERROR) << "convertAidlNanDataPathInitiatorRequestToLegacy: "
2145                           "passphrase_len too large";
2146             return false;
2147         }
2148         memcpy(legacy_request->key_info.body.passphrase_info.passphrase,
2149                aidl_request.securityConfig.passphrase.data(),
2150                legacy_request->key_info.body.passphrase_info.passphrase_len);
2151     }
2152     legacy_request->service_name_len = aidl_request.serviceNameOutOfBand.size();
2153     if (legacy_request->service_name_len > NAN_MAX_SERVICE_NAME_LEN) {
2154         LOG(ERROR) << "convertAidlNanDataPathInitiatorRequestToLegacy: "
2155                       "service_name_len too large";
2156         return false;
2157     }
2158     memcpy(legacy_request->service_name, aidl_request.serviceNameOutOfBand.data(),
2159            legacy_request->service_name_len);
2160     legacy_request->scid_len = aidl_request.securityConfig.scid.size();
2161     if (legacy_request->scid_len > NAN_MAX_SCID_BUF_LEN) {
2162         LOG(ERROR) << "convertAidlNanDataPathInitiatorRequestToLegacy: scid_len too large";
2163         return false;
2164     }
2165     memcpy(legacy_request->scid, aidl_request.securityConfig.scid.data(), legacy_request->scid_len);
2166     legacy_request->publish_subscribe_id = static_cast<uint8_t>(aidl_request.discoverySessionId);
2167 
2168     legacy_request->csia_capabilities |=
2169             aidl_request.securityConfig.enable16ReplyCountersForTksa ? 0x1 : 0x0;
2170     legacy_request->csia_capabilities |=
2171             aidl_request.securityConfig.enable16ReplyCountersForGtksa ? 0x8 : 0x0;
2172     if (aidl_request.securityConfig.supportGtkAndIgtk) {
2173         legacy_request->csia_capabilities |= aidl_request.securityConfig.supportBigtksa ? 0x4 : 0x2;
2174     }
2175     legacy_request->csia_capabilities |= aidl_request.securityConfig.enableNcsBip256 ? 0x16 : 0x0;
2176     legacy_request->gtk_protection =
2177             aidl_request.securityConfig.requiresEnhancedFrameProtection ? 1 : 0;
2178 
2179     return true;
2180 }
2181 
convertAidlNanDataPathIndicationResponseToLegacy(const NanRespondToDataPathIndicationRequest & aidl_request,legacy_hal::NanDataPathIndicationResponse * legacy_request)2182 bool convertAidlNanDataPathIndicationResponseToLegacy(
2183         const NanRespondToDataPathIndicationRequest& aidl_request,
2184         legacy_hal::NanDataPathIndicationResponse* legacy_request) {
2185     if (!legacy_request) {
2186         LOG(ERROR) << "convertAidlNanDataPathIndicationResponseToLegacy: "
2187                       "legacy_request is null";
2188         return false;
2189     }
2190     *legacy_request = {};
2191 
2192     legacy_request->rsp_code = aidl_request.acceptRequest ? legacy_hal::NAN_DP_REQUEST_ACCEPT
2193                                                           : legacy_hal::NAN_DP_REQUEST_REJECT;
2194     legacy_request->ndp_instance_id = aidl_request.ndpInstanceId;
2195     if (strnlen(aidl_request.ifaceName.c_str(), IFNAMSIZ + 1) == IFNAMSIZ + 1) {
2196         LOG(ERROR) << "convertAidlNanDataPathIndicationResponseToLegacy: "
2197                       "ifaceName too long";
2198         return false;
2199     }
2200     strlcpy(legacy_request->ndp_iface, aidl_request.ifaceName.c_str(), IFNAMSIZ + 1);
2201     legacy_request->ndp_cfg.security_cfg =
2202             (aidl_request.securityConfig.securityType != NanDataPathSecurityType::OPEN)
2203                     ? legacy_hal::NAN_DP_CONFIG_SECURITY
2204                     : legacy_hal::NAN_DP_CONFIG_NO_SECURITY;
2205     legacy_request->app_info.ndp_app_info_len = aidl_request.appInfo.size();
2206     if (legacy_request->app_info.ndp_app_info_len > NAN_DP_MAX_APP_INFO_LEN) {
2207         LOG(ERROR) << "convertAidlNanDataPathIndicationResponseToLegacy: "
2208                       "ndp_app_info_len too large";
2209         return false;
2210     }
2211     memcpy(legacy_request->app_info.ndp_app_info, aidl_request.appInfo.data(),
2212            legacy_request->app_info.ndp_app_info_len);
2213     legacy_request->cipher_type = (unsigned int)aidl_request.securityConfig.cipherType;
2214     if (aidl_request.securityConfig.securityType == NanDataPathSecurityType::PMK) {
2215         legacy_request->key_info.key_type = legacy_hal::NAN_SECURITY_KEY_INPUT_PMK;
2216         legacy_request->key_info.body.pmk_info.pmk_len = aidl_request.securityConfig.pmk.size();
2217         if (legacy_request->key_info.body.pmk_info.pmk_len != NAN_PMK_INFO_LEN) {
2218             LOG(ERROR) << "convertAidlNanDataPathIndicationResponseToLegacy: "
2219                           "invalid pmk_len";
2220             return false;
2221         }
2222         memcpy(legacy_request->key_info.body.pmk_info.pmk, aidl_request.securityConfig.pmk.data(),
2223                legacy_request->key_info.body.pmk_info.pmk_len);
2224     }
2225     if (aidl_request.securityConfig.securityType == NanDataPathSecurityType::PASSPHRASE) {
2226         legacy_request->key_info.key_type = legacy_hal::NAN_SECURITY_KEY_INPUT_PASSPHRASE;
2227         legacy_request->key_info.body.passphrase_info.passphrase_len =
2228                 aidl_request.securityConfig.passphrase.size();
2229         if (legacy_request->key_info.body.passphrase_info.passphrase_len <
2230             NAN_SECURITY_MIN_PASSPHRASE_LEN) {
2231             LOG(ERROR) << "convertAidlNanDataPathIndicationResponseToLegacy: "
2232                           "passphrase_len too small";
2233             return false;
2234         }
2235         if (legacy_request->key_info.body.passphrase_info.passphrase_len >
2236             NAN_SECURITY_MAX_PASSPHRASE_LEN) {
2237             LOG(ERROR) << "convertAidlNanDataPathIndicationResponseToLegacy: "
2238                           "passphrase_len too large";
2239             return false;
2240         }
2241         memcpy(legacy_request->key_info.body.passphrase_info.passphrase,
2242                aidl_request.securityConfig.passphrase.data(),
2243                legacy_request->key_info.body.passphrase_info.passphrase_len);
2244     }
2245     legacy_request->service_name_len = aidl_request.serviceNameOutOfBand.size();
2246     if (legacy_request->service_name_len > NAN_MAX_SERVICE_NAME_LEN) {
2247         LOG(ERROR) << "convertAidlNanDataPathIndicationResponseToLegacy: "
2248                       "service_name_len too large";
2249         return false;
2250     }
2251     memcpy(legacy_request->service_name, aidl_request.serviceNameOutOfBand.data(),
2252            legacy_request->service_name_len);
2253     legacy_request->scid_len = aidl_request.securityConfig.scid.size();
2254     if (legacy_request->scid_len > NAN_MAX_SCID_BUF_LEN) {
2255         LOG(ERROR) << "convertAidlNanDataPathIndicationResponseToLegacy: scid_len too large";
2256         return false;
2257     }
2258     memcpy(legacy_request->scid, aidl_request.securityConfig.scid.data(), legacy_request->scid_len);
2259     legacy_request->publish_subscribe_id = static_cast<uint8_t>(aidl_request.discoverySessionId);
2260 
2261     legacy_request->csia_capabilities |=
2262             aidl_request.securityConfig.enable16ReplyCountersForTksa ? 0x1 : 0x0;
2263     legacy_request->csia_capabilities |=
2264             aidl_request.securityConfig.enable16ReplyCountersForGtksa ? 0x8 : 0x0;
2265     if (aidl_request.securityConfig.supportGtkAndIgtk) {
2266         legacy_request->csia_capabilities |= aidl_request.securityConfig.supportBigtksa ? 0x4 : 0x2;
2267     }
2268     legacy_request->csia_capabilities |= aidl_request.securityConfig.enableNcsBip256 ? 0x16 : 0x0;
2269     legacy_request->gtk_protection =
2270             aidl_request.securityConfig.requiresEnhancedFrameProtection ? 1 : 0;
2271 
2272     return true;
2273 }
2274 
convertLegacyNanResponseHeaderToAidl(const legacy_hal::NanResponseMsg & legacy_response,NanStatus * nanStatus)2275 bool convertLegacyNanResponseHeaderToAidl(const legacy_hal::NanResponseMsg& legacy_response,
2276                                           NanStatus* nanStatus) {
2277     if (!nanStatus) {
2278         LOG(ERROR) << "convertLegacyNanResponseHeaderToAidl: nanStatus is null";
2279         return false;
2280     }
2281     *nanStatus = {};
2282 
2283     convertToNanStatus(legacy_response.status, legacy_response.nan_error,
2284                        sizeof(legacy_response.nan_error), nanStatus);
2285     return true;
2286 }
2287 
convertLegacyNanCapabilitiesResponseToAidl(const legacy_hal::NanCapabilities & legacy_response,NanCapabilities * aidl_response)2288 bool convertLegacyNanCapabilitiesResponseToAidl(const legacy_hal::NanCapabilities& legacy_response,
2289                                                 NanCapabilities* aidl_response) {
2290     if (!aidl_response) {
2291         LOG(ERROR) << "convertLegacyNanCapabilitiesResponseToAidl: "
2292                       "aidl_response is null";
2293         return false;
2294     }
2295     *aidl_response = {};
2296 
2297     aidl_response->maxConcurrentClusters = legacy_response.max_concurrent_nan_clusters;
2298     aidl_response->maxPublishes = legacy_response.max_publishes;
2299     aidl_response->maxSubscribes = legacy_response.max_subscribes;
2300     aidl_response->maxServiceNameLen = legacy_response.max_service_name_len;
2301     aidl_response->maxMatchFilterLen = legacy_response.max_match_filter_len;
2302     aidl_response->maxTotalMatchFilterLen = legacy_response.max_total_match_filter_len;
2303     aidl_response->maxServiceSpecificInfoLen = legacy_response.max_service_specific_info_len;
2304     aidl_response->maxExtendedServiceSpecificInfoLen =
2305             legacy_response.max_sdea_service_specific_info_len;
2306     aidl_response->maxNdiInterfaces = legacy_response.max_ndi_interfaces;
2307     aidl_response->maxNdpSessions = legacy_response.max_ndp_sessions;
2308     aidl_response->maxAppInfoLen = legacy_response.max_app_info_len;
2309     aidl_response->maxQueuedTransmitFollowupMsgs =
2310             legacy_response.max_queued_transmit_followup_msgs;
2311     aidl_response->maxSubscribeInterfaceAddresses = legacy_response.max_subscribe_address;
2312     aidl_response->supportedCipherSuites = legacy_response.cipher_suites_supported;
2313     aidl_response->instantCommunicationModeSupportFlag = legacy_response.is_instant_mode_supported;
2314     aidl_response->supports6g = legacy_response.is_6g_supported;
2315     aidl_response->supportsHe = legacy_response.is_he_supported;
2316     aidl_response->supportsPairing = legacy_response.is_pairing_supported;
2317     aidl_response->supportsSetClusterId = legacy_response.is_set_cluster_id_supported;
2318     aidl_response->supportsSuspension = legacy_response.is_suspension_supported;
2319     aidl_response->supportsPeriodicRanging = legacy_response.is_periodic_ranging_supported;
2320     aidl_response->maxSupportedBandwidth = convertLegacyRttBwToAidl(legacy_response.supported_bw);
2321     aidl_response->maxNumRxChainsSupported = legacy_response.num_rx_chains_supported;
2322 
2323     return true;
2324 }
2325 
convertLegacyNanMatchIndToAidl(const legacy_hal::NanMatchInd & legacy_ind,NanMatchInd * aidl_ind)2326 bool convertLegacyNanMatchIndToAidl(const legacy_hal::NanMatchInd& legacy_ind,
2327                                     NanMatchInd* aidl_ind) {
2328     if (!aidl_ind) {
2329         LOG(ERROR) << "convertLegacyNanMatchIndToAidl: aidl_ind is null";
2330         return false;
2331     }
2332     *aidl_ind = {};
2333 
2334     aidl_ind->discoverySessionId = legacy_ind.publish_subscribe_id;
2335     aidl_ind->peerId = legacy_ind.requestor_instance_id;
2336     aidl_ind->addr = std::array<uint8_t, 6>();
2337     std::copy(legacy_ind.addr, legacy_ind.addr + 6, std::begin(aidl_ind->addr));
2338     aidl_ind->serviceSpecificInfo = std::vector<uint8_t>(
2339             legacy_ind.service_specific_info,
2340             legacy_ind.service_specific_info + legacy_ind.service_specific_info_len);
2341     aidl_ind->extendedServiceSpecificInfo = std::vector<uint8_t>(
2342             legacy_ind.sdea_service_specific_info,
2343             legacy_ind.sdea_service_specific_info + legacy_ind.sdea_service_specific_info_len);
2344     aidl_ind->matchFilter =
2345             std::vector<uint8_t>(legacy_ind.sdf_match_filter,
2346                                  legacy_ind.sdf_match_filter + legacy_ind.sdf_match_filter_len);
2347     aidl_ind->matchOccurredInBeaconFlag = legacy_ind.match_occured_flag == 1;  // NOTYPO
2348     aidl_ind->outOfResourceFlag = legacy_ind.out_of_resource_flag == 1;
2349     aidl_ind->rssiValue = legacy_ind.rssi_value;
2350     aidl_ind->peerCipherType = (NanCipherSuiteType)legacy_ind.peer_cipher_type;
2351     aidl_ind->peerRequiresSecurityEnabledInNdp =
2352             legacy_ind.peer_sdea_params.security_cfg == legacy_hal::NAN_DP_CONFIG_SECURITY;
2353     aidl_ind->peerRequiresRanging =
2354             legacy_ind.peer_sdea_params.ranging_state == legacy_hal::NAN_RANGING_ENABLE;
2355     aidl_ind->rangingMeasurementInMm = legacy_ind.range_info.range_measurement_mm;
2356     aidl_ind->rangingIndicationType = legacy_ind.range_info.ranging_event_type;
2357     aidl_ind->scid = std::vector<uint8_t>(legacy_ind.scid, legacy_ind.scid + legacy_ind.scid_len);
2358 
2359     if (!convertLegacyNiraToAidl(legacy_ind.nira, &aidl_ind->peerNira)) {
2360         LOG(ERROR) << "convertLegacyNanMatchIndToAidl: invalid NIRA";
2361         return false;
2362     }
2363     if (!convertLegacyPairingConfigToAidl(legacy_ind.peer_pairing_config,
2364                                           &aidl_ind->peerPairingConfig)) {
2365         LOG(ERROR) << "convertLegacyNanMatchIndToAidl: invalid pairing config";
2366         return false;
2367     }
2368     return true;
2369 }
2370 
convertLegacyNanFollowupIndToAidl(const legacy_hal::NanFollowupInd & legacy_ind,NanFollowupReceivedInd * aidl_ind)2371 bool convertLegacyNanFollowupIndToAidl(const legacy_hal::NanFollowupInd& legacy_ind,
2372                                        NanFollowupReceivedInd* aidl_ind) {
2373     if (!aidl_ind) {
2374         LOG(ERROR) << "convertLegacyNanFollowupIndToAidl: aidl_ind is null";
2375         return false;
2376     }
2377     *aidl_ind = {};
2378 
2379     aidl_ind->discoverySessionId = legacy_ind.publish_subscribe_id;
2380     aidl_ind->peerId = legacy_ind.requestor_instance_id;
2381     aidl_ind->addr = std::array<uint8_t, 6>();
2382     std::copy(legacy_ind.addr, legacy_ind.addr + 6, std::begin(aidl_ind->addr));
2383     aidl_ind->receivedInFaw = legacy_ind.dw_or_faw == 1;
2384     aidl_ind->serviceSpecificInfo = std::vector<uint8_t>(
2385             legacy_ind.service_specific_info,
2386             legacy_ind.service_specific_info + legacy_ind.service_specific_info_len);
2387     aidl_ind->extendedServiceSpecificInfo = std::vector<uint8_t>(
2388             legacy_ind.sdea_service_specific_info,
2389             legacy_ind.sdea_service_specific_info + legacy_ind.sdea_service_specific_info_len);
2390 
2391     return true;
2392 }
2393 
convertLegacyNanDataPathRequestIndToAidl(const legacy_hal::NanDataPathRequestInd & legacy_ind,NanDataPathRequestInd * aidl_ind)2394 bool convertLegacyNanDataPathRequestIndToAidl(const legacy_hal::NanDataPathRequestInd& legacy_ind,
2395                                               NanDataPathRequestInd* aidl_ind) {
2396     if (!aidl_ind) {
2397         LOG(ERROR) << "convertLegacyNanDataPathRequestIndToAidl: aidl_ind is null";
2398         return false;
2399     }
2400     *aidl_ind = {};
2401 
2402     aidl_ind->discoverySessionId = legacy_ind.service_instance_id;
2403     aidl_ind->peerDiscMacAddr = std::array<uint8_t, 6>();
2404     std::copy(legacy_ind.peer_disc_mac_addr, legacy_ind.peer_disc_mac_addr + 6,
2405               std::begin(aidl_ind->peerDiscMacAddr));
2406     aidl_ind->ndpInstanceId = legacy_ind.ndp_instance_id;
2407     aidl_ind->securityRequired =
2408             legacy_ind.ndp_cfg.security_cfg == legacy_hal::NAN_DP_CONFIG_SECURITY;
2409     aidl_ind->appInfo = std::vector<uint8_t>(
2410             legacy_ind.app_info.ndp_app_info,
2411             legacy_ind.app_info.ndp_app_info + legacy_ind.app_info.ndp_app_info_len);
2412 
2413     return true;
2414 }
2415 
convertLegacyNdpChannelInfoToAidl(const legacy_hal::NanChannelInfo & legacy_struct,NanDataPathChannelInfo * aidl_struct)2416 bool convertLegacyNdpChannelInfoToAidl(const legacy_hal::NanChannelInfo& legacy_struct,
2417                                        NanDataPathChannelInfo* aidl_struct) {
2418     if (!aidl_struct) {
2419         LOG(ERROR) << "convertLegacyNdpChannelInfoToAidl: aidl_struct is null";
2420         return false;
2421     }
2422     *aidl_struct = {};
2423 
2424     aidl_struct->channelFreq = legacy_struct.channel;
2425     aidl_struct->channelBandwidth = convertLegacyWifiChannelWidthToAidl(
2426             (legacy_hal::wifi_channel_width)legacy_struct.bandwidth);
2427     aidl_struct->numSpatialStreams = legacy_struct.nss;
2428 
2429     return true;
2430 }
2431 
convertLegacyNanDataPathConfirmIndToAidl(const legacy_hal::NanDataPathConfirmInd & legacy_ind,NanDataPathConfirmInd * aidl_ind)2432 bool convertLegacyNanDataPathConfirmIndToAidl(const legacy_hal::NanDataPathConfirmInd& legacy_ind,
2433                                               NanDataPathConfirmInd* aidl_ind) {
2434     if (!aidl_ind) {
2435         LOG(ERROR) << "convertLegacyNanDataPathConfirmIndToAidl: aidl_ind is null";
2436         return false;
2437     }
2438     *aidl_ind = {};
2439 
2440     aidl_ind->ndpInstanceId = legacy_ind.ndp_instance_id;
2441     aidl_ind->dataPathSetupSuccess = legacy_ind.rsp_code == legacy_hal::NAN_DP_REQUEST_ACCEPT;
2442     aidl_ind->peerNdiMacAddr = std::array<uint8_t, 6>();
2443     std::copy(legacy_ind.peer_ndi_mac_addr, legacy_ind.peer_ndi_mac_addr + 6,
2444               std::begin(aidl_ind->peerNdiMacAddr));
2445     aidl_ind->appInfo = std::vector<uint8_t>(
2446             legacy_ind.app_info.ndp_app_info,
2447             legacy_ind.app_info.ndp_app_info + legacy_ind.app_info.ndp_app_info_len);
2448     aidl_ind->status.status = convertLegacyNanStatusTypeToAidl(legacy_ind.reason_code);
2449     aidl_ind->status.description = "";
2450 
2451     std::vector<NanDataPathChannelInfo> channelInfo;
2452     for (unsigned int i = 0; i < legacy_ind.num_channels; ++i) {
2453         NanDataPathChannelInfo aidl_struct;
2454         if (!convertLegacyNdpChannelInfoToAidl(legacy_ind.channel_info[i], &aidl_struct)) {
2455             return false;
2456         }
2457         channelInfo.push_back(aidl_struct);
2458     }
2459     aidl_ind->channelInfo = channelInfo;
2460 
2461     return true;
2462 }
2463 
convertLegacyNanDataPathScheduleUpdateIndToAidl(const legacy_hal::NanDataPathScheduleUpdateInd & legacy_ind,NanDataPathScheduleUpdateInd * aidl_ind)2464 bool convertLegacyNanDataPathScheduleUpdateIndToAidl(
2465         const legacy_hal::NanDataPathScheduleUpdateInd& legacy_ind,
2466         NanDataPathScheduleUpdateInd* aidl_ind) {
2467     if (!aidl_ind) {
2468         LOG(ERROR) << "convertLegacyNanDataPathScheduleUpdateIndToAidl: "
2469                       "aidl_ind is null";
2470         return false;
2471     }
2472     *aidl_ind = {};
2473 
2474     aidl_ind->peerDiscoveryAddress = std::array<uint8_t, 6>();
2475     std::copy(legacy_ind.peer_mac_addr, legacy_ind.peer_mac_addr + 6,
2476               std::begin(aidl_ind->peerDiscoveryAddress));
2477     std::vector<NanDataPathChannelInfo> channelInfo;
2478     for (unsigned int i = 0; i < legacy_ind.num_channels; ++i) {
2479         NanDataPathChannelInfo aidl_struct;
2480         if (!convertLegacyNdpChannelInfoToAidl(legacy_ind.channel_info[i], &aidl_struct)) {
2481             return false;
2482         }
2483         channelInfo.push_back(aidl_struct);
2484     }
2485     aidl_ind->channelInfo = channelInfo;
2486     std::vector<uint32_t> ndpInstanceIds;
2487     for (unsigned int i = 0; i < legacy_ind.num_ndp_instances; ++i) {
2488         ndpInstanceIds.push_back(legacy_ind.ndp_instance_id[i]);
2489     }
2490     aidl_ind->ndpInstanceIds = uintToIntVec(ndpInstanceIds);
2491 
2492     return true;
2493 }
2494 
convertAidlRttTypeToLegacy(RttType type)2495 legacy_hal::wifi_rtt_type convertAidlRttTypeToLegacy(RttType type) {
2496     switch (type) {
2497         case RttType::ONE_SIDED:
2498             return legacy_hal::RTT_TYPE_1_SIDED;
2499         case RttType::TWO_SIDED_11MC:
2500             // Same as RttType::TWO_SIDED
2501             return legacy_hal::RTT_TYPE_2_SIDED_11MC;
2502         case RttType::TWO_SIDED_11AZ_NTB:
2503             return legacy_hal::RTT_TYPE_2_SIDED_11AZ_NTB;
2504         case RttType::TWO_SIDED_11AZ_NTB_SECURE:
2505             return legacy_hal::RTT_TYPE_2_SIDED_11AZ_NTB_SECURE;
2506     };
2507     CHECK(false);
2508 }
2509 
convertLegacyRttTypeToAidl(legacy_hal::wifi_rtt_type type)2510 RttType convertLegacyRttTypeToAidl(legacy_hal::wifi_rtt_type type) {
2511     switch (type) {
2512         case legacy_hal::RTT_TYPE_1_SIDED:
2513             return RttType::ONE_SIDED;
2514         case legacy_hal::RTT_TYPE_2_SIDED_11MC:
2515             // Same as legacy_hal::RTT_TYPE_2_SIDED
2516             return RttType::TWO_SIDED_11MC;
2517         case legacy_hal::RTT_TYPE_2_SIDED_11AZ_NTB:
2518             return RttType::TWO_SIDED_11AZ_NTB;
2519         case legacy_hal::RTT_TYPE_2_SIDED_11AZ_NTB_SECURE:
2520             return RttType::TWO_SIDED_11AZ_NTB_SECURE;
2521     };
2522     CHECK(false) << "Unknown legacy type: " << type;
2523 }
2524 
convertAidlRttPeerTypeToLegacy(RttPeerType type)2525 legacy_hal::rtt_peer_type convertAidlRttPeerTypeToLegacy(RttPeerType type) {
2526     switch (type) {
2527         case RttPeerType::AP:
2528             return legacy_hal::RTT_PEER_AP;
2529         case RttPeerType::STA:
2530             return legacy_hal::RTT_PEER_STA;
2531         case RttPeerType::P2P_GO:
2532             return legacy_hal::RTT_PEER_P2P_GO;
2533         case RttPeerType::P2P_CLIENT:
2534             return legacy_hal::RTT_PEER_P2P_CLIENT;
2535         case RttPeerType::NAN_TYPE:
2536             return legacy_hal::RTT_PEER_NAN;
2537     };
2538     CHECK(false);
2539 }
2540 
convertAidlWifiChannelWidthToLegacy(WifiChannelWidthInMhz type)2541 legacy_hal::wifi_channel_width convertAidlWifiChannelWidthToLegacy(WifiChannelWidthInMhz type) {
2542     switch (type) {
2543         case WifiChannelWidthInMhz::WIDTH_20:
2544             return legacy_hal::WIFI_CHAN_WIDTH_20;
2545         case WifiChannelWidthInMhz::WIDTH_40:
2546             return legacy_hal::WIFI_CHAN_WIDTH_40;
2547         case WifiChannelWidthInMhz::WIDTH_80:
2548             return legacy_hal::WIFI_CHAN_WIDTH_80;
2549         case WifiChannelWidthInMhz::WIDTH_160:
2550             return legacy_hal::WIFI_CHAN_WIDTH_160;
2551         case WifiChannelWidthInMhz::WIDTH_80P80:
2552             return legacy_hal::WIFI_CHAN_WIDTH_80P80;
2553         case WifiChannelWidthInMhz::WIDTH_5:
2554             return legacy_hal::WIFI_CHAN_WIDTH_5;
2555         case WifiChannelWidthInMhz::WIDTH_10:
2556             return legacy_hal::WIFI_CHAN_WIDTH_10;
2557         case WifiChannelWidthInMhz::WIDTH_320:
2558             return legacy_hal::WIFI_CHAN_WIDTH_320;
2559         case WifiChannelWidthInMhz::WIDTH_INVALID:
2560             return legacy_hal::WIFI_CHAN_WIDTH_INVALID;
2561     };
2562     CHECK(false);
2563 }
2564 
convertLegacyWifiChannelWidthToAidl(legacy_hal::wifi_channel_width type)2565 WifiChannelWidthInMhz convertLegacyWifiChannelWidthToAidl(legacy_hal::wifi_channel_width type) {
2566     switch (type) {
2567         case legacy_hal::WIFI_CHAN_WIDTH_20:
2568             return WifiChannelWidthInMhz::WIDTH_20;
2569         case legacy_hal::WIFI_CHAN_WIDTH_40:
2570             return WifiChannelWidthInMhz::WIDTH_40;
2571         case legacy_hal::WIFI_CHAN_WIDTH_80:
2572             return WifiChannelWidthInMhz::WIDTH_80;
2573         case legacy_hal::WIFI_CHAN_WIDTH_160:
2574             return WifiChannelWidthInMhz::WIDTH_160;
2575         case legacy_hal::WIFI_CHAN_WIDTH_80P80:
2576             return WifiChannelWidthInMhz::WIDTH_80P80;
2577         case legacy_hal::WIFI_CHAN_WIDTH_5:
2578             return WifiChannelWidthInMhz::WIDTH_5;
2579         case legacy_hal::WIFI_CHAN_WIDTH_10:
2580             return WifiChannelWidthInMhz::WIDTH_10;
2581         case legacy_hal::WIFI_CHAN_WIDTH_320:
2582             return WifiChannelWidthInMhz::WIDTH_320;
2583         default:
2584             return WifiChannelWidthInMhz::WIDTH_INVALID;
2585     };
2586 }
2587 
convertAidlRttPreambleToLegacy(RttPreamble type)2588 legacy_hal::wifi_rtt_preamble convertAidlRttPreambleToLegacy(RttPreamble type) {
2589     switch (type) {
2590         case RttPreamble::LEGACY:
2591             return legacy_hal::WIFI_RTT_PREAMBLE_LEGACY;
2592         case RttPreamble::HT:
2593             return legacy_hal::WIFI_RTT_PREAMBLE_HT;
2594         case RttPreamble::VHT:
2595             return legacy_hal::WIFI_RTT_PREAMBLE_VHT;
2596         case RttPreamble::HE:
2597             return legacy_hal::WIFI_RTT_PREAMBLE_HE;
2598         case RttPreamble::EHT:
2599             return legacy_hal::WIFI_RTT_PREAMBLE_EHT;
2600         case RttPreamble::INVALID:
2601             return legacy_hal::WIFI_RTT_PREAMBLE_INVALID;
2602     };
2603     CHECK(false);
2604 }
2605 
convertLegacyRttPreambleToAidl(legacy_hal::wifi_rtt_preamble type)2606 RttPreamble convertLegacyRttPreambleToAidl(legacy_hal::wifi_rtt_preamble type) {
2607     switch (type) {
2608         case legacy_hal::WIFI_RTT_PREAMBLE_LEGACY:
2609             return RttPreamble::LEGACY;
2610         case legacy_hal::WIFI_RTT_PREAMBLE_HT:
2611             return RttPreamble::HT;
2612         case legacy_hal::WIFI_RTT_PREAMBLE_VHT:
2613             return RttPreamble::VHT;
2614         case legacy_hal::WIFI_RTT_PREAMBLE_HE:
2615             return RttPreamble::HE;
2616         case legacy_hal::WIFI_RTT_PREAMBLE_EHT:
2617             return RttPreamble::EHT;
2618         case legacy_hal::WIFI_RTT_PREAMBLE_INVALID:
2619             return RttPreamble::INVALID;
2620     };
2621     CHECK(false) << "Unknown legacy type: " << type;
2622 }
2623 
convertAidlRttBwToLegacy(RttBw type)2624 legacy_hal::wifi_rtt_bw convertAidlRttBwToLegacy(RttBw type) {
2625     switch (type) {
2626         case RttBw::BW_5MHZ:
2627             return legacy_hal::WIFI_RTT_BW_5;
2628         case RttBw::BW_10MHZ:
2629             return legacy_hal::WIFI_RTT_BW_10;
2630         case RttBw::BW_20MHZ:
2631             return legacy_hal::WIFI_RTT_BW_20;
2632         case RttBw::BW_40MHZ:
2633             return legacy_hal::WIFI_RTT_BW_40;
2634         case RttBw::BW_80MHZ:
2635             return legacy_hal::WIFI_RTT_BW_80;
2636         case RttBw::BW_160MHZ:
2637             return legacy_hal::WIFI_RTT_BW_160;
2638         case RttBw::BW_320MHZ:
2639             return legacy_hal::WIFI_RTT_BW_320;
2640         case RttBw::BW_UNSPECIFIED:
2641             return legacy_hal::WIFI_RTT_BW_UNSPECIFIED;
2642     };
2643     CHECK(false);
2644 }
2645 
convertLegacyRttBwToAidl(legacy_hal::wifi_rtt_bw type)2646 RttBw convertLegacyRttBwToAidl(legacy_hal::wifi_rtt_bw type) {
2647     switch (type) {
2648         case legacy_hal::WIFI_RTT_BW_5:
2649             return RttBw::BW_5MHZ;
2650         case legacy_hal::WIFI_RTT_BW_10:
2651             return RttBw::BW_10MHZ;
2652         case legacy_hal::WIFI_RTT_BW_20:
2653             return RttBw::BW_20MHZ;
2654         case legacy_hal::WIFI_RTT_BW_40:
2655             return RttBw::BW_40MHZ;
2656         case legacy_hal::WIFI_RTT_BW_80:
2657             return RttBw::BW_80MHZ;
2658         case legacy_hal::WIFI_RTT_BW_160:
2659             return RttBw::BW_160MHZ;
2660         case legacy_hal::WIFI_RTT_BW_320:
2661             return RttBw::BW_320MHZ;
2662         case legacy_hal::WIFI_RTT_BW_UNSPECIFIED:
2663             return RttBw::BW_UNSPECIFIED;
2664     };
2665     CHECK(false) << "Unknown legacy type: " << type;
2666 }
2667 
convertAidlRttMotionPatternToLegacy(RttMotionPattern type)2668 legacy_hal::wifi_motion_pattern convertAidlRttMotionPatternToLegacy(RttMotionPattern type) {
2669     switch (type) {
2670         case RttMotionPattern::NOT_EXPECTED:
2671             return legacy_hal::WIFI_MOTION_NOT_EXPECTED;
2672         case RttMotionPattern::EXPECTED:
2673             return legacy_hal::WIFI_MOTION_EXPECTED;
2674         case RttMotionPattern::UNKNOWN:
2675             return legacy_hal::WIFI_MOTION_UNKNOWN;
2676     };
2677     CHECK(false);
2678 }
2679 
convertLegacyWifiRatePreambleToAidl(uint8_t preamble)2680 WifiRatePreamble convertLegacyWifiRatePreambleToAidl(uint8_t preamble) {
2681     switch (preamble) {
2682         case 0:
2683             return WifiRatePreamble::OFDM;
2684         case 1:
2685             return WifiRatePreamble::CCK;
2686         case 2:
2687             return WifiRatePreamble::HT;
2688         case 3:
2689             return WifiRatePreamble::VHT;
2690         case 4:
2691             return WifiRatePreamble::HE;
2692         case 5:
2693             return WifiRatePreamble::EHT;
2694         default:
2695             return WifiRatePreamble::RESERVED;
2696     };
2697     CHECK(false) << "Unknown legacy preamble: " << preamble;
2698 }
2699 
convertLegacyWifiRateNssToAidl(uint8_t nss)2700 WifiRateNss convertLegacyWifiRateNssToAidl(uint8_t nss) {
2701     switch (nss) {
2702         case 0:
2703             return WifiRateNss::NSS_1x1;
2704         case 1:
2705             return WifiRateNss::NSS_2x2;
2706         case 2:
2707             return WifiRateNss::NSS_3x3;
2708         case 3:
2709             return WifiRateNss::NSS_4x4;
2710     };
2711     CHECK(false) << "Unknown legacy nss: " << nss;
2712     return {};
2713 }
2714 
convertLegacyRttStatusToAidl(legacy_hal::wifi_rtt_status status)2715 RttStatus convertLegacyRttStatusToAidl(legacy_hal::wifi_rtt_status status) {
2716     switch (status) {
2717         case legacy_hal::RTT_STATUS_SUCCESS:
2718             return RttStatus::SUCCESS;
2719         case legacy_hal::RTT_STATUS_FAILURE:
2720             return RttStatus::FAILURE;
2721         case legacy_hal::RTT_STATUS_FAIL_NO_RSP:
2722             return RttStatus::FAIL_NO_RSP;
2723         case legacy_hal::RTT_STATUS_FAIL_REJECTED:
2724             return RttStatus::FAIL_REJECTED;
2725         case legacy_hal::RTT_STATUS_FAIL_NOT_SCHEDULED_YET:
2726             return RttStatus::FAIL_NOT_SCHEDULED_YET;
2727         case legacy_hal::RTT_STATUS_FAIL_TM_TIMEOUT:
2728             return RttStatus::FAIL_TM_TIMEOUT;
2729         case legacy_hal::RTT_STATUS_FAIL_AP_ON_DIFF_CHANNEL:
2730             return RttStatus::FAIL_AP_ON_DIFF_CHANNEL;
2731         case legacy_hal::RTT_STATUS_FAIL_NO_CAPABILITY:
2732             return RttStatus::FAIL_NO_CAPABILITY;
2733         case legacy_hal::RTT_STATUS_ABORTED:
2734             return RttStatus::ABORTED;
2735         case legacy_hal::RTT_STATUS_FAIL_INVALID_TS:
2736             return RttStatus::FAIL_INVALID_TS;
2737         case legacy_hal::RTT_STATUS_FAIL_PROTOCOL:
2738             return RttStatus::FAIL_PROTOCOL;
2739         case legacy_hal::RTT_STATUS_FAIL_SCHEDULE:
2740             return RttStatus::FAIL_SCHEDULE;
2741         case legacy_hal::RTT_STATUS_FAIL_BUSY_TRY_LATER:
2742             return RttStatus::FAIL_BUSY_TRY_LATER;
2743         case legacy_hal::RTT_STATUS_INVALID_REQ:
2744             return RttStatus::INVALID_REQ;
2745         case legacy_hal::RTT_STATUS_NO_WIFI:
2746             return RttStatus::NO_WIFI;
2747         case legacy_hal::RTT_STATUS_FAIL_FTM_PARAM_OVERRIDE:
2748             return RttStatus::FAIL_FTM_PARAM_OVERRIDE;
2749         case legacy_hal::RTT_STATUS_NAN_RANGING_PROTOCOL_FAILURE:
2750             return RttStatus::NAN_RANGING_PROTOCOL_FAILURE;
2751         case legacy_hal::RTT_STATUS_NAN_RANGING_CONCURRENCY_NOT_SUPPORTED:
2752             return RttStatus::NAN_RANGING_CONCURRENCY_NOT_SUPPORTED;
2753         case legacy_hal::RTT_STATUS_SECURE_RANGING_FAILURE_INVALID_AKM:
2754             return RttStatus::SECURE_RANGING_FAILURE_INVALID_AKM;
2755         case legacy_hal::RTT_STATUS_SECURE_RANGING_FAILURE_INVALID_CIPHER:
2756             return RttStatus::SECURE_RANGING_FAILURE_INVALID_CIPHER;
2757         case legacy_hal::RTT_STATUS_SECURE_RANGING_FAILURE_INVALID_CONFIG:
2758             return RttStatus::SECURE_RANGING_FAILURE_INVALID_CONFIG;
2759         case legacy_hal::RTT_STATUS_SECURE_RANGING_FAILURE_REJECTED:
2760             return RttStatus::SECURE_RANGING_FAILURE_REJECTED;
2761         case legacy_hal::RTT_STATUS_SECURE_RANGING_FAILURE_UNKNOWN:
2762             return RttStatus::SECURE_RANGING_FAILURE_UNKNOWN;
2763     };
2764     CHECK(false) << "Unknown legacy status: " << status;
2765 }
2766 
convertAidlWifiChannelInfoToLegacy(const WifiChannelInfo & aidl_info,legacy_hal::wifi_channel_info * legacy_info)2767 bool convertAidlWifiChannelInfoToLegacy(const WifiChannelInfo& aidl_info,
2768                                         legacy_hal::wifi_channel_info* legacy_info) {
2769     if (!legacy_info) {
2770         return false;
2771     }
2772     *legacy_info = {};
2773     legacy_info->width = convertAidlWifiChannelWidthToLegacy(aidl_info.width);
2774     legacy_info->center_freq = aidl_info.centerFreq;
2775     legacy_info->center_freq0 = aidl_info.centerFreq0;
2776     legacy_info->center_freq1 = aidl_info.centerFreq1;
2777     return true;
2778 }
2779 
convertLegacyWifiChannelInfoToAidl(const legacy_hal::wifi_channel_info & legacy_info,WifiChannelInfo * aidl_info)2780 bool convertLegacyWifiChannelInfoToAidl(const legacy_hal::wifi_channel_info& legacy_info,
2781                                         WifiChannelInfo* aidl_info) {
2782     if (!aidl_info) {
2783         return false;
2784     }
2785     *aidl_info = {};
2786     aidl_info->width = convertLegacyWifiChannelWidthToAidl(legacy_info.width);
2787     aidl_info->centerFreq = legacy_info.center_freq;
2788     aidl_info->centerFreq0 = legacy_info.center_freq0;
2789     aidl_info->centerFreq1 = legacy_info.center_freq1;
2790     return true;
2791 }
2792 
convertAidlRttConfigToLegacy(const RttConfig & aidl_config,legacy_hal::wifi_rtt_config * legacy_config)2793 bool convertAidlRttConfigToLegacy(const RttConfig& aidl_config,
2794                                   legacy_hal::wifi_rtt_config* legacy_config) {
2795     if (!legacy_config) {
2796         return false;
2797     }
2798     *legacy_config = {};
2799     CHECK(aidl_config.addr.size() == sizeof(legacy_config->addr));
2800     memcpy(legacy_config->addr, aidl_config.addr.data(), aidl_config.addr.size());
2801     legacy_config->type = convertAidlRttTypeToLegacy(aidl_config.type);
2802     legacy_config->peer = convertAidlRttPeerTypeToLegacy(aidl_config.peer);
2803     if (!convertAidlWifiChannelInfoToLegacy(aidl_config.channel, &legacy_config->channel)) {
2804         return false;
2805     }
2806     legacy_config->burst_period = aidl_config.burstPeriod;
2807     legacy_config->num_burst = aidl_config.numBurst;
2808     legacy_config->num_frames_per_burst = aidl_config.numFramesPerBurst;
2809     legacy_config->num_retries_per_rtt_frame = aidl_config.numRetriesPerRttFrame;
2810     legacy_config->num_retries_per_ftmr = aidl_config.numRetriesPerFtmr;
2811     legacy_config->LCI_request = aidl_config.mustRequestLci;
2812     legacy_config->LCR_request = aidl_config.mustRequestLcr;
2813     legacy_config->burst_duration = aidl_config.burstDuration;
2814     legacy_config->preamble = convertAidlRttPreambleToLegacy(aidl_config.preamble);
2815     legacy_config->bw = convertAidlRttBwToLegacy(aidl_config.bw);
2816     return true;
2817 }
2818 
convertAidlRttConfigToLegacyV3(const RttConfig & aidl_config,legacy_hal::wifi_rtt_config_v3 * legacy_config)2819 bool convertAidlRttConfigToLegacyV3(const RttConfig& aidl_config,
2820                                     legacy_hal::wifi_rtt_config_v3* legacy_config) {
2821     if (!legacy_config) {
2822         return false;
2823     }
2824     *legacy_config = {};
2825     if (!convertAidlRttConfigToLegacy(aidl_config, &(legacy_config->rtt_config))) {
2826         return false;
2827     }
2828     legacy_config->ntb_min_measurement_time = aidl_config.ntbMinMeasurementTime;
2829     legacy_config->ntb_max_measurement_time = aidl_config.ntbMaxMeasurementTime;
2830     return true;
2831 }
2832 
convertLegacyAkmsToAidl(legacy_hal::wifi_rtt_akm akms)2833 long convertLegacyAkmsToAidl(legacy_hal::wifi_rtt_akm akms) {
2834     long aidl_akms = Akm::NONE;
2835     if ((akms & legacy_hal::WPA_KEY_MGMT_PASN) != 0) {
2836         aidl_akms |= Akm::PASN;
2837     }
2838     if ((akms & legacy_hal::WPA_KEY_MGMT_SAE) != 0) {
2839         aidl_akms |= Akm::SAE;
2840     }
2841     if ((akms & legacy_hal::WPA_KEY_MGMT_EAP_FT_SHA256) != 0) {
2842         aidl_akms |= Akm::FT_EAP_SHA256;
2843     }
2844     if ((akms & legacy_hal::WPA_KEY_MGMT_FT_PSK_SHA256) != 0) {
2845         aidl_akms |= Akm::FT_PSK_SHA256;
2846     }
2847     if ((akms & legacy_hal::WPA_KEY_MGMT_EAP_FT_SHA384) != 0) {
2848         aidl_akms |= Akm::FT_EAP_SHA384;
2849     }
2850     if ((akms & legacy_hal::WPA_KEY_MGMT_FT_PSK_SHA384) != 0) {
2851         aidl_akms |= Akm::FT_PSK_SHA384;
2852     }
2853     if ((akms & legacy_hal::WPA_KEY_MGMT_EAP_FILS_SHA256) != 0) {
2854         aidl_akms |= Akm::FILS_EAP_SHA256;
2855     }
2856     if ((akms & legacy_hal::WPA_KEY_MGMT_EAP_FILS_SHA384) != 0) {
2857         aidl_akms |= Akm::FILS_EAP_SHA384;
2858     }
2859     return aidl_akms;
2860 }
2861 
convertAidlAkmToLegacy(long akm)2862 legacy_hal::wifi_rtt_akm convertAidlAkmToLegacy(long akm) {
2863     switch (akm) {
2864         case Akm::PASN:
2865             return legacy_hal::WPA_KEY_MGMT_PASN;
2866         case Akm::SAE:
2867             return legacy_hal::WPA_KEY_MGMT_SAE;
2868         case Akm::FT_EAP_SHA256:
2869             return legacy_hal::WPA_KEY_MGMT_EAP_FT_SHA256;
2870         case Akm::FT_PSK_SHA256:
2871             return legacy_hal::WPA_KEY_MGMT_FT_PSK_SHA256;
2872         case Akm::FT_EAP_SHA384:
2873             return legacy_hal::WPA_KEY_MGMT_EAP_FT_SHA384;
2874         case Akm::FT_PSK_SHA384:
2875             return legacy_hal::WPA_KEY_MGMT_FT_PSK_SHA384;
2876         case Akm::FILS_EAP_SHA256:
2877             return legacy_hal::WPA_KEY_MGMT_EAP_FILS_SHA256;
2878         case Akm::FILS_EAP_SHA384:
2879             return legacy_hal::WPA_KEY_MGMT_EAP_FILS_SHA384;
2880         default:
2881             return legacy_hal::WPA_KEY_MGMT_NONE;
2882     }
2883 }
2884 
convertLegacyCipherSuitesToAidl(legacy_hal::wifi_rtt_cipher_suite ciphers)2885 long convertLegacyCipherSuitesToAidl(legacy_hal::wifi_rtt_cipher_suite ciphers) {
2886     long aidl_ciphers = CipherSuite::NONE;
2887     if ((ciphers & legacy_hal::WPA_CIPHER_CCMP_128) != 0) {
2888         aidl_ciphers |= CipherSuite::CCMP_128;
2889     }
2890     if ((ciphers & legacy_hal::WPA_CIPHER_CCMP_256) != 0) {
2891         aidl_ciphers |= CipherSuite::CCMP_256;
2892     }
2893     if ((ciphers & legacy_hal::WPA_CIPHER_GCMP_128) != 0) {
2894         aidl_ciphers |= CipherSuite::GCMP_128;
2895     }
2896     if ((ciphers & legacy_hal::WPA_CIPHER_GCMP_256) != 0) {
2897         aidl_ciphers |= CipherSuite::GCMP_256;
2898     }
2899     return aidl_ciphers;
2900 }
2901 
convertAidlCipherSuiteToLegacy(long cipher)2902 legacy_hal::wifi_rtt_cipher_suite convertAidlCipherSuiteToLegacy(long cipher) {
2903     switch (cipher) {
2904         case CipherSuite::CCMP_128:
2905             return WPA_CIPHER_CCMP_128;
2906         case CipherSuite::CCMP_256:
2907             return WPA_CIPHER_CCMP_256;
2908         case CipherSuite::GCMP_128:
2909             return WPA_CIPHER_GCMP_128;
2910         case CipherSuite::GCMP_256:
2911             return WPA_CIPHER_GCMP_256;
2912         default:
2913             return WPA_CIPHER_NONE;
2914     }
2915 }
2916 
convertAidlRttConfigToLegacyV4(const RttConfig & aidl_config,legacy_hal::wifi_rtt_config_v4 * legacy_config)2917 bool convertAidlRttConfigToLegacyV4(const RttConfig& aidl_config,
2918                                     legacy_hal::wifi_rtt_config_v4* legacy_config) {
2919     if (!legacy_config) {
2920         return false;
2921     }
2922     *legacy_config = {};
2923     if (!convertAidlRttConfigToLegacyV3(aidl_config, &(legacy_config->rtt_config))) {
2924         return false;
2925     }
2926     if (aidl_config.secureConfig.has_value()) {
2927         legacy_config->rtt_secure_config.enable_secure_he_ltf =
2928                 aidl_config.secureConfig->enableSecureHeLtf;
2929         legacy_config->rtt_secure_config.enable_ranging_frame_protection =
2930                 aidl_config.secureConfig->enableRangingFrameProtection;
2931         if (aidl_config.secureConfig->pasnComebackCookie.has_value() &&
2932             aidl_config.secureConfig->pasnComebackCookie->size() <= RTT_MAX_COOKIE_LEN) {
2933             legacy_config->rtt_secure_config.pasn_config.comeback_cookie_len =
2934                     aidl_config.secureConfig->pasnComebackCookie->size();
2935             memcpy(legacy_config->rtt_secure_config.pasn_config.comeback_cookie,
2936                    aidl_config.secureConfig->pasnComebackCookie->data(),
2937                    aidl_config.secureConfig->pasnComebackCookie->size());
2938         }
2939         legacy_config->rtt_secure_config.pasn_config.base_akm =
2940                 convertAidlAkmToLegacy(aidl_config.secureConfig->pasnConfig.baseAkm);
2941         legacy_config->rtt_secure_config.pasn_config.pairwise_cipher_suite =
2942                 convertAidlCipherSuiteToLegacy(aidl_config.secureConfig->pasnConfig.cipherSuite);
2943         if (aidl_config.secureConfig->pasnConfig.passphrase.has_value() &&
2944             aidl_config.secureConfig->pasnConfig.passphrase->size() <=
2945                     RTT_SECURITY_MAX_PASSPHRASE_LEN) {
2946             legacy_config->rtt_secure_config.pasn_config.passphrase_len =
2947                     aidl_config.secureConfig->pasnConfig.passphrase->size();
2948             memcpy(legacy_config->rtt_secure_config.pasn_config.passphrase,
2949                    aidl_config.secureConfig->pasnConfig.passphrase->data(),
2950                    aidl_config.secureConfig->pasnConfig.passphrase->size());
2951         }
2952         if (aidl_config.secureConfig->pasnConfig.pmkid.has_value() &&
2953             aidl_config.secureConfig->pasnConfig.pmkid->size() == PMKID_LEN) {
2954             legacy_config->rtt_secure_config.pasn_config.pmkid_len =
2955                     aidl_config.secureConfig->pasnConfig.pmkid->size();
2956             memcpy(legacy_config->rtt_secure_config.pasn_config.pmkid,
2957                    aidl_config.secureConfig->pasnConfig.pmkid->data(),
2958                    aidl_config.secureConfig->pasnConfig.pmkid->size());
2959         }
2960     }
2961 
2962     return true;
2963 }
2964 
convertAidlVectorOfRttConfigToLegacy(const std::vector<RttConfig> & aidl_configs,std::vector<legacy_hal::wifi_rtt_config> * legacy_configs)2965 bool convertAidlVectorOfRttConfigToLegacy(
2966         const std::vector<RttConfig>& aidl_configs,
2967         std::vector<legacy_hal::wifi_rtt_config>* legacy_configs) {
2968     if (!legacy_configs) {
2969         return false;
2970     }
2971     *legacy_configs = {};
2972     for (const auto& aidl_config : aidl_configs) {
2973         legacy_hal::wifi_rtt_config legacy_config;
2974         if (!convertAidlRttConfigToLegacy(aidl_config, &(legacy_config))) {
2975             return false;
2976         }
2977         legacy_configs->push_back(legacy_config);
2978     }
2979     return true;
2980 }
2981 
convertAidlVectorOfRttConfigToLegacyV3(const std::vector<RttConfig> & aidl_configs,std::vector<legacy_hal::wifi_rtt_config_v3> * legacy_configs)2982 bool convertAidlVectorOfRttConfigToLegacyV3(
2983         const std::vector<RttConfig>& aidl_configs,
2984         std::vector<legacy_hal::wifi_rtt_config_v3>* legacy_configs) {
2985     if (!legacy_configs) {
2986         return false;
2987     }
2988     *legacy_configs = {};
2989     for (const auto& aidl_config : aidl_configs) {
2990         legacy_hal::wifi_rtt_config_v3 legacy_config;
2991         if (!convertAidlRttConfigToLegacyV3(aidl_config, &legacy_config)) {
2992             return false;
2993         }
2994         legacy_configs->push_back(legacy_config);
2995     }
2996     return true;
2997 }
2998 
convertAidlVectorOfRttConfigToLegacyV4(const std::vector<RttConfig> & aidl_configs,std::vector<legacy_hal::wifi_rtt_config_v4> * legacy_configs)2999 bool convertAidlVectorOfRttConfigToLegacyV4(
3000         const std::vector<RttConfig>& aidl_configs,
3001         std::vector<legacy_hal::wifi_rtt_config_v4>* legacy_configs) {
3002     if (!legacy_configs) {
3003         return false;
3004     }
3005     *legacy_configs = {};
3006     for (const auto& aidl_config : aidl_configs) {
3007         legacy_hal::wifi_rtt_config_v4 legacy_config;
3008         if (!convertAidlRttConfigToLegacyV4(aidl_config, &legacy_config)) {
3009             return false;
3010         }
3011         legacy_configs->push_back(legacy_config);
3012     }
3013     return true;
3014 }
3015 
convertAidlRttLciInformationToLegacy(const RttLciInformation & aidl_info,legacy_hal::wifi_lci_information * legacy_info)3016 bool convertAidlRttLciInformationToLegacy(const RttLciInformation& aidl_info,
3017                                           legacy_hal::wifi_lci_information* legacy_info) {
3018     if (!legacy_info) {
3019         return false;
3020     }
3021     *legacy_info = {};
3022     legacy_info->latitude = aidl_info.latitude;
3023     legacy_info->longitude = aidl_info.longitude;
3024     legacy_info->altitude = aidl_info.altitude;
3025     legacy_info->latitude_unc = aidl_info.latitudeUnc;
3026     legacy_info->longitude_unc = aidl_info.longitudeUnc;
3027     legacy_info->altitude_unc = aidl_info.altitudeUnc;
3028     legacy_info->motion_pattern = convertAidlRttMotionPatternToLegacy(aidl_info.motionPattern);
3029     legacy_info->floor = aidl_info.floor;
3030     legacy_info->height_above_floor = aidl_info.heightAboveFloor;
3031     legacy_info->height_unc = aidl_info.heightUnc;
3032     return true;
3033 }
3034 
convertAidlRttLcrInformationToLegacy(const RttLcrInformation & aidl_info,legacy_hal::wifi_lcr_information * legacy_info)3035 bool convertAidlRttLcrInformationToLegacy(const RttLcrInformation& aidl_info,
3036                                           legacy_hal::wifi_lcr_information* legacy_info) {
3037     if (!legacy_info) {
3038         return false;
3039     }
3040     *legacy_info = {};
3041     CHECK(aidl_info.countryCode.size() == sizeof(legacy_info->country_code));
3042     memcpy(legacy_info->country_code, aidl_info.countryCode.data(), aidl_info.countryCode.size());
3043     if (aidl_info.civicInfo.size() > sizeof(legacy_info->civic_info)) {
3044         return false;
3045     }
3046     legacy_info->length = aidl_info.civicInfo.size();
3047     memcpy(legacy_info->civic_info, aidl_info.civicInfo.c_str(), aidl_info.civicInfo.size());
3048     return true;
3049 }
3050 
convertAidlRttResponderToLegacy(const RttResponder & aidl_responder,legacy_hal::wifi_rtt_responder * legacy_responder)3051 bool convertAidlRttResponderToLegacy(const RttResponder& aidl_responder,
3052                                      legacy_hal::wifi_rtt_responder* legacy_responder) {
3053     if (!legacy_responder) {
3054         return false;
3055     }
3056     *legacy_responder = {};
3057     if (!convertAidlWifiChannelInfoToLegacy(aidl_responder.channel, &legacy_responder->channel)) {
3058         return false;
3059     }
3060     legacy_responder->preamble = convertAidlRttPreambleToLegacy(aidl_responder.preamble);
3061     return true;
3062 }
3063 
convertLegacyRttResponderToAidl(const legacy_hal::wifi_rtt_responder & legacy_responder,RttResponder * aidl_responder)3064 bool convertLegacyRttResponderToAidl(const legacy_hal::wifi_rtt_responder& legacy_responder,
3065                                      RttResponder* aidl_responder) {
3066     if (!aidl_responder) {
3067         return false;
3068     }
3069     *aidl_responder = {};
3070     if (!convertLegacyWifiChannelInfoToAidl(legacy_responder.channel, &aidl_responder->channel)) {
3071         return false;
3072     }
3073     aidl_responder->preamble = convertLegacyRttPreambleToAidl(legacy_responder.preamble);
3074     return true;
3075 }
3076 
convertLegacyRttPreambleBitmapToAidl(byte legacyPreambleBitmap)3077 RttPreamble convertLegacyRttPreambleBitmapToAidl(byte legacyPreambleBitmap) {
3078     int32_t aidlPreambleBitmap = 0;
3079     for (const auto flag : {legacy_hal::WIFI_RTT_PREAMBLE_LEGACY, legacy_hal::WIFI_RTT_PREAMBLE_HT,
3080                             legacy_hal::WIFI_RTT_PREAMBLE_VHT, legacy_hal::WIFI_RTT_PREAMBLE_HE,
3081                             legacy_hal::WIFI_RTT_PREAMBLE_EHT}) {
3082         if (legacyPreambleBitmap & flag) {
3083             aidlPreambleBitmap |= static_cast<std::underlying_type<RttPreamble>::type>(
3084                     convertLegacyRttPreambleToAidl(flag));
3085         }
3086     }
3087 
3088     return static_cast<RttPreamble>(aidlPreambleBitmap);
3089 }
3090 
convertLegacyRttBwBitmapToAidl(byte legacyBwBitmap)3091 RttBw convertLegacyRttBwBitmapToAidl(byte legacyBwBitmap) {
3092     int32_t aidlBwBitmap = 0;
3093     for (const auto flag :
3094          {legacy_hal::WIFI_RTT_BW_5, legacy_hal::WIFI_RTT_BW_10, legacy_hal::WIFI_RTT_BW_20,
3095           legacy_hal::WIFI_RTT_BW_40, legacy_hal::WIFI_RTT_BW_80, legacy_hal::WIFI_RTT_BW_160,
3096           legacy_hal::WIFI_RTT_BW_320}) {
3097         if (legacyBwBitmap & flag) {
3098             aidlBwBitmap |=
3099                     static_cast<std::underlying_type<RttBw>::type>(convertLegacyRttBwToAidl(flag));
3100         }
3101     }
3102     return static_cast<RttBw>(aidlBwBitmap);
3103 }
3104 
convertLegacyRttCapabilitiesToAidl(const legacy_hal::wifi_rtt_capabilities & legacy_capabilities,RttCapabilities * aidl_capabilities)3105 bool convertLegacyRttCapabilitiesToAidl(
3106         const legacy_hal::wifi_rtt_capabilities& legacy_capabilities,
3107         RttCapabilities* aidl_capabilities) {
3108     if (!aidl_capabilities) {
3109         return false;
3110     }
3111     *aidl_capabilities = {};
3112     aidl_capabilities->rttOneSidedSupported = legacy_capabilities.rtt_one_sided_supported;
3113     aidl_capabilities->rttFtmSupported = legacy_capabilities.rtt_ftm_supported;
3114     aidl_capabilities->lciSupported = legacy_capabilities.lci_support;
3115     aidl_capabilities->lcrSupported = legacy_capabilities.lcr_support;
3116     aidl_capabilities->responderSupported = legacy_capabilities.responder_supported;
3117     aidl_capabilities->preambleSupport =
3118             convertLegacyRttPreambleBitmapToAidl(legacy_capabilities.preamble_support);
3119     aidl_capabilities->bwSupport = convertLegacyRttBwBitmapToAidl(legacy_capabilities.bw_support);
3120     aidl_capabilities->mcVersion = legacy_capabilities.mc_version;
3121     // Initialize 11az parameters to default
3122     aidl_capabilities->azPreambleSupport = (int)RttPreamble::INVALID;
3123     aidl_capabilities->azBwSupport = (int)RttBw::BW_UNSPECIFIED;
3124     aidl_capabilities->ntbInitiatorSupported = false;
3125     aidl_capabilities->ntbResponderSupported = false;
3126     // Initialize 11az secure ranging parameters to default
3127     aidl_capabilities->akmsSupported = Akm::NONE;
3128     aidl_capabilities->cipherSuitesSupported = CipherSuite::NONE;
3129     aidl_capabilities->secureHeLtfSupported = false;
3130     aidl_capabilities->rangingFrameProtectionSupported = false;
3131     aidl_capabilities->maxSupportedSecureHeLtfProtocolVersion = false;
3132     return true;
3133 }
3134 
convertLegacyRttCapabilitiesV3ToAidl(const legacy_hal::wifi_rtt_capabilities_v3 & legacy_capabilities_v3,RttCapabilities * aidl_capabilities)3135 bool convertLegacyRttCapabilitiesV3ToAidl(
3136         const legacy_hal::wifi_rtt_capabilities_v3& legacy_capabilities_v3,
3137         RttCapabilities* aidl_capabilities) {
3138     if (!aidl_capabilities) {
3139         return false;
3140     }
3141     *aidl_capabilities = {};
3142     aidl_capabilities->rttOneSidedSupported =
3143             legacy_capabilities_v3.rtt_capab.rtt_one_sided_supported;
3144     aidl_capabilities->rttFtmSupported = legacy_capabilities_v3.rtt_capab.rtt_ftm_supported;
3145     aidl_capabilities->lciSupported = legacy_capabilities_v3.rtt_capab.lci_support;
3146     aidl_capabilities->lcrSupported = legacy_capabilities_v3.rtt_capab.lcr_support;
3147     aidl_capabilities->responderSupported = legacy_capabilities_v3.rtt_capab.responder_supported;
3148     aidl_capabilities->preambleSupport =
3149             convertLegacyRttPreambleBitmapToAidl(legacy_capabilities_v3.rtt_capab.preamble_support);
3150     aidl_capabilities->bwSupport =
3151             convertLegacyRttBwBitmapToAidl(legacy_capabilities_v3.rtt_capab.bw_support);
3152     aidl_capabilities->mcVersion = legacy_capabilities_v3.rtt_capab.mc_version;
3153     aidl_capabilities->azPreambleSupport =
3154             (int)convertLegacyRttPreambleBitmapToAidl(legacy_capabilities_v3.az_preamble_support);
3155     aidl_capabilities->azBwSupport =
3156             (int)convertLegacyRttBwBitmapToAidl(legacy_capabilities_v3.az_bw_support);
3157     aidl_capabilities->ntbInitiatorSupported = legacy_capabilities_v3.ntb_initiator_supported;
3158     aidl_capabilities->ntbResponderSupported = legacy_capabilities_v3.ntb_responder_supported;
3159     // Initialize 11az secure ranging parameters to default
3160     aidl_capabilities->akmsSupported = Akm::NONE;
3161     aidl_capabilities->cipherSuitesSupported = CipherSuite::NONE;
3162     aidl_capabilities->secureHeLtfSupported = false;
3163     aidl_capabilities->rangingFrameProtectionSupported = false;
3164     aidl_capabilities->maxSupportedSecureHeLtfProtocolVersion = false;
3165 
3166     return true;
3167 }
3168 
convertLegacyRttCapabilitiesV4ToAidl(const legacy_hal::wifi_rtt_capabilities_v4 & legacy_capabilities_v4,RttCapabilities * aidl_capabilities)3169 bool convertLegacyRttCapabilitiesV4ToAidl(
3170         const legacy_hal::wifi_rtt_capabilities_v4& legacy_capabilities_v4,
3171         RttCapabilities* aidl_capabilities) {
3172     if (!aidl_capabilities) {
3173         return false;
3174     }
3175     *aidl_capabilities = {};
3176     aidl_capabilities->rttOneSidedSupported =
3177             legacy_capabilities_v4.rtt_capab_v3.rtt_capab.rtt_one_sided_supported;
3178     aidl_capabilities->rttFtmSupported =
3179             legacy_capabilities_v4.rtt_capab_v3.rtt_capab.rtt_ftm_supported;
3180     aidl_capabilities->lciSupported = legacy_capabilities_v4.rtt_capab_v3.rtt_capab.lci_support;
3181     aidl_capabilities->lcrSupported = legacy_capabilities_v4.rtt_capab_v3.rtt_capab.lcr_support;
3182     aidl_capabilities->responderSupported =
3183             legacy_capabilities_v4.rtt_capab_v3.rtt_capab.responder_supported;
3184     aidl_capabilities->preambleSupport = convertLegacyRttPreambleBitmapToAidl(
3185             legacy_capabilities_v4.rtt_capab_v3.rtt_capab.preamble_support);
3186     aidl_capabilities->bwSupport = convertLegacyRttBwBitmapToAidl(
3187             legacy_capabilities_v4.rtt_capab_v3.rtt_capab.bw_support);
3188     aidl_capabilities->mcVersion = legacy_capabilities_v4.rtt_capab_v3.rtt_capab.mc_version;
3189     aidl_capabilities->azPreambleSupport = (int)convertLegacyRttPreambleBitmapToAidl(
3190             legacy_capabilities_v4.rtt_capab_v3.az_preamble_support);
3191     aidl_capabilities->azBwSupport =
3192             (int)convertLegacyRttBwBitmapToAidl(legacy_capabilities_v4.rtt_capab_v3.az_bw_support);
3193     aidl_capabilities->ntbInitiatorSupported =
3194             legacy_capabilities_v4.rtt_capab_v3.ntb_initiator_supported;
3195     aidl_capabilities->ntbResponderSupported =
3196             legacy_capabilities_v4.rtt_capab_v3.ntb_responder_supported;
3197     aidl_capabilities->akmsSupported =
3198             convertLegacyAkmsToAidl(legacy_capabilities_v4.supported_akms);
3199     aidl_capabilities->cipherSuitesSupported =
3200             convertLegacyCipherSuitesToAidl(legacy_capabilities_v4.supported_cipher_suites);
3201     aidl_capabilities->secureHeLtfSupported = legacy_capabilities_v4.secure_he_ltf_supported;
3202     aidl_capabilities->rangingFrameProtectionSupported =
3203             legacy_capabilities_v4.ranging_fame_protection_supported;
3204     aidl_capabilities->maxSupportedSecureHeLtfProtocolVersion =
3205             legacy_capabilities_v4.max_supported_secure_he_ltf_protocol_ver;
3206     return true;
3207 }
3208 
convertLegacyWifiRateInfoToAidl(const legacy_hal::wifi_rate & legacy_rate,WifiRateInfo * aidl_rate)3209 bool convertLegacyWifiRateInfoToAidl(const legacy_hal::wifi_rate& legacy_rate,
3210                                      WifiRateInfo* aidl_rate) {
3211     if (!aidl_rate) {
3212         return false;
3213     }
3214     *aidl_rate = {};
3215     aidl_rate->preamble = convertLegacyWifiRatePreambleToAidl(legacy_rate.preamble);
3216     aidl_rate->nss = convertLegacyWifiRateNssToAidl(legacy_rate.nss);
3217     aidl_rate->bw = convertLegacyWifiChannelWidthToAidl(
3218             static_cast<legacy_hal::wifi_channel_width>(legacy_rate.bw));
3219     aidl_rate->rateMcsIdx = legacy_rate.rateMcsIdx;
3220     aidl_rate->bitRateInKbps = legacy_rate.bitrate;
3221     return true;
3222 }
3223 
convertLegacyRttResultToAidl(const legacy_hal::wifi_rtt_result & legacy_result,RttResult * aidl_result)3224 bool convertLegacyRttResultToAidl(const legacy_hal::wifi_rtt_result& legacy_result,
3225                                   RttResult* aidl_result) {
3226     if (!aidl_result) {
3227         return false;
3228     }
3229     *aidl_result = {};
3230     aidl_result->addr = std::array<uint8_t, 6>();
3231     CHECK(sizeof(legacy_result.addr) == aidl_result->addr.size());
3232     std::copy(legacy_result.addr, legacy_result.addr + 6, std::begin(aidl_result->addr));
3233     aidl_result->burstNum = legacy_result.burst_num;
3234     aidl_result->measurementNumber = legacy_result.measurement_number;
3235     aidl_result->successNumber = legacy_result.success_number;
3236     aidl_result->numberPerBurstPeer = legacy_result.number_per_burst_peer;
3237     aidl_result->status = convertLegacyRttStatusToAidl(legacy_result.status);
3238     aidl_result->retryAfterDuration = legacy_result.retry_after_duration;
3239     aidl_result->type = convertLegacyRttTypeToAidl(legacy_result.type);
3240     aidl_result->rssi = legacy_result.rssi;
3241     aidl_result->rssiSpread = legacy_result.rssi_spread;
3242     if (!convertLegacyWifiRateInfoToAidl(legacy_result.tx_rate, &aidl_result->txRate)) {
3243         return false;
3244     }
3245     if (!convertLegacyWifiRateInfoToAidl(legacy_result.rx_rate, &aidl_result->rxRate)) {
3246         return false;
3247     }
3248     aidl_result->rtt = legacy_result.rtt;
3249     aidl_result->rttSd = legacy_result.rtt_sd;
3250     aidl_result->rttSpread = legacy_result.rtt_spread;
3251     aidl_result->distanceInMm = legacy_result.distance_mm;
3252     aidl_result->distanceSdInMm = legacy_result.distance_sd_mm;
3253     aidl_result->distanceSpreadInMm = legacy_result.distance_spread_mm;
3254     aidl_result->timeStampInUs = legacy_result.ts;
3255     aidl_result->burstDurationInMs = legacy_result.burst_duration;
3256     aidl_result->negotiatedBurstNum = legacy_result.negotiated_burst_num;
3257     if (legacy_result.LCI && !convertLegacyIeToAidl(*legacy_result.LCI, &aidl_result->lci)) {
3258         return false;
3259     }
3260     if (legacy_result.LCR && !convertLegacyIeToAidl(*legacy_result.LCR, &aidl_result->lcr)) {
3261         return false;
3262     }
3263     return true;
3264 }
3265 
convertLegacyVectorOfRttResultToAidl(const std::vector<const legacy_hal::wifi_rtt_result * > & legacy_results,std::vector<RttResult> * aidl_results)3266 bool convertLegacyVectorOfRttResultToAidl(
3267         const std::vector<const legacy_hal::wifi_rtt_result*>& legacy_results,
3268         std::vector<RttResult>* aidl_results) {
3269     if (!aidl_results) {
3270         return false;
3271     }
3272     *aidl_results = {};
3273     for (const auto legacy_result : legacy_results) {
3274         RttResult aidl_result;
3275         if (!convertLegacyRttResultToAidl(*legacy_result, &aidl_result)) {
3276             return false;
3277         }
3278         aidl_result.channelFreqMHz = 0;
3279         aidl_result.packetBw = RttBw::BW_UNSPECIFIED;
3280         aidl_result.i2rTxLtfRepetitionCount = 0;
3281         aidl_result.r2iTxLtfRepetitionCount = 0;
3282         aidl_result.ntbMinMeasurementTime = 0;
3283         aidl_result.ntbMaxMeasurementTime = 0;
3284         aidl_result.numTxSpatialStreams = 0;
3285         aidl_result.numRxSpatialStreams = 0;
3286         aidl_result.isRangingFrameProtectionEnabled = false;
3287         aidl_result.isSecureLtfEnabled = false;
3288         aidl_result.baseAkm = Akm::NONE;
3289         aidl_result.cipherSuite = CipherSuite::NONE;
3290         aidl_result.secureHeLtfProtocolVersion = 0;
3291         aidl_result.pasnComebackAfterMillis = 0;
3292         aidl_result.pasnComebackCookie = std::nullopt;
3293         aidl_results->push_back(aidl_result);
3294     }
3295     return true;
3296 }
3297 
convertLegacyVectorOfRttResultV2ToAidl(const std::vector<const legacy_hal::wifi_rtt_result_v2 * > & legacy_results,std::vector<RttResult> * aidl_results)3298 bool convertLegacyVectorOfRttResultV2ToAidl(
3299         const std::vector<const legacy_hal::wifi_rtt_result_v2*>& legacy_results,
3300         std::vector<RttResult>* aidl_results) {
3301     if (!aidl_results) {
3302         return false;
3303     }
3304     *aidl_results = {};
3305     for (const auto legacy_result : legacy_results) {
3306         RttResult aidl_result;
3307         if (!convertLegacyRttResultToAidl(legacy_result->rtt_result, &aidl_result)) {
3308             return false;
3309         }
3310         aidl_result.channelFreqMHz =
3311                 legacy_result->frequency != UNSPECIFIED ? legacy_result->frequency : 0;
3312         aidl_result.packetBw = convertLegacyRttBwToAidl(legacy_result->packet_bw);
3313         aidl_result.i2rTxLtfRepetitionCount = 0;
3314         aidl_result.r2iTxLtfRepetitionCount = 0;
3315         aidl_result.ntbMinMeasurementTime = 0;
3316         aidl_result.ntbMaxMeasurementTime = 0;
3317         aidl_result.numTxSpatialStreams = 0;
3318         aidl_result.numRxSpatialStreams = 0;
3319         aidl_result.isRangingFrameProtectionEnabled = false;
3320         aidl_result.isSecureLtfEnabled = false;
3321         aidl_result.baseAkm = Akm::NONE;
3322         aidl_result.cipherSuite = CipherSuite::NONE;
3323         aidl_result.secureHeLtfProtocolVersion = 0;
3324         aidl_result.pasnComebackAfterMillis = 0;
3325         aidl_result.pasnComebackCookie = std::nullopt;
3326         aidl_results->push_back(aidl_result);
3327     }
3328     return true;
3329 }
3330 
convertLegacyVectorOfRttResultV3ToAidl(const std::vector<const legacy_hal::wifi_rtt_result_v3 * > & legacy_results,std::vector<RttResult> * aidl_results)3331 bool convertLegacyVectorOfRttResultV3ToAidl(
3332         const std::vector<const legacy_hal::wifi_rtt_result_v3*>& legacy_results,
3333         std::vector<RttResult>* aidl_results) {
3334     if (!aidl_results) {
3335         return false;
3336     }
3337     *aidl_results = {};
3338     for (const auto legacy_result : legacy_results) {
3339         RttResult aidl_result;
3340         if (!convertLegacyRttResultToAidl(legacy_result->rtt_result.rtt_result, &aidl_result)) {
3341             return false;
3342         }
3343         aidl_result.channelFreqMHz = legacy_result->rtt_result.frequency != UNSPECIFIED
3344                                              ? legacy_result->rtt_result.frequency
3345                                              : 0;
3346         aidl_result.packetBw = convertLegacyRttBwToAidl(legacy_result->rtt_result.packet_bw);
3347         aidl_result.i2rTxLtfRepetitionCount = legacy_result->i2r_tx_ltf_repetition_count;
3348         aidl_result.r2iTxLtfRepetitionCount = legacy_result->r2i_tx_ltf_repetition_count;
3349         aidl_result.ntbMinMeasurementTime = legacy_result->ntb_min_measurement_time;
3350         aidl_result.ntbMaxMeasurementTime = legacy_result->ntb_max_measurement_time;
3351         aidl_result.numTxSpatialStreams = legacy_result->num_tx_sts;
3352         aidl_result.numRxSpatialStreams = legacy_result->num_rx_sts;
3353         aidl_result.isRangingFrameProtectionEnabled = false;
3354         aidl_result.isSecureLtfEnabled = false;
3355         aidl_result.baseAkm = Akm::NONE;
3356         aidl_result.cipherSuite = CipherSuite::NONE;
3357         aidl_result.secureHeLtfProtocolVersion = 0;
3358         aidl_result.pasnComebackAfterMillis = 0;
3359         aidl_result.pasnComebackCookie = std::nullopt;
3360         aidl_results->push_back(aidl_result);
3361     }
3362     return true;
3363 }
3364 
convertLegacyVectorOfRttResultV4ToAidl(const std::vector<const legacy_hal::wifi_rtt_result_v4 * > & legacy_results,std::vector<RttResult> * aidl_results)3365 bool convertLegacyVectorOfRttResultV4ToAidl(
3366         const std::vector<const legacy_hal::wifi_rtt_result_v4*>& legacy_results,
3367         std::vector<RttResult>* aidl_results) {
3368     if (!aidl_results) {
3369         return false;
3370     }
3371     *aidl_results = {};
3372     for (const auto legacy_result : legacy_results) {
3373         RttResult aidl_result;
3374         if (!convertLegacyRttResultToAidl(legacy_result->rtt_result_v3.rtt_result.rtt_result,
3375                                           &aidl_result)) {
3376             return false;
3377         }
3378         aidl_result.channelFreqMHz =
3379                 legacy_result->rtt_result_v3.rtt_result.frequency != UNSPECIFIED
3380                         ? legacy_result->rtt_result_v3.rtt_result.frequency
3381                         : 0;
3382         aidl_result.packetBw =
3383                 convertLegacyRttBwToAidl(legacy_result->rtt_result_v3.rtt_result.packet_bw);
3384         aidl_result.i2rTxLtfRepetitionCount =
3385                 legacy_result->rtt_result_v3.i2r_tx_ltf_repetition_count;
3386         aidl_result.r2iTxLtfRepetitionCount =
3387                 legacy_result->rtt_result_v3.r2i_tx_ltf_repetition_count;
3388         aidl_result.ntbMinMeasurementTime = legacy_result->rtt_result_v3.ntb_min_measurement_time;
3389         aidl_result.ntbMaxMeasurementTime = legacy_result->rtt_result_v3.ntb_max_measurement_time;
3390         aidl_result.numTxSpatialStreams = legacy_result->rtt_result_v3.num_tx_sts;
3391         aidl_result.numRxSpatialStreams = legacy_result->rtt_result_v3.num_rx_sts;
3392         aidl_result.isRangingFrameProtectionEnabled = legacy_result->is_ranging_protection_enabled;
3393         aidl_result.isSecureLtfEnabled = legacy_result->is_secure_he_ltf_enabled;
3394         aidl_result.baseAkm = convertLegacyAkmsToAidl(legacy_result->base_akm);
3395         aidl_result.cipherSuite = convertLegacyCipherSuitesToAidl(legacy_result->cipher_suite);
3396         aidl_result.secureHeLtfProtocolVersion = legacy_result->secure_he_ltf_protocol_version;
3397         aidl_result.pasnComebackAfterMillis = legacy_result->pasn_comeback_after_millis;
3398         if (legacy_result->pasn_comeback_cookie_len > 0 &&
3399             legacy_result->pasn_comeback_cookie_len <= RTT_MAX_COOKIE_LEN) {
3400             aidl_result.pasnComebackCookie = std::vector<uint8_t>(
3401                     legacy_result->pasn_comeback_cookie,
3402                     legacy_result->pasn_comeback_cookie + legacy_result->pasn_comeback_cookie_len);
3403         }
3404         aidl_results->push_back(aidl_result);
3405     }
3406     return true;
3407 }
3408 
convertAidlIfaceTypeToLegacy(IfaceType aidl_interface_type)3409 legacy_hal::wifi_interface_type convertAidlIfaceTypeToLegacy(IfaceType aidl_interface_type) {
3410     switch (aidl_interface_type) {
3411         case IfaceType::STA:
3412             return legacy_hal::WIFI_INTERFACE_TYPE_STA;
3413         case IfaceType::AP:
3414             return legacy_hal::WIFI_INTERFACE_TYPE_AP;
3415         case IfaceType::P2P:
3416             return legacy_hal::WIFI_INTERFACE_TYPE_P2P;
3417         case IfaceType::NAN_IFACE:
3418             return legacy_hal::WIFI_INTERFACE_TYPE_NAN;
3419     }
3420     CHECK(false);
3421 }
3422 
convertAidlMultiStaUseCaseToLegacy(IWifiChip::MultiStaUseCase use_case)3423 legacy_hal::wifi_multi_sta_use_case convertAidlMultiStaUseCaseToLegacy(
3424         IWifiChip::MultiStaUseCase use_case) {
3425     switch (use_case) {
3426         case IWifiChip::MultiStaUseCase::DUAL_STA_TRANSIENT_PREFER_PRIMARY:
3427             return legacy_hal::WIFI_DUAL_STA_TRANSIENT_PREFER_PRIMARY;
3428         case IWifiChip::MultiStaUseCase::DUAL_STA_NON_TRANSIENT_UNBIASED:
3429             return legacy_hal::WIFI_DUAL_STA_NON_TRANSIENT_UNBIASED;
3430     }
3431     CHECK(false);
3432 }
3433 
convertAidlCoexUnsafeChannelToLegacy(const IWifiChip::CoexUnsafeChannel & aidl_unsafe_channel,legacy_hal::wifi_coex_unsafe_channel * legacy_unsafe_channel)3434 bool convertAidlCoexUnsafeChannelToLegacy(
3435         const IWifiChip::CoexUnsafeChannel& aidl_unsafe_channel,
3436         legacy_hal::wifi_coex_unsafe_channel* legacy_unsafe_channel) {
3437     if (!legacy_unsafe_channel) {
3438         return false;
3439     }
3440     *legacy_unsafe_channel = {};
3441     switch (aidl_unsafe_channel.band) {
3442         case WifiBand::BAND_24GHZ:
3443             legacy_unsafe_channel->band = legacy_hal::WLAN_MAC_2_4_BAND;
3444             break;
3445         case WifiBand::BAND_5GHZ:
3446             legacy_unsafe_channel->band = legacy_hal::WLAN_MAC_5_0_BAND;
3447             break;
3448         default:
3449             return false;
3450     };
3451     legacy_unsafe_channel->channel = aidl_unsafe_channel.channel;
3452     legacy_unsafe_channel->power_cap_dbm = aidl_unsafe_channel.powerCapDbm;
3453     return true;
3454 }
3455 
convertAidlVectorOfCoexUnsafeChannelToLegacy(const std::vector<IWifiChip::CoexUnsafeChannel> & aidl_unsafe_channels,std::vector<legacy_hal::wifi_coex_unsafe_channel> * legacy_unsafe_channels)3456 bool convertAidlVectorOfCoexUnsafeChannelToLegacy(
3457         const std::vector<IWifiChip::CoexUnsafeChannel>& aidl_unsafe_channels,
3458         std::vector<legacy_hal::wifi_coex_unsafe_channel>* legacy_unsafe_channels) {
3459     if (!legacy_unsafe_channels) {
3460         return false;
3461     }
3462     *legacy_unsafe_channels = {};
3463     for (const auto& aidl_unsafe_channel : aidl_unsafe_channels) {
3464         legacy_hal::wifi_coex_unsafe_channel legacy_unsafe_channel;
3465         if (!aidl_struct_util::convertAidlCoexUnsafeChannelToLegacy(aidl_unsafe_channel,
3466                                                                     &legacy_unsafe_channel)) {
3467             return false;
3468         }
3469         legacy_unsafe_channels->push_back(legacy_unsafe_channel);
3470     }
3471     return true;
3472 }
3473 
convertLegacyAntennaConfigurationToAidl(uint32_t antenna_cfg)3474 WifiAntennaMode convertLegacyAntennaConfigurationToAidl(uint32_t antenna_cfg) {
3475     switch (antenna_cfg) {
3476         case legacy_hal::WIFI_ANTENNA_1X1:
3477             return WifiAntennaMode::WIFI_ANTENNA_MODE_1X1;
3478         case legacy_hal::WIFI_ANTENNA_2X2:
3479             return WifiAntennaMode::WIFI_ANTENNA_MODE_2X2;
3480         case legacy_hal::WIFI_ANTENNA_3X3:
3481             return WifiAntennaMode::WIFI_ANTENNA_MODE_3X3;
3482         case legacy_hal::WIFI_ANTENNA_4X4:
3483             return WifiAntennaMode::WIFI_ANTENNA_MODE_4X4;
3484         default:
3485             return WifiAntennaMode::WIFI_ANTENNA_MODE_UNSPECIFIED;
3486     }
3487 }
3488 
convertLegacyWifiRadioConfigurationToAidl(legacy_hal::wifi_radio_configuration * radio_configuration,WifiRadioConfiguration * aidl_radio_configuration)3489 bool convertLegacyWifiRadioConfigurationToAidl(
3490         legacy_hal::wifi_radio_configuration* radio_configuration,
3491         WifiRadioConfiguration* aidl_radio_configuration) {
3492     if (!aidl_radio_configuration) {
3493         return false;
3494     }
3495     *aidl_radio_configuration = {};
3496     aidl_radio_configuration->bandInfo =
3497             aidl_struct_util::convertLegacyMacBandToAidlWifiBand(radio_configuration->band);
3498     if (aidl_radio_configuration->bandInfo == WifiBand::BAND_UNSPECIFIED) {
3499         LOG(ERROR) << "Unspecified band";
3500         return false;
3501     }
3502     aidl_radio_configuration->antennaMode =
3503             aidl_struct_util::convertLegacyAntennaConfigurationToAidl(
3504                     radio_configuration->antenna_cfg);
3505     return true;
3506 }
3507 
convertLegacyRadioCombinationsMatrixToAidl(legacy_hal::wifi_radio_combination_matrix * legacy_matrix,std::vector<WifiRadioCombination> * aidl_combinations)3508 bool convertLegacyRadioCombinationsMatrixToAidl(
3509         legacy_hal::wifi_radio_combination_matrix* legacy_matrix,
3510         std::vector<WifiRadioCombination>* aidl_combinations) {
3511     if (!aidl_combinations || !legacy_matrix) {
3512         return false;
3513     }
3514     *aidl_combinations = {};
3515 
3516     int num_combinations = legacy_matrix->num_radio_combinations;
3517     if (!num_combinations) {
3518         LOG(ERROR) << "zero radio combinations";
3519         return false;
3520     }
3521     wifi_radio_combination* l_radio_combinations_ptr = legacy_matrix->radio_combinations;
3522     for (int i = 0; i < num_combinations; i++) {
3523         int num_configurations = l_radio_combinations_ptr->num_radio_configurations;
3524         WifiRadioCombination radioCombination;
3525         std::vector<WifiRadioConfiguration> radio_configurations_vec;
3526         if (!num_configurations) {
3527             LOG(ERROR) << "zero radio configurations";
3528             return false;
3529         }
3530         for (int j = 0; j < num_configurations; j++) {
3531             WifiRadioConfiguration radioConfiguration;
3532             wifi_radio_configuration* l_radio_configurations_ptr =
3533                     &l_radio_combinations_ptr->radio_configurations[j];
3534             if (!aidl_struct_util::convertLegacyWifiRadioConfigurationToAidl(
3535                         l_radio_configurations_ptr, &radioConfiguration)) {
3536                 LOG(ERROR) << "Error converting wifi radio configuration";
3537                 return false;
3538             }
3539             radio_configurations_vec.push_back(radioConfiguration);
3540         }
3541         radioCombination.radioConfigurations = radio_configurations_vec;
3542         aidl_combinations->push_back(radioCombination);
3543         l_radio_combinations_ptr =
3544                 (wifi_radio_combination*)((u8*)l_radio_combinations_ptr +
3545                                           sizeof(wifi_radio_combination) +
3546                                           (sizeof(wifi_radio_configuration) * num_configurations));
3547     }
3548     return true;
3549 }
3550 
convertAidlNanPairingInitiatorRequestToLegacy(const NanPairingRequest & aidl_request,legacy_hal::NanPairingRequest * legacy_request)3551 bool convertAidlNanPairingInitiatorRequestToLegacy(const NanPairingRequest& aidl_request,
3552                                                    legacy_hal::NanPairingRequest* legacy_request) {
3553     if (!legacy_request) {
3554         LOG(ERROR) << "convertAidlNanPairingInitiatorRequestToLegacy: "
3555                       "legacy_request is null";
3556         return false;
3557     }
3558     *legacy_request = {};
3559 
3560     legacy_request->requestor_instance_id = aidl_request.peerId;
3561     memcpy(legacy_request->peer_disc_mac_addr, aidl_request.peerDiscMacAddr.data(), 6);
3562     legacy_request->nan_pairing_request_type =
3563             convertAidlNanPairingRequestTypeToLegacy(aidl_request.requestType);
3564     legacy_request->enable_pairing_cache = aidl_request.enablePairingCache;
3565 
3566     memcpy(legacy_request->nan_identity_key, aidl_request.pairingIdentityKey.data(),
3567            NAN_IDENTITY_KEY_LEN);
3568 
3569     legacy_request->is_opportunistic =
3570             aidl_request.securityConfig.securityType == NanPairingSecurityType::OPPORTUNISTIC ? 1
3571                                                                                               : 0;
3572     legacy_request->akm = convertAidlAkmTypeToLegacy(aidl_request.securityConfig.akm);
3573     legacy_request->cipher_type = (unsigned int)aidl_request.securityConfig.cipherType;
3574     if (aidl_request.securityConfig.securityType == NanPairingSecurityType::PMK) {
3575         legacy_request->key_info.key_type = legacy_hal::NAN_SECURITY_KEY_INPUT_PMK;
3576         legacy_request->key_info.body.pmk_info.pmk_len = aidl_request.securityConfig.pmk.size();
3577         if (legacy_request->key_info.body.pmk_info.pmk_len != NAN_PMK_INFO_LEN) {
3578             LOG(ERROR) << "convertAidlNanPairingInitiatorRequestToLegacy: "
3579                           "invalid pmk_len";
3580             return false;
3581         }
3582         memcpy(legacy_request->key_info.body.pmk_info.pmk, aidl_request.securityConfig.pmk.data(),
3583                legacy_request->key_info.body.pmk_info.pmk_len);
3584     }
3585     if (aidl_request.securityConfig.securityType == NanPairingSecurityType::PASSPHRASE) {
3586         legacy_request->key_info.key_type = legacy_hal::NAN_SECURITY_KEY_INPUT_PASSPHRASE;
3587         legacy_request->key_info.body.passphrase_info.passphrase_len =
3588                 aidl_request.securityConfig.passphrase.size();
3589         if (legacy_request->key_info.body.passphrase_info.passphrase_len <
3590             NAN_SECURITY_MIN_PASSPHRASE_LEN) {
3591             LOG(ERROR) << "convertAidlNanPairingInitiatorRequestToLegacy: "
3592                           "passphrase_len too small";
3593             return false;
3594         }
3595         if (legacy_request->key_info.body.passphrase_info.passphrase_len >
3596             NAN_SECURITY_MAX_PASSPHRASE_LEN) {
3597             LOG(ERROR) << "convertAidlNanPairingInitiatorRequestToLegacy: "
3598                           "passphrase_len too large";
3599             return false;
3600         }
3601         memcpy(legacy_request->key_info.body.passphrase_info.passphrase,
3602                aidl_request.securityConfig.passphrase.data(),
3603                legacy_request->key_info.body.passphrase_info.passphrase_len);
3604     }
3605 
3606     return true;
3607 }
3608 
convertAidlNanPairingIndicationResponseToLegacy(const NanRespondToPairingIndicationRequest & aidl_request,legacy_hal::NanPairingIndicationResponse * legacy_request)3609 bool convertAidlNanPairingIndicationResponseToLegacy(
3610         const NanRespondToPairingIndicationRequest& aidl_request,
3611         legacy_hal::NanPairingIndicationResponse* legacy_request) {
3612     if (!legacy_request) {
3613         LOG(ERROR) << "convertAidlNanPairingIndicationResponseToLegacy: "
3614                       "legacy_request is null";
3615         return false;
3616     }
3617     *legacy_request = {};
3618 
3619     legacy_request->pairing_instance_id = aidl_request.pairingInstanceId;
3620     legacy_request->nan_pairing_request_type =
3621             convertAidlNanPairingRequestTypeToLegacy(aidl_request.requestType);
3622     legacy_request->enable_pairing_cache = aidl_request.enablePairingCache;
3623 
3624     memcpy(legacy_request->nan_identity_key, aidl_request.pairingIdentityKey.data(),
3625            NAN_IDENTITY_KEY_LEN);
3626 
3627     legacy_request->is_opportunistic =
3628             aidl_request.securityConfig.securityType == NanPairingSecurityType::OPPORTUNISTIC ? 1
3629                                                                                               : 0;
3630     legacy_request->akm = convertAidlAkmTypeToLegacy(aidl_request.securityConfig.akm);
3631     legacy_request->cipher_type = (unsigned int)aidl_request.securityConfig.cipherType;
3632     legacy_request->rsp_code =
3633             aidl_request.acceptRequest ? NAN_PAIRING_REQUEST_ACCEPT : NAN_PAIRING_REQUEST_REJECT;
3634     if (aidl_request.securityConfig.securityType == NanPairingSecurityType::PMK) {
3635         legacy_request->key_info.key_type = legacy_hal::NAN_SECURITY_KEY_INPUT_PMK;
3636         legacy_request->key_info.body.pmk_info.pmk_len = aidl_request.securityConfig.pmk.size();
3637         if (legacy_request->key_info.body.pmk_info.pmk_len != NAN_PMK_INFO_LEN) {
3638             LOG(ERROR) << "convertAidlNanPairingIndicationResponseToLegacy: "
3639                           "invalid pmk_len";
3640             return false;
3641         }
3642         memcpy(legacy_request->key_info.body.pmk_info.pmk, aidl_request.securityConfig.pmk.data(),
3643                legacy_request->key_info.body.pmk_info.pmk_len);
3644     }
3645     if (aidl_request.securityConfig.securityType == NanPairingSecurityType::PASSPHRASE) {
3646         legacy_request->key_info.key_type = legacy_hal::NAN_SECURITY_KEY_INPUT_PASSPHRASE;
3647         legacy_request->key_info.body.passphrase_info.passphrase_len =
3648                 aidl_request.securityConfig.passphrase.size();
3649         if (legacy_request->key_info.body.passphrase_info.passphrase_len <
3650             NAN_SECURITY_MIN_PASSPHRASE_LEN) {
3651             LOG(ERROR) << "convertAidlNanPairingIndicationResponseToLegacy: "
3652                           "passphrase_len too small";
3653             return false;
3654         }
3655         if (legacy_request->key_info.body.passphrase_info.passphrase_len >
3656             NAN_SECURITY_MAX_PASSPHRASE_LEN) {
3657             LOG(ERROR) << "convertAidlNanPairingIndicationResponseToLegacy: "
3658                           "passphrase_len too large";
3659             return false;
3660         }
3661         memcpy(legacy_request->key_info.body.passphrase_info.passphrase,
3662                aidl_request.securityConfig.passphrase.data(),
3663                legacy_request->key_info.body.passphrase_info.passphrase_len);
3664     }
3665 
3666     return true;
3667 }
3668 
convertAidlNanBootstrappingInitiatorRequestToLegacy(const NanBootstrappingRequest & aidl_request,legacy_hal::NanBootstrappingRequest * legacy_request)3669 bool convertAidlNanBootstrappingInitiatorRequestToLegacy(
3670         const NanBootstrappingRequest& aidl_request,
3671         legacy_hal::NanBootstrappingRequest* legacy_request) {
3672     if (!legacy_request) {
3673         LOG(ERROR) << "convertAidlNanBootstrappingInitiatorRequestToLegacy: "
3674                       "legacy_request is null";
3675         return false;
3676     }
3677     *legacy_request = {};
3678 
3679     legacy_request->requestor_instance_id = aidl_request.peerId;
3680     memcpy(legacy_request->peer_disc_mac_addr, aidl_request.peerDiscMacAddr.data(), 6);
3681     legacy_request->request_bootstrapping_method =
3682             convertAidlBootstrappingMethodToLegacy(aidl_request.requestBootstrappingMethod);
3683     legacy_request->cookie_length = aidl_request.cookie.size();
3684 
3685     memcpy(legacy_request->cookie, aidl_request.cookie.data(), legacy_request->cookie_length);
3686     legacy_request->publish_subscribe_id = static_cast<uint8_t>(aidl_request.discoverySessionId);
3687     legacy_request->comeback = aidl_request.isComeback ? 0x1 : 0x0;
3688 
3689     return true;
3690 }
3691 
convertAidlNanBootstrappingIndicationResponseToLegacy(const NanBootstrappingResponse & aidl_request,legacy_hal::NanBootstrappingIndicationResponse * legacy_request)3692 bool convertAidlNanBootstrappingIndicationResponseToLegacy(
3693         const NanBootstrappingResponse& aidl_request,
3694         legacy_hal::NanBootstrappingIndicationResponse* legacy_request) {
3695     if (!legacy_request) {
3696         LOG(ERROR) << "convertAidlNanBootstrappingIndicationResponseToLegacy: "
3697                       "legacy_request is null";
3698         return false;
3699     }
3700     *legacy_request = {};
3701 
3702     legacy_request->service_instance_id = aidl_request.bootstrappingInstanceId;
3703     legacy_request->bootstrapping_instance_id = aidl_request.bootstrappingInstanceId;
3704     legacy_request->rsp_code = aidl_request.acceptRequest ? NAN_BOOTSTRAPPING_REQUEST_ACCEPT
3705                                                           : NAN_BOOTSTRAPPING_REQUEST_REJECT;
3706     legacy_request->publish_subscribe_id = static_cast<uint8_t>(aidl_request.discoverySessionId);
3707 
3708     return true;
3709 }
3710 
convertLegacyNanPairingRequestIndToAidl(const legacy_hal::NanPairingRequestInd & legacy_ind,NanPairingRequestInd * aidl_ind)3711 bool convertLegacyNanPairingRequestIndToAidl(const legacy_hal::NanPairingRequestInd& legacy_ind,
3712                                              NanPairingRequestInd* aidl_ind) {
3713     if (!aidl_ind) {
3714         LOG(ERROR) << "convertLegacyNanPairingRequestIndToAidl: aidl_ind is null";
3715         return false;
3716     }
3717     *aidl_ind = {};
3718 
3719     aidl_ind->discoverySessionId = legacy_ind.publish_subscribe_id;
3720     aidl_ind->peerId = legacy_ind.requestor_instance_id;
3721     aidl_ind->peerDiscMacAddr = std::array<uint8_t, 6>();
3722     std::copy(legacy_ind.peer_disc_mac_addr, legacy_ind.peer_disc_mac_addr + 6,
3723               std::begin(aidl_ind->peerDiscMacAddr));
3724     aidl_ind->pairingInstanceId = legacy_ind.pairing_instance_id;
3725     aidl_ind->enablePairingCache = legacy_ind.enable_pairing_cache == 1;
3726     aidl_ind->requestType =
3727             convertLegacyNanPairingRequestTypeToAidl(legacy_ind.nan_pairing_request_type);
3728     if (!convertLegacyNiraToAidl(legacy_ind.nira, &aidl_ind->peerNira)) {
3729         return false;
3730     }
3731     return true;
3732 }
3733 
convertLegacyNanPairingConfirmIndToAidl(const legacy_hal::NanPairingConfirmInd & legacy_ind,NanPairingConfirmInd * aidl_ind)3734 bool convertLegacyNanPairingConfirmIndToAidl(const legacy_hal::NanPairingConfirmInd& legacy_ind,
3735                                              NanPairingConfirmInd* aidl_ind) {
3736     if (!aidl_ind) {
3737         LOG(ERROR) << "convertLegacyNanPairingRequestIndToAidl: aidl_ind is null";
3738         return false;
3739     }
3740     *aidl_ind = {};
3741 
3742     aidl_ind->pairingInstanceId = legacy_ind.pairing_instance_id;
3743     aidl_ind->enablePairingCache = legacy_ind.enable_pairing_cache == 1;
3744     aidl_ind->requestType =
3745             convertLegacyNanPairingRequestTypeToAidl(legacy_ind.nan_pairing_request_type);
3746     aidl_ind->pairingSuccess = legacy_ind.rsp_code == NAN_PAIRING_REQUEST_ACCEPT;
3747     aidl_ind->status.status = convertLegacyNanStatusTypeToAidl(legacy_ind.reason_code);
3748     if (!convertLegacyNpsaToAidl(legacy_ind.npk_security_association, &aidl_ind->npksa)) {
3749         return false;
3750     }
3751     return true;
3752 }
3753 
convertLegacyNanBootstrappingRequestIndToAidl(const legacy_hal::NanBootstrappingRequestInd & legacy_ind,NanBootstrappingRequestInd * aidl_ind)3754 bool convertLegacyNanBootstrappingRequestIndToAidl(
3755         const legacy_hal::NanBootstrappingRequestInd& legacy_ind,
3756         NanBootstrappingRequestInd* aidl_ind) {
3757     if (!aidl_ind) {
3758         LOG(ERROR) << "convertLegacyNanBootstrappingRequestIndToAidl: aidl_ind is null";
3759         return false;
3760     }
3761     *aidl_ind = {};
3762 
3763     aidl_ind->discoverySessionId = legacy_ind.publish_subscribe_id;
3764     aidl_ind->peerId = legacy_ind.requestor_instance_id;
3765     aidl_ind->peerDiscMacAddr = std::array<uint8_t, 6>();
3766     std::copy(legacy_ind.peer_disc_mac_addr, legacy_ind.peer_disc_mac_addr + 6,
3767               std::begin(aidl_ind->peerDiscMacAddr));
3768     aidl_ind->bootstrappingInstanceId = legacy_ind.bootstrapping_instance_id;
3769     aidl_ind->requestBootstrappingMethod =
3770             convertLegacyBootstrappingMethodToAidl(legacy_ind.request_bootstrapping_method);
3771     return true;
3772 }
3773 
convertLegacyNanBootstrappingConfirmIndToAidl(const legacy_hal::NanBootstrappingConfirmInd & legacy_ind,NanBootstrappingConfirmInd * aidl_ind)3774 bool convertLegacyNanBootstrappingConfirmIndToAidl(
3775         const legacy_hal::NanBootstrappingConfirmInd& legacy_ind,
3776         NanBootstrappingConfirmInd* aidl_ind) {
3777     if (!aidl_ind) {
3778         LOG(ERROR) << "convertLegacyNanBootstrappingConfirmIndToAidl: aidl_ind is null";
3779         return false;
3780     }
3781     *aidl_ind = {};
3782 
3783     aidl_ind->bootstrappingInstanceId = legacy_ind.bootstrapping_instance_id;
3784     aidl_ind->responseCode = static_cast<NanBootstrappingResponseCode>(legacy_ind.rsp_code);
3785     aidl_ind->reasonCode.status = convertLegacyNanStatusTypeToAidl(legacy_ind.reason_code);
3786     aidl_ind->comeBackDelay = legacy_ind.come_back_delay;
3787     aidl_ind->cookie =
3788             std::vector<uint8_t>(legacy_ind.cookie, legacy_ind.cookie + legacy_ind.cookie_length);
3789     return true;
3790 }
3791 
convertLegacyWifiChipCapabilitiesToAidl(const legacy_hal::wifi_chip_capabilities & legacy_chip_capabilities,WifiChipCapabilities & aidl_chip_capabilities)3792 bool convertLegacyWifiChipCapabilitiesToAidl(
3793         const legacy_hal::wifi_chip_capabilities& legacy_chip_capabilities,
3794         WifiChipCapabilities& aidl_chip_capabilities) {
3795     aidl_chip_capabilities.maxMloStrLinkCount = legacy_chip_capabilities.max_mlo_str_link_count;
3796     aidl_chip_capabilities.maxMloAssociationLinkCount =
3797             legacy_chip_capabilities.max_mlo_association_link_count;
3798     aidl_chip_capabilities.maxConcurrentTdlsSessionCount =
3799             legacy_chip_capabilities.max_concurrent_tdls_session_count;
3800     return true;
3801 }
3802 
convertAidlChannelCategoryToLegacy(uint32_t aidl_channel_category_mask)3803 uint32_t convertAidlChannelCategoryToLegacy(uint32_t aidl_channel_category_mask) {
3804     uint32_t channel_category_mask = 0;
3805     if (aidl_channel_category_mask &
3806         static_cast<int32_t>(IWifiChip::ChannelCategoryMask::INDOOR_CHANNEL)) {
3807         channel_category_mask |= legacy_hal::WIFI_INDOOR_CHANNEL;
3808     }
3809     if (aidl_channel_category_mask &
3810         static_cast<int32_t>(IWifiChip::ChannelCategoryMask::DFS_CHANNEL)) {
3811         channel_category_mask |= legacy_hal::WIFI_DFS_CHANNEL;
3812     }
3813     return channel_category_mask;
3814 }
3815 
convertLegacyIfaceMaskToIfaceConcurrencyType(u32 mask,std::vector<IfaceConcurrencyType> * types)3816 bool convertLegacyIfaceMaskToIfaceConcurrencyType(u32 mask,
3817                                                   std::vector<IfaceConcurrencyType>* types) {
3818     if (!mask) return false;
3819 
3820 #ifndef BIT
3821 #define BIT(x) (1 << (x))
3822 #endif
3823     if (mask & BIT(WIFI_INTERFACE_TYPE_STA)) types->push_back(IfaceConcurrencyType::STA);
3824     if (mask & BIT(WIFI_INTERFACE_TYPE_AP)) types->push_back(IfaceConcurrencyType::AP);
3825     if (mask & BIT(WIFI_INTERFACE_TYPE_AP_BRIDGED))
3826         types->push_back(IfaceConcurrencyType::AP_BRIDGED);
3827     if (mask & BIT(WIFI_INTERFACE_TYPE_P2P)) types->push_back(IfaceConcurrencyType::P2P);
3828     if (mask & BIT(WIFI_INTERFACE_TYPE_NAN)) types->push_back(IfaceConcurrencyType::NAN_IFACE);
3829 
3830     return true;
3831 }
3832 
convertLegacyIfaceCombinationsMatrixToChipMode(legacy_hal::wifi_iface_concurrency_matrix & legacy_matrix,IWifiChip::ChipMode * chip_mode)3833 bool convertLegacyIfaceCombinationsMatrixToChipMode(
3834         legacy_hal::wifi_iface_concurrency_matrix& legacy_matrix, IWifiChip::ChipMode* chip_mode) {
3835     if (!chip_mode) {
3836         LOG(ERROR) << "chip_mode is null";
3837         return false;
3838     }
3839     *chip_mode = {};
3840 
3841     int num_combinations = legacy_matrix.num_iface_combinations;
3842     std::vector<IWifiChip::ChipConcurrencyCombination> driver_Combinations_vec;
3843     if (!num_combinations) {
3844         LOG(ERROR) << "zero iface combinations";
3845         return false;
3846     }
3847 
3848     for (int i = 0; i < num_combinations; i++) {
3849         IWifiChip::ChipConcurrencyCombination chipComb;
3850         std::vector<IWifiChip::ChipConcurrencyCombinationLimit> limits;
3851         wifi_iface_combination* comb = &legacy_matrix.iface_combinations[i];
3852         if (!comb->num_iface_limits) continue;
3853         for (u32 j = 0; j < comb->num_iface_limits; j++) {
3854             IWifiChip::ChipConcurrencyCombinationLimit chipLimit;
3855             chipLimit.maxIfaces = comb->iface_limits[j].max_limit;
3856             std::vector<IfaceConcurrencyType> types;
3857             if (!convertLegacyIfaceMaskToIfaceConcurrencyType(comb->iface_limits[j].iface_mask,
3858                                                               &types)) {
3859                 LOG(ERROR) << "Failed to convert from iface_mask:"
3860                            << comb->iface_limits[j].iface_mask;
3861                 return false;
3862             }
3863             chipLimit.types = types;
3864             limits.push_back(chipLimit);
3865         }
3866         chipComb.limits = limits;
3867         driver_Combinations_vec.push_back(chipComb);
3868     }
3869 
3870     chip_mode->availableCombinations = driver_Combinations_vec;
3871     return true;
3872 }
3873 
convertCachedScanReportToAidl(const legacy_hal::WifiCachedScanReport & report,CachedScanData * aidl_scan_data)3874 bool convertCachedScanReportToAidl(const legacy_hal::WifiCachedScanReport& report,
3875                                    CachedScanData* aidl_scan_data) {
3876     if (!aidl_scan_data) {
3877         return false;
3878     }
3879     *aidl_scan_data = {};
3880 
3881     std::vector<CachedScanResult> aidl_scan_results;
3882     for (const auto& result : report.results) {
3883         CachedScanResult aidl_scan_result;
3884         if (!convertCachedScanResultToAidl(result, report.ts, &aidl_scan_result)) {
3885             return false;
3886         }
3887         aidl_scan_results.push_back(aidl_scan_result);
3888     }
3889     aidl_scan_data->cachedScanResults = aidl_scan_results;
3890 
3891     aidl_scan_data->scannedFrequenciesMhz = report.scanned_freqs;
3892     return true;
3893 }
3894 
convertCachedScanResultToAidl(const legacy_hal::wifi_cached_scan_result & legacy_scan_result,uint64_t ts_us,CachedScanResult * aidl_scan_result)3895 bool convertCachedScanResultToAidl(const legacy_hal::wifi_cached_scan_result& legacy_scan_result,
3896                                    uint64_t ts_us, CachedScanResult* aidl_scan_result) {
3897     if (!aidl_scan_result) {
3898         return false;
3899     }
3900     *aidl_scan_result = {};
3901     // Ensure that subtracting does not result in a negative value
3902     uint64_t age_us = static_cast<uint64_t>(legacy_scan_result.age_ms) * 1000;
3903     if (ts_us < age_us) {
3904         aidl_scan_result->timeStampInUs = 0;
3905         return false;
3906     }
3907     aidl_scan_result->timeStampInUs = ts_us - age_us;
3908     size_t max_len_excluding_null = sizeof(legacy_scan_result.ssid) - 1;
3909     size_t ssid_len = strnlen((const char*)legacy_scan_result.ssid, max_len_excluding_null);
3910     aidl_scan_result->ssid =
3911             std::vector<uint8_t>(legacy_scan_result.ssid, legacy_scan_result.ssid + ssid_len);
3912     aidl_scan_result->bssid = std::array<uint8_t, 6>();
3913     std::copy(legacy_scan_result.bssid, legacy_scan_result.bssid + 6,
3914               std::begin(aidl_scan_result->bssid));
3915     aidl_scan_result->frequencyMhz = legacy_scan_result.chanspec.primary_frequency;
3916     aidl_scan_result->channelWidthMhz =
3917             convertLegacyWifiChannelWidthToAidl(legacy_scan_result.chanspec.width);
3918     aidl_scan_result->rssiDbm = legacy_scan_result.rssi;
3919     aidl_scan_result->preambleType = convertScanResultFlagsToPreambleType(legacy_scan_result.flags);
3920     return true;
3921 }
3922 
convertScanResultFlagsToPreambleType(int flags)3923 WifiRatePreamble convertScanResultFlagsToPreambleType(int flags) {
3924     if ((flags & WIFI_CACHED_SCAN_RESULT_FLAGS_EHT_OPS_PRESENT) > 0) {
3925         return WifiRatePreamble::EHT;
3926     }
3927     if ((flags & WIFI_CACHED_SCAN_RESULT_FLAGS_HE_OPS_PRESENT) > 0) {
3928         return WifiRatePreamble::HE;
3929     }
3930     if ((flags & WIFI_CACHED_SCAN_RESULT_FLAGS_VHT_OPS_PRESENT) > 0) {
3931         return WifiRatePreamble::VHT;
3932     }
3933     if ((flags & WIFI_CACHED_SCAN_RESULT_FLAGS_HT_OPS_PRESENT) > 0) {
3934         return WifiRatePreamble::HT;
3935     }
3936     return WifiRatePreamble::OFDM;
3937 }
3938 
convertTwtCapabilitiesToAidl(legacy_hal::wifi_twt_capabilities legacy_twt_capabs,TwtCapabilities * aidl_twt_capabs)3939 bool convertTwtCapabilitiesToAidl(legacy_hal::wifi_twt_capabilities legacy_twt_capabs,
3940                                   TwtCapabilities* aidl_twt_capabs) {
3941     if (!aidl_twt_capabs) {
3942         return false;
3943     }
3944     aidl_twt_capabs->isTwtRequesterSupported = legacy_twt_capabs.is_twt_requester_supported;
3945     aidl_twt_capabs->isTwtResponderSupported = legacy_twt_capabs.is_twt_responder_supported;
3946     aidl_twt_capabs->isBroadcastTwtSupported = legacy_twt_capabs.is_flexible_twt_supported;
3947     if (legacy_twt_capabs.min_wake_duration_micros > legacy_twt_capabs.max_wake_duration_micros) {
3948         return false;
3949     }
3950     aidl_twt_capabs->minWakeDurationUs = legacy_twt_capabs.min_wake_duration_micros;
3951     aidl_twt_capabs->maxWakeDurationUs = legacy_twt_capabs.max_wake_duration_micros;
3952     if (legacy_twt_capabs.min_wake_interval_micros > legacy_twt_capabs.max_wake_interval_micros) {
3953         return false;
3954     }
3955     aidl_twt_capabs->minWakeIntervalUs = legacy_twt_capabs.min_wake_interval_micros;
3956     aidl_twt_capabs->maxWakeIntervalUs = legacy_twt_capabs.max_wake_interval_micros;
3957     return true;
3958 }
3959 
convertAidlTwtRequestToLegacy(const TwtRequest aidl_twt_request,legacy_hal::wifi_twt_request * legacy_twt_request)3960 bool convertAidlTwtRequestToLegacy(const TwtRequest aidl_twt_request,
3961                                    legacy_hal::wifi_twt_request* legacy_twt_request) {
3962     if (legacy_twt_request == nullptr) {
3963         return false;
3964     }
3965     legacy_twt_request->mlo_link_id = aidl_twt_request.mloLinkId;
3966     if (aidl_twt_request.minWakeDurationUs > aidl_twt_request.maxWakeDurationUs) {
3967         return false;
3968     }
3969     legacy_twt_request->min_wake_duration_micros = aidl_twt_request.minWakeDurationUs;
3970     legacy_twt_request->max_wake_duration_micros = aidl_twt_request.maxWakeDurationUs;
3971     if (aidl_twt_request.minWakeIntervalUs > aidl_twt_request.maxWakeIntervalUs) {
3972         return false;
3973     }
3974     legacy_twt_request->min_wake_interval_micros = aidl_twt_request.minWakeIntervalUs;
3975     legacy_twt_request->max_wake_interval_micros = aidl_twt_request.maxWakeIntervalUs;
3976     return true;
3977 }
3978 
convertLegacyHalTwtErrorCodeToAidl(legacy_hal::wifi_twt_error_code legacy_error_code)3979 IWifiStaIfaceEventCallback::TwtErrorCode convertLegacyHalTwtErrorCodeToAidl(
3980         legacy_hal::wifi_twt_error_code legacy_error_code) {
3981     switch (legacy_error_code) {
3982         case WIFI_TWT_ERROR_CODE_TIMEOUT:
3983             return IWifiStaIfaceEventCallback::TwtErrorCode::TIMEOUT;
3984         case WIFI_TWT_ERROR_CODE_PEER_REJECTED:
3985             return IWifiStaIfaceEventCallback::TwtErrorCode::PEER_REJECTED;
3986         case WIFI_TWT_ERROR_CODE_PEER_NOT_SUPPORTED:
3987             return IWifiStaIfaceEventCallback::TwtErrorCode::PEER_NOT_SUPPORTED;
3988         case WIFI_TWT_ERROR_CODE_NOT_SUPPORTED:
3989             return IWifiStaIfaceEventCallback::TwtErrorCode::NOT_SUPPORTED;
3990         case WIFI_TWT_ERROR_CODE_NOT_AVAILABLE:
3991             return IWifiStaIfaceEventCallback::TwtErrorCode::NOT_AVAILABLE;
3992         case WIFI_TWT_ERROR_CODE_MAX_SESSION_REACHED:
3993             return IWifiStaIfaceEventCallback::TwtErrorCode::MAX_SESSION_REACHED;
3994         case WIFI_TWT_ERROR_CODE_INVALID_PARAMS:
3995             return IWifiStaIfaceEventCallback::TwtErrorCode::INVALID_PARAMS;
3996         case WIFI_TWT_ERROR_CODE_ALREADY_SUSPENDED:
3997             return IWifiStaIfaceEventCallback::TwtErrorCode::ALREADY_SUSPENDED;
3998         case WIFI_TWT_ERROR_CODE_ALREADY_RESUMED:
3999             return IWifiStaIfaceEventCallback::TwtErrorCode::ALREADY_RESUMED;
4000         default:
4001             return IWifiStaIfaceEventCallback::TwtErrorCode::FAILURE_UNKNOWN;
4002     }
4003 }
4004 
convertLegacyHalTwtReasonCodeToAidl(legacy_hal::wifi_twt_teardown_reason_code legacy_reason_code)4005 IWifiStaIfaceEventCallback::TwtTeardownReasonCode convertLegacyHalTwtReasonCodeToAidl(
4006         legacy_hal::wifi_twt_teardown_reason_code legacy_reason_code) {
4007     switch (legacy_reason_code) {
4008         case WIFI_TWT_TEARDOWN_REASON_CODE_LOCALLY_REQUESTED:
4009             return IWifiStaIfaceEventCallback::TwtTeardownReasonCode::LOCALLY_REQUESTED;
4010         case WIFI_TWT_TEARDOWN_REASON_CODE_INTERNALLY_INITIATED:
4011             return IWifiStaIfaceEventCallback::TwtTeardownReasonCode::INTERNALLY_INITIATED;
4012         case WIFI_TWT_TEARDOWN_REASON_CODE_PEER_INITIATED:
4013             return IWifiStaIfaceEventCallback::TwtTeardownReasonCode::PEER_INITIATED;
4014         default:
4015             return IWifiStaIfaceEventCallback::TwtTeardownReasonCode::UNKNOWN;
4016     }
4017 }
4018 
convertLegacyHalTwtSessionToAidl(legacy_hal::wifi_twt_session twt_session,TwtSession * aidl_twt_session)4019 bool convertLegacyHalTwtSessionToAidl(legacy_hal::wifi_twt_session twt_session,
4020                                       TwtSession* aidl_twt_session) {
4021     if (aidl_twt_session == nullptr) {
4022         return false;
4023     }
4024 
4025     aidl_twt_session->sessionId = twt_session.session_id;
4026     aidl_twt_session->mloLinkId = twt_session.mlo_link_id;
4027     aidl_twt_session->wakeDurationUs = twt_session.wake_duration_micros;
4028     aidl_twt_session->wakeIntervalUs = twt_session.wake_interval_micros;
4029     switch (twt_session.negotiation_type) {
4030         case WIFI_TWT_NEGO_TYPE_INDIVIDUAL:
4031             aidl_twt_session->negotiationType = TwtSession::TwtNegotiationType::INDIVIDUAL;
4032             break;
4033         case WIFI_TWT_NEGO_TYPE_BROADCAST:
4034             aidl_twt_session->negotiationType = TwtSession::TwtNegotiationType::BROADCAST;
4035             break;
4036         default:
4037             return false;
4038     }
4039     aidl_twt_session->isTriggerEnabled = twt_session.is_trigger_enabled;
4040     aidl_twt_session->isAnnounced = twt_session.is_announced;
4041     aidl_twt_session->isImplicit = twt_session.is_implicit;
4042     aidl_twt_session->isProtected = twt_session.is_protected;
4043     aidl_twt_session->isUpdatable = twt_session.is_updatable;
4044     aidl_twt_session->isSuspendable = twt_session.is_suspendable;
4045     aidl_twt_session->isResponderPmModeEnabled = twt_session.is_responder_pm_mode_enabled;
4046     return true;
4047 }
4048 
convertLegacyHalTwtSessionStatsToAidl(legacy_hal::wifi_twt_session_stats twt_stats,TwtSessionStats * aidl_twt_stats)4049 bool convertLegacyHalTwtSessionStatsToAidl(legacy_hal::wifi_twt_session_stats twt_stats,
4050                                            TwtSessionStats* aidl_twt_stats) {
4051     if (aidl_twt_stats == nullptr) {
4052         return false;
4053     }
4054 
4055     aidl_twt_stats->avgTxPktCount = twt_stats.avg_pkt_num_tx;
4056     aidl_twt_stats->avgRxPktCount = twt_stats.avg_pkt_num_rx;
4057     aidl_twt_stats->avgTxPktSize = twt_stats.avg_tx_pkt_size;
4058     aidl_twt_stats->avgRxPktSize = twt_stats.avg_rx_pkt_size;
4059     aidl_twt_stats->avgEospDurationUs = twt_stats.avg_eosp_dur_us;
4060     aidl_twt_stats->eospCount = twt_stats.eosp_count;
4061 
4062     return true;
4063 }
4064 
4065 }  // namespace aidl_struct_util
4066 }  // namespace wifi
4067 }  // namespace hardware
4068 }  // namespace android
4069 }  // namespace aidl
4070