1 /* 2 * Copyright (C) 2021 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 package android.net.vcn.persistablebundleutils; 18 19 import static com.android.internal.annotations.VisibleForTesting.Visibility; 20 21 import android.annotation.NonNull; 22 import android.net.InetAddresses; 23 import android.net.ipsec.ike.IkeTrafficSelector; 24 import android.os.PersistableBundle; 25 26 import com.android.internal.annotations.VisibleForTesting; 27 28 import java.util.Objects; 29 30 /** 31 * Provides utility methods to convert IkeTrafficSelector to/from PersistableBundle. 32 * 33 * @hide 34 */ 35 @VisibleForTesting(visibility = Visibility.PRIVATE) 36 public final class IkeTrafficSelectorUtils { 37 private static final String START_PORT_KEY = "START_PORT_KEY"; 38 private static final String END_PORT_KEY = "END_PORT_KEY"; 39 private static final String START_ADDRESS_KEY = "START_ADDRESS_KEY"; 40 private static final String END_ADDRESS_KEY = "END_ADDRESS_KEY"; 41 42 /** Constructs an IkeTrafficSelector by deserializing a PersistableBundle. */ 43 @NonNull fromPersistableBundle(@onNull PersistableBundle in)44 public static IkeTrafficSelector fromPersistableBundle(@NonNull PersistableBundle in) { 45 Objects.requireNonNull(in, "PersistableBundle was null"); 46 47 final int startPort = in.getInt(START_PORT_KEY); 48 final int endPort = in.getInt(END_PORT_KEY); 49 50 final String startingAddress = in.getString(START_ADDRESS_KEY); 51 final String endingAddress = in.getString(END_ADDRESS_KEY); 52 Objects.requireNonNull(startingAddress, "startAddress was null"); 53 Objects.requireNonNull(startingAddress, "endAddress was null"); 54 55 return new IkeTrafficSelector( 56 startPort, 57 endPort, 58 InetAddresses.parseNumericAddress(startingAddress), 59 InetAddresses.parseNumericAddress(endingAddress)); 60 } 61 62 /** Serializes an IkeTrafficSelector to a PersistableBundle. */ 63 @NonNull toPersistableBundle(@onNull IkeTrafficSelector ts)64 public static PersistableBundle toPersistableBundle(@NonNull IkeTrafficSelector ts) { 65 final PersistableBundle result = new PersistableBundle(); 66 67 result.putInt(START_PORT_KEY, ts.startPort); 68 result.putInt(END_PORT_KEY, ts.endPort); 69 result.putString(START_ADDRESS_KEY, ts.startingAddress.getHostAddress()); 70 result.putString(END_ADDRESS_KEY, ts.endingAddress.getHostAddress()); 71 72 return result; 73 } 74 } 75