blob: 9c01ddaf192556cc03f4f7ece76a46ea683e3757 [file] [log] [blame]
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001/*
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002 * Copyright (C) 2021 The Android Open Source Project
Irfan Sheriff77ec5582012-03-22 17:01:39 -07003 *
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
17package com.android.server;
18
Yuyang Huangd5896e72023-11-28 13:23:59 +090019import static android.Manifest.permission.DEVICE_POWER;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090020import static android.Manifest.permission.NETWORK_SETTINGS;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090021import static android.Manifest.permission.NETWORK_STACK;
paulhu2b9ed952022-02-10 21:58:32 +080022import static android.net.ConnectivityManager.NETID_UNSET;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090023import static android.net.NetworkCapabilities.TRANSPORT_VPN;
24import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090025import static android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK;
Paul Hu019621e2023-01-13 23:26:49 +080026import static android.net.nsd.NsdManager.MDNS_DISCOVERY_MANAGER_EVENT;
paulhu2b9ed952022-02-10 21:58:32 +080027import static android.net.nsd.NsdManager.MDNS_SERVICE_EVENT;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +090028import static android.net.nsd.NsdManager.RESOLVE_SERVICE_SUCCEEDED;
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +090029import static android.provider.DeviceConfig.NAMESPACE_TETHERING;
Motomu Utsumied4e7ec2023-09-13 14:58:32 +090030
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090031import static com.android.modules.utils.build.SdkLevel.isAtLeastU;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090032import static com.android.networkstack.apishim.ConstantsShim.REGISTER_NSD_OFFLOAD_ENGINE;
Paul Hu043bcd42023-07-14 16:38:25 +080033import static com.android.server.connectivity.mdns.MdnsAdvertiser.AdvertiserMetrics;
34import static com.android.server.connectivity.mdns.MdnsConstants.NO_PACKET;
Yuyang Huangde802c82023-05-02 17:14:22 +090035import static com.android.server.connectivity.mdns.MdnsRecord.MAX_LABEL_LENGTH;
Paul Hucdef3532023-06-18 14:47:35 +000036import static com.android.server.connectivity.mdns.util.MdnsUtils.Clock;
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090037
Paul Hu23fa2022023-01-13 22:57:24 +080038import android.annotation.NonNull;
Paul Hu4bd98ef2023-01-12 13:42:07 +080039import android.annotation.Nullable;
Yuyang Huangfc831702023-08-21 17:48:48 +090040import android.annotation.RequiresApi;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090041import android.app.ActivityManager;
paulhua262cc12019-08-12 16:25:11 +080042import android.content.Context;
Irfan Sheriff75006652012-04-17 23:15:29 -070043import android.content.Intent;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090044import android.net.ConnectivityManager;
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +090045import android.net.INetd;
Paul Hu75069ed2023-01-14 00:31:09 +080046import android.net.InetAddresses;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090047import android.net.LinkProperties;
48import android.net.Network;
paulhu2b9ed952022-02-10 21:58:32 +080049import android.net.mdns.aidl.DiscoveryInfo;
50import android.net.mdns.aidl.GetAddressInfo;
51import android.net.mdns.aidl.IMDnsEventListener;
52import android.net.mdns.aidl.RegistrationInfo;
53import android.net.mdns.aidl.ResolutionInfo;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070054import android.net.nsd.INsdManager;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090055import android.net.nsd.INsdManagerCallback;
56import android.net.nsd.INsdServiceConnector;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090057import android.net.nsd.IOffloadEngine;
paulhu2b9ed952022-02-10 21:58:32 +080058import android.net.nsd.MDnsManager;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070059import android.net.nsd.NsdManager;
paulhua262cc12019-08-12 16:25:11 +080060import android.net.nsd.NsdServiceInfo;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090061import android.net.nsd.OffloadEngine;
62import android.net.nsd.OffloadServiceInfo;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090063import android.net.wifi.WifiManager;
Paul Hub2e67d32023-04-18 05:50:14 +000064import android.os.Binder;
Yuyang Huangfc831702023-08-21 17:48:48 +090065import android.os.Build;
Hugo Benichi803a2f02017-04-24 11:35:06 +090066import android.os.Handler;
paulhua262cc12019-08-12 16:25:11 +080067import android.os.HandlerThread;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090068import android.os.IBinder;
Paul Hu4bd98ef2023-01-12 13:42:07 +080069import android.os.Looper;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070070import android.os.Message;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090071import android.os.RemoteCallbackList;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090072import android.os.RemoteException;
Dianne Hackborn692107e2012-08-29 18:32:08 -070073import android.os.UserHandle;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090074import android.provider.DeviceConfig;
Paul Hu23fa2022023-01-13 22:57:24 +080075import android.text.TextUtils;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090076import android.util.ArraySet;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090077import android.util.Log;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +090078import android.util.Pair;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070079import android.util.SparseArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070080
paulhua262cc12019-08-12 16:25:11 +080081import com.android.internal.annotations.VisibleForTesting;
Paul Hub2e67d32023-04-18 05:50:14 +000082import com.android.internal.util.IndentingPrintWriter;
paulhua262cc12019-08-12 16:25:11 +080083import com.android.internal.util.State;
84import com.android.internal.util.StateMachine;
Paul Hucdef3532023-06-18 14:47:35 +000085import com.android.metrics.NetworkNsdReportedMetrics;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090086import com.android.modules.utils.build.SdkLevel;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090087import com.android.net.module.util.CollectionUtils;
Paul Hu4bd98ef2023-01-12 13:42:07 +080088import com.android.net.module.util.DeviceConfigUtils;
Yuyang Huanga6a6ff92023-04-24 13:33:34 +090089import com.android.net.module.util.InetAddressUtils;
paulhu3ffffe72021-09-16 10:15:22 +080090import com.android.net.module.util.PermissionUtils;
Paul Hub2e67d32023-04-18 05:50:14 +000091import com.android.net.module.util.SharedLog;
Paul Hu4bd98ef2023-01-12 13:42:07 +080092import com.android.server.connectivity.mdns.ExecutorProvider;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090093import com.android.server.connectivity.mdns.MdnsAdvertiser;
Yuyang Huange5cba9c2023-11-02 18:05:47 +090094import com.android.server.connectivity.mdns.MdnsAdvertisingOptions;
Paul Hu4bd98ef2023-01-12 13:42:07 +080095import com.android.server.connectivity.mdns.MdnsDiscoveryManager;
Yuyang Huangb96a0712023-09-07 15:13:15 +090096import com.android.server.connectivity.mdns.MdnsFeatureFlags;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090097import com.android.server.connectivity.mdns.MdnsInterfaceSocket;
Paul Hu4bd98ef2023-01-12 13:42:07 +080098import com.android.server.connectivity.mdns.MdnsMultinetworkSocketClient;
Paul Hu23fa2022023-01-13 22:57:24 +080099import com.android.server.connectivity.mdns.MdnsSearchOptions;
100import com.android.server.connectivity.mdns.MdnsServiceBrowserListener;
101import com.android.server.connectivity.mdns.MdnsServiceInfo;
Paul Hu4bd98ef2023-01-12 13:42:07 +0800102import com.android.server.connectivity.mdns.MdnsSocketProvider;
Yuyang Huangde802c82023-05-02 17:14:22 +0900103import com.android.server.connectivity.mdns.util.MdnsUtils;
paulhua262cc12019-08-12 16:25:11 +0800104
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700105import java.io.FileDescriptor;
106import java.io.PrintWriter;
Yuyang Huangaa0e9602023-03-17 12:43:09 +0900107import java.net.Inet6Address;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700108import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900109import java.net.NetworkInterface;
110import java.net.SocketException;
111import java.net.UnknownHostException;
Paul Hu2b865912023-03-06 14:27:53 +0800112import java.util.ArrayList;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900113import java.util.Arrays;
Kangping Dong5af24b62023-12-10 21:41:16 +0800114import java.util.Collection;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700115import java.util.HashMap;
Kangping Dong5af24b62023-12-10 21:41:16 +0800116import java.util.LinkedHashMap;
Paul Hu23fa2022023-01-13 22:57:24 +0800117import java.util.List;
Paul Hu75069ed2023-01-14 00:31:09 +0800118import java.util.Map;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900119import java.util.Objects;
Paul Hu812e9212023-06-20 06:24:53 +0000120import java.util.Set;
Paul Hu23fa2022023-01-13 22:57:24 +0800121import java.util.regex.Matcher;
122import java.util.regex.Pattern;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700123
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700124/**
125 * Network Service Discovery Service handles remote service discovery operation requests by
126 * implementing the INsdManager interface.
127 *
128 * @hide
129 */
Yuyang Huangfc831702023-08-21 17:48:48 +0900130@RequiresApi(Build.VERSION_CODES.TIRAMISU)
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700131public class NsdService extends INsdManager.Stub {
132 private static final String TAG = "NsdService";
133 private static final String MDNS_TAG = "mDnsConnector";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900134 /**
135 * Enable discovery using the Java DiscoveryManager, instead of the legacy mdnsresponder
136 * implementation.
137 */
Paul Hu4bd98ef2023-01-12 13:42:07 +0800138 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Paul Hu23fa2022023-01-13 22:57:24 +0800139 private static final String LOCAL_DOMAIN_NAME = "local";
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700140
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900141 /**
142 * Enable advertising using the Java MdnsAdvertiser, instead of the legacy mdnsresponder
143 * implementation.
144 */
145 private static final String MDNS_ADVERTISER_VERSION = "mdns_advertiser_version";
146
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900147 /**
148 * Comma-separated list of type:flag mappings indicating the flags to use to allowlist
149 * discovery/advertising using MdnsDiscoveryManager / MdnsAdvertiser for a given type.
150 *
151 * For example _mytype._tcp.local and _othertype._tcp.local would be configured with:
152 * _mytype._tcp:mytype,_othertype._tcp.local:othertype
153 *
154 * In which case the flags:
155 * "mdns_discovery_manager_allowlist_mytype_version",
156 * "mdns_advertiser_allowlist_mytype_version",
157 * "mdns_discovery_manager_allowlist_othertype_version",
158 * "mdns_advertiser_allowlist_othertype_version"
159 * would be used to toggle MdnsDiscoveryManager / MdnsAdvertiser for each type. The flags will
160 * be read with
Motomu Utsumi624aeb42023-08-15 15:52:27 +0900161 * {@link DeviceConfigUtils#isTetheringFeatureEnabled}
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900162 *
163 * @see #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX
164 * @see #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX
165 * @see #MDNS_ALLOWLIST_FLAG_SUFFIX
166 */
167 private static final String MDNS_TYPE_ALLOWLIST_FLAGS = "mdns_type_allowlist_flags";
168
169 private static final String MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX =
170 "mdns_discovery_manager_allowlist_";
171 private static final String MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX =
172 "mdns_advertiser_allowlist_";
173 private static final String MDNS_ALLOWLIST_FLAG_SUFFIX = "_version";
174
Kangping Dong5af24b62023-12-10 21:41:16 +0800175 private static final String TYPE_SUBTYPE_LABEL_REGEX = "_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]";
176
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900177 @VisibleForTesting
178 static final String MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
179 "mdns_config_running_app_active_importance_cutoff";
180 @VisibleForTesting
181 static final int DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
182 ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
183 private final int mRunningAppActiveImportanceCutoff;
184
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900185 public static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +0000186 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900187 private static final int IFACE_IDX_ANY = 0;
Paul Hu812e9212023-06-20 06:24:53 +0000188 private static final int MAX_SERVICES_COUNT_METRIC_PER_CLIENT = 100;
189 @VisibleForTesting
190 static final int NO_TRANSACTION = -1;
Paul Hubad6fe92023-07-24 21:25:22 +0800191 private static final int NO_SENT_QUERY_COUNT = 0;
192 private static final int DISCOVERY_QUERY_SENT_CALLBACK = 1000;
Kangping Dong5af24b62023-12-10 21:41:16 +0800193 private static final int MAX_SUBTYPE_COUNT = 100;
Paul Hu14667de2023-04-17 22:42:47 +0800194 private static final SharedLog LOGGER = new SharedLog("serviceDiscovery");
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700195
Hugo Benichi32be63d2017-04-05 14:06:11 +0900196 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900197 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +0800198 private final MDnsManager mMDnsManager;
199 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900200 @NonNull
201 private final Dependencies mDeps;
202 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800203 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900204 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800205 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900206 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800207 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900208 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900209 private final MdnsAdvertiser mAdvertiser;
Paul Hu777ed052023-06-19 13:35:15 +0000210 @NonNull
211 private final Clock mClock;
Paul Hu14667de2023-04-17 22:42:47 +0800212 private final SharedLog mServiceLogs = LOGGER.forSubComponent(TAG);
Paul Hu23fa2022023-01-13 22:57:24 +0800213 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800214 // state machine thread. If change this outside state machine, it will need to introduce
215 // synchronization.
216 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800217 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700218
219 /**
220 * Clients receiving asynchronous messages
221 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900222 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700223
Paul Hud44e1b72023-06-16 02:07:42 +0000224 /* A map from transaction(unique) id to client info */
225 private final SparseArray<ClientInfo> mTransactionIdToClientInfoMap = new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700226
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900227 // Note this is not final to avoid depending on the Wi-Fi service starting before NsdService
228 @Nullable
229 private WifiManager.MulticastLock mHeldMulticastLock;
230 // Fulfilled network requests that require the Wi-Fi lock: key is the obtained Network
231 // (non-null), value is the requested Network (nullable)
232 @NonNull
233 private final ArraySet<Network> mWifiLockRequiredNetworks = new ArraySet<>();
234 @NonNull
235 private final ArraySet<Integer> mRunningAppActiveUids = new ArraySet<>();
236
Luke Huang05298582021-06-13 16:52:05 +0000237 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700238
Hugo Benichi32be63d2017-04-05 14:06:11 +0900239 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700240 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800241 // The count of the connected legacy clients.
242 private int mLegacyClientCount = 0;
Paul Hub2e67d32023-04-18 05:50:14 +0000243 // The number of client that ever connected.
244 private int mClientNumberId = 1;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700245
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900246 private final RemoteCallbackList<IOffloadEngine> mOffloadEngines =
247 new RemoteCallbackList<>();
248
249 private static class OffloadEngineInfo {
250 @NonNull final String mInterfaceName;
251 final long mOffloadCapabilities;
252 final long mOffloadType;
253 @NonNull final IOffloadEngine mOffloadEngine;
254
255 OffloadEngineInfo(@NonNull IOffloadEngine offloadEngine,
256 @NonNull String interfaceName, long capabilities, long offloadType) {
257 this.mOffloadEngine = offloadEngine;
258 this.mInterfaceName = interfaceName;
259 this.mOffloadCapabilities = capabilities;
260 this.mOffloadType = offloadType;
261 }
262 }
263
Paul Hu812e9212023-06-20 06:24:53 +0000264 @VisibleForTesting
265 static class MdnsListener implements MdnsServiceBrowserListener {
Paul Hud44e1b72023-06-16 02:07:42 +0000266 protected final int mClientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800267 protected final int mTransactionId;
268 @NonNull
269 protected final NsdServiceInfo mReqServiceInfo;
270 @NonNull
271 protected final String mListenedServiceType;
272
Paul Hud44e1b72023-06-16 02:07:42 +0000273 MdnsListener(int clientRequestId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
Paul Hu23fa2022023-01-13 22:57:24 +0800274 @NonNull String listenedServiceType) {
Paul Hud44e1b72023-06-16 02:07:42 +0000275 mClientRequestId = clientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800276 mTransactionId = transactionId;
277 mReqServiceInfo = reqServiceInfo;
278 mListenedServiceType = listenedServiceType;
279 }
280
281 @NonNull
282 public String getListenedServiceType() {
283 return mListenedServiceType;
284 }
285
286 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000287 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
288 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800289
290 @Override
291 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
292
293 @Override
294 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
295
296 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000297 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
298 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800299
300 @Override
301 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
302
303 @Override
304 public void onSearchStoppedWithError(int error) { }
305
306 @Override
307 public void onSearchFailedToStart() { }
308
309 @Override
Paul Hubad6fe92023-07-24 21:25:22 +0800310 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
311 int sentQueryTransactionId) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800312
313 @Override
314 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
315 }
316
317 private class DiscoveryListener extends MdnsListener {
318
Paul Hud44e1b72023-06-16 02:07:42 +0000319 DiscoveryListener(int clientRequestId, int transactionId,
320 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
321 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800322 }
323
324 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000325 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
326 boolean isServiceFromCache) {
Paul Hu019621e2023-01-13 23:26:49 +0800327 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
328 NsdManager.SERVICE_FOUND,
Paul Hua6bc4632023-06-26 01:18:29 +0000329 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu23fa2022023-01-13 22:57:24 +0800330 }
331
332 @Override
333 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800334 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
335 NsdManager.SERVICE_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000336 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800337 }
Paul Hubad6fe92023-07-24 21:25:22 +0800338
339 @Override
340 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
341 int sentQueryTransactionId) {
342 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
343 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
344 }
Paul Hu23fa2022023-01-13 22:57:24 +0800345 }
346
Paul Hu75069ed2023-01-14 00:31:09 +0800347 private class ResolutionListener extends MdnsListener {
348
Paul Hud44e1b72023-06-16 02:07:42 +0000349 ResolutionListener(int clientRequestId, int transactionId,
350 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
351 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800352 }
353
354 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000355 public void onServiceFound(MdnsServiceInfo serviceInfo, boolean isServiceFromCache) {
Paul Hu75069ed2023-01-14 00:31:09 +0800356 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
357 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
Paul Hua6bc4632023-06-26 01:18:29 +0000358 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu75069ed2023-01-14 00:31:09 +0800359 }
Paul Hubad6fe92023-07-24 21:25:22 +0800360
361 @Override
362 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
363 int sentQueryTransactionId) {
364 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
365 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
366 }
Paul Hu75069ed2023-01-14 00:31:09 +0800367 }
368
Paul Hu30bd70d2023-02-07 13:20:56 +0000369 private class ServiceInfoListener extends MdnsListener {
370
Paul Hud44e1b72023-06-16 02:07:42 +0000371 ServiceInfoListener(int clientRequestId, int transactionId,
372 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
373 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +0000374 }
375
376 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000377 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
378 boolean isServiceFromCache) {
Paul Hu30bd70d2023-02-07 13:20:56 +0000379 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
380 NsdManager.SERVICE_UPDATED,
Paul Hua6bc4632023-06-26 01:18:29 +0000381 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu30bd70d2023-02-07 13:20:56 +0000382 }
383
384 @Override
385 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) {
386 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
387 NsdManager.SERVICE_UPDATED,
Paul Hud44e1b72023-06-16 02:07:42 +0000388 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000389 }
390
391 @Override
392 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) {
393 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
394 NsdManager.SERVICE_UPDATED_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000395 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000396 }
Paul Hubad6fe92023-07-24 21:25:22 +0800397
398 @Override
399 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
400 int sentQueryTransactionId) {
401 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
402 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
403 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000404 }
405
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900406 private class SocketRequestMonitor implements MdnsSocketProvider.SocketRequestMonitor {
407 @Override
408 public void onSocketRequestFulfilled(@Nullable Network socketNetwork,
409 @NonNull MdnsInterfaceSocket socket, @NonNull int[] transports) {
410 // The network may be null for Wi-Fi SoftAp interfaces (tethering), but there is no APF
411 // filtering on such interfaces, so taking the multicast lock is not necessary to
412 // disable APF filtering of multicast.
413 if (socketNetwork == null
414 || !CollectionUtils.contains(transports, TRANSPORT_WIFI)
415 || CollectionUtils.contains(transports, TRANSPORT_VPN)) {
416 return;
417 }
418
419 if (mWifiLockRequiredNetworks.add(socketNetwork)) {
420 updateMulticastLock();
421 }
422 }
423
424 @Override
425 public void onSocketDestroyed(@Nullable Network socketNetwork,
426 @NonNull MdnsInterfaceSocket socket) {
427 if (mWifiLockRequiredNetworks.remove(socketNetwork)) {
428 updateMulticastLock();
429 }
430 }
431 }
432
433 private class UidImportanceListener implements ActivityManager.OnUidImportanceListener {
434 private final Handler mHandler;
435
436 private UidImportanceListener(Handler handler) {
437 mHandler = handler;
438 }
439
440 @Override
441 public void onUidImportance(int uid, int importance) {
442 mHandler.post(() -> handleUidImportanceChanged(uid, importance));
443 }
444 }
445
446 private void handleUidImportanceChanged(int uid, int importance) {
447 // Lower importance values are more "important"
448 final boolean modified = importance <= mRunningAppActiveImportanceCutoff
449 ? mRunningAppActiveUids.add(uid)
450 : mRunningAppActiveUids.remove(uid);
451 if (modified) {
452 updateMulticastLock();
453 }
454 }
455
456 /**
457 * Take or release the lock based on updated internal state.
458 *
459 * This determines whether the lock needs to be held based on
460 * {@link #mWifiLockRequiredNetworks}, {@link #mRunningAppActiveUids} and
461 * {@link ClientInfo#mClientRequests}, so it must be called after any of the these have been
462 * updated.
463 */
464 private void updateMulticastLock() {
465 final int needsLockUid = getMulticastLockNeededUid();
466 if (needsLockUid >= 0 && mHeldMulticastLock == null) {
467 final WifiManager wm = mContext.getSystemService(WifiManager.class);
468 if (wm == null) {
469 Log.wtf(TAG, "Got a TRANSPORT_WIFI network without WifiManager");
470 return;
471 }
472 mHeldMulticastLock = wm.createMulticastLock(TAG);
473 mHeldMulticastLock.acquire();
474 mServiceLogs.log("Taking multicast lock for uid " + needsLockUid);
475 } else if (needsLockUid < 0 && mHeldMulticastLock != null) {
476 mHeldMulticastLock.release();
477 mHeldMulticastLock = null;
478 mServiceLogs.log("Released multicast lock");
479 }
480 }
481
482 /**
483 * @return The UID of an app requiring the multicast lock, or -1 if none.
484 */
485 private int getMulticastLockNeededUid() {
486 if (mWifiLockRequiredNetworks.size() == 0) {
487 // Return early if NSD is not active, or not on any relevant network
488 return -1;
489 }
Paul Hud44e1b72023-06-16 02:07:42 +0000490 for (int i = 0; i < mTransactionIdToClientInfoMap.size(); i++) {
491 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.valueAt(i);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900492 if (!mRunningAppActiveUids.contains(clientInfo.mUid)) {
493 // Ignore non-active UIDs
494 continue;
495 }
496
497 if (clientInfo.hasAnyJavaBackendRequestForNetworks(mWifiLockRequiredNetworks)) {
498 return clientInfo.mUid;
499 }
500 }
501 return -1;
502 }
503
Paul Hu019621e2023-01-13 23:26:49 +0800504 /**
505 * Data class of mdns service callback information.
506 */
507 private static class MdnsEvent {
Paul Hud44e1b72023-06-16 02:07:42 +0000508 final int mClientRequestId;
Paul Hubad6fe92023-07-24 21:25:22 +0800509 @Nullable
Paul Hu019621e2023-01-13 23:26:49 +0800510 final MdnsServiceInfo mMdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000511 final boolean mIsServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800512
Paul Hubad6fe92023-07-24 21:25:22 +0800513 MdnsEvent(int clientRequestId) {
514 this(clientRequestId, null /* mdnsServiceInfo */, false /* isServiceFromCache */);
515 }
516
517 MdnsEvent(int clientRequestId, @Nullable MdnsServiceInfo mdnsServiceInfo) {
Paul Hua6bc4632023-06-26 01:18:29 +0000518 this(clientRequestId, mdnsServiceInfo, false /* isServiceFromCache */);
519 }
520
Paul Hubad6fe92023-07-24 21:25:22 +0800521 MdnsEvent(int clientRequestId, @Nullable MdnsServiceInfo mdnsServiceInfo,
Paul Hua6bc4632023-06-26 01:18:29 +0000522 boolean isServiceFromCache) {
Paul Hud44e1b72023-06-16 02:07:42 +0000523 mClientRequestId = clientRequestId;
Paul Hu019621e2023-01-13 23:26:49 +0800524 mMdnsServiceInfo = mdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000525 mIsServiceFromCache = isServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800526 }
527 }
528
Paul Hu77c11182023-10-23 16:17:32 +0800529 // TODO: Use a Handler instead of a StateMachine since there are no state changes.
Irfan Sheriff75006652012-04-17 23:15:29 -0700530 private class NsdStateMachine extends StateMachine {
531
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700532 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700533
534 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700535 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900536 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700537 }
538
Luke Huang92860f92021-06-23 06:29:30 +0000539 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800540 if (mIsDaemonStarted) {
541 if (DBG) Log.d(TAG, "Daemon is already started.");
542 return;
543 }
544 mMDnsManager.registerEventListener(mMDnsEventCallback);
545 mMDnsManager.startDaemon();
546 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000547 maybeScheduleStop();
Paul Hub2e67d32023-04-18 05:50:14 +0000548 mServiceLogs.log("Start mdns_responder daemon");
Luke Huang05298582021-06-13 16:52:05 +0000549 }
550
paulhu2b9ed952022-02-10 21:58:32 +0800551 private void maybeStopDaemon() {
552 if (!mIsDaemonStarted) {
553 if (DBG) Log.d(TAG, "Daemon has not been started.");
554 return;
555 }
556 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
557 mMDnsManager.stopDaemon();
558 mIsDaemonStarted = false;
Paul Hub2e67d32023-04-18 05:50:14 +0000559 mServiceLogs.log("Stop mdns_responder daemon");
paulhu2b9ed952022-02-10 21:58:32 +0800560 }
561
Luke Huang92860f92021-06-23 06:29:30 +0000562 private boolean isAnyRequestActive() {
Paul Hud44e1b72023-06-16 02:07:42 +0000563 return mTransactionIdToClientInfoMap.size() != 0;
Luke Huang92860f92021-06-23 06:29:30 +0000564 }
565
566 private void scheduleStop() {
567 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
568 }
569 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800570 // The native daemon should stay alive and can't be cleanup
571 // if any legacy client connected.
572 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000573 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000574 }
575 }
576
Luke Huang92860f92021-06-23 06:29:30 +0000577 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000578 this.removeMessages(NsdManager.DAEMON_CLEANUP);
579 }
580
Paul Hu23fa2022023-01-13 22:57:24 +0800581 private void maybeStartMonitoringSockets() {
582 if (mIsMonitoringSocketsStarted) {
583 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
584 return;
585 }
586
587 mMdnsSocketProvider.startMonitoringSockets();
588 mIsMonitoringSocketsStarted = true;
589 }
590
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900591 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
592 if (!mIsMonitoringSocketsStarted) return;
593 if (isAnyRequestActive()) return;
594
Paul Hu58f20602023-02-18 11:41:07 +0800595 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800596 mIsMonitoringSocketsStarted = false;
597 }
598
Hugo Benichi803a2f02017-04-24 11:35:06 +0900599 NsdStateMachine(String name, Handler handler) {
600 super(name, handler);
Paul Hu77c11182023-10-23 16:17:32 +0800601 addState(mEnabledState);
paulhu5568f452021-11-30 13:31:29 +0800602 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900603 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700604 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700605 }
606
Irfan Sheriff75006652012-04-17 23:15:29 -0700607 class EnabledState extends State {
608 @Override
609 public void enter() {
610 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700611 }
612
613 @Override
614 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000615 // TODO: it is incorrect to stop the daemon without expunging all requests
616 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000617 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700618 }
619
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700620 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900621 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800622 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700623 return true;
624 }
625 return false;
626 }
627
Paul Hu508a0122023-09-11 15:31:33 +0800628 private ClientRequest storeLegacyRequestMap(int clientRequestId, int transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +0000629 ClientInfo clientInfo, int what, long startTimeMs) {
Paul Hu508a0122023-09-11 15:31:33 +0800630 final LegacyClientRequest request =
631 new LegacyClientRequest(transactionId, what, startTimeMs);
632 clientInfo.mClientRequests.put(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000633 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000634 // Remove the cleanup event because here comes a new request.
635 cancelStop();
Paul Hu508a0122023-09-11 15:31:33 +0800636 return request;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700637 }
638
Paul Hud44e1b72023-06-16 02:07:42 +0000639 private void storeAdvertiserRequestMap(int clientRequestId, int transactionId,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900640 ClientInfo clientInfo, @Nullable Network requestedNetwork) {
Paul Hu777ed052023-06-19 13:35:15 +0000641 clientInfo.mClientRequests.put(clientRequestId, new AdvertiserClientRequest(
Paul Hu812e9212023-06-20 06:24:53 +0000642 transactionId, requestedNetwork, mClock.elapsedRealtime()));
Paul Hud44e1b72023-06-16 02:07:42 +0000643 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900644 updateMulticastLock();
Paul Hu23fa2022023-01-13 22:57:24 +0800645 }
646
Paul Hud44e1b72023-06-16 02:07:42 +0000647 private void removeRequestMap(
648 int clientRequestId, int transactionId, ClientInfo clientInfo) {
649 final ClientRequest existing = clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900650 if (existing == null) return;
Paul Hud44e1b72023-06-16 02:07:42 +0000651 clientInfo.mClientRequests.remove(clientRequestId);
652 mTransactionIdToClientInfoMap.remove(transactionId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900653
654 if (existing instanceof LegacyClientRequest) {
655 maybeScheduleStop();
656 } else {
657 maybeStopMonitoringSocketsIfNoActiveRequest();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900658 updateMulticastLock();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900659 }
660 }
661
Paul Hu508a0122023-09-11 15:31:33 +0800662 private ClientRequest storeDiscoveryManagerRequestMap(int clientRequestId,
663 int transactionId, MdnsListener listener, ClientInfo clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900664 @Nullable Network requestedNetwork) {
Paul Hu508a0122023-09-11 15:31:33 +0800665 final DiscoveryManagerRequest request = new DiscoveryManagerRequest(transactionId,
666 listener, requestedNetwork, mClock.elapsedRealtime());
667 clientInfo.mClientRequests.put(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000668 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900669 updateMulticastLock();
Paul Hu508a0122023-09-11 15:31:33 +0800670 return request;
Paul Hu23fa2022023-01-13 22:57:24 +0800671 }
672
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900673 /**
674 * Truncate a service name to up to 63 UTF-8 bytes.
675 *
676 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
677 * names used in registerService follows historical behavior (see mdnsresponder
678 * handle_regservice_request).
679 */
680 @NonNull
681 private String truncateServiceName(@NonNull String originalName) {
Yuyang Huangde802c82023-05-02 17:14:22 +0900682 return MdnsUtils.truncateServiceName(originalName, MAX_LABEL_LENGTH);
Paul Hu23fa2022023-01-13 22:57:24 +0800683 }
684
Paul Hud44e1b72023-06-16 02:07:42 +0000685 private void stopDiscoveryManagerRequest(ClientRequest request, int clientRequestId,
686 int transactionId, ClientInfo clientInfo) {
Paul Hue4f5f252023-02-16 21:13:47 +0800687 clientInfo.unregisterMdnsListenerFromRequest(request);
Paul Hud44e1b72023-06-16 02:07:42 +0000688 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hue4f5f252023-02-16 21:13:47 +0800689 }
690
Paul Hu77c11182023-10-23 16:17:32 +0800691 private ClientInfo getClientInfoForReply(Message msg) {
692 final ListenerArgs args = (ListenerArgs) msg.obj;
693 return mClients.get(args.connector);
694 }
695
Kangping Dong5af24b62023-12-10 21:41:16 +0800696 /**
697 * Returns {@code false} if {@code subtypes} exceeds the maximum number limit or
698 * contains invalid subtype label.
699 */
700 private boolean checkSubtypeLabels(Set<String> subtypes) {
701 if (subtypes.size() > MAX_SUBTYPE_COUNT) {
702 mServiceLogs.e(
703 "Too many subtypes: " + subtypes.size() + " (max = "
704 + MAX_SUBTYPE_COUNT + ")");
705 return false;
706 }
707
708 for (String subtype : subtypes) {
709 if (!checkSubtypeLabel(subtype)) {
710 mServiceLogs.e("Subtype " + subtype + " is invalid");
711 return false;
712 }
713 }
714 return true;
715 }
716
717 private Set<String> dedupSubtypeLabels(Collection<String> subtypes) {
718 final Map<String, String> subtypeMap = new LinkedHashMap<>(subtypes.size());
719 for (String subtype : subtypes) {
720 subtypeMap.put(MdnsUtils.toDnsLowerCase(subtype), subtype);
721 }
722 return new ArraySet<>(subtypeMap.values());
723 }
724
Irfan Sheriff75006652012-04-17 23:15:29 -0700725 @Override
726 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900727 final ClientInfo clientInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000728 final int transactionId;
729 final int clientRequestId = msg.arg2;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900730 final ListenerArgs args;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900731 final OffloadEngineInfo offloadEngineInfo;
Irfan Sheriff75006652012-04-17 23:15:29 -0700732 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800733 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800734 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900735 args = (ListenerArgs) msg.obj;
736 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000737 // If the binder death notification for a INsdManagerCallback was received
738 // before any calls are received by NsdService, the clientInfo would be
739 // cleared and cause NPE. Add a null check here to prevent this corner case.
740 if (clientInfo == null) {
741 Log.e(TAG, "Unknown connector in discovery");
742 break;
743 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700744
745 if (requestLimitReached(clientInfo)) {
Paul Hu508a0122023-09-11 15:31:33 +0800746 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
747 NsdManager.FAILURE_MAX_LIMIT, true /* isLegacy */);
Irfan Sheriff75006652012-04-17 23:15:29 -0700748 break;
749 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700750
Paul Hu23fa2022023-01-13 22:57:24 +0800751 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000752 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900753 final Pair<String, String> typeAndSubtype =
754 parseTypeAndSubtype(info.getServiceType());
755 final String serviceType = typeAndSubtype == null
756 ? null : typeAndSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800757 if (clientInfo.mUseJavaBackend
758 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900759 || useDiscoveryManagerForType(serviceType)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800760 if (serviceType == null) {
Paul Hu508a0122023-09-11 15:31:33 +0800761 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
762 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Paul Hu23fa2022023-01-13 22:57:24 +0800763 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700764 }
Paul Hu23fa2022023-01-13 22:57:24 +0800765
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900766 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800767 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +0000768 final MdnsListener listener = new DiscoveryListener(clientRequestId,
769 transactionId, info, listenServiceType);
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900770 final MdnsSearchOptions.Builder optionsBuilder =
771 MdnsSearchOptions.newBuilder()
772 .setNetwork(info.getNetwork())
Yuyang Huangff963222023-06-01 18:42:42 +0900773 .setRemoveExpiredService(true)
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900774 .setIsPassiveMode(true);
775 if (typeAndSubtype.second != null) {
776 // The parsing ensures subtype starts with an underscore.
777 // MdnsSearchOptions expects the underscore to not be present.
778 optionsBuilder.addSubtype(typeAndSubtype.second.substring(1));
779 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900780 mMdnsDiscoveryManager.registerListener(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900781 listenServiceType, listener, optionsBuilder.build());
Paul Hu508a0122023-09-11 15:31:33 +0800782 final ClientRequest request = storeDiscoveryManagerRequestMap(
783 clientRequestId, transactionId, listener, clientInfo,
784 info.getNetwork());
785 clientInfo.onDiscoverServicesStarted(clientRequestId, info, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000786 clientInfo.log("Register a DiscoveryListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +0000787 + " for service type:" + listenServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700788 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800789 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000790 if (discoverServices(transactionId, info)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800791 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +0000792 Log.d(TAG, "Discover " + msg.arg2 + " " + transactionId
Paul Hu23fa2022023-01-13 22:57:24 +0800793 + info.getServiceType());
794 }
Paul Hu508a0122023-09-11 15:31:33 +0800795 final ClientRequest request = storeLegacyRequestMap(clientRequestId,
796 transactionId, clientInfo, msg.what,
797 mClock.elapsedRealtime());
Paul Hu812e9212023-06-20 06:24:53 +0000798 clientInfo.onDiscoverServicesStarted(
Paul Hu508a0122023-09-11 15:31:33 +0800799 clientRequestId, info, request);
Paul Hu23fa2022023-01-13 22:57:24 +0800800 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000801 stopServiceDiscovery(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +0800802 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
803 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Paul Hu23fa2022023-01-13 22:57:24 +0800804 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700805 }
806 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800807 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900808 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800809 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900810 args = (ListenerArgs) msg.obj;
811 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000812 // If the binder death notification for a INsdManagerCallback was received
813 // before any calls are received by NsdService, the clientInfo would be
814 // cleared and cause NPE. Add a null check here to prevent this corner case.
815 if (clientInfo == null) {
816 Log.e(TAG, "Unknown connector in stop discovery");
817 break;
818 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700819
Paul Hud44e1b72023-06-16 02:07:42 +0000820 final ClientRequest request =
821 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900822 if (request == null) {
823 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700824 break;
825 }
Paul Hud44e1b72023-06-16 02:07:42 +0000826 transactionId = request.mTransactionId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900827 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
828 // point, so this needs to check the type of the original request to
829 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900830 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +0000831 stopDiscoveryManagerRequest(
832 request, clientRequestId, transactionId, clientInfo);
Paul Hu812e9212023-06-20 06:24:53 +0000833 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000834 clientInfo.log("Unregister the DiscoveryListener " + transactionId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700835 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000836 removeRequestMap(clientRequestId, transactionId, clientInfo);
837 if (stopServiceDiscovery(transactionId)) {
Paul Hu812e9212023-06-20 06:24:53 +0000838 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hu23fa2022023-01-13 22:57:24 +0800839 } else {
840 clientInfo.onStopDiscoveryFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000841 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu23fa2022023-01-13 22:57:24 +0800842 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700843 }
844 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900845 }
846 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800847 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900848 args = (ListenerArgs) msg.obj;
849 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000850 // If the binder death notification for a INsdManagerCallback was received
851 // before any calls are received by NsdService, the clientInfo would be
852 // cleared and cause NPE. Add a null check here to prevent this corner case.
853 if (clientInfo == null) {
854 Log.e(TAG, "Unknown connector in registration");
855 break;
856 }
857
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700858 if (requestLimitReached(clientInfo)) {
Paul Hu508a0122023-09-11 15:31:33 +0800859 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
860 NsdManager.FAILURE_MAX_LIMIT, true /* isLegacy */);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700861 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700862 }
863
Paul Hud44e1b72023-06-16 02:07:42 +0000864 transactionId = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900865 final NsdServiceInfo serviceInfo = args.serviceInfo;
866 final String serviceType = serviceInfo.getServiceType();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900867 final Pair<String, String> typeSubtype = parseTypeAndSubtype(serviceType);
868 final String registerServiceType = typeSubtype == null
869 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800870 if (clientInfo.mUseJavaBackend
871 || mDeps.isMdnsAdvertiserEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900872 || useAdvertiserForType(registerServiceType)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900873 if (registerServiceType == null) {
874 Log.e(TAG, "Invalid service type: " + serviceType);
Paul Hu508a0122023-09-11 15:31:33 +0800875 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
876 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900877 break;
878 }
879 serviceInfo.setServiceType(registerServiceType);
880 serviceInfo.setServiceName(truncateServiceName(
881 serviceInfo.getServiceName()));
882
Kangping Dong5af24b62023-12-10 21:41:16 +0800883 Set<String> subtypes = new ArraySet<>(serviceInfo.getSubtypes());
884 if (!TextUtils.isEmpty(typeSubtype.second)) {
885 subtypes.add(typeSubtype.second);
886 }
887
888 subtypes = dedupSubtypeLabels(subtypes);
889
890 if (!checkSubtypeLabels(subtypes)) {
891 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
892 NsdManager.FAILURE_BAD_PARAMETERS, false /* isLegacy */);
893 break;
894 }
895
896 serviceInfo.setSubtypes(subtypes);
897
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900898 maybeStartMonitoringSockets();
Yuyang Huange5cba9c2023-11-02 18:05:47 +0900899 mAdvertiser.addOrUpdateService(transactionId, serviceInfo,
Yuyang Huange5cba9c2023-11-02 18:05:47 +0900900 MdnsAdvertisingOptions.newBuilder().build());
Paul Hud44e1b72023-06-16 02:07:42 +0000901 storeAdvertiserRequestMap(clientRequestId, transactionId, clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900902 serviceInfo.getNetwork());
Irfan Sheriff75006652012-04-17 23:15:29 -0700903 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900904 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000905 if (registerService(transactionId, serviceInfo)) {
906 if (DBG) {
907 Log.d(TAG, "Register " + clientRequestId
908 + " " + transactionId);
909 }
Paul Hua6bc4632023-06-26 01:18:29 +0000910 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
911 msg.what, mClock.elapsedRealtime());
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900912 // Return success after mDns reports success
913 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000914 unregisterService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +0800915 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
916 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900917 }
918
Irfan Sheriff75006652012-04-17 23:15:29 -0700919 }
920 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900921 }
922 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800923 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900924 args = (ListenerArgs) msg.obj;
925 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000926 // If the binder death notification for a INsdManagerCallback was received
927 // before any calls are received by NsdService, the clientInfo would be
928 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900929 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800930 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700931 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700932 }
Paul Hud44e1b72023-06-16 02:07:42 +0000933 final ClientRequest request =
934 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900935 if (request == null) {
936 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
937 break;
938 }
Paul Hud44e1b72023-06-16 02:07:42 +0000939 transactionId = request.mTransactionId;
940 removeRequestMap(clientRequestId, transactionId, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900941
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900942 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
943 // so this needs to check the type of the original request to unregister
944 // instead of looking at the flag value.
945 if (request instanceof AdvertiserClientRequest) {
Paul Hu043bcd42023-07-14 16:38:25 +0800946 final AdvertiserMetrics metrics =
947 mAdvertiser.getAdvertiserMetrics(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +0000948 mAdvertiser.removeService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +0800949 clientInfo.onUnregisterServiceSucceeded(
950 clientRequestId, request, metrics);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700951 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000952 if (unregisterService(transactionId)) {
Paul Hu508a0122023-09-11 15:31:33 +0800953 clientInfo.onUnregisterServiceSucceeded(clientRequestId, request,
Paul Hu043bcd42023-07-14 16:38:25 +0800954 new AdvertiserMetrics(NO_PACKET /* repliedRequestsCount */,
955 NO_PACKET /* sentPacketCount */,
956 0 /* conflictDuringProbingCount */,
957 0 /* conflictAfterProbingCount */));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900958 } else {
959 clientInfo.onUnregisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000960 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900961 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700962 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700963 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900964 }
Paul Hu75069ed2023-01-14 00:31:09 +0800965 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800966 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900967 args = (ListenerArgs) msg.obj;
968 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000969 // If the binder death notification for a INsdManagerCallback was received
970 // before any calls are received by NsdService, the clientInfo would be
971 // cleared and cause NPE. Add a null check here to prevent this corner case.
972 if (clientInfo == null) {
973 Log.e(TAG, "Unknown connector in resolution");
974 break;
975 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700976
Paul Hu75069ed2023-01-14 00:31:09 +0800977 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000978 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900979 final Pair<String, String> typeSubtype =
980 parseTypeAndSubtype(info.getServiceType());
981 final String serviceType = typeSubtype == null
982 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800983 if (clientInfo.mUseJavaBackend
984 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900985 || useDiscoveryManagerForType(serviceType)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800986 if (serviceType == null) {
Paul Hu508a0122023-09-11 15:31:33 +0800987 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
988 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +0800989 break;
990 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900991 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +0800992
993 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +0000994 final MdnsListener listener = new ResolutionListener(clientRequestId,
995 transactionId, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800996 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
997 .setNetwork(info.getNetwork())
998 .setIsPassiveMode(true)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900999 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001000 .setRemoveExpiredService(true)
Paul Hu75069ed2023-01-14 00:31:09 +08001001 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001002 mMdnsDiscoveryManager.registerListener(
1003 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001004 storeDiscoveryManagerRequestMap(clientRequestId, transactionId,
1005 listener, clientInfo, info.getNetwork());
1006 clientInfo.log("Register a ResolutionListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001007 + " for service type:" + resolveServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -07001008 } else {
Paul Hu75069ed2023-01-14 00:31:09 +08001009 if (clientInfo.mResolvedService != null) {
Paul Hu508a0122023-09-11 15:31:33 +08001010 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
1011 NsdManager.FAILURE_ALREADY_ACTIVE, true /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +08001012 break;
1013 }
1014
1015 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +00001016 if (resolveService(transactionId, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +08001017 clientInfo.mResolvedService = new NsdServiceInfo();
Paul Hua6bc4632023-06-26 01:18:29 +00001018 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
1019 msg.what, mClock.elapsedRealtime());
Paul Hu75069ed2023-01-14 00:31:09 +08001020 } else {
Paul Hu508a0122023-09-11 15:31:33 +08001021 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
1022 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +08001023 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001024 }
1025 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001026 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001027 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +00001028 if (DBG) Log.d(TAG, "Stop service resolution");
1029 args = (ListenerArgs) msg.obj;
1030 clientInfo = mClients.get(args.connector);
1031 // If the binder death notification for a INsdManagerCallback was received
1032 // before any calls are received by NsdService, the clientInfo would be
1033 // cleared and cause NPE. Add a null check here to prevent this corner case.
1034 if (clientInfo == null) {
1035 Log.e(TAG, "Unknown connector in stop resolution");
1036 break;
1037 }
1038
Paul Hud44e1b72023-06-16 02:07:42 +00001039 final ClientRequest request =
1040 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001041 if (request == null) {
1042 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
1043 break;
1044 }
Paul Hud44e1b72023-06-16 02:07:42 +00001045 transactionId = request.mTransactionId;
Paul Hue4f5f252023-02-16 21:13:47 +08001046 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
1047 // point, so this needs to check the type of the original request to
1048 // unregister instead of looking at the flag value.
1049 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001050 stopDiscoveryManagerRequest(
1051 request, clientRequestId, transactionId, clientInfo);
Paul Hu60149052023-07-31 14:26:08 +08001052 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001053 clientInfo.log("Unregister the ResolutionListener " + transactionId);
Paul Hub58deb72022-12-26 09:24:42 +00001054 } else {
Paul Hud44e1b72023-06-16 02:07:42 +00001055 removeRequestMap(clientRequestId, transactionId, clientInfo);
1056 if (stopResolveService(transactionId)) {
Paul Hu60149052023-07-31 14:26:08 +08001057 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hue4f5f252023-02-16 21:13:47 +08001058 } else {
1059 clientInfo.onStopResolutionFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001060 clientRequestId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hue4f5f252023-02-16 21:13:47 +08001061 }
1062 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +00001063 }
Paul Hub58deb72022-12-26 09:24:42 +00001064 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001065 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001066 case NsdManager.REGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001067 if (DBG) Log.d(TAG, "Register a service callback");
1068 args = (ListenerArgs) msg.obj;
1069 clientInfo = mClients.get(args.connector);
1070 // If the binder death notification for a INsdManagerCallback was received
1071 // before any calls are received by NsdService, the clientInfo would be
1072 // cleared and cause NPE. Add a null check here to prevent this corner case.
1073 if (clientInfo == null) {
1074 Log.e(TAG, "Unknown connector in callback registration");
1075 break;
1076 }
1077
Paul Hu30bd70d2023-02-07 13:20:56 +00001078 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001079 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001080 final Pair<String, String> typeAndSubtype =
1081 parseTypeAndSubtype(info.getServiceType());
1082 final String serviceType = typeAndSubtype == null
1083 ? null : typeAndSubtype.first;
Paul Hu30bd70d2023-02-07 13:20:56 +00001084 if (serviceType == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001085 clientInfo.onServiceInfoCallbackRegistrationFailed(clientRequestId,
Paul Hu30bd70d2023-02-07 13:20:56 +00001086 NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +00001087 break;
1088 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001089 final String resolveServiceType = serviceType + ".local";
Paul Hu18aeccc2022-12-27 08:48:48 +00001090
Paul Hu30bd70d2023-02-07 13:20:56 +00001091 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001092 final MdnsListener listener = new ServiceInfoListener(clientRequestId,
1093 transactionId, info, resolveServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +00001094 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1095 .setNetwork(info.getNetwork())
1096 .setIsPassiveMode(true)
1097 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001098 .setRemoveExpiredService(true)
Paul Hu30bd70d2023-02-07 13:20:56 +00001099 .build();
1100 mMdnsDiscoveryManager.registerListener(
1101 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001102 storeDiscoveryManagerRequestMap(clientRequestId, transactionId, listener,
1103 clientInfo, info.getNetwork());
Paul Huddce5912023-08-01 10:26:49 +08001104 clientInfo.onServiceInfoCallbackRegistered(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00001105 clientInfo.log("Register a ServiceInfoListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001106 + " for service type:" + resolveServiceType);
Paul Hu18aeccc2022-12-27 08:48:48 +00001107 break;
Paul Hu30bd70d2023-02-07 13:20:56 +00001108 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001109 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001110 if (DBG) Log.d(TAG, "Unregister a service callback");
1111 args = (ListenerArgs) msg.obj;
1112 clientInfo = mClients.get(args.connector);
1113 // If the binder death notification for a INsdManagerCallback was received
1114 // before any calls are received by NsdService, the clientInfo would be
1115 // cleared and cause NPE. Add a null check here to prevent this corner case.
1116 if (clientInfo == null) {
1117 Log.e(TAG, "Unknown connector in callback unregistration");
1118 break;
1119 }
1120
Paul Hud44e1b72023-06-16 02:07:42 +00001121 final ClientRequest request =
1122 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001123 if (request == null) {
Paul Hu30bd70d2023-02-07 13:20:56 +00001124 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE_CALLBACK");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001125 break;
1126 }
Paul Hud44e1b72023-06-16 02:07:42 +00001127 transactionId = request.mTransactionId;
Paul Hu30bd70d2023-02-07 13:20:56 +00001128 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001129 stopDiscoveryManagerRequest(
1130 request, clientRequestId, transactionId, clientInfo);
Paul Huddce5912023-08-01 10:26:49 +08001131 clientInfo.onServiceInfoCallbackUnregistered(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001132 clientInfo.log("Unregister the ServiceInfoListener " + transactionId);
Paul Hu18aeccc2022-12-27 08:48:48 +00001133 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001134 loge("Unregister failed with non-DiscoveryManagerRequest.");
Paul Hu18aeccc2022-12-27 08:48:48 +00001135 }
Paul Hu18aeccc2022-12-27 08:48:48 +00001136 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001137 }
paulhu2b9ed952022-02-10 21:58:32 +08001138 case MDNS_SERVICE_EVENT:
1139 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +09001140 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001141 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001142 break;
Paul Hu019621e2023-01-13 23:26:49 +08001143 case MDNS_DISCOVERY_MANAGER_EVENT:
1144 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
1145 return NOT_HANDLED;
1146 }
1147 break;
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001148 case NsdManager.REGISTER_OFFLOAD_ENGINE:
1149 offloadEngineInfo = (OffloadEngineInfo) msg.obj;
1150 // TODO: Limits the number of registrations created by a given class.
1151 mOffloadEngines.register(offloadEngineInfo.mOffloadEngine,
1152 offloadEngineInfo);
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001153 sendAllOffloadServiceInfos(offloadEngineInfo);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001154 break;
1155 case NsdManager.UNREGISTER_OFFLOAD_ENGINE:
1156 mOffloadEngines.unregister((IOffloadEngine) msg.obj);
1157 break;
Paul Hu77c11182023-10-23 16:17:32 +08001158 case NsdManager.REGISTER_CLIENT:
1159 final ConnectorArgs arg = (ConnectorArgs) msg.obj;
1160 final INsdManagerCallback cb = arg.callback;
1161 try {
1162 cb.asBinder().linkToDeath(arg.connector, 0);
1163 final String tag = "Client" + arg.uid + "-" + mClientNumberId++;
1164 final NetworkNsdReportedMetrics metrics =
1165 mDeps.makeNetworkNsdReportedMetrics(
1166 (int) mClock.elapsedRealtime());
1167 clientInfo = new ClientInfo(cb, arg.uid, arg.useJavaBackend,
1168 mServiceLogs.forSubComponent(tag), metrics);
1169 mClients.put(arg.connector, clientInfo);
1170 } catch (RemoteException e) {
1171 Log.w(TAG, "Client request id " + clientRequestId
1172 + " has already died");
1173 }
1174 break;
1175 case NsdManager.UNREGISTER_CLIENT:
1176 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
1177 clientInfo = mClients.remove(connector);
1178 if (clientInfo != null) {
1179 clientInfo.expungeAllRequests();
1180 if (clientInfo.isPreSClient()) {
1181 mLegacyClientCount -= 1;
1182 }
1183 }
1184 maybeStopMonitoringSocketsIfNoActiveRequest();
1185 maybeScheduleStop();
1186 break;
1187 case NsdManager.DAEMON_CLEANUP:
1188 maybeStopDaemon();
1189 break;
1190 // This event should be only sent by the legacy (target SDK < S) clients.
1191 // Mark the sending client as legacy.
1192 case NsdManager.DAEMON_STARTUP:
1193 clientInfo = getClientInfoForReply(msg);
1194 if (clientInfo != null) {
1195 cancelStop();
1196 clientInfo.setPreSClient();
1197 mLegacyClientCount += 1;
1198 maybeStartDaemon();
1199 }
1200 break;
Irfan Sheriff75006652012-04-17 23:15:29 -07001201 default:
Paul Hu77c11182023-10-23 16:17:32 +08001202 Log.wtf(TAG, "Unhandled " + msg);
Hugo Benichif0c84092017-04-05 14:43:29 +09001203 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001204 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001205 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001206 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001207
Paul Hud44e1b72023-06-16 02:07:42 +00001208 private boolean handleMDnsServiceEvent(int code, int transactionId, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001209 NsdServiceInfo servInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001210 ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001211 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001212 Log.e(TAG, String.format(
1213 "transactionId %d for %d has no client mapping", transactionId, code));
Hugo Benichif0c84092017-04-05 14:43:29 +09001214 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001215 }
1216
1217 /* This goes in response as msg.arg2 */
Paul Hud44e1b72023-06-16 02:07:42 +00001218 int clientRequestId = clientInfo.getClientRequestId(transactionId);
1219 if (clientRequestId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -07001220 // This can happen because of race conditions. For example,
1221 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
1222 // and we may get in this situation.
Paul Hud44e1b72023-06-16 02:07:42 +00001223 Log.d(TAG, String.format("%d for transactionId %d that is no longer active",
1224 code, transactionId));
Hugo Benichif0c84092017-04-05 14:43:29 +09001225 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001226 }
Paul Hu812e9212023-06-20 06:24:53 +00001227 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1228 if (request == null) {
1229 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1230 return false;
1231 }
Hugo Benichi32be63d2017-04-05 14:06:11 +09001232 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00001233 Log.d(TAG, String.format(
1234 "MDns service event code:%d transactionId=%d", code, transactionId));
Hugo Benichi32be63d2017-04-05 14:06:11 +09001235 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001236 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +08001237 case IMDnsEventListener.SERVICE_FOUND: {
1238 final DiscoveryInfo info = (DiscoveryInfo) obj;
1239 final String name = info.serviceName;
1240 final String type = info.registrationType;
1241 servInfo = new NsdServiceInfo(name, type);
1242 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001243 if (foundNetId == 0L) {
1244 // Ignore services that do not have a Network: they are not usable
1245 // by apps, as they would need privileged permissions to use
1246 // interfaces that do not have an associated Network.
1247 break;
1248 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +09001249 if (foundNetId == INetd.DUMMY_NET_ID) {
1250 // Ignore services on the dummy0 interface: they are only seen when
1251 // discovering locally advertised services, and are not reachable
1252 // through that interface.
1253 break;
1254 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001255 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001256
1257 clientInfo.onServiceFound(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001258 break;
paulhu2b9ed952022-02-10 21:58:32 +08001259 }
1260 case IMDnsEventListener.SERVICE_LOST: {
1261 final DiscoveryInfo info = (DiscoveryInfo) obj;
1262 final String name = info.serviceName;
1263 final String type = info.registrationType;
1264 final int lostNetId = info.netId;
1265 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001266 // The network could be set to null (netId 0) if it was torn down when the
1267 // service is lost
1268 // TODO: avoid returning null in that case, possibly by remembering
1269 // found services on the same interface index and their network at the time
1270 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001271 clientInfo.onServiceLost(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001272 break;
paulhu2b9ed952022-02-10 21:58:32 +08001273 }
1274 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Paul Hu812e9212023-06-20 06:24:53 +00001275 clientInfo.onDiscoverServicesFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001276 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1277 transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001278 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001279 break;
paulhu2b9ed952022-02-10 21:58:32 +08001280 case IMDnsEventListener.SERVICE_REGISTERED: {
1281 final RegistrationInfo info = (RegistrationInfo) obj;
1282 final String name = info.serviceName;
1283 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Paul Hu508a0122023-09-11 15:31:33 +08001284 clientInfo.onRegisterServiceSucceeded(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001285 break;
paulhu2b9ed952022-02-10 21:58:32 +08001286 }
1287 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Paul Hu777ed052023-06-19 13:35:15 +00001288 clientInfo.onRegisterServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001289 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1290 transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001291 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001292 break;
paulhu2b9ed952022-02-10 21:58:32 +08001293 case IMDnsEventListener.SERVICE_RESOLVED: {
1294 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001295 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +08001296 final String fullName = info.serviceFullName;
1297 while (index < fullName.length() && fullName.charAt(index) != '.') {
1298 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001299 ++index;
1300 }
1301 ++index;
1302 }
paulhu2b9ed952022-02-10 21:58:32 +08001303 if (index >= fullName.length()) {
1304 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001305 break;
1306 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001307
paulhube186602022-04-12 07:18:23 +00001308 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001309 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001310 String type = rest.replace(".local.", "");
1311
Paul Hu30bd70d2023-02-07 13:20:56 +00001312 final NsdServiceInfo serviceInfo = clientInfo.mResolvedService;
Paul Hu18aeccc2022-12-27 08:48:48 +00001313 serviceInfo.setServiceName(name);
1314 serviceInfo.setServiceType(type);
1315 serviceInfo.setPort(info.port);
1316 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001317 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001318
Paul Hud44e1b72023-06-16 02:07:42 +00001319 stopResolveService(transactionId);
1320 removeRequestMap(clientRequestId, transactionId, clientInfo);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001321
Paul Hud44e1b72023-06-16 02:07:42 +00001322 final int transactionId2 = getUniqueId();
1323 if (getAddrInfo(transactionId2, info.hostname, info.interfaceIdx)) {
1324 storeLegacyRequestMap(clientRequestId, transactionId2, clientInfo,
Paul Hua6bc4632023-06-26 01:18:29 +00001325 NsdManager.RESOLVE_SERVICE, request.mStartTimeMs);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001326 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001327 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001328 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1329 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001330 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001331 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001332 }
1333 break;
paulhu2b9ed952022-02-10 21:58:32 +08001334 }
1335 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001336 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001337 stopResolveService(transactionId);
1338 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001339 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001340 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1341 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001342 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001343 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001344 break;
paulhu2b9ed952022-02-10 21:58:32 +08001345 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001346 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001347 stopGetAddrInfo(transactionId);
1348 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001349 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001350 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1351 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001352 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001353 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001354 break;
paulhu2b9ed952022-02-10 21:58:32 +08001355 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001356 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001357 final GetAddressInfo info = (GetAddressInfo) obj;
1358 final String address = info.address;
1359 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001360 InetAddress serviceHost = null;
1361 try {
paulhu2b9ed952022-02-10 21:58:32 +08001362 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001363 } catch (UnknownHostException e) {
1364 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1365 }
1366
1367 // If the resolved service is on an interface without a network, consider it
1368 // as a failure: it would not be usable by apps as they would need
1369 // privileged permissions.
Paul Hu30bd70d2023-02-07 13:20:56 +00001370 if (netId != NETID_UNSET && serviceHost != null) {
1371 clientInfo.mResolvedService.setHost(serviceHost);
1372 setServiceNetworkForCallback(clientInfo.mResolvedService,
1373 netId, info.interfaceIdx);
1374 clientInfo.onResolveServiceSucceeded(
Paul Hua6bc4632023-06-26 01:18:29 +00001375 clientRequestId, clientInfo.mResolvedService, request);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001376 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001377 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001378 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1379 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001380 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001381 }
Paul Hud44e1b72023-06-16 02:07:42 +00001382 stopGetAddrInfo(transactionId);
1383 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001384 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001385 break;
paulhu2b9ed952022-02-10 21:58:32 +08001386 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001387 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001388 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001389 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001390 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001391 }
Paul Hu019621e2023-01-13 23:26:49 +08001392
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001393 @Nullable
1394 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(
1395 final MdnsEvent event, int code) {
Paul Hu019621e2023-01-13 23:26:49 +08001396 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001397 final String[] typeArray = serviceInfo.getServiceType();
1398 final String joinedType;
1399 if (typeArray.length == 0
1400 || !typeArray[typeArray.length - 1].equals(LOCAL_DOMAIN_NAME)) {
1401 Log.wtf(TAG, "MdnsServiceInfo type does not end in .local: "
1402 + Arrays.toString(typeArray));
1403 return null;
1404 } else {
1405 joinedType = TextUtils.join(".",
1406 Arrays.copyOfRange(typeArray, 0, typeArray.length - 1));
1407 }
1408 final String serviceType;
1409 switch (code) {
1410 case NsdManager.SERVICE_FOUND:
1411 case NsdManager.SERVICE_LOST:
1412 // For consistency with historical behavior, discovered service types have
1413 // a dot at the end.
1414 serviceType = joinedType + ".";
1415 break;
1416 case RESOLVE_SERVICE_SUCCEEDED:
1417 // For consistency with historical behavior, resolved service types have
1418 // a dot at the beginning.
1419 serviceType = "." + joinedType;
1420 break;
1421 default:
1422 serviceType = joinedType;
1423 break;
1424 }
Paul Hu019621e2023-01-13 23:26:49 +08001425 final String serviceName = serviceInfo.getServiceInstanceName();
1426 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1427 final Network network = serviceInfo.getNetwork();
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001428 // In MdnsDiscoveryManagerEvent, the Network can be null which means it is a
1429 // network for Tethering interface. In other words, the network == null means the
1430 // network has netId = INetd.LOCAL_NET_ID.
Paul Hu019621e2023-01-13 23:26:49 +08001431 setServiceNetworkForCallback(
1432 servInfo,
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001433 network == null ? INetd.LOCAL_NET_ID : network.netId,
Paul Hu019621e2023-01-13 23:26:49 +08001434 serviceInfo.getInterfaceIndex());
Kangping Dong5af24b62023-12-10 21:41:16 +08001435 servInfo.setSubtypes(dedupSubtypeLabels(serviceInfo.getSubtypes()));
Paul Hu019621e2023-01-13 23:26:49 +08001436 return servInfo;
1437 }
1438
1439 private boolean handleMdnsDiscoveryManagerEvent(
1440 int transactionId, int code, Object obj) {
Paul Hud44e1b72023-06-16 02:07:42 +00001441 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Paul Hu019621e2023-01-13 23:26:49 +08001442 if (clientInfo == null) {
1443 Log.e(TAG, String.format(
1444 "id %d for %d has no client mapping", transactionId, code));
1445 return false;
1446 }
1447
1448 final MdnsEvent event = (MdnsEvent) obj;
Paul Hud44e1b72023-06-16 02:07:42 +00001449 final int clientRequestId = event.mClientRequestId;
Paul Hubad6fe92023-07-24 21:25:22 +08001450 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1451 if (request == null) {
1452 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1453 return false;
1454 }
1455
1456 // Deal with the discovery sent callback
1457 if (code == DISCOVERY_QUERY_SENT_CALLBACK) {
1458 request.onQuerySent();
1459 return true;
1460 }
1461
1462 // Deal with other callbacks.
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001463 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event, code);
1464 // Errors are already logged if null
1465 if (info == null) return false;
Paul Hu83ec7f42023-06-07 18:04:09 +08001466 mServiceLogs.log(String.format(
1467 "MdnsDiscoveryManager event code=%s transactionId=%d",
1468 NsdManager.nameOf(code), transactionId));
Paul Hu019621e2023-01-13 23:26:49 +08001469 switch (code) {
1470 case NsdManager.SERVICE_FOUND:
Paul Hu812e9212023-06-20 06:24:53 +00001471 clientInfo.onServiceFound(clientRequestId, info, request);
Paul Hu319751a2023-01-13 23:56:34 +08001472 break;
1473 case NsdManager.SERVICE_LOST:
Paul Hu812e9212023-06-20 06:24:53 +00001474 clientInfo.onServiceLost(clientRequestId, info, request);
Paul Hu019621e2023-01-13 23:26:49 +08001475 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001476 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
1477 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Paul Hu75069ed2023-01-14 00:31:09 +08001478 info.setPort(serviceInfo.getPort());
1479
1480 Map<String, String> attrs = serviceInfo.getAttributes();
1481 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1482 final String key = kv.getKey();
1483 try {
1484 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1485 } catch (IllegalArgumentException e) {
1486 Log.e(TAG, "Invalid attribute", e);
1487 }
1488 }
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001489 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu2b865912023-03-06 14:27:53 +08001490 if (addresses.size() != 0) {
1491 info.setHostAddresses(addresses);
Paul Hua6bc4632023-06-26 01:18:29 +00001492 request.setServiceFromCache(event.mIsServiceFromCache);
1493 clientInfo.onResolveServiceSucceeded(clientRequestId, info, request);
Paul Hu2b865912023-03-06 14:27:53 +08001494 } else {
1495 // No address. Notify resolution failure.
Paul Hua6bc4632023-06-26 01:18:29 +00001496 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001497 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */,
1498 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001499 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu75069ed2023-01-14 00:31:09 +08001500 }
1501
1502 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001503 if (!(request instanceof DiscoveryManagerRequest)) {
1504 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1505 break;
1506 }
Paul Hud44e1b72023-06-16 02:07:42 +00001507 stopDiscoveryManagerRequest(
1508 request, clientRequestId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001509 break;
1510 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001511 case NsdManager.SERVICE_UPDATED: {
1512 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1513 info.setPort(serviceInfo.getPort());
1514
1515 Map<String, String> attrs = serviceInfo.getAttributes();
1516 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1517 final String key = kv.getKey();
1518 try {
1519 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1520 } catch (IllegalArgumentException e) {
1521 Log.e(TAG, "Invalid attribute", e);
1522 }
1523 }
1524
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001525 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001526 info.setHostAddresses(addresses);
Paul Huddce5912023-08-01 10:26:49 +08001527 clientInfo.onServiceUpdated(clientRequestId, info, request);
1528 // Set the ServiceFromCache flag only if the service is actually being
1529 // retrieved from the cache. This flag should not be overridden by later
1530 // service updates, which may not be cached.
1531 if (event.mIsServiceFromCache) {
1532 request.setServiceFromCache(true);
1533 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001534 break;
1535 }
1536 case NsdManager.SERVICE_UPDATED_LOST:
Paul Huddce5912023-08-01 10:26:49 +08001537 clientInfo.onServiceUpdatedLost(clientRequestId, request);
Paul Hu30bd70d2023-02-07 13:20:56 +00001538 break;
Paul Hu019621e2023-01-13 23:26:49 +08001539 default:
1540 return false;
1541 }
1542 return true;
1543 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001544 }
1545 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001546
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001547 @NonNull
1548 private static List<InetAddress> getInetAddresses(@NonNull MdnsServiceInfo serviceInfo) {
1549 final List<String> v4Addrs = serviceInfo.getIpv4Addresses();
1550 final List<String> v6Addrs = serviceInfo.getIpv6Addresses();
1551 final List<InetAddress> addresses = new ArrayList<>(v4Addrs.size() + v6Addrs.size());
1552 for (String ipv4Address : v4Addrs) {
1553 try {
1554 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1555 } catch (IllegalArgumentException e) {
1556 Log.wtf(TAG, "Invalid ipv4 address", e);
1557 }
1558 }
1559 for (String ipv6Address : v6Addrs) {
1560 try {
Yuyang Huanga6a6ff92023-04-24 13:33:34 +09001561 final Inet6Address addr = (Inet6Address) InetAddresses.parseNumericAddress(
1562 ipv6Address);
1563 addresses.add(InetAddressUtils.withScopeId(addr, serviceInfo.getInterfaceIndex()));
1564 } catch (IllegalArgumentException e) {
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001565 Log.wtf(TAG, "Invalid ipv6 address", e);
1566 }
1567 }
1568 return addresses;
1569 }
1570
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001571 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1572 switch (netId) {
1573 case NETID_UNSET:
1574 info.setNetwork(null);
1575 break;
1576 case INetd.LOCAL_NET_ID:
1577 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1578 // visible / usable for apps, so do not return it. Store the interface
1579 // index instead, so at least if the client tries to resolve the service
1580 // with that NsdServiceInfo, it will be done on the same interface.
1581 // If they recreate the NsdServiceInfo themselves, resolution would be
1582 // done on all interfaces as before T, which should also work.
1583 info.setNetwork(null);
1584 info.setInterfaceIndex(ifaceIdx);
1585 break;
1586 default:
1587 info.setNetwork(new Network(netId));
1588 }
1589 }
1590
paulhube186602022-04-12 07:18:23 +00001591 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1592 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1593 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1594 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1595 private String unescape(String s) {
1596 StringBuilder sb = new StringBuilder(s.length());
1597 for (int i = 0; i < s.length(); ++i) {
1598 char c = s.charAt(i);
1599 if (c == '\\') {
1600 if (++i >= s.length()) {
1601 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1602 break;
1603 }
1604 c = s.charAt(i);
1605 if (c != '.' && c != '\\') {
1606 if (i + 2 >= s.length()) {
1607 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1608 break;
1609 }
1610 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1611 + (s.charAt(i + 2) - '0'));
1612 i += 2;
1613 }
1614 }
1615 sb.append(c);
1616 }
1617 return sb.toString();
1618 }
1619
Paul Hu7445e3d2023-03-03 15:14:00 +08001620 /**
1621 * Check the given service type is valid and construct it to a service type
1622 * which can use for discovery / resolution service.
1623 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001624 * <p>The valid service type should be 2 labels, or 3 labels if the query is for a
Paul Hu7445e3d2023-03-03 15:14:00 +08001625 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1626 * underscore; they are alphanumerical characters or dashes or underscore, except the
1627 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1628 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001629 * <p>The subtype may also be specified with a comma after the service type, for example
1630 * _type._tcp,_subtype.
1631 *
Paul Hu7445e3d2023-03-03 15:14:00 +08001632 * @param serviceType the request service type for discovery / resolution service
1633 * @return constructed service type or null if the given service type is invalid.
1634 */
1635 @Nullable
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001636 public static Pair<String, String> parseTypeAndSubtype(String serviceType) {
Paul Hu7445e3d2023-03-03 15:14:00 +08001637 if (TextUtils.isEmpty(serviceType)) return null;
1638
1639 final Pattern serviceTypePattern = Pattern.compile(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001640 // Optional leading subtype (_subtype._type._tcp)
1641 // (?: xxx) is a non-capturing parenthesis, don't capture the dot
Kangping Dong5af24b62023-12-10 21:41:16 +08001642 "^(?:(" + TYPE_SUBTYPE_LABEL_REGEX + ")\\.)?"
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001643 // Actual type (_type._tcp.local)
Kangping Dong5af24b62023-12-10 21:41:16 +08001644 + "(" + TYPE_SUBTYPE_LABEL_REGEX + "\\._(?:tcp|udp))"
Paul Hu7445e3d2023-03-03 15:14:00 +08001645 // Drop '.' at the end of service type that is compatible with old backend.
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001646 // e.g. allow "_type._tcp.local."
1647 + "\\.?"
1648 // Optional subtype after comma, for "_type._tcp,_subtype" format
Kangping Dong5af24b62023-12-10 21:41:16 +08001649 + "(?:,(" + TYPE_SUBTYPE_LABEL_REGEX + "))?"
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001650 + "$");
Paul Hu7445e3d2023-03-03 15:14:00 +08001651 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1652 if (!matcher.matches()) return null;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001653 // Use the subtype either at the beginning or after the comma
1654 final String subtype = matcher.group(1) != null ? matcher.group(1) : matcher.group(3);
1655 return new Pair<>(matcher.group(2), subtype);
Paul Hu7445e3d2023-03-03 15:14:00 +08001656 }
1657
Kangping Dong5af24b62023-12-10 21:41:16 +08001658 /** Returns {@code true} if {@code subtype} is a valid DNS-SD subtype label. */
1659 private static boolean checkSubtypeLabel(String subtype) {
1660 return Pattern.compile("^" + TYPE_SUBTYPE_LABEL_REGEX + "$").matcher(subtype).matches();
1661 }
1662
Hugo Benichi803a2f02017-04-24 11:35:06 +09001663 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001664 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001665 this(ctx, handler, cleanupDelayMs, new Dependencies());
1666 }
1667
1668 @VisibleForTesting
1669 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001670 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001671 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001672 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001673 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001674 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1675 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001676 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001677
Paul Hu14667de2023-04-17 22:42:47 +08001678 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper(),
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001679 LOGGER.forSubComponent("MdnsSocketProvider"), new SocketRequestMonitor());
Yuyang Huang700778b2023-03-08 16:17:05 +09001680 // Netlink monitor starts on boot, and intentionally never stopped, to ensure that all
Yuyang Huangfca402a2023-05-24 14:45:59 +09001681 // address events are received. When the netlink monitor starts, any IP addresses already
1682 // on the interfaces will not be seen. In practice, the network will not connect at boot
1683 // time As a result, all the netlink message should be observed if the netlink monitor
1684 // starts here.
Yuyang Huang700778b2023-03-08 16:17:05 +09001685 handler.post(mMdnsSocketProvider::startNetLinkMonitor);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001686
1687 // NsdService is started after ActivityManager (startOtherServices in SystemServer, vs.
1688 // startBootstrapServices).
1689 mRunningAppActiveImportanceCutoff = mDeps.getDeviceConfigInt(
1690 MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF,
1691 DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF);
1692 final ActivityManager am = ctx.getSystemService(ActivityManager.class);
1693 am.addOnUidImportanceListener(new UidImportanceListener(handler),
1694 mRunningAppActiveImportanceCutoff);
1695
Paul Huf3fe3332023-10-16 17:13:25 +08001696 final MdnsFeatureFlags flags = new MdnsFeatureFlags.Builder()
1697 .setIsMdnsOffloadFeatureEnabled(mDeps.isTetheringFeatureNotChickenedOut(
1698 mContext, MdnsFeatureFlags.NSD_FORCE_DISABLE_MDNS_OFFLOAD))
1699 .setIncludeInetAddressRecordsInProbing(mDeps.isFeatureEnabled(
1700 mContext, MdnsFeatureFlags.INCLUDE_INET_ADDRESS_RECORDS_IN_PROBING))
Paul Hu596a5002023-10-18 17:07:31 +08001701 .setIsExpiredServicesRemovalEnabled(mDeps.isFeatureEnabled(
1702 mContext, MdnsFeatureFlags.NSD_EXPIRED_SERVICES_REMOVAL))
Paul Hufd357ef2023-11-01 16:32:45 +08001703 .setIsLabelCountLimitEnabled(mDeps.isTetheringFeatureNotChickenedOut(
1704 mContext, MdnsFeatureFlags.NSD_LIMIT_LABEL_COUNT))
Paul Huf3fe3332023-10-16 17:13:25 +08001705 .build();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001706 mMdnsSocketClient =
Yuyang Huang7ddf2932023-08-01 18:16:30 +09001707 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider,
Paul Hufd357ef2023-11-01 16:32:45 +08001708 LOGGER.forSubComponent("MdnsMultinetworkSocketClient"), flags);
Paul Hu14667de2023-04-17 22:42:47 +08001709 mMdnsDiscoveryManager = deps.makeMdnsDiscoveryManager(new ExecutorProvider(),
Paul Huf3fe3332023-10-16 17:13:25 +08001710 mMdnsSocketClient, LOGGER.forSubComponent("MdnsDiscoveryManager"), flags);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001711 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1712 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
Yuyang Huangb96a0712023-09-07 15:13:15 +09001713 new AdvertiserCallback(), LOGGER.forSubComponent("MdnsAdvertiser"), flags);
Paul Hu777ed052023-06-19 13:35:15 +00001714 mClock = deps.makeClock();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001715 }
1716
1717 /**
1718 * Dependencies of NsdService, for injection in tests.
1719 */
1720 @VisibleForTesting
1721 public static class Dependencies {
1722 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001723 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001724 *
1725 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001726 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001727 */
1728 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001729 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001730 MDNS_DISCOVERY_MANAGER_VERSION);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001731 }
1732
1733 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001734 * Check whether the MdnsAdvertiser feature is enabled.
1735 *
1736 * @param context The global context information about an app environment.
1737 * @return true if the MdnsAdvertiser feature is enabled.
1738 */
1739 public boolean isMdnsAdvertiserEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001740 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001741 MDNS_ADVERTISER_VERSION);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001742 }
1743
1744 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001745 * Get the type allowlist flag value.
1746 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1747 */
1748 @Nullable
1749 public String getTypeAllowlistFlags() {
1750 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1751 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1752 }
1753
1754 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001755 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001756 */
1757 public boolean isFeatureEnabled(Context context, String feature) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001758 return DeviceConfigUtils.isTetheringFeatureEnabled(context, feature);
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001759 }
1760
1761 /**
Yuyang Huangb96a0712023-09-07 15:13:15 +09001762 * @see DeviceConfigUtils#isTetheringFeatureNotChickenedOut
1763 */
Motomu Utsumied4e7ec2023-09-13 14:58:32 +09001764 public boolean isTetheringFeatureNotChickenedOut(Context context, String feature) {
1765 return DeviceConfigUtils.isTetheringFeatureNotChickenedOut(context, feature);
Yuyang Huangb96a0712023-09-07 15:13:15 +09001766 }
1767
1768 /**
Paul Huf3fe3332023-10-16 17:13:25 +08001769 * @see DeviceConfigUtils#isTrunkStableFeatureEnabled
1770 */
1771 public boolean isTrunkStableFeatureEnabled(String feature) {
1772 return DeviceConfigUtils.isTrunkStableFeatureEnabled(feature);
1773 }
1774
1775 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001776 * @see MdnsDiscoveryManager
1777 */
1778 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
Paul Hu14667de2023-04-17 22:42:47 +08001779 @NonNull ExecutorProvider executorProvider,
Paul Huf3fe3332023-10-16 17:13:25 +08001780 @NonNull MdnsMultinetworkSocketClient socketClient, @NonNull SharedLog sharedLog,
1781 @NonNull MdnsFeatureFlags featureFlags) {
1782 return new MdnsDiscoveryManager(
1783 executorProvider, socketClient, sharedLog, featureFlags);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001784 }
1785
1786 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001787 * @see MdnsAdvertiser
1788 */
1789 public MdnsAdvertiser makeMdnsAdvertiser(
1790 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
Yuyang Huangb96a0712023-09-07 15:13:15 +09001791 @NonNull MdnsAdvertiser.AdvertiserCallback cb, @NonNull SharedLog sharedLog,
1792 MdnsFeatureFlags featureFlags) {
1793 return new MdnsAdvertiser(looper, socketProvider, cb, sharedLog, featureFlags);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001794 }
1795
1796 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001797 * @see MdnsSocketProvider
1798 */
Paul Hu14667de2023-04-17 22:42:47 +08001799 public MdnsSocketProvider makeMdnsSocketProvider(@NonNull Context context,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001800 @NonNull Looper looper, @NonNull SharedLog sharedLog,
1801 @NonNull MdnsSocketProvider.SocketRequestMonitor socketCreationCallback) {
1802 return new MdnsSocketProvider(context, looper, sharedLog, socketCreationCallback);
1803 }
1804
1805 /**
1806 * @see DeviceConfig#getInt(String, String, int)
1807 */
1808 public int getDeviceConfigInt(@NonNull String config, int defaultValue) {
1809 return DeviceConfig.getInt(NAMESPACE_TETHERING, config, defaultValue);
1810 }
1811
1812 /**
1813 * @see Binder#getCallingUid()
1814 */
1815 public int getCallingUid() {
1816 return Binder.getCallingUid();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001817 }
Paul Hu777ed052023-06-19 13:35:15 +00001818
1819 /**
1820 * @see NetworkNsdReportedMetrics
1821 */
Paul Hu508a0122023-09-11 15:31:33 +08001822 public NetworkNsdReportedMetrics makeNetworkNsdReportedMetrics(int clientId) {
1823 return new NetworkNsdReportedMetrics(clientId);
Paul Hu777ed052023-06-19 13:35:15 +00001824 }
1825
1826 /**
1827 * @see MdnsUtils.Clock
1828 */
1829 public Clock makeClock() {
1830 return new Clock();
1831 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001832 }
1833
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001834 /**
1835 * Return whether a type is allowlisted to use the Java backend.
1836 * @param type The service type
1837 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1838 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1839 */
1840 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1841 @NonNull String flagPrefix) {
1842 if (type == null) return false;
1843 final String typesConfig = mDeps.getTypeAllowlistFlags();
1844 if (TextUtils.isEmpty(typesConfig)) return false;
1845
1846 final String mappingPrefix = type + ":";
1847 String mappedFlag = null;
1848 for (String mapping : TextUtils.split(typesConfig, ",")) {
1849 if (mapping.startsWith(mappingPrefix)) {
1850 mappedFlag = mapping.substring(mappingPrefix.length());
1851 break;
1852 }
1853 }
1854
1855 if (mappedFlag == null) return false;
1856
1857 return mDeps.isFeatureEnabled(mContext,
1858 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1859 }
1860
1861 private boolean useDiscoveryManagerForType(@Nullable String type) {
1862 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1863 }
1864
1865 private boolean useAdvertiserForType(@Nullable String type) {
1866 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1867 }
1868
paulhu1b35e822022-04-08 14:48:41 +08001869 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001870 HandlerThread thread = new HandlerThread(TAG);
1871 thread.start();
1872 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001873 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001874 return service;
1875 }
1876
paulhu2b9ed952022-02-10 21:58:32 +08001877 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1878 private final StateMachine mStateMachine;
1879
1880 MDnsEventCallback(StateMachine sm) {
1881 mStateMachine = sm;
1882 }
1883
1884 @Override
1885 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1886 mStateMachine.sendMessage(
1887 MDNS_SERVICE_EVENT, status.result, status.id, status);
1888 }
1889
1890 @Override
1891 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1892 mStateMachine.sendMessage(
1893 MDNS_SERVICE_EVENT, status.result, status.id, status);
1894 }
1895
1896 @Override
1897 public void onServiceResolutionStatus(final ResolutionInfo status) {
1898 mStateMachine.sendMessage(
1899 MDNS_SERVICE_EVENT, status.result, status.id, status);
1900 }
1901
1902 @Override
1903 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1904 mStateMachine.sendMessage(
1905 MDNS_SERVICE_EVENT, status.result, status.id, status);
1906 }
1907
1908 @Override
1909 public int getInterfaceVersion() throws RemoteException {
1910 return this.VERSION;
1911 }
1912
1913 @Override
1914 public String getInterfaceHash() throws RemoteException {
1915 return this.HASH;
1916 }
1917 }
1918
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001919 private void sendAllOffloadServiceInfos(@NonNull OffloadEngineInfo offloadEngineInfo) {
1920 final String targetInterface = offloadEngineInfo.mInterfaceName;
1921 final IOffloadEngine offloadEngine = offloadEngineInfo.mOffloadEngine;
1922 final List<MdnsAdvertiser.OffloadServiceInfoWrapper> offloadWrappers =
1923 mAdvertiser.getAllInterfaceOffloadServiceInfos(targetInterface);
1924 for (MdnsAdvertiser.OffloadServiceInfoWrapper wrapper : offloadWrappers) {
1925 try {
1926 offloadEngine.onOffloadServiceUpdated(wrapper.mOffloadServiceInfo);
1927 } catch (RemoteException e) {
1928 // Can happen in regular cases, do not log a stacktrace
1929 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
1930 }
1931 }
1932 }
1933
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001934 private void sendOffloadServiceInfosUpdate(@NonNull String targetInterfaceName,
1935 @NonNull OffloadServiceInfo offloadServiceInfo, boolean isRemove) {
1936 final int count = mOffloadEngines.beginBroadcast();
1937 try {
1938 for (int i = 0; i < count; i++) {
1939 final OffloadEngineInfo offloadEngineInfo =
1940 (OffloadEngineInfo) mOffloadEngines.getBroadcastCookie(i);
1941 final String interfaceName = offloadEngineInfo.mInterfaceName;
1942 if (!targetInterfaceName.equals(interfaceName)
1943 || ((offloadEngineInfo.mOffloadType
1944 & offloadServiceInfo.getOffloadType()) == 0)) {
1945 continue;
1946 }
1947 try {
1948 if (isRemove) {
1949 mOffloadEngines.getBroadcastItem(i).onOffloadServiceRemoved(
1950 offloadServiceInfo);
1951 } else {
1952 mOffloadEngines.getBroadcastItem(i).onOffloadServiceUpdated(
1953 offloadServiceInfo);
1954 }
1955 } catch (RemoteException e) {
1956 // Can happen in regular cases, do not log a stacktrace
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001957 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001958 }
1959 }
1960 } finally {
1961 mOffloadEngines.finishBroadcast();
1962 }
1963 }
1964
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001965 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001966 // TODO: add a callback to notify when a service is being added on each interface (as soon
1967 // as probing starts), and call mOffloadCallbacks. This callback is for
1968 // OFFLOAD_CAPABILITY_FILTER_REPLIES offload type.
1969
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001970 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001971 public void onRegisterServiceSucceeded(int transactionId, NsdServiceInfo registeredInfo) {
1972 mServiceLogs.log("onRegisterServiceSucceeded: transactionId " + transactionId);
1973 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001974 if (clientInfo == null) return;
1975
Paul Hud44e1b72023-06-16 02:07:42 +00001976 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1977 if (clientRequestId < 0) return;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001978
1979 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1980 // historical behavior.
1981 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
Paul Hu777ed052023-06-19 13:35:15 +00001982 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu508a0122023-09-11 15:31:33 +08001983 clientInfo.onRegisterServiceSucceeded(clientRequestId, cbInfo, request);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001984 }
1985
1986 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001987 public void onRegisterServiceFailed(int transactionId, int errorCode) {
1988 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001989 if (clientInfo == null) return;
1990
Paul Hud44e1b72023-06-16 02:07:42 +00001991 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1992 if (clientRequestId < 0) return;
Paul Hu777ed052023-06-19 13:35:15 +00001993 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu508a0122023-09-11 15:31:33 +08001994 clientInfo.onRegisterServiceFailed(clientRequestId, errorCode, false /* isLegacy */,
1995 transactionId, request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001996 }
1997
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001998 @Override
1999 public void onOffloadStartOrUpdate(@NonNull String interfaceName,
2000 @NonNull OffloadServiceInfo offloadServiceInfo) {
2001 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, false /* isRemove */);
2002 }
2003
2004 @Override
2005 public void onOffloadStop(@NonNull String interfaceName,
2006 @NonNull OffloadServiceInfo offloadServiceInfo) {
2007 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, true /* isRemove */);
2008 }
2009
Paul Hud44e1b72023-06-16 02:07:42 +00002010 private ClientInfo getClientInfoOrLog(int transactionId) {
2011 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002012 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00002013 Log.e(TAG, String.format("Callback for service %d has no client", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002014 }
2015 return clientInfo;
2016 }
2017
Paul Hud44e1b72023-06-16 02:07:42 +00002018 private int getClientRequestIdOrLog(@NonNull ClientInfo info, int transactionId) {
2019 final int clientRequestId = info.getClientRequestId(transactionId);
2020 if (clientRequestId < 0) {
2021 Log.e(TAG, String.format(
2022 "Client request ID not found for service %d", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002023 }
Paul Hud44e1b72023-06-16 02:07:42 +00002024 return clientRequestId;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002025 }
2026 }
2027
Paul Hu2e0a88c2023-03-09 16:05:01 +08002028 private static class ConnectorArgs {
2029 @NonNull public final NsdServiceConnector connector;
2030 @NonNull public final INsdManagerCallback callback;
2031 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002032 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002033
2034 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00002035 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08002036 this.connector = connector;
2037 this.callback = callback;
2038 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002039 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002040 }
2041 }
2042
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002043 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08002044 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09002045 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu101dbf52023-08-09 16:05:20 +08002046 final int uid = mDeps.getCallingUid();
2047 if (cb == null) {
2048 throw new IllegalArgumentException("Unknown client callback from uid=" + uid);
2049 }
Paul Hu2e0a88c2023-03-09 16:05:01 +08002050 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002051 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00002052 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
Paul Hu101dbf52023-08-09 16:05:20 +08002053 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend, uid)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002054 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07002055 }
2056
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002057 private static class ListenerArgs {
2058 public final NsdServiceConnector connector;
2059 public final NsdServiceInfo serviceInfo;
2060 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
2061 this.connector = connector;
2062 this.serviceInfo = serviceInfo;
2063 }
2064 }
2065
2066 private class NsdServiceConnector extends INsdServiceConnector.Stub
2067 implements IBinder.DeathRecipient {
2068 @Override
2069 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
2070 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2071 NsdManager.REGISTER_SERVICE, 0, listenerKey,
2072 new ListenerArgs(this, serviceInfo)));
2073 }
2074
2075 @Override
2076 public void unregisterService(int listenerKey) {
2077 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2078 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
2079 new ListenerArgs(this, null)));
2080 }
2081
2082 @Override
2083 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
2084 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2085 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
2086 new ListenerArgs(this, serviceInfo)));
2087 }
2088
2089 @Override
2090 public void stopDiscovery(int listenerKey) {
2091 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2092 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
2093 }
2094
2095 @Override
2096 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
2097 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2098 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
2099 new ListenerArgs(this, serviceInfo)));
2100 }
2101
2102 @Override
Paul Hub58deb72022-12-26 09:24:42 +00002103 public void stopResolution(int listenerKey) {
2104 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2105 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
2106 }
2107
2108 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00002109 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
2110 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2111 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
2112 new ListenerArgs(this, serviceInfo)));
2113 }
2114
2115 @Override
2116 public void unregisterServiceInfoCallback(int listenerKey) {
2117 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2118 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
2119 new ListenerArgs(this, null)));
2120 }
2121
2122 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002123 public void startDaemon() {
2124 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2125 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
2126 }
2127
2128 @Override
2129 public void binderDied() {
2130 mNsdStateMachine.sendMessage(
2131 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002132
2133 }
2134
2135 @Override
2136 public void registerOffloadEngine(String ifaceName, IOffloadEngine cb,
2137 @OffloadEngine.OffloadCapability long offloadCapabilities,
2138 @OffloadEngine.OffloadType long offloadTypes) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002139 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002140 Objects.requireNonNull(ifaceName);
2141 Objects.requireNonNull(cb);
2142 mNsdStateMachine.sendMessage(
2143 mNsdStateMachine.obtainMessage(NsdManager.REGISTER_OFFLOAD_ENGINE,
2144 new OffloadEngineInfo(cb, ifaceName, offloadCapabilities,
2145 offloadTypes)));
2146 }
2147
2148 @Override
2149 public void unregisterOffloadEngine(IOffloadEngine cb) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002150 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002151 Objects.requireNonNull(cb);
2152 mNsdStateMachine.sendMessage(
2153 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_OFFLOAD_ENGINE, cb));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002154 }
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002155
2156 private static void checkOffloadEnginePermission(Context context) {
2157 if (!SdkLevel.isAtLeastT()) {
2158 throw new SecurityException("API is not available in before API level 33");
2159 }
Yuyang Huangd5896e72023-11-28 13:23:59 +09002160
2161 // REGISTER_NSD_OFFLOAD_ENGINE was only added to the SDK in V.
2162 if (SdkLevel.isAtLeastV() && PermissionUtils.checkAnyPermissionOf(context,
2163 REGISTER_NSD_OFFLOAD_ENGINE)) {
2164 return;
2165 }
2166
2167 // REGISTER_NSD_OFFLOAD_ENGINE cannot be backport to U. In U, check the DEVICE_POWER
2168 // permission instead.
2169 if (!SdkLevel.isAtLeastV() && SdkLevel.isAtLeastU()
2170 && PermissionUtils.checkAnyPermissionOf(context, DEVICE_POWER)) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002171 return;
2172 }
2173 if (PermissionUtils.checkAnyPermissionOf(context, NETWORK_STACK,
2174 PERMISSION_MAINLINE_NETWORK_STACK, NETWORK_SETTINGS)) {
2175 return;
2176 }
2177 throw new SecurityException("Requires one of the following permissions: "
2178 + String.join(", ", List.of(REGISTER_NSD_OFFLOAD_ENGINE, NETWORK_STACK,
2179 PERMISSION_MAINLINE_NETWORK_STACK, NETWORK_SETTINGS)) + ".");
2180 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002181 }
2182
Hugo Benichi912db992017-04-24 16:41:03 +09002183 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07002184 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07002185 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09002186 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
2187 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07002188 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07002189 }
2190
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002191 private int getUniqueId() {
2192 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
2193 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002194 }
2195
Paul Hud44e1b72023-06-16 02:07:42 +00002196 private boolean registerService(int transactionId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09002197 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002198 Log.d(TAG, "registerService: " + transactionId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002199 }
Hugo Benichi6d706442017-04-24 16:19:58 +09002200 String name = service.getServiceName();
2201 String type = service.getServiceType();
2202 int port = service.getPort();
2203 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002204 final int registerInterface = getNetworkInterfaceIndex(service);
2205 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08002206 Log.e(TAG, "Interface to register service on not found");
2207 return false;
2208 }
Paul Hud44e1b72023-06-16 02:07:42 +00002209 return mMDnsManager.registerService(
2210 transactionId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002211 }
2212
Paul Hud44e1b72023-06-16 02:07:42 +00002213 private boolean unregisterService(int transactionId) {
2214 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002215 }
2216
Paul Hud44e1b72023-06-16 02:07:42 +00002217 private boolean discoverServices(int transactionId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08002218 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002219 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
2220 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002221 Log.e(TAG, "Interface to discover service on not found");
2222 return false;
2223 }
Paul Hud44e1b72023-06-16 02:07:42 +00002224 return mMDnsManager.discover(transactionId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002225 }
2226
Paul Hud44e1b72023-06-16 02:07:42 +00002227 private boolean stopServiceDiscovery(int transactionId) {
2228 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002229 }
2230
Paul Hud44e1b72023-06-16 02:07:42 +00002231 private boolean resolveService(int transactionId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002232 final String name = service.getServiceName();
2233 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002234 final int resolveInterface = getNetworkInterfaceIndex(service);
2235 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002236 Log.e(TAG, "Interface to resolve service on not found");
2237 return false;
2238 }
Paul Hud44e1b72023-06-16 02:07:42 +00002239 return mMDnsManager.resolve(transactionId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002240 }
2241
2242 /**
2243 * Guess the interface to use to resolve or discover a service on a specific network.
2244 *
2245 * This is an imperfect guess, as for example the network may be gone or not yet fully
2246 * registered. This is fine as failing is correct if the network is gone, and a client
2247 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
2248 * this is to support the legacy mdnsresponder implementation, which historically resolved
2249 * services on an unspecified network.
2250 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002251 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
2252 final Network network = serviceInfo.getNetwork();
2253 if (network == null) {
2254 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
2255 // provided by NsdService from discovery results, and the service was found on an
2256 // interface that has no app-usable Network).
2257 if (serviceInfo.getInterfaceIndex() != 0) {
2258 return serviceInfo.getInterfaceIndex();
2259 }
2260 return IFACE_IDX_ANY;
2261 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002262
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002263 String interfaceName = getNetworkInterfaceName(network);
2264 if (interfaceName == null) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002265 return IFACE_IDX_ANY;
2266 }
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002267 return getNetworkInterfaceIndexByName(interfaceName);
2268 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002269
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002270 private String getNetworkInterfaceName(@Nullable Network network) {
2271 if (network == null) {
2272 return null;
2273 }
2274 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
2275 if (cm == null) {
2276 Log.wtf(TAG, "No ConnectivityManager");
2277 return null;
2278 }
2279 final LinkProperties lp = cm.getLinkProperties(network);
2280 if (lp == null) {
2281 return null;
2282 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002283 // Only resolve on non-stacked interfaces
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002284 return lp.getInterfaceName();
2285 }
2286
2287 private int getNetworkInterfaceIndexByName(final String ifaceName) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002288 final NetworkInterface iface;
2289 try {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002290 iface = NetworkInterface.getByName(ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002291 } catch (SocketException e) {
2292 Log.e(TAG, "Error querying interface", e);
2293 return IFACE_IDX_ANY;
2294 }
2295
2296 if (iface == null) {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002297 Log.e(TAG, "Interface not found: " + ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002298 return IFACE_IDX_ANY;
2299 }
2300
2301 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002302 }
2303
Paul Hud44e1b72023-06-16 02:07:42 +00002304 private boolean stopResolveService(int transactionId) {
2305 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002306 }
2307
Paul Hud44e1b72023-06-16 02:07:42 +00002308 private boolean getAddrInfo(int transactionId, String hostname, int interfaceIdx) {
2309 return mMDnsManager.getServiceAddress(transactionId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002310 }
2311
Paul Hud44e1b72023-06-16 02:07:42 +00002312 private boolean stopGetAddrInfo(int transactionId) {
2313 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002314 }
2315
2316 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00002317 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2318 if (!PermissionUtils.checkDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002319
Paul Hub2e67d32023-04-18 05:50:14 +00002320 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
2321 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07002322 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00002323
2324 // Dump service and clients logs
2325 pw.println();
Paul Hu14667de2023-04-17 22:42:47 +08002326 pw.println("Logs:");
Paul Hub2e67d32023-04-18 05:50:14 +00002327 pw.increaseIndent();
2328 mServiceLogs.reverseDump(pw);
2329 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002330 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002331
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002332 private abstract static class ClientRequest {
Paul Hud44e1b72023-06-16 02:07:42 +00002333 private final int mTransactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002334 private final long mStartTimeMs;
Paul Hu812e9212023-06-20 06:24:53 +00002335 private int mFoundServiceCount = 0;
2336 private int mLostServiceCount = 0;
2337 private final Set<String> mServices = new ArraySet<>();
Paul Hua6bc4632023-06-26 01:18:29 +00002338 private boolean mIsServiceFromCache = false;
Paul Hubad6fe92023-07-24 21:25:22 +08002339 private int mSentQueryCount = NO_SENT_QUERY_COUNT;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002340
Paul Hu812e9212023-06-20 06:24:53 +00002341 private ClientRequest(int transactionId, long startTimeMs) {
Paul Hud44e1b72023-06-16 02:07:42 +00002342 mTransactionId = transactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002343 mStartTimeMs = startTimeMs;
2344 }
2345
Paul Hu812e9212023-06-20 06:24:53 +00002346 public long calculateRequestDurationMs(long stopTimeMs) {
Paul Hu777ed052023-06-19 13:35:15 +00002347 return stopTimeMs - mStartTimeMs;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002348 }
Paul Hu812e9212023-06-20 06:24:53 +00002349
2350 public void onServiceFound(String serviceName) {
2351 mFoundServiceCount++;
2352 if (mServices.size() <= MAX_SERVICES_COUNT_METRIC_PER_CLIENT) {
2353 mServices.add(serviceName);
2354 }
2355 }
2356
2357 public void onServiceLost() {
2358 mLostServiceCount++;
2359 }
2360
2361 public int getFoundServiceCount() {
2362 return mFoundServiceCount;
2363 }
2364
2365 public int getLostServiceCount() {
2366 return mLostServiceCount;
2367 }
2368
2369 public int getServicesCount() {
2370 return mServices.size();
2371 }
Paul Hua6bc4632023-06-26 01:18:29 +00002372
2373 public void setServiceFromCache(boolean isServiceFromCache) {
2374 mIsServiceFromCache = isServiceFromCache;
2375 }
2376
2377 public boolean isServiceFromCache() {
2378 return mIsServiceFromCache;
2379 }
Paul Hubad6fe92023-07-24 21:25:22 +08002380
2381 public void onQuerySent() {
2382 mSentQueryCount++;
2383 }
2384
2385 public int getSentQueryCount() {
2386 return mSentQueryCount;
2387 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002388 }
2389
2390 private static class LegacyClientRequest extends ClientRequest {
2391 private final int mRequestCode;
2392
Paul Hu812e9212023-06-20 06:24:53 +00002393 private LegacyClientRequest(int transactionId, int requestCode, long startTimeMs) {
2394 super(transactionId, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002395 mRequestCode = requestCode;
2396 }
2397 }
2398
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002399 private abstract static class JavaBackendClientRequest extends ClientRequest {
2400 @Nullable
2401 private final Network mRequestedNetwork;
2402
Paul Hu777ed052023-06-19 13:35:15 +00002403 private JavaBackendClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002404 long startTimeMs) {
2405 super(transactionId, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002406 mRequestedNetwork = requestedNetwork;
2407 }
2408
2409 @Nullable
2410 public Network getRequestedNetwork() {
2411 return mRequestedNetwork;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002412 }
2413 }
2414
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002415 private static class AdvertiserClientRequest extends JavaBackendClientRequest {
Paul Hu777ed052023-06-19 13:35:15 +00002416 private AdvertiserClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002417 long startTimeMs) {
2418 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002419 }
2420 }
2421
2422 private static class DiscoveryManagerRequest extends JavaBackendClientRequest {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002423 @NonNull
2424 private final MdnsListener mListener;
2425
Paul Hud44e1b72023-06-16 02:07:42 +00002426 private DiscoveryManagerRequest(int transactionId, @NonNull MdnsListener listener,
Paul Hu812e9212023-06-20 06:24:53 +00002427 @Nullable Network requestedNetwork, long startTimeMs) {
2428 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002429 mListener = listener;
2430 }
2431 }
2432
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002433 /* Information tracked per client */
2434 private class ClientInfo {
2435
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002436 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002437 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002438 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002439 private NsdServiceInfo mResolvedService;
2440
Paul Hud44e1b72023-06-16 02:07:42 +00002441 /* A map from client request ID (listenerKey) to the request */
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002442 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08002443
Luke Huangf7277ed2021-07-12 21:15:10 +08002444 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002445 private boolean mIsPreSClient = false;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002446 private final int mUid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002447 // The flag of using java backend if the client's target SDK >= U
2448 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002449 // Store client logs
2450 private final SharedLog mClientLogs;
Paul Hucdef3532023-06-18 14:47:35 +00002451 // Report the nsd metrics data
2452 private final NetworkNsdReportedMetrics mMetrics;
Luke Huangf7277ed2021-07-12 21:15:10 +08002453
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002454 private ClientInfo(INsdManagerCallback cb, int uid, boolean useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +00002455 SharedLog sharedLog, NetworkNsdReportedMetrics metrics) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002456 mCb = cb;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002457 mUid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002458 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002459 mClientLogs = sharedLog;
2460 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Paul Hucdef3532023-06-18 14:47:35 +00002461 mMetrics = metrics;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002462 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002463
2464 @Override
2465 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06002466 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07002467 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002468 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002469 sb.append("mUseJavaBackend ").append(mUseJavaBackend).append("\n");
2470 sb.append("mUid ").append(mUid).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002471 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002472 int clientRequestId = mClientRequests.keyAt(i);
2473 sb.append("clientRequestId ")
2474 .append(clientRequestId)
2475 .append(" transactionId ").append(mClientRequests.valueAt(i).mTransactionId)
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002476 .append(" type ").append(
2477 mClientRequests.valueAt(i).getClass().getSimpleName())
2478 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07002479 }
2480 return sb.toString();
2481 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002482
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002483 private boolean isPreSClient() {
2484 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08002485 }
2486
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002487 private void setPreSClient() {
2488 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08002489 }
2490
Paul Hu812e9212023-06-20 06:24:53 +00002491 private MdnsListener unregisterMdnsListenerFromRequest(ClientRequest request) {
Paul Hue4f5f252023-02-16 21:13:47 +08002492 final MdnsListener listener =
2493 ((DiscoveryManagerRequest) request).mListener;
2494 mMdnsDiscoveryManager.unregisterListener(
2495 listener.getListenedServiceType(), listener);
Paul Hu812e9212023-06-20 06:24:53 +00002496 return listener;
Paul Hue4f5f252023-02-16 21:13:47 +08002497 }
2498
Dave Plattfeff2af2014-03-07 14:48:22 -08002499 // Remove any pending requests from the global map when we get rid of a client,
2500 // and send cancellations to the daemon.
2501 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00002502 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09002503 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002504 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002505 final int clientRequestId = mClientRequests.keyAt(i);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002506 final ClientRequest request = mClientRequests.valueAt(i);
Paul Hud44e1b72023-06-16 02:07:42 +00002507 final int transactionId = request.mTransactionId;
2508 mTransactionIdToClientInfoMap.remove(transactionId);
paulhub2225702021-11-17 09:35:33 +08002509 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002510 Log.d(TAG, "Terminating clientRequestId " + clientRequestId
2511 + " transactionId " + transactionId
2512 + " type " + mClientRequests.get(clientRequestId));
paulhub2225702021-11-17 09:35:33 +08002513 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002514
2515 if (request instanceof DiscoveryManagerRequest) {
Paul Hu812e9212023-06-20 06:24:53 +00002516 final MdnsListener listener = unregisterMdnsListenerFromRequest(request);
2517 if (listener instanceof DiscoveryListener) {
Paul Hu508a0122023-09-11 15:31:33 +08002518 mMetrics.reportServiceDiscoveryStop(false /* isLegacy */, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00002519 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2520 request.getFoundServiceCount(),
2521 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002522 request.getServicesCount(),
2523 request.getSentQueryCount());
Paul Hu60149052023-07-31 14:26:08 +08002524 } else if (listener instanceof ResolutionListener) {
Paul Hu508a0122023-09-11 15:31:33 +08002525 mMetrics.reportServiceResolutionStop(false /* isLegacy */, transactionId,
Paul Hu60149052023-07-31 14:26:08 +08002526 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Huddce5912023-08-01 10:26:49 +08002527 } else if (listener instanceof ServiceInfoListener) {
2528 mMetrics.reportServiceInfoCallbackUnregistered(transactionId,
2529 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2530 request.getFoundServiceCount(),
2531 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002532 request.isServiceFromCache(),
2533 request.getSentQueryCount());
Paul Hu812e9212023-06-20 06:24:53 +00002534 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002535 continue;
2536 }
2537
2538 if (request instanceof AdvertiserClientRequest) {
Paul Hu043bcd42023-07-14 16:38:25 +08002539 final AdvertiserMetrics metrics =
2540 mAdvertiser.getAdvertiserMetrics(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00002541 mAdvertiser.removeService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002542 mMetrics.reportServiceUnregistration(false /* isLegacy */, transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002543 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2544 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2545 metrics.mConflictDuringProbingCount,
2546 metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002547 continue;
2548 }
2549
2550 if (!(request instanceof LegacyClientRequest)) {
2551 throw new IllegalStateException("Unknown request type: " + request.getClass());
2552 }
2553
2554 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08002555 case NsdManager.DISCOVER_SERVICES:
Paul Hud44e1b72023-06-16 02:07:42 +00002556 stopServiceDiscovery(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002557 mMetrics.reportServiceDiscoveryStop(true /* isLegacy */, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00002558 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2559 request.getFoundServiceCount(),
2560 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002561 request.getServicesCount(),
2562 NO_SENT_QUERY_COUNT);
Dave Plattfeff2af2014-03-07 14:48:22 -08002563 break;
2564 case NsdManager.RESOLVE_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002565 stopResolveService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002566 mMetrics.reportServiceResolutionStop(true /* isLegacy */, transactionId,
Paul Hu60149052023-07-31 14:26:08 +08002567 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Dave Plattfeff2af2014-03-07 14:48:22 -08002568 break;
2569 case NsdManager.REGISTER_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002570 unregisterService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002571 mMetrics.reportServiceUnregistration(true /* isLegacy */, transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002572 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2573 NO_PACKET /* repliedRequestsCount */,
2574 NO_PACKET /* sentPacketCount */,
2575 0 /* conflictDuringProbingCount */,
2576 0 /* conflictAfterProbingCount */);
Dave Plattfeff2af2014-03-07 14:48:22 -08002577 break;
2578 default:
2579 break;
2580 }
2581 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002582 mClientRequests.clear();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002583 updateMulticastLock();
2584 }
2585
2586 /**
2587 * Returns true if this client has any Java backend request that requests one of the given
2588 * networks.
2589 */
2590 boolean hasAnyJavaBackendRequestForNetworks(@NonNull ArraySet<Network> networks) {
2591 for (int i = 0; i < mClientRequests.size(); i++) {
2592 final ClientRequest req = mClientRequests.valueAt(i);
2593 if (!(req instanceof JavaBackendClientRequest)) {
2594 continue;
2595 }
2596 final Network reqNetwork = ((JavaBackendClientRequest) mClientRequests.valueAt(i))
2597 .getRequestedNetwork();
2598 if (MdnsUtils.isAnyNetworkMatched(reqNetwork, networks)) {
2599 return true;
2600 }
2601 }
2602 return false;
Dave Plattfeff2af2014-03-07 14:48:22 -08002603 }
2604
Paul Hud44e1b72023-06-16 02:07:42 +00002605 // mClientRequests is a sparse array of client request id -> ClientRequest. For a given
2606 // transaction id, return the corresponding client request id.
2607 private int getClientRequestId(final int transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002608 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002609 if (mClientRequests.valueAt(i).mTransactionId == transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002610 return mClientRequests.keyAt(i);
2611 }
Christopher Lane74411222014-04-25 18:39:07 -07002612 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002613 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07002614 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002615
Paul Hub2e67d32023-04-18 05:50:14 +00002616 private void log(String message) {
2617 mClientLogs.log(message);
2618 }
2619
Paul Hu508a0122023-09-11 15:31:33 +08002620 private static boolean isLegacyClientRequest(@NonNull ClientRequest request) {
2621 return !(request instanceof DiscoveryManagerRequest)
2622 && !(request instanceof AdvertiserClientRequest);
2623 }
2624
2625 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info,
2626 ClientRequest request) {
2627 mMetrics.reportServiceDiscoveryStarted(
2628 isLegacyClientRequest(request), request.mTransactionId);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002629 try {
2630 mCb.onDiscoverServicesStarted(listenerKey, info);
2631 } catch (RemoteException e) {
2632 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
2633 }
2634 }
Paul Hu508a0122023-09-11 15:31:33 +08002635 void onDiscoverServicesFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2636 onDiscoverServicesFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2637 0L /* durationMs */);
Paul Hu812e9212023-06-20 06:24:53 +00002638 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002639
Paul Hu508a0122023-09-11 15:31:33 +08002640 void onDiscoverServicesFailed(int listenerKey, int error, boolean isLegacy,
2641 int transactionId, long durationMs) {
2642 mMetrics.reportServiceDiscoveryFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002643 try {
2644 mCb.onDiscoverServicesFailed(listenerKey, error);
2645 } catch (RemoteException e) {
2646 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
2647 }
2648 }
2649
Paul Hu812e9212023-06-20 06:24:53 +00002650 void onServiceFound(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2651 request.onServiceFound(info.getServiceName());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002652 try {
2653 mCb.onServiceFound(listenerKey, info);
2654 } catch (RemoteException e) {
2655 Log.e(TAG, "Error calling onServiceFound(", e);
2656 }
2657 }
2658
Paul Hu812e9212023-06-20 06:24:53 +00002659 void onServiceLost(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2660 request.onServiceLost();
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002661 try {
2662 mCb.onServiceLost(listenerKey, info);
2663 } catch (RemoteException e) {
2664 Log.e(TAG, "Error calling onServiceLost(", e);
2665 }
2666 }
2667
2668 void onStopDiscoveryFailed(int listenerKey, int error) {
2669 try {
2670 mCb.onStopDiscoveryFailed(listenerKey, error);
2671 } catch (RemoteException e) {
2672 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
2673 }
2674 }
2675
Paul Hu812e9212023-06-20 06:24:53 +00002676 void onStopDiscoverySucceeded(int listenerKey, ClientRequest request) {
2677 mMetrics.reportServiceDiscoveryStop(
Paul Hu508a0122023-09-11 15:31:33 +08002678 isLegacyClientRequest(request),
Paul Hu812e9212023-06-20 06:24:53 +00002679 request.mTransactionId,
2680 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2681 request.getFoundServiceCount(),
2682 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002683 request.getServicesCount(),
2684 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002685 try {
2686 mCb.onStopDiscoverySucceeded(listenerKey);
2687 } catch (RemoteException e) {
2688 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
2689 }
2690 }
2691
Paul Hu508a0122023-09-11 15:31:33 +08002692 void onRegisterServiceFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2693 onRegisterServiceFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2694 0L /* durationMs */);
Paul Hu777ed052023-06-19 13:35:15 +00002695 }
2696
Paul Hu508a0122023-09-11 15:31:33 +08002697 void onRegisterServiceFailed(int listenerKey, int error, boolean isLegacy,
2698 int transactionId, long durationMs) {
2699 mMetrics.reportServiceRegistrationFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002700 try {
2701 mCb.onRegisterServiceFailed(listenerKey, error);
2702 } catch (RemoteException e) {
2703 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2704 }
2705 }
2706
Paul Hu508a0122023-09-11 15:31:33 +08002707 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info,
2708 ClientRequest request) {
2709 mMetrics.reportServiceRegistrationSucceeded(isLegacyClientRequest(request),
2710 request.mTransactionId,
2711 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002712 try {
2713 mCb.onRegisterServiceSucceeded(listenerKey, info);
2714 } catch (RemoteException e) {
2715 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2716 }
2717 }
2718
2719 void onUnregisterServiceFailed(int listenerKey, int error) {
2720 try {
2721 mCb.onUnregisterServiceFailed(listenerKey, error);
2722 } catch (RemoteException e) {
2723 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2724 }
2725 }
2726
Paul Hu508a0122023-09-11 15:31:33 +08002727 void onUnregisterServiceSucceeded(int listenerKey, ClientRequest request,
Paul Hu043bcd42023-07-14 16:38:25 +08002728 AdvertiserMetrics metrics) {
Paul Hu508a0122023-09-11 15:31:33 +08002729 mMetrics.reportServiceUnregistration(isLegacyClientRequest(request),
2730 request.mTransactionId,
2731 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hu043bcd42023-07-14 16:38:25 +08002732 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2733 metrics.mConflictDuringProbingCount, metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002734 try {
2735 mCb.onUnregisterServiceSucceeded(listenerKey);
2736 } catch (RemoteException e) {
2737 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2738 }
2739 }
2740
Paul Hu508a0122023-09-11 15:31:33 +08002741 void onResolveServiceFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2742 onResolveServiceFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2743 0L /* durationMs */);
Paul Hua6bc4632023-06-26 01:18:29 +00002744 }
2745
Paul Hu508a0122023-09-11 15:31:33 +08002746 void onResolveServiceFailed(int listenerKey, int error, boolean isLegacy,
2747 int transactionId, long durationMs) {
2748 mMetrics.reportServiceResolutionFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002749 try {
2750 mCb.onResolveServiceFailed(listenerKey, error);
2751 } catch (RemoteException e) {
2752 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2753 }
2754 }
2755
Paul Hua6bc4632023-06-26 01:18:29 +00002756 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info,
2757 ClientRequest request) {
2758 mMetrics.reportServiceResolved(
Paul Hu508a0122023-09-11 15:31:33 +08002759 isLegacyClientRequest(request),
Paul Hua6bc4632023-06-26 01:18:29 +00002760 request.mTransactionId,
2761 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hubad6fe92023-07-24 21:25:22 +08002762 request.isServiceFromCache(),
2763 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002764 try {
2765 mCb.onResolveServiceSucceeded(listenerKey, info);
2766 } catch (RemoteException e) {
2767 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2768 }
2769 }
Paul Hub58deb72022-12-26 09:24:42 +00002770
2771 void onStopResolutionFailed(int listenerKey, int error) {
2772 try {
2773 mCb.onStopResolutionFailed(listenerKey, error);
2774 } catch (RemoteException e) {
2775 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2776 }
2777 }
2778
Paul Hu60149052023-07-31 14:26:08 +08002779 void onStopResolutionSucceeded(int listenerKey, ClientRequest request) {
2780 mMetrics.reportServiceResolutionStop(
Paul Hu508a0122023-09-11 15:31:33 +08002781 isLegacyClientRequest(request),
Paul Hu60149052023-07-31 14:26:08 +08002782 request.mTransactionId,
2783 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hub58deb72022-12-26 09:24:42 +00002784 try {
2785 mCb.onStopResolutionSucceeded(listenerKey);
2786 } catch (RemoteException e) {
2787 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2788 }
2789 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002790
2791 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
Paul Huddce5912023-08-01 10:26:49 +08002792 mMetrics.reportServiceInfoCallbackRegistrationFailed(NO_TRANSACTION);
Paul Hu18aeccc2022-12-27 08:48:48 +00002793 try {
2794 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2795 } catch (RemoteException e) {
2796 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2797 }
2798 }
2799
Paul Huddce5912023-08-01 10:26:49 +08002800 void onServiceInfoCallbackRegistered(int transactionId) {
2801 mMetrics.reportServiceInfoCallbackRegistered(transactionId);
2802 }
2803
2804 void onServiceUpdated(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2805 request.onServiceFound(info.getServiceName());
Paul Hu18aeccc2022-12-27 08:48:48 +00002806 try {
2807 mCb.onServiceUpdated(listenerKey, info);
2808 } catch (RemoteException e) {
2809 Log.e(TAG, "Error calling onServiceUpdated", e);
2810 }
2811 }
2812
Paul Huddce5912023-08-01 10:26:49 +08002813 void onServiceUpdatedLost(int listenerKey, ClientRequest request) {
2814 request.onServiceLost();
Paul Hu18aeccc2022-12-27 08:48:48 +00002815 try {
2816 mCb.onServiceUpdatedLost(listenerKey);
2817 } catch (RemoteException e) {
2818 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2819 }
2820 }
2821
Paul Huddce5912023-08-01 10:26:49 +08002822 void onServiceInfoCallbackUnregistered(int listenerKey, ClientRequest request) {
2823 mMetrics.reportServiceInfoCallbackUnregistered(
2824 request.mTransactionId,
2825 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2826 request.getFoundServiceCount(),
2827 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002828 request.isServiceFromCache(),
2829 request.getSentQueryCount());
Paul Hu18aeccc2022-12-27 08:48:48 +00002830 try {
2831 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2832 } catch (RemoteException e) {
2833 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2834 }
2835 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002836 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002837}