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