blob: e4d5b812b2da38589895fb66c1cbf96b9cb96bd3 [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 Huang33fa4d22023-02-14 22:59:37 +090019import static android.Manifest.permission.NETWORK_SETTINGS;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090020import static android.Manifest.permission.NETWORK_STACK;
paulhu2b9ed952022-02-10 21:58:32 +080021import static android.net.ConnectivityManager.NETID_UNSET;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090022import static android.net.NetworkCapabilities.TRANSPORT_VPN;
23import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090024import static android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK;
Paul Hu019621e2023-01-13 23:26:49 +080025import static android.net.nsd.NsdManager.MDNS_DISCOVERY_MANAGER_EVENT;
paulhu2b9ed952022-02-10 21:58:32 +080026import static android.net.nsd.NsdManager.MDNS_SERVICE_EVENT;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +090027import static android.net.nsd.NsdManager.RESOLVE_SERVICE_SUCCEEDED;
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +090028import static android.provider.DeviceConfig.NAMESPACE_TETHERING;
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090029import static com.android.modules.utils.build.SdkLevel.isAtLeastU;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090030import static com.android.networkstack.apishim.ConstantsShim.REGISTER_NSD_OFFLOAD_ENGINE;
Paul Hu043bcd42023-07-14 16:38:25 +080031import static com.android.server.connectivity.mdns.MdnsAdvertiser.AdvertiserMetrics;
32import static com.android.server.connectivity.mdns.MdnsConstants.NO_PACKET;
Yuyang Huangde802c82023-05-02 17:14:22 +090033import static com.android.server.connectivity.mdns.MdnsRecord.MAX_LABEL_LENGTH;
Paul Hucdef3532023-06-18 14:47:35 +000034import static com.android.server.connectivity.mdns.util.MdnsUtils.Clock;
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090035
Paul Hu23fa2022023-01-13 22:57:24 +080036import android.annotation.NonNull;
Paul Hu4bd98ef2023-01-12 13:42:07 +080037import android.annotation.Nullable;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090038import android.app.ActivityManager;
paulhua262cc12019-08-12 16:25:11 +080039import android.content.Context;
Irfan Sheriff75006652012-04-17 23:15:29 -070040import android.content.Intent;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090041import android.net.ConnectivityManager;
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +090042import android.net.INetd;
Paul Hu75069ed2023-01-14 00:31:09 +080043import android.net.InetAddresses;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090044import android.net.LinkProperties;
45import android.net.Network;
paulhu2b9ed952022-02-10 21:58:32 +080046import android.net.mdns.aidl.DiscoveryInfo;
47import android.net.mdns.aidl.GetAddressInfo;
48import android.net.mdns.aidl.IMDnsEventListener;
49import android.net.mdns.aidl.RegistrationInfo;
50import android.net.mdns.aidl.ResolutionInfo;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070051import android.net.nsd.INsdManager;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090052import android.net.nsd.INsdManagerCallback;
53import android.net.nsd.INsdServiceConnector;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090054import android.net.nsd.IOffloadEngine;
paulhu2b9ed952022-02-10 21:58:32 +080055import android.net.nsd.MDnsManager;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070056import android.net.nsd.NsdManager;
paulhua262cc12019-08-12 16:25:11 +080057import android.net.nsd.NsdServiceInfo;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090058import android.net.nsd.OffloadEngine;
59import android.net.nsd.OffloadServiceInfo;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090060import android.net.wifi.WifiManager;
Paul Hub2e67d32023-04-18 05:50:14 +000061import android.os.Binder;
Hugo Benichi803a2f02017-04-24 11:35:06 +090062import android.os.Handler;
paulhua262cc12019-08-12 16:25:11 +080063import android.os.HandlerThread;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090064import android.os.IBinder;
Paul Hu4bd98ef2023-01-12 13:42:07 +080065import android.os.Looper;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070066import android.os.Message;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090067import android.os.RemoteCallbackList;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090068import android.os.RemoteException;
Dianne Hackborn692107e2012-08-29 18:32:08 -070069import android.os.UserHandle;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090070import android.provider.DeviceConfig;
Paul Hu23fa2022023-01-13 22:57:24 +080071import android.text.TextUtils;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090072import android.util.ArraySet;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090073import android.util.Log;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +090074import android.util.Pair;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070075import android.util.SparseArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070076
paulhua262cc12019-08-12 16:25:11 +080077import com.android.internal.annotations.VisibleForTesting;
Paul Hub2e67d32023-04-18 05:50:14 +000078import com.android.internal.util.IndentingPrintWriter;
paulhua262cc12019-08-12 16:25:11 +080079import com.android.internal.util.State;
80import com.android.internal.util.StateMachine;
Paul Hucdef3532023-06-18 14:47:35 +000081import com.android.metrics.NetworkNsdReportedMetrics;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090082import com.android.modules.utils.build.SdkLevel;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090083import com.android.net.module.util.CollectionUtils;
Paul Hu4bd98ef2023-01-12 13:42:07 +080084import com.android.net.module.util.DeviceConfigUtils;
Yuyang Huanga6a6ff92023-04-24 13:33:34 +090085import com.android.net.module.util.InetAddressUtils;
paulhu3ffffe72021-09-16 10:15:22 +080086import com.android.net.module.util.PermissionUtils;
Paul Hub2e67d32023-04-18 05:50:14 +000087import com.android.net.module.util.SharedLog;
Paul Hu4bd98ef2023-01-12 13:42:07 +080088import com.android.server.connectivity.mdns.ExecutorProvider;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090089import com.android.server.connectivity.mdns.MdnsAdvertiser;
Paul Hu4bd98ef2023-01-12 13:42:07 +080090import com.android.server.connectivity.mdns.MdnsDiscoveryManager;
Yuyang Huangb96a0712023-09-07 15:13:15 +090091import com.android.server.connectivity.mdns.MdnsFeatureFlags;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090092import com.android.server.connectivity.mdns.MdnsInterfaceSocket;
Paul Hu4bd98ef2023-01-12 13:42:07 +080093import com.android.server.connectivity.mdns.MdnsMultinetworkSocketClient;
Paul Hu23fa2022023-01-13 22:57:24 +080094import com.android.server.connectivity.mdns.MdnsSearchOptions;
95import com.android.server.connectivity.mdns.MdnsServiceBrowserListener;
96import com.android.server.connectivity.mdns.MdnsServiceInfo;
Paul Hu4bd98ef2023-01-12 13:42:07 +080097import com.android.server.connectivity.mdns.MdnsSocketProvider;
Yuyang Huangde802c82023-05-02 17:14:22 +090098import com.android.server.connectivity.mdns.util.MdnsUtils;
paulhua262cc12019-08-12 16:25:11 +080099
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700100import java.io.FileDescriptor;
101import java.io.PrintWriter;
Yuyang Huangaa0e9602023-03-17 12:43:09 +0900102import java.net.Inet6Address;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700103import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900104import java.net.NetworkInterface;
105import java.net.SocketException;
106import java.net.UnknownHostException;
Paul Hu2b865912023-03-06 14:27:53 +0800107import java.util.ArrayList;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900108import java.util.Arrays;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700109import java.util.HashMap;
Paul Hu23fa2022023-01-13 22:57:24 +0800110import java.util.List;
Paul Hu75069ed2023-01-14 00:31:09 +0800111import java.util.Map;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900112import java.util.Objects;
Paul Hu812e9212023-06-20 06:24:53 +0000113import java.util.Set;
Paul Hu23fa2022023-01-13 22:57:24 +0800114import java.util.regex.Matcher;
115import java.util.regex.Pattern;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700116
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700117/**
118 * Network Service Discovery Service handles remote service discovery operation requests by
119 * implementing the INsdManager interface.
120 *
121 * @hide
122 */
123public class NsdService extends INsdManager.Stub {
124 private static final String TAG = "NsdService";
125 private static final String MDNS_TAG = "mDnsConnector";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900126 /**
127 * Enable discovery using the Java DiscoveryManager, instead of the legacy mdnsresponder
128 * implementation.
129 */
Paul Hu4bd98ef2023-01-12 13:42:07 +0800130 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Paul Hu23fa2022023-01-13 22:57:24 +0800131 private static final String LOCAL_DOMAIN_NAME = "local";
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700132
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900133 /**
134 * Enable advertising using the Java MdnsAdvertiser, instead of the legacy mdnsresponder
135 * implementation.
136 */
137 private static final String MDNS_ADVERTISER_VERSION = "mdns_advertiser_version";
138
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900139 /**
140 * Comma-separated list of type:flag mappings indicating the flags to use to allowlist
141 * discovery/advertising using MdnsDiscoveryManager / MdnsAdvertiser for a given type.
142 *
143 * For example _mytype._tcp.local and _othertype._tcp.local would be configured with:
144 * _mytype._tcp:mytype,_othertype._tcp.local:othertype
145 *
146 * In which case the flags:
147 * "mdns_discovery_manager_allowlist_mytype_version",
148 * "mdns_advertiser_allowlist_mytype_version",
149 * "mdns_discovery_manager_allowlist_othertype_version",
150 * "mdns_advertiser_allowlist_othertype_version"
151 * would be used to toggle MdnsDiscoveryManager / MdnsAdvertiser for each type. The flags will
152 * be read with
Motomu Utsumi624aeb42023-08-15 15:52:27 +0900153 * {@link DeviceConfigUtils#isTetheringFeatureEnabled}
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900154 *
155 * @see #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX
156 * @see #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX
157 * @see #MDNS_ALLOWLIST_FLAG_SUFFIX
158 */
159 private static final String MDNS_TYPE_ALLOWLIST_FLAGS = "mdns_type_allowlist_flags";
160
161 private static final String MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX =
162 "mdns_discovery_manager_allowlist_";
163 private static final String MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX =
164 "mdns_advertiser_allowlist_";
165 private static final String MDNS_ALLOWLIST_FLAG_SUFFIX = "_version";
166
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900167 @VisibleForTesting
168 static final String MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
169 "mdns_config_running_app_active_importance_cutoff";
170 @VisibleForTesting
171 static final int DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
172 ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
173 private final int mRunningAppActiveImportanceCutoff;
174
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900175 public static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +0000176 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900177 private static final int IFACE_IDX_ANY = 0;
Paul Hu812e9212023-06-20 06:24:53 +0000178 private static final int MAX_SERVICES_COUNT_METRIC_PER_CLIENT = 100;
179 @VisibleForTesting
180 static final int NO_TRANSACTION = -1;
Paul Hubad6fe92023-07-24 21:25:22 +0800181 private static final int NO_SENT_QUERY_COUNT = 0;
182 private static final int DISCOVERY_QUERY_SENT_CALLBACK = 1000;
Paul Hu14667de2023-04-17 22:42:47 +0800183 private static final SharedLog LOGGER = new SharedLog("serviceDiscovery");
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700184
Hugo Benichi32be63d2017-04-05 14:06:11 +0900185 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900186 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +0800187 private final MDnsManager mMDnsManager;
188 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900189 @NonNull
190 private final Dependencies mDeps;
191 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800192 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900193 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800194 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900195 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800196 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900197 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900198 private final MdnsAdvertiser mAdvertiser;
Paul Hu777ed052023-06-19 13:35:15 +0000199 @NonNull
200 private final Clock mClock;
Paul Hu14667de2023-04-17 22:42:47 +0800201 private final SharedLog mServiceLogs = LOGGER.forSubComponent(TAG);
Paul Hu23fa2022023-01-13 22:57:24 +0800202 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800203 // state machine thread. If change this outside state machine, it will need to introduce
204 // synchronization.
205 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800206 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700207
208 /**
209 * Clients receiving asynchronous messages
210 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900211 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700212
Paul Hud44e1b72023-06-16 02:07:42 +0000213 /* A map from transaction(unique) id to client info */
214 private final SparseArray<ClientInfo> mTransactionIdToClientInfoMap = new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700215
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900216 // Note this is not final to avoid depending on the Wi-Fi service starting before NsdService
217 @Nullable
218 private WifiManager.MulticastLock mHeldMulticastLock;
219 // Fulfilled network requests that require the Wi-Fi lock: key is the obtained Network
220 // (non-null), value is the requested Network (nullable)
221 @NonNull
222 private final ArraySet<Network> mWifiLockRequiredNetworks = new ArraySet<>();
223 @NonNull
224 private final ArraySet<Integer> mRunningAppActiveUids = new ArraySet<>();
225
Luke Huang05298582021-06-13 16:52:05 +0000226 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700227
Hugo Benichi32be63d2017-04-05 14:06:11 +0900228 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700229 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800230 // The count of the connected legacy clients.
231 private int mLegacyClientCount = 0;
Paul Hub2e67d32023-04-18 05:50:14 +0000232 // The number of client that ever connected.
233 private int mClientNumberId = 1;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700234
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900235 private final RemoteCallbackList<IOffloadEngine> mOffloadEngines =
236 new RemoteCallbackList<>();
237
238 private static class OffloadEngineInfo {
239 @NonNull final String mInterfaceName;
240 final long mOffloadCapabilities;
241 final long mOffloadType;
242 @NonNull final IOffloadEngine mOffloadEngine;
243
244 OffloadEngineInfo(@NonNull IOffloadEngine offloadEngine,
245 @NonNull String interfaceName, long capabilities, long offloadType) {
246 this.mOffloadEngine = offloadEngine;
247 this.mInterfaceName = interfaceName;
248 this.mOffloadCapabilities = capabilities;
249 this.mOffloadType = offloadType;
250 }
251 }
252
Paul Hu812e9212023-06-20 06:24:53 +0000253 @VisibleForTesting
254 static class MdnsListener implements MdnsServiceBrowserListener {
Paul Hud44e1b72023-06-16 02:07:42 +0000255 protected final int mClientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800256 protected final int mTransactionId;
257 @NonNull
258 protected final NsdServiceInfo mReqServiceInfo;
259 @NonNull
260 protected final String mListenedServiceType;
261
Paul Hud44e1b72023-06-16 02:07:42 +0000262 MdnsListener(int clientRequestId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
Paul Hu23fa2022023-01-13 22:57:24 +0800263 @NonNull String listenedServiceType) {
Paul Hud44e1b72023-06-16 02:07:42 +0000264 mClientRequestId = clientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800265 mTransactionId = transactionId;
266 mReqServiceInfo = reqServiceInfo;
267 mListenedServiceType = listenedServiceType;
268 }
269
270 @NonNull
271 public String getListenedServiceType() {
272 return mListenedServiceType;
273 }
274
275 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000276 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
277 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800278
279 @Override
280 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
281
282 @Override
283 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
284
285 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000286 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
287 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800288
289 @Override
290 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
291
292 @Override
293 public void onSearchStoppedWithError(int error) { }
294
295 @Override
296 public void onSearchFailedToStart() { }
297
298 @Override
Paul Hubad6fe92023-07-24 21:25:22 +0800299 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
300 int sentQueryTransactionId) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800301
302 @Override
303 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
304 }
305
306 private class DiscoveryListener extends MdnsListener {
307
Paul Hud44e1b72023-06-16 02:07:42 +0000308 DiscoveryListener(int clientRequestId, int transactionId,
309 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
310 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800311 }
312
313 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000314 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
315 boolean isServiceFromCache) {
Paul Hu019621e2023-01-13 23:26:49 +0800316 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
317 NsdManager.SERVICE_FOUND,
Paul Hua6bc4632023-06-26 01:18:29 +0000318 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu23fa2022023-01-13 22:57:24 +0800319 }
320
321 @Override
322 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800323 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
324 NsdManager.SERVICE_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000325 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800326 }
Paul Hubad6fe92023-07-24 21:25:22 +0800327
328 @Override
329 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
330 int sentQueryTransactionId) {
331 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
332 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
333 }
Paul Hu23fa2022023-01-13 22:57:24 +0800334 }
335
Paul Hu75069ed2023-01-14 00:31:09 +0800336 private class ResolutionListener extends MdnsListener {
337
Paul Hud44e1b72023-06-16 02:07:42 +0000338 ResolutionListener(int clientRequestId, int transactionId,
339 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
340 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800341 }
342
343 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000344 public void onServiceFound(MdnsServiceInfo serviceInfo, boolean isServiceFromCache) {
Paul Hu75069ed2023-01-14 00:31:09 +0800345 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
346 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
Paul Hua6bc4632023-06-26 01:18:29 +0000347 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu75069ed2023-01-14 00:31:09 +0800348 }
Paul Hubad6fe92023-07-24 21:25:22 +0800349
350 @Override
351 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
352 int sentQueryTransactionId) {
353 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
354 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
355 }
Paul Hu75069ed2023-01-14 00:31:09 +0800356 }
357
Paul Hu30bd70d2023-02-07 13:20:56 +0000358 private class ServiceInfoListener extends MdnsListener {
359
Paul Hud44e1b72023-06-16 02:07:42 +0000360 ServiceInfoListener(int clientRequestId, int transactionId,
361 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
362 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +0000363 }
364
365 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000366 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
367 boolean isServiceFromCache) {
Paul Hu30bd70d2023-02-07 13:20:56 +0000368 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
369 NsdManager.SERVICE_UPDATED,
Paul Hua6bc4632023-06-26 01:18:29 +0000370 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu30bd70d2023-02-07 13:20:56 +0000371 }
372
373 @Override
374 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) {
375 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
376 NsdManager.SERVICE_UPDATED,
Paul Hud44e1b72023-06-16 02:07:42 +0000377 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000378 }
379
380 @Override
381 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) {
382 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
383 NsdManager.SERVICE_UPDATED_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000384 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000385 }
Paul Hubad6fe92023-07-24 21:25:22 +0800386
387 @Override
388 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
389 int sentQueryTransactionId) {
390 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
391 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
392 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000393 }
394
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900395 private class SocketRequestMonitor implements MdnsSocketProvider.SocketRequestMonitor {
396 @Override
397 public void onSocketRequestFulfilled(@Nullable Network socketNetwork,
398 @NonNull MdnsInterfaceSocket socket, @NonNull int[] transports) {
399 // The network may be null for Wi-Fi SoftAp interfaces (tethering), but there is no APF
400 // filtering on such interfaces, so taking the multicast lock is not necessary to
401 // disable APF filtering of multicast.
402 if (socketNetwork == null
403 || !CollectionUtils.contains(transports, TRANSPORT_WIFI)
404 || CollectionUtils.contains(transports, TRANSPORT_VPN)) {
405 return;
406 }
407
408 if (mWifiLockRequiredNetworks.add(socketNetwork)) {
409 updateMulticastLock();
410 }
411 }
412
413 @Override
414 public void onSocketDestroyed(@Nullable Network socketNetwork,
415 @NonNull MdnsInterfaceSocket socket) {
416 if (mWifiLockRequiredNetworks.remove(socketNetwork)) {
417 updateMulticastLock();
418 }
419 }
420 }
421
422 private class UidImportanceListener implements ActivityManager.OnUidImportanceListener {
423 private final Handler mHandler;
424
425 private UidImportanceListener(Handler handler) {
426 mHandler = handler;
427 }
428
429 @Override
430 public void onUidImportance(int uid, int importance) {
431 mHandler.post(() -> handleUidImportanceChanged(uid, importance));
432 }
433 }
434
435 private void handleUidImportanceChanged(int uid, int importance) {
436 // Lower importance values are more "important"
437 final boolean modified = importance <= mRunningAppActiveImportanceCutoff
438 ? mRunningAppActiveUids.add(uid)
439 : mRunningAppActiveUids.remove(uid);
440 if (modified) {
441 updateMulticastLock();
442 }
443 }
444
445 /**
446 * Take or release the lock based on updated internal state.
447 *
448 * This determines whether the lock needs to be held based on
449 * {@link #mWifiLockRequiredNetworks}, {@link #mRunningAppActiveUids} and
450 * {@link ClientInfo#mClientRequests}, so it must be called after any of the these have been
451 * updated.
452 */
453 private void updateMulticastLock() {
454 final int needsLockUid = getMulticastLockNeededUid();
455 if (needsLockUid >= 0 && mHeldMulticastLock == null) {
456 final WifiManager wm = mContext.getSystemService(WifiManager.class);
457 if (wm == null) {
458 Log.wtf(TAG, "Got a TRANSPORT_WIFI network without WifiManager");
459 return;
460 }
461 mHeldMulticastLock = wm.createMulticastLock(TAG);
462 mHeldMulticastLock.acquire();
463 mServiceLogs.log("Taking multicast lock for uid " + needsLockUid);
464 } else if (needsLockUid < 0 && mHeldMulticastLock != null) {
465 mHeldMulticastLock.release();
466 mHeldMulticastLock = null;
467 mServiceLogs.log("Released multicast lock");
468 }
469 }
470
471 /**
472 * @return The UID of an app requiring the multicast lock, or -1 if none.
473 */
474 private int getMulticastLockNeededUid() {
475 if (mWifiLockRequiredNetworks.size() == 0) {
476 // Return early if NSD is not active, or not on any relevant network
477 return -1;
478 }
Paul Hud44e1b72023-06-16 02:07:42 +0000479 for (int i = 0; i < mTransactionIdToClientInfoMap.size(); i++) {
480 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.valueAt(i);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900481 if (!mRunningAppActiveUids.contains(clientInfo.mUid)) {
482 // Ignore non-active UIDs
483 continue;
484 }
485
486 if (clientInfo.hasAnyJavaBackendRequestForNetworks(mWifiLockRequiredNetworks)) {
487 return clientInfo.mUid;
488 }
489 }
490 return -1;
491 }
492
Paul Hu019621e2023-01-13 23:26:49 +0800493 /**
494 * Data class of mdns service callback information.
495 */
496 private static class MdnsEvent {
Paul Hud44e1b72023-06-16 02:07:42 +0000497 final int mClientRequestId;
Paul Hubad6fe92023-07-24 21:25:22 +0800498 @Nullable
Paul Hu019621e2023-01-13 23:26:49 +0800499 final MdnsServiceInfo mMdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000500 final boolean mIsServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800501
Paul Hubad6fe92023-07-24 21:25:22 +0800502 MdnsEvent(int clientRequestId) {
503 this(clientRequestId, null /* mdnsServiceInfo */, false /* isServiceFromCache */);
504 }
505
506 MdnsEvent(int clientRequestId, @Nullable MdnsServiceInfo mdnsServiceInfo) {
Paul Hua6bc4632023-06-26 01:18:29 +0000507 this(clientRequestId, mdnsServiceInfo, false /* isServiceFromCache */);
508 }
509
Paul Hubad6fe92023-07-24 21:25:22 +0800510 MdnsEvent(int clientRequestId, @Nullable MdnsServiceInfo mdnsServiceInfo,
Paul Hua6bc4632023-06-26 01:18:29 +0000511 boolean isServiceFromCache) {
Paul Hud44e1b72023-06-16 02:07:42 +0000512 mClientRequestId = clientRequestId;
Paul Hu019621e2023-01-13 23:26:49 +0800513 mMdnsServiceInfo = mdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000514 mIsServiceFromCache = isServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800515 }
516 }
517
Irfan Sheriff75006652012-04-17 23:15:29 -0700518 private class NsdStateMachine extends StateMachine {
519
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700520 private final DefaultState mDefaultState = new DefaultState();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700521 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700522
523 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700524 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900525 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700526 }
527
Luke Huang92860f92021-06-23 06:29:30 +0000528 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800529 if (mIsDaemonStarted) {
530 if (DBG) Log.d(TAG, "Daemon is already started.");
531 return;
532 }
533 mMDnsManager.registerEventListener(mMDnsEventCallback);
534 mMDnsManager.startDaemon();
535 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000536 maybeScheduleStop();
Paul Hub2e67d32023-04-18 05:50:14 +0000537 mServiceLogs.log("Start mdns_responder daemon");
Luke Huang05298582021-06-13 16:52:05 +0000538 }
539
paulhu2b9ed952022-02-10 21:58:32 +0800540 private void maybeStopDaemon() {
541 if (!mIsDaemonStarted) {
542 if (DBG) Log.d(TAG, "Daemon has not been started.");
543 return;
544 }
545 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
546 mMDnsManager.stopDaemon();
547 mIsDaemonStarted = false;
Paul Hub2e67d32023-04-18 05:50:14 +0000548 mServiceLogs.log("Stop mdns_responder daemon");
paulhu2b9ed952022-02-10 21:58:32 +0800549 }
550
Luke Huang92860f92021-06-23 06:29:30 +0000551 private boolean isAnyRequestActive() {
Paul Hud44e1b72023-06-16 02:07:42 +0000552 return mTransactionIdToClientInfoMap.size() != 0;
Luke Huang92860f92021-06-23 06:29:30 +0000553 }
554
555 private void scheduleStop() {
556 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
557 }
558 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800559 // The native daemon should stay alive and can't be cleanup
560 // if any legacy client connected.
561 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000562 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000563 }
564 }
565
Luke Huang92860f92021-06-23 06:29:30 +0000566 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000567 this.removeMessages(NsdManager.DAEMON_CLEANUP);
568 }
569
Paul Hu23fa2022023-01-13 22:57:24 +0800570 private void maybeStartMonitoringSockets() {
571 if (mIsMonitoringSocketsStarted) {
572 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
573 return;
574 }
575
576 mMdnsSocketProvider.startMonitoringSockets();
577 mIsMonitoringSocketsStarted = true;
578 }
579
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900580 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
581 if (!mIsMonitoringSocketsStarted) return;
582 if (isAnyRequestActive()) return;
583
Paul Hu58f20602023-02-18 11:41:07 +0800584 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800585 mIsMonitoringSocketsStarted = false;
586 }
587
Hugo Benichi803a2f02017-04-24 11:35:06 +0900588 NsdStateMachine(String name, Handler handler) {
589 super(name, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -0700590 addState(mDefaultState);
Irfan Sheriff75006652012-04-17 23:15:29 -0700591 addState(mEnabledState, mDefaultState);
paulhu5568f452021-11-30 13:31:29 +0800592 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900593 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700594 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700595 }
596
597 class DefaultState extends State {
598 @Override
599 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900600 final ClientInfo cInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000601 final int clientRequestId = msg.arg2;
Irfan Sheriff75006652012-04-17 23:15:29 -0700602 switch (msg.what) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900603 case NsdManager.REGISTER_CLIENT:
Paul Hu2e0a88c2023-03-09 16:05:01 +0800604 final ConnectorArgs arg = (ConnectorArgs) msg.obj;
605 final INsdManagerCallback cb = arg.callback;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900606 try {
Paul Hu2e0a88c2023-03-09 16:05:01 +0800607 cb.asBinder().linkToDeath(arg.connector, 0);
Paul Hub2e67d32023-04-18 05:50:14 +0000608 final String tag = "Client" + arg.uid + "-" + mClientNumberId++;
Paul Hu777ed052023-06-19 13:35:15 +0000609 final NetworkNsdReportedMetrics metrics =
610 mDeps.makeNetworkNsdReportedMetrics(
Paul Hu508a0122023-09-11 15:31:33 +0800611 (int) mClock.elapsedRealtime());
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900612 cInfo = new ClientInfo(cb, arg.uid, arg.useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +0000613 mServiceLogs.forSubComponent(tag), metrics);
Paul Hu2e0a88c2023-03-09 16:05:01 +0800614 mClients.put(arg.connector, cInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900615 } catch (RemoteException e) {
Paul Hud44e1b72023-06-16 02:07:42 +0000616 Log.w(TAG, "Client request id " + clientRequestId
617 + " has already died");
Irfan Sheriff75006652012-04-17 23:15:29 -0700618 }
619 break;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900620 case NsdManager.UNREGISTER_CLIENT:
621 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
622 cInfo = mClients.remove(connector);
Dave Plattfeff2af2014-03-07 14:48:22 -0800623 if (cInfo != null) {
624 cInfo.expungeAllRequests();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900625 if (cInfo.isPreSClient()) {
Luke Huangf7277ed2021-07-12 21:15:10 +0800626 mLegacyClientCount -= 1;
627 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800628 }
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900629 maybeStopMonitoringSocketsIfNoActiveRequest();
Luke Huangf7277ed2021-07-12 21:15:10 +0800630 maybeScheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700631 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700632 case NsdManager.DISCOVER_SERVICES:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900633 cInfo = getClientInfoForReply(msg);
634 if (cInfo != null) {
Paul Hu508a0122023-09-11 15:31:33 +0800635 cInfo.onDiscoverServicesFailedImmediately(clientRequestId,
636 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900637 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700638 break;
639 case NsdManager.STOP_DISCOVERY:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900640 cInfo = getClientInfoForReply(msg);
641 if (cInfo != null) {
642 cInfo.onStopDiscoveryFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000643 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900644 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700645 break;
646 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900647 cInfo = getClientInfoForReply(msg);
648 if (cInfo != null) {
Paul Hu508a0122023-09-11 15:31:33 +0800649 cInfo.onRegisterServiceFailedImmediately(clientRequestId,
650 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900651 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700652 break;
653 case NsdManager.UNREGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900654 cInfo = getClientInfoForReply(msg);
655 if (cInfo != null) {
656 cInfo.onUnregisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000657 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900658 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700659 break;
660 case NsdManager.RESOLVE_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900661 cInfo = getClientInfoForReply(msg);
662 if (cInfo != null) {
Paul Hu508a0122023-09-11 15:31:33 +0800663 cInfo.onResolveServiceFailedImmediately(clientRequestId,
664 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900665 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700666 break;
Paul Hub58deb72022-12-26 09:24:42 +0000667 case NsdManager.STOP_RESOLUTION:
668 cInfo = getClientInfoForReply(msg);
669 if (cInfo != null) {
670 cInfo.onStopResolutionFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000671 clientRequestId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hub58deb72022-12-26 09:24:42 +0000672 }
673 break;
Paul Hu18aeccc2022-12-27 08:48:48 +0000674 case NsdManager.REGISTER_SERVICE_CALLBACK:
675 cInfo = getClientInfoForReply(msg);
676 if (cInfo != null) {
677 cInfo.onServiceInfoCallbackRegistrationFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000678 clientRequestId, NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +0000679 }
680 break;
Luke Huang05298582021-06-13 16:52:05 +0000681 case NsdManager.DAEMON_CLEANUP:
paulhu2b9ed952022-02-10 21:58:32 +0800682 maybeStopDaemon();
Luke Huang05298582021-06-13 16:52:05 +0000683 break;
Luke Huangf7277ed2021-07-12 21:15:10 +0800684 // This event should be only sent by the legacy (target SDK < S) clients.
685 // Mark the sending client as legacy.
686 case NsdManager.DAEMON_STARTUP:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900687 cInfo = getClientInfoForReply(msg);
Luke Huangf7277ed2021-07-12 21:15:10 +0800688 if (cInfo != null) {
689 cancelStop();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900690 cInfo.setPreSClient();
Luke Huangf7277ed2021-07-12 21:15:10 +0800691 mLegacyClientCount += 1;
692 maybeStartDaemon();
693 }
694 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700695 default:
paulhub2225702021-11-17 09:35:33 +0800696 Log.e(TAG, "Unhandled " + msg);
Irfan Sheriff75006652012-04-17 23:15:29 -0700697 return NOT_HANDLED;
698 }
699 return HANDLED;
700 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900701
702 private ClientInfo getClientInfoForReply(Message msg) {
703 final ListenerArgs args = (ListenerArgs) msg.obj;
704 return mClients.get(args.connector);
705 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700706 }
707
Irfan Sheriff75006652012-04-17 23:15:29 -0700708 class EnabledState extends State {
709 @Override
710 public void enter() {
711 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700712 }
713
714 @Override
715 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000716 // TODO: it is incorrect to stop the daemon without expunging all requests
717 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000718 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700719 }
720
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700721 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900722 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800723 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700724 return true;
725 }
726 return false;
727 }
728
Paul Hu508a0122023-09-11 15:31:33 +0800729 private ClientRequest storeLegacyRequestMap(int clientRequestId, int transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +0000730 ClientInfo clientInfo, int what, long startTimeMs) {
Paul Hu508a0122023-09-11 15:31:33 +0800731 final LegacyClientRequest request =
732 new LegacyClientRequest(transactionId, what, startTimeMs);
733 clientInfo.mClientRequests.put(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000734 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000735 // Remove the cleanup event because here comes a new request.
736 cancelStop();
Paul Hu508a0122023-09-11 15:31:33 +0800737 return request;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700738 }
739
Paul Hud44e1b72023-06-16 02:07:42 +0000740 private void storeAdvertiserRequestMap(int clientRequestId, int transactionId,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900741 ClientInfo clientInfo, @Nullable Network requestedNetwork) {
Paul Hu777ed052023-06-19 13:35:15 +0000742 clientInfo.mClientRequests.put(clientRequestId, new AdvertiserClientRequest(
Paul Hu812e9212023-06-20 06:24:53 +0000743 transactionId, requestedNetwork, mClock.elapsedRealtime()));
Paul Hud44e1b72023-06-16 02:07:42 +0000744 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900745 updateMulticastLock();
Paul Hu23fa2022023-01-13 22:57:24 +0800746 }
747
Paul Hud44e1b72023-06-16 02:07:42 +0000748 private void removeRequestMap(
749 int clientRequestId, int transactionId, ClientInfo clientInfo) {
750 final ClientRequest existing = clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900751 if (existing == null) return;
Paul Hud44e1b72023-06-16 02:07:42 +0000752 clientInfo.mClientRequests.remove(clientRequestId);
753 mTransactionIdToClientInfoMap.remove(transactionId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900754
755 if (existing instanceof LegacyClientRequest) {
756 maybeScheduleStop();
757 } else {
758 maybeStopMonitoringSocketsIfNoActiveRequest();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900759 updateMulticastLock();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900760 }
761 }
762
Paul Hu508a0122023-09-11 15:31:33 +0800763 private ClientRequest storeDiscoveryManagerRequestMap(int clientRequestId,
764 int transactionId, MdnsListener listener, ClientInfo clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900765 @Nullable Network requestedNetwork) {
Paul Hu508a0122023-09-11 15:31:33 +0800766 final DiscoveryManagerRequest request = new DiscoveryManagerRequest(transactionId,
767 listener, requestedNetwork, mClock.elapsedRealtime());
768 clientInfo.mClientRequests.put(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000769 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900770 updateMulticastLock();
Paul Hu508a0122023-09-11 15:31:33 +0800771 return request;
Paul Hu23fa2022023-01-13 22:57:24 +0800772 }
773
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900774 /**
775 * Truncate a service name to up to 63 UTF-8 bytes.
776 *
777 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
778 * names used in registerService follows historical behavior (see mdnsresponder
779 * handle_regservice_request).
780 */
781 @NonNull
782 private String truncateServiceName(@NonNull String originalName) {
Yuyang Huangde802c82023-05-02 17:14:22 +0900783 return MdnsUtils.truncateServiceName(originalName, MAX_LABEL_LENGTH);
Paul Hu23fa2022023-01-13 22:57:24 +0800784 }
785
Paul Hud44e1b72023-06-16 02:07:42 +0000786 private void stopDiscoveryManagerRequest(ClientRequest request, int clientRequestId,
787 int transactionId, ClientInfo clientInfo) {
Paul Hue4f5f252023-02-16 21:13:47 +0800788 clientInfo.unregisterMdnsListenerFromRequest(request);
Paul Hud44e1b72023-06-16 02:07:42 +0000789 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hue4f5f252023-02-16 21:13:47 +0800790 }
791
Irfan Sheriff75006652012-04-17 23:15:29 -0700792 @Override
793 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900794 final ClientInfo clientInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000795 final int transactionId;
796 final int clientRequestId = msg.arg2;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900797 final ListenerArgs args;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900798 final OffloadEngineInfo offloadEngineInfo;
Irfan Sheriff75006652012-04-17 23:15:29 -0700799 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800800 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800801 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900802 args = (ListenerArgs) msg.obj;
803 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000804 // If the binder death notification for a INsdManagerCallback was received
805 // before any calls are received by NsdService, the clientInfo would be
806 // cleared and cause NPE. Add a null check here to prevent this corner case.
807 if (clientInfo == null) {
808 Log.e(TAG, "Unknown connector in discovery");
809 break;
810 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700811
812 if (requestLimitReached(clientInfo)) {
Paul Hu508a0122023-09-11 15:31:33 +0800813 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
814 NsdManager.FAILURE_MAX_LIMIT, true /* isLegacy */);
Irfan Sheriff75006652012-04-17 23:15:29 -0700815 break;
816 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700817
Paul Hu23fa2022023-01-13 22:57:24 +0800818 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000819 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900820 final Pair<String, String> typeAndSubtype =
821 parseTypeAndSubtype(info.getServiceType());
822 final String serviceType = typeAndSubtype == null
823 ? null : typeAndSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800824 if (clientInfo.mUseJavaBackend
825 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900826 || useDiscoveryManagerForType(serviceType)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800827 if (serviceType == null) {
Paul Hu508a0122023-09-11 15:31:33 +0800828 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
829 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Paul Hu23fa2022023-01-13 22:57:24 +0800830 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700831 }
Paul Hu23fa2022023-01-13 22:57:24 +0800832
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900833 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800834 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +0000835 final MdnsListener listener = new DiscoveryListener(clientRequestId,
836 transactionId, info, listenServiceType);
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900837 final MdnsSearchOptions.Builder optionsBuilder =
838 MdnsSearchOptions.newBuilder()
839 .setNetwork(info.getNetwork())
Yuyang Huangff963222023-06-01 18:42:42 +0900840 .setRemoveExpiredService(true)
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900841 .setIsPassiveMode(true);
842 if (typeAndSubtype.second != null) {
843 // The parsing ensures subtype starts with an underscore.
844 // MdnsSearchOptions expects the underscore to not be present.
845 optionsBuilder.addSubtype(typeAndSubtype.second.substring(1));
846 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900847 mMdnsDiscoveryManager.registerListener(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900848 listenServiceType, listener, optionsBuilder.build());
Paul Hu508a0122023-09-11 15:31:33 +0800849 final ClientRequest request = storeDiscoveryManagerRequestMap(
850 clientRequestId, transactionId, listener, clientInfo,
851 info.getNetwork());
852 clientInfo.onDiscoverServicesStarted(clientRequestId, info, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000853 clientInfo.log("Register a DiscoveryListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +0000854 + " for service type:" + listenServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700855 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800856 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000857 if (discoverServices(transactionId, info)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800858 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +0000859 Log.d(TAG, "Discover " + msg.arg2 + " " + transactionId
Paul Hu23fa2022023-01-13 22:57:24 +0800860 + info.getServiceType());
861 }
Paul Hu508a0122023-09-11 15:31:33 +0800862 final ClientRequest request = storeLegacyRequestMap(clientRequestId,
863 transactionId, clientInfo, msg.what,
864 mClock.elapsedRealtime());
Paul Hu812e9212023-06-20 06:24:53 +0000865 clientInfo.onDiscoverServicesStarted(
Paul Hu508a0122023-09-11 15:31:33 +0800866 clientRequestId, info, request);
Paul Hu23fa2022023-01-13 22:57:24 +0800867 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000868 stopServiceDiscovery(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +0800869 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
870 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Paul Hu23fa2022023-01-13 22:57:24 +0800871 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700872 }
873 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800874 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900875 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800876 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900877 args = (ListenerArgs) msg.obj;
878 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000879 // If the binder death notification for a INsdManagerCallback was received
880 // before any calls are received by NsdService, the clientInfo would be
881 // cleared and cause NPE. Add a null check here to prevent this corner case.
882 if (clientInfo == null) {
883 Log.e(TAG, "Unknown connector in stop discovery");
884 break;
885 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700886
Paul Hud44e1b72023-06-16 02:07:42 +0000887 final ClientRequest request =
888 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900889 if (request == null) {
890 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700891 break;
892 }
Paul Hud44e1b72023-06-16 02:07:42 +0000893 transactionId = request.mTransactionId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900894 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
895 // point, so this needs to check the type of the original request to
896 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900897 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +0000898 stopDiscoveryManagerRequest(
899 request, clientRequestId, transactionId, clientInfo);
Paul Hu812e9212023-06-20 06:24:53 +0000900 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000901 clientInfo.log("Unregister the DiscoveryListener " + transactionId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700902 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000903 removeRequestMap(clientRequestId, transactionId, clientInfo);
904 if (stopServiceDiscovery(transactionId)) {
Paul Hu812e9212023-06-20 06:24:53 +0000905 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hu23fa2022023-01-13 22:57:24 +0800906 } else {
907 clientInfo.onStopDiscoveryFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000908 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu23fa2022023-01-13 22:57:24 +0800909 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700910 }
911 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900912 }
913 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800914 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900915 args = (ListenerArgs) msg.obj;
916 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000917 // If the binder death notification for a INsdManagerCallback was received
918 // before any calls are received by NsdService, the clientInfo would be
919 // cleared and cause NPE. Add a null check here to prevent this corner case.
920 if (clientInfo == null) {
921 Log.e(TAG, "Unknown connector in registration");
922 break;
923 }
924
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700925 if (requestLimitReached(clientInfo)) {
Paul Hu508a0122023-09-11 15:31:33 +0800926 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
927 NsdManager.FAILURE_MAX_LIMIT, true /* isLegacy */);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700928 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700929 }
930
Paul Hud44e1b72023-06-16 02:07:42 +0000931 transactionId = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900932 final NsdServiceInfo serviceInfo = args.serviceInfo;
933 final String serviceType = serviceInfo.getServiceType();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900934 final Pair<String, String> typeSubtype = parseTypeAndSubtype(serviceType);
935 final String registerServiceType = typeSubtype == null
936 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800937 if (clientInfo.mUseJavaBackend
938 || mDeps.isMdnsAdvertiserEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900939 || useAdvertiserForType(registerServiceType)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900940 if (registerServiceType == null) {
941 Log.e(TAG, "Invalid service type: " + serviceType);
Paul Hu508a0122023-09-11 15:31:33 +0800942 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
943 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900944 break;
945 }
946 serviceInfo.setServiceType(registerServiceType);
947 serviceInfo.setServiceName(truncateServiceName(
948 serviceInfo.getServiceName()));
949
950 maybeStartMonitoringSockets();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900951 // TODO: pass in the subtype as well. Including the subtype in the
952 // service type would generate service instance names like
953 // Name._subtype._sub._type._tcp, which is incorrect
954 // (it should be Name._type._tcp).
Paul Hud44e1b72023-06-16 02:07:42 +0000955 mAdvertiser.addService(transactionId, serviceInfo, typeSubtype.second);
956 storeAdvertiserRequestMap(clientRequestId, transactionId, clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900957 serviceInfo.getNetwork());
Irfan Sheriff75006652012-04-17 23:15:29 -0700958 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900959 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000960 if (registerService(transactionId, serviceInfo)) {
961 if (DBG) {
962 Log.d(TAG, "Register " + clientRequestId
963 + " " + transactionId);
964 }
Paul Hua6bc4632023-06-26 01:18:29 +0000965 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
966 msg.what, mClock.elapsedRealtime());
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900967 // Return success after mDns reports success
968 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000969 unregisterService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +0800970 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
971 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900972 }
973
Irfan Sheriff75006652012-04-17 23:15:29 -0700974 }
975 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900976 }
977 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800978 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900979 args = (ListenerArgs) msg.obj;
980 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000981 // If the binder death notification for a INsdManagerCallback was received
982 // before any calls are received by NsdService, the clientInfo would be
983 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900984 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800985 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700986 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700987 }
Paul Hud44e1b72023-06-16 02:07:42 +0000988 final ClientRequest request =
989 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900990 if (request == null) {
991 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
992 break;
993 }
Paul Hud44e1b72023-06-16 02:07:42 +0000994 transactionId = request.mTransactionId;
995 removeRequestMap(clientRequestId, transactionId, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900996
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900997 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
998 // so this needs to check the type of the original request to unregister
999 // instead of looking at the flag value.
1000 if (request instanceof AdvertiserClientRequest) {
Paul Hu043bcd42023-07-14 16:38:25 +08001001 final AdvertiserMetrics metrics =
1002 mAdvertiser.getAdvertiserMetrics(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00001003 mAdvertiser.removeService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08001004 clientInfo.onUnregisterServiceSucceeded(
1005 clientRequestId, request, metrics);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001006 } else {
Paul Hud44e1b72023-06-16 02:07:42 +00001007 if (unregisterService(transactionId)) {
Paul Hu508a0122023-09-11 15:31:33 +08001008 clientInfo.onUnregisterServiceSucceeded(clientRequestId, request,
Paul Hu043bcd42023-07-14 16:38:25 +08001009 new AdvertiserMetrics(NO_PACKET /* repliedRequestsCount */,
1010 NO_PACKET /* sentPacketCount */,
1011 0 /* conflictDuringProbingCount */,
1012 0 /* conflictAfterProbingCount */));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001013 } else {
1014 clientInfo.onUnregisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001015 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001016 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001017 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001018 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001019 }
Paul Hu75069ed2023-01-14 00:31:09 +08001020 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +08001021 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001022 args = (ListenerArgs) msg.obj;
1023 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +00001024 // If the binder death notification for a INsdManagerCallback was received
1025 // before any calls are received by NsdService, the clientInfo would be
1026 // cleared and cause NPE. Add a null check here to prevent this corner case.
1027 if (clientInfo == null) {
1028 Log.e(TAG, "Unknown connector in resolution");
1029 break;
1030 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001031
Paul Hu75069ed2023-01-14 00:31:09 +08001032 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001033 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001034 final Pair<String, String> typeSubtype =
1035 parseTypeAndSubtype(info.getServiceType());
1036 final String serviceType = typeSubtype == null
1037 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001038 if (clientInfo.mUseJavaBackend
1039 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001040 || useDiscoveryManagerForType(serviceType)) {
Paul Hu75069ed2023-01-14 00:31:09 +08001041 if (serviceType == null) {
Paul Hu508a0122023-09-11 15:31:33 +08001042 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
1043 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +08001044 break;
1045 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001046 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +08001047
1048 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001049 final MdnsListener listener = new ResolutionListener(clientRequestId,
1050 transactionId, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +08001051 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1052 .setNetwork(info.getNetwork())
1053 .setIsPassiveMode(true)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +09001054 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001055 .setRemoveExpiredService(true)
Paul Hu75069ed2023-01-14 00:31:09 +08001056 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001057 mMdnsDiscoveryManager.registerListener(
1058 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001059 storeDiscoveryManagerRequestMap(clientRequestId, transactionId,
1060 listener, clientInfo, info.getNetwork());
1061 clientInfo.log("Register a ResolutionListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001062 + " for service type:" + resolveServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -07001063 } else {
Paul Hu75069ed2023-01-14 00:31:09 +08001064 if (clientInfo.mResolvedService != null) {
Paul Hu508a0122023-09-11 15:31:33 +08001065 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
1066 NsdManager.FAILURE_ALREADY_ACTIVE, true /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +08001067 break;
1068 }
1069
1070 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +00001071 if (resolveService(transactionId, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +08001072 clientInfo.mResolvedService = new NsdServiceInfo();
Paul Hua6bc4632023-06-26 01:18:29 +00001073 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
1074 msg.what, mClock.elapsedRealtime());
Paul Hu75069ed2023-01-14 00:31:09 +08001075 } else {
Paul Hu508a0122023-09-11 15:31:33 +08001076 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
1077 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +08001078 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001079 }
1080 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001081 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001082 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +00001083 if (DBG) Log.d(TAG, "Stop service resolution");
1084 args = (ListenerArgs) msg.obj;
1085 clientInfo = mClients.get(args.connector);
1086 // If the binder death notification for a INsdManagerCallback was received
1087 // before any calls are received by NsdService, the clientInfo would be
1088 // cleared and cause NPE. Add a null check here to prevent this corner case.
1089 if (clientInfo == null) {
1090 Log.e(TAG, "Unknown connector in stop resolution");
1091 break;
1092 }
1093
Paul Hud44e1b72023-06-16 02:07:42 +00001094 final ClientRequest request =
1095 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001096 if (request == null) {
1097 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
1098 break;
1099 }
Paul Hud44e1b72023-06-16 02:07:42 +00001100 transactionId = request.mTransactionId;
Paul Hue4f5f252023-02-16 21:13:47 +08001101 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
1102 // point, so this needs to check the type of the original request to
1103 // unregister instead of looking at the flag value.
1104 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001105 stopDiscoveryManagerRequest(
1106 request, clientRequestId, transactionId, clientInfo);
Paul Hu60149052023-07-31 14:26:08 +08001107 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001108 clientInfo.log("Unregister the ResolutionListener " + transactionId);
Paul Hub58deb72022-12-26 09:24:42 +00001109 } else {
Paul Hud44e1b72023-06-16 02:07:42 +00001110 removeRequestMap(clientRequestId, transactionId, clientInfo);
1111 if (stopResolveService(transactionId)) {
Paul Hu60149052023-07-31 14:26:08 +08001112 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hue4f5f252023-02-16 21:13:47 +08001113 } else {
1114 clientInfo.onStopResolutionFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001115 clientRequestId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hue4f5f252023-02-16 21:13:47 +08001116 }
1117 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +00001118 }
Paul Hub58deb72022-12-26 09:24:42 +00001119 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001120 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001121 case NsdManager.REGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001122 if (DBG) Log.d(TAG, "Register a service callback");
1123 args = (ListenerArgs) msg.obj;
1124 clientInfo = mClients.get(args.connector);
1125 // If the binder death notification for a INsdManagerCallback was received
1126 // before any calls are received by NsdService, the clientInfo would be
1127 // cleared and cause NPE. Add a null check here to prevent this corner case.
1128 if (clientInfo == null) {
1129 Log.e(TAG, "Unknown connector in callback registration");
1130 break;
1131 }
1132
Paul Hu30bd70d2023-02-07 13:20:56 +00001133 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001134 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001135 final Pair<String, String> typeAndSubtype =
1136 parseTypeAndSubtype(info.getServiceType());
1137 final String serviceType = typeAndSubtype == null
1138 ? null : typeAndSubtype.first;
Paul Hu30bd70d2023-02-07 13:20:56 +00001139 if (serviceType == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001140 clientInfo.onServiceInfoCallbackRegistrationFailed(clientRequestId,
Paul Hu30bd70d2023-02-07 13:20:56 +00001141 NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +00001142 break;
1143 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001144 final String resolveServiceType = serviceType + ".local";
Paul Hu18aeccc2022-12-27 08:48:48 +00001145
Paul Hu30bd70d2023-02-07 13:20:56 +00001146 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001147 final MdnsListener listener = new ServiceInfoListener(clientRequestId,
1148 transactionId, info, resolveServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +00001149 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1150 .setNetwork(info.getNetwork())
1151 .setIsPassiveMode(true)
1152 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001153 .setRemoveExpiredService(true)
Paul Hu30bd70d2023-02-07 13:20:56 +00001154 .build();
1155 mMdnsDiscoveryManager.registerListener(
1156 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001157 storeDiscoveryManagerRequestMap(clientRequestId, transactionId, listener,
1158 clientInfo, info.getNetwork());
Paul Huddce5912023-08-01 10:26:49 +08001159 clientInfo.onServiceInfoCallbackRegistered(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00001160 clientInfo.log("Register a ServiceInfoListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001161 + " for service type:" + resolveServiceType);
Paul Hu18aeccc2022-12-27 08:48:48 +00001162 break;
Paul Hu30bd70d2023-02-07 13:20:56 +00001163 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001164 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001165 if (DBG) Log.d(TAG, "Unregister a service callback");
1166 args = (ListenerArgs) msg.obj;
1167 clientInfo = mClients.get(args.connector);
1168 // If the binder death notification for a INsdManagerCallback was received
1169 // before any calls are received by NsdService, the clientInfo would be
1170 // cleared and cause NPE. Add a null check here to prevent this corner case.
1171 if (clientInfo == null) {
1172 Log.e(TAG, "Unknown connector in callback unregistration");
1173 break;
1174 }
1175
Paul Hud44e1b72023-06-16 02:07:42 +00001176 final ClientRequest request =
1177 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001178 if (request == null) {
Paul Hu30bd70d2023-02-07 13:20:56 +00001179 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE_CALLBACK");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001180 break;
1181 }
Paul Hud44e1b72023-06-16 02:07:42 +00001182 transactionId = request.mTransactionId;
Paul Hu30bd70d2023-02-07 13:20:56 +00001183 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001184 stopDiscoveryManagerRequest(
1185 request, clientRequestId, transactionId, clientInfo);
Paul Huddce5912023-08-01 10:26:49 +08001186 clientInfo.onServiceInfoCallbackUnregistered(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001187 clientInfo.log("Unregister the ServiceInfoListener " + transactionId);
Paul Hu18aeccc2022-12-27 08:48:48 +00001188 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001189 loge("Unregister failed with non-DiscoveryManagerRequest.");
Paul Hu18aeccc2022-12-27 08:48:48 +00001190 }
Paul Hu18aeccc2022-12-27 08:48:48 +00001191 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001192 }
paulhu2b9ed952022-02-10 21:58:32 +08001193 case MDNS_SERVICE_EVENT:
1194 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +09001195 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001196 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001197 break;
Paul Hu019621e2023-01-13 23:26:49 +08001198 case MDNS_DISCOVERY_MANAGER_EVENT:
1199 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
1200 return NOT_HANDLED;
1201 }
1202 break;
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001203 case NsdManager.REGISTER_OFFLOAD_ENGINE:
1204 offloadEngineInfo = (OffloadEngineInfo) msg.obj;
1205 // TODO: Limits the number of registrations created by a given class.
1206 mOffloadEngines.register(offloadEngineInfo.mOffloadEngine,
1207 offloadEngineInfo);
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001208 sendAllOffloadServiceInfos(offloadEngineInfo);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001209 break;
1210 case NsdManager.UNREGISTER_OFFLOAD_ENGINE:
1211 mOffloadEngines.unregister((IOffloadEngine) msg.obj);
1212 break;
Irfan Sheriff75006652012-04-17 23:15:29 -07001213 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001214 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001215 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001216 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001217 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001218
Paul Hud44e1b72023-06-16 02:07:42 +00001219 private boolean handleMDnsServiceEvent(int code, int transactionId, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001220 NsdServiceInfo servInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001221 ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001222 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001223 Log.e(TAG, String.format(
1224 "transactionId %d for %d has no client mapping", transactionId, code));
Hugo Benichif0c84092017-04-05 14:43:29 +09001225 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001226 }
1227
1228 /* This goes in response as msg.arg2 */
Paul Hud44e1b72023-06-16 02:07:42 +00001229 int clientRequestId = clientInfo.getClientRequestId(transactionId);
1230 if (clientRequestId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -07001231 // This can happen because of race conditions. For example,
1232 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
1233 // and we may get in this situation.
Paul Hud44e1b72023-06-16 02:07:42 +00001234 Log.d(TAG, String.format("%d for transactionId %d that is no longer active",
1235 code, transactionId));
Hugo Benichif0c84092017-04-05 14:43:29 +09001236 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001237 }
Paul Hu812e9212023-06-20 06:24:53 +00001238 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1239 if (request == null) {
1240 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1241 return false;
1242 }
Hugo Benichi32be63d2017-04-05 14:06:11 +09001243 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00001244 Log.d(TAG, String.format(
1245 "MDns service event code:%d transactionId=%d", code, transactionId));
Hugo Benichi32be63d2017-04-05 14:06:11 +09001246 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001247 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +08001248 case IMDnsEventListener.SERVICE_FOUND: {
1249 final DiscoveryInfo info = (DiscoveryInfo) obj;
1250 final String name = info.serviceName;
1251 final String type = info.registrationType;
1252 servInfo = new NsdServiceInfo(name, type);
1253 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001254 if (foundNetId == 0L) {
1255 // Ignore services that do not have a Network: they are not usable
1256 // by apps, as they would need privileged permissions to use
1257 // interfaces that do not have an associated Network.
1258 break;
1259 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +09001260 if (foundNetId == INetd.DUMMY_NET_ID) {
1261 // Ignore services on the dummy0 interface: they are only seen when
1262 // discovering locally advertised services, and are not reachable
1263 // through that interface.
1264 break;
1265 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001266 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001267
1268 clientInfo.onServiceFound(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001269 break;
paulhu2b9ed952022-02-10 21:58:32 +08001270 }
1271 case IMDnsEventListener.SERVICE_LOST: {
1272 final DiscoveryInfo info = (DiscoveryInfo) obj;
1273 final String name = info.serviceName;
1274 final String type = info.registrationType;
1275 final int lostNetId = info.netId;
1276 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001277 // The network could be set to null (netId 0) if it was torn down when the
1278 // service is lost
1279 // TODO: avoid returning null in that case, possibly by remembering
1280 // found services on the same interface index and their network at the time
1281 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001282 clientInfo.onServiceLost(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001283 break;
paulhu2b9ed952022-02-10 21:58:32 +08001284 }
1285 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Paul Hu812e9212023-06-20 06:24:53 +00001286 clientInfo.onDiscoverServicesFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001287 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1288 transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001289 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001290 break;
paulhu2b9ed952022-02-10 21:58:32 +08001291 case IMDnsEventListener.SERVICE_REGISTERED: {
1292 final RegistrationInfo info = (RegistrationInfo) obj;
1293 final String name = info.serviceName;
1294 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Paul Hu508a0122023-09-11 15:31:33 +08001295 clientInfo.onRegisterServiceSucceeded(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001296 break;
paulhu2b9ed952022-02-10 21:58:32 +08001297 }
1298 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Paul Hu777ed052023-06-19 13:35:15 +00001299 clientInfo.onRegisterServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001300 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1301 transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001302 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001303 break;
paulhu2b9ed952022-02-10 21:58:32 +08001304 case IMDnsEventListener.SERVICE_RESOLVED: {
1305 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001306 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +08001307 final String fullName = info.serviceFullName;
1308 while (index < fullName.length() && fullName.charAt(index) != '.') {
1309 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001310 ++index;
1311 }
1312 ++index;
1313 }
paulhu2b9ed952022-02-10 21:58:32 +08001314 if (index >= fullName.length()) {
1315 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001316 break;
1317 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001318
paulhube186602022-04-12 07:18:23 +00001319 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001320 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001321 String type = rest.replace(".local.", "");
1322
Paul Hu30bd70d2023-02-07 13:20:56 +00001323 final NsdServiceInfo serviceInfo = clientInfo.mResolvedService;
Paul Hu18aeccc2022-12-27 08:48:48 +00001324 serviceInfo.setServiceName(name);
1325 serviceInfo.setServiceType(type);
1326 serviceInfo.setPort(info.port);
1327 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001328 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001329
Paul Hud44e1b72023-06-16 02:07:42 +00001330 stopResolveService(transactionId);
1331 removeRequestMap(clientRequestId, transactionId, clientInfo);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001332
Paul Hud44e1b72023-06-16 02:07:42 +00001333 final int transactionId2 = getUniqueId();
1334 if (getAddrInfo(transactionId2, info.hostname, info.interfaceIdx)) {
1335 storeLegacyRequestMap(clientRequestId, transactionId2, clientInfo,
Paul Hua6bc4632023-06-26 01:18:29 +00001336 NsdManager.RESOLVE_SERVICE, request.mStartTimeMs);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001337 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001338 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001339 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1340 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001341 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001342 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001343 }
1344 break;
paulhu2b9ed952022-02-10 21:58:32 +08001345 }
1346 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001347 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001348 stopResolveService(transactionId);
1349 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001350 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001351 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1352 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001353 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001354 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001355 break;
paulhu2b9ed952022-02-10 21:58:32 +08001356 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001357 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001358 stopGetAddrInfo(transactionId);
1359 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001360 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001361 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1362 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001363 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001364 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001365 break;
paulhu2b9ed952022-02-10 21:58:32 +08001366 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001367 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001368 final GetAddressInfo info = (GetAddressInfo) obj;
1369 final String address = info.address;
1370 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001371 InetAddress serviceHost = null;
1372 try {
paulhu2b9ed952022-02-10 21:58:32 +08001373 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001374 } catch (UnknownHostException e) {
1375 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1376 }
1377
1378 // If the resolved service is on an interface without a network, consider it
1379 // as a failure: it would not be usable by apps as they would need
1380 // privileged permissions.
Paul Hu30bd70d2023-02-07 13:20:56 +00001381 if (netId != NETID_UNSET && serviceHost != null) {
1382 clientInfo.mResolvedService.setHost(serviceHost);
1383 setServiceNetworkForCallback(clientInfo.mResolvedService,
1384 netId, info.interfaceIdx);
1385 clientInfo.onResolveServiceSucceeded(
Paul Hua6bc4632023-06-26 01:18:29 +00001386 clientRequestId, clientInfo.mResolvedService, request);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001387 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001388 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001389 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1390 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001391 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001392 }
Paul Hud44e1b72023-06-16 02:07:42 +00001393 stopGetAddrInfo(transactionId);
1394 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001395 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001396 break;
paulhu2b9ed952022-02-10 21:58:32 +08001397 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001398 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001399 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001400 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001401 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001402 }
Paul Hu019621e2023-01-13 23:26:49 +08001403
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001404 @Nullable
1405 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(
1406 final MdnsEvent event, int code) {
Paul Hu019621e2023-01-13 23:26:49 +08001407 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001408 final String[] typeArray = serviceInfo.getServiceType();
1409 final String joinedType;
1410 if (typeArray.length == 0
1411 || !typeArray[typeArray.length - 1].equals(LOCAL_DOMAIN_NAME)) {
1412 Log.wtf(TAG, "MdnsServiceInfo type does not end in .local: "
1413 + Arrays.toString(typeArray));
1414 return null;
1415 } else {
1416 joinedType = TextUtils.join(".",
1417 Arrays.copyOfRange(typeArray, 0, typeArray.length - 1));
1418 }
1419 final String serviceType;
1420 switch (code) {
1421 case NsdManager.SERVICE_FOUND:
1422 case NsdManager.SERVICE_LOST:
1423 // For consistency with historical behavior, discovered service types have
1424 // a dot at the end.
1425 serviceType = joinedType + ".";
1426 break;
1427 case RESOLVE_SERVICE_SUCCEEDED:
1428 // For consistency with historical behavior, resolved service types have
1429 // a dot at the beginning.
1430 serviceType = "." + joinedType;
1431 break;
1432 default:
1433 serviceType = joinedType;
1434 break;
1435 }
Paul Hu019621e2023-01-13 23:26:49 +08001436 final String serviceName = serviceInfo.getServiceInstanceName();
1437 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1438 final Network network = serviceInfo.getNetwork();
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001439 // In MdnsDiscoveryManagerEvent, the Network can be null which means it is a
1440 // network for Tethering interface. In other words, the network == null means the
1441 // network has netId = INetd.LOCAL_NET_ID.
Paul Hu019621e2023-01-13 23:26:49 +08001442 setServiceNetworkForCallback(
1443 servInfo,
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001444 network == null ? INetd.LOCAL_NET_ID : network.netId,
Paul Hu019621e2023-01-13 23:26:49 +08001445 serviceInfo.getInterfaceIndex());
1446 return servInfo;
1447 }
1448
1449 private boolean handleMdnsDiscoveryManagerEvent(
1450 int transactionId, int code, Object obj) {
Paul Hud44e1b72023-06-16 02:07:42 +00001451 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Paul Hu019621e2023-01-13 23:26:49 +08001452 if (clientInfo == null) {
1453 Log.e(TAG, String.format(
1454 "id %d for %d has no client mapping", transactionId, code));
1455 return false;
1456 }
1457
1458 final MdnsEvent event = (MdnsEvent) obj;
Paul Hud44e1b72023-06-16 02:07:42 +00001459 final int clientRequestId = event.mClientRequestId;
Paul Hubad6fe92023-07-24 21:25:22 +08001460 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1461 if (request == null) {
1462 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1463 return false;
1464 }
1465
1466 // Deal with the discovery sent callback
1467 if (code == DISCOVERY_QUERY_SENT_CALLBACK) {
1468 request.onQuerySent();
1469 return true;
1470 }
1471
1472 // Deal with other callbacks.
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001473 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event, code);
1474 // Errors are already logged if null
1475 if (info == null) return false;
Paul Hu83ec7f42023-06-07 18:04:09 +08001476 mServiceLogs.log(String.format(
1477 "MdnsDiscoveryManager event code=%s transactionId=%d",
1478 NsdManager.nameOf(code), transactionId));
Paul Hu019621e2023-01-13 23:26:49 +08001479 switch (code) {
1480 case NsdManager.SERVICE_FOUND:
Paul Hu812e9212023-06-20 06:24:53 +00001481 clientInfo.onServiceFound(clientRequestId, info, request);
Paul Hu319751a2023-01-13 23:56:34 +08001482 break;
1483 case NsdManager.SERVICE_LOST:
Paul Hu812e9212023-06-20 06:24:53 +00001484 clientInfo.onServiceLost(clientRequestId, info, request);
Paul Hu019621e2023-01-13 23:26:49 +08001485 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001486 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
1487 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Paul Hu75069ed2023-01-14 00:31:09 +08001488 info.setPort(serviceInfo.getPort());
1489
1490 Map<String, String> attrs = serviceInfo.getAttributes();
1491 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1492 final String key = kv.getKey();
1493 try {
1494 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1495 } catch (IllegalArgumentException e) {
1496 Log.e(TAG, "Invalid attribute", e);
1497 }
1498 }
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001499 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu2b865912023-03-06 14:27:53 +08001500 if (addresses.size() != 0) {
1501 info.setHostAddresses(addresses);
Paul Hua6bc4632023-06-26 01:18:29 +00001502 request.setServiceFromCache(event.mIsServiceFromCache);
1503 clientInfo.onResolveServiceSucceeded(clientRequestId, info, request);
Paul Hu2b865912023-03-06 14:27:53 +08001504 } else {
1505 // No address. Notify resolution failure.
Paul Hua6bc4632023-06-26 01:18:29 +00001506 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001507 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */,
1508 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001509 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu75069ed2023-01-14 00:31:09 +08001510 }
1511
1512 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001513 if (!(request instanceof DiscoveryManagerRequest)) {
1514 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1515 break;
1516 }
Paul Hud44e1b72023-06-16 02:07:42 +00001517 stopDiscoveryManagerRequest(
1518 request, clientRequestId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001519 break;
1520 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001521 case NsdManager.SERVICE_UPDATED: {
1522 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1523 info.setPort(serviceInfo.getPort());
1524
1525 Map<String, String> attrs = serviceInfo.getAttributes();
1526 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1527 final String key = kv.getKey();
1528 try {
1529 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1530 } catch (IllegalArgumentException e) {
1531 Log.e(TAG, "Invalid attribute", e);
1532 }
1533 }
1534
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001535 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001536 info.setHostAddresses(addresses);
Paul Huddce5912023-08-01 10:26:49 +08001537 clientInfo.onServiceUpdated(clientRequestId, info, request);
1538 // Set the ServiceFromCache flag only if the service is actually being
1539 // retrieved from the cache. This flag should not be overridden by later
1540 // service updates, which may not be cached.
1541 if (event.mIsServiceFromCache) {
1542 request.setServiceFromCache(true);
1543 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001544 break;
1545 }
1546 case NsdManager.SERVICE_UPDATED_LOST:
Paul Huddce5912023-08-01 10:26:49 +08001547 clientInfo.onServiceUpdatedLost(clientRequestId, request);
Paul Hu30bd70d2023-02-07 13:20:56 +00001548 break;
Paul Hu019621e2023-01-13 23:26:49 +08001549 default:
1550 return false;
1551 }
1552 return true;
1553 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001554 }
1555 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001556
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001557 @NonNull
1558 private static List<InetAddress> getInetAddresses(@NonNull MdnsServiceInfo serviceInfo) {
1559 final List<String> v4Addrs = serviceInfo.getIpv4Addresses();
1560 final List<String> v6Addrs = serviceInfo.getIpv6Addresses();
1561 final List<InetAddress> addresses = new ArrayList<>(v4Addrs.size() + v6Addrs.size());
1562 for (String ipv4Address : v4Addrs) {
1563 try {
1564 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1565 } catch (IllegalArgumentException e) {
1566 Log.wtf(TAG, "Invalid ipv4 address", e);
1567 }
1568 }
1569 for (String ipv6Address : v6Addrs) {
1570 try {
Yuyang Huanga6a6ff92023-04-24 13:33:34 +09001571 final Inet6Address addr = (Inet6Address) InetAddresses.parseNumericAddress(
1572 ipv6Address);
1573 addresses.add(InetAddressUtils.withScopeId(addr, serviceInfo.getInterfaceIndex()));
1574 } catch (IllegalArgumentException e) {
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001575 Log.wtf(TAG, "Invalid ipv6 address", e);
1576 }
1577 }
1578 return addresses;
1579 }
1580
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001581 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1582 switch (netId) {
1583 case NETID_UNSET:
1584 info.setNetwork(null);
1585 break;
1586 case INetd.LOCAL_NET_ID:
1587 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1588 // visible / usable for apps, so do not return it. Store the interface
1589 // index instead, so at least if the client tries to resolve the service
1590 // with that NsdServiceInfo, it will be done on the same interface.
1591 // If they recreate the NsdServiceInfo themselves, resolution would be
1592 // done on all interfaces as before T, which should also work.
1593 info.setNetwork(null);
1594 info.setInterfaceIndex(ifaceIdx);
1595 break;
1596 default:
1597 info.setNetwork(new Network(netId));
1598 }
1599 }
1600
paulhube186602022-04-12 07:18:23 +00001601 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1602 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1603 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1604 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1605 private String unescape(String s) {
1606 StringBuilder sb = new StringBuilder(s.length());
1607 for (int i = 0; i < s.length(); ++i) {
1608 char c = s.charAt(i);
1609 if (c == '\\') {
1610 if (++i >= s.length()) {
1611 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1612 break;
1613 }
1614 c = s.charAt(i);
1615 if (c != '.' && c != '\\') {
1616 if (i + 2 >= s.length()) {
1617 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1618 break;
1619 }
1620 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1621 + (s.charAt(i + 2) - '0'));
1622 i += 2;
1623 }
1624 }
1625 sb.append(c);
1626 }
1627 return sb.toString();
1628 }
1629
Paul Hu7445e3d2023-03-03 15:14:00 +08001630 /**
1631 * Check the given service type is valid and construct it to a service type
1632 * which can use for discovery / resolution service.
1633 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001634 * <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 +08001635 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1636 * underscore; they are alphanumerical characters or dashes or underscore, except the
1637 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1638 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001639 * <p>The subtype may also be specified with a comma after the service type, for example
1640 * _type._tcp,_subtype.
1641 *
Paul Hu7445e3d2023-03-03 15:14:00 +08001642 * @param serviceType the request service type for discovery / resolution service
1643 * @return constructed service type or null if the given service type is invalid.
1644 */
1645 @Nullable
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001646 public static Pair<String, String> parseTypeAndSubtype(String serviceType) {
Paul Hu7445e3d2023-03-03 15:14:00 +08001647 if (TextUtils.isEmpty(serviceType)) return null;
1648
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001649 final String typeOrSubtypePattern = "_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]";
Paul Hu7445e3d2023-03-03 15:14:00 +08001650 final Pattern serviceTypePattern = Pattern.compile(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001651 // Optional leading subtype (_subtype._type._tcp)
1652 // (?: xxx) is a non-capturing parenthesis, don't capture the dot
1653 "^(?:(" + typeOrSubtypePattern + ")\\.)?"
1654 // Actual type (_type._tcp.local)
1655 + "(" + typeOrSubtypePattern + "\\._(?:tcp|udp))"
Paul Hu7445e3d2023-03-03 15:14:00 +08001656 // Drop '.' at the end of service type that is compatible with old backend.
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001657 // e.g. allow "_type._tcp.local."
1658 + "\\.?"
1659 // Optional subtype after comma, for "_type._tcp,_subtype" format
1660 + "(?:,(" + typeOrSubtypePattern + "))?"
1661 + "$");
Paul Hu7445e3d2023-03-03 15:14:00 +08001662 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1663 if (!matcher.matches()) return null;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001664 // Use the subtype either at the beginning or after the comma
1665 final String subtype = matcher.group(1) != null ? matcher.group(1) : matcher.group(3);
1666 return new Pair<>(matcher.group(2), subtype);
Paul Hu7445e3d2023-03-03 15:14:00 +08001667 }
1668
Hugo Benichi803a2f02017-04-24 11:35:06 +09001669 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001670 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001671 this(ctx, handler, cleanupDelayMs, new Dependencies());
1672 }
1673
1674 @VisibleForTesting
1675 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001676 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001677 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001678 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001679 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001680 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1681 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001682 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001683
Paul Hu14667de2023-04-17 22:42:47 +08001684 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper(),
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001685 LOGGER.forSubComponent("MdnsSocketProvider"), new SocketRequestMonitor());
Yuyang Huang700778b2023-03-08 16:17:05 +09001686 // Netlink monitor starts on boot, and intentionally never stopped, to ensure that all
Yuyang Huangfca402a2023-05-24 14:45:59 +09001687 // address events are received. When the netlink monitor starts, any IP addresses already
1688 // on the interfaces will not be seen. In practice, the network will not connect at boot
1689 // time As a result, all the netlink message should be observed if the netlink monitor
1690 // starts here.
Yuyang Huang700778b2023-03-08 16:17:05 +09001691 handler.post(mMdnsSocketProvider::startNetLinkMonitor);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001692
1693 // NsdService is started after ActivityManager (startOtherServices in SystemServer, vs.
1694 // startBootstrapServices).
1695 mRunningAppActiveImportanceCutoff = mDeps.getDeviceConfigInt(
1696 MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF,
1697 DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF);
1698 final ActivityManager am = ctx.getSystemService(ActivityManager.class);
1699 am.addOnUidImportanceListener(new UidImportanceListener(handler),
1700 mRunningAppActiveImportanceCutoff);
1701
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001702 mMdnsSocketClient =
Yuyang Huang7ddf2932023-08-01 18:16:30 +09001703 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider,
1704 LOGGER.forSubComponent("MdnsMultinetworkSocketClient"));
Paul Hu14667de2023-04-17 22:42:47 +08001705 mMdnsDiscoveryManager = deps.makeMdnsDiscoveryManager(new ExecutorProvider(),
Yuyang Huang243d1a52023-05-23 17:26:52 +09001706 mMdnsSocketClient, LOGGER.forSubComponent("MdnsDiscoveryManager"));
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001707 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
Yuyang Huangb96a0712023-09-07 15:13:15 +09001708 MdnsFeatureFlags flags = new MdnsFeatureFlags.Builder().setIsMdnsOffloadFeatureEnabled(
1709 mDeps.isTetheringFeatureNotChickenedOut(
1710 MdnsFeatureFlags.NSD_FORCE_DISABLE_MDNS_OFFLOAD)).build();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001711 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
Yuyang Huangb96a0712023-09-07 15:13:15 +09001712 new AdvertiserCallback(), LOGGER.forSubComponent("MdnsAdvertiser"), flags);
Paul Hu777ed052023-06-19 13:35:15 +00001713 mClock = deps.makeClock();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001714 }
1715
1716 /**
1717 * Dependencies of NsdService, for injection in tests.
1718 */
1719 @VisibleForTesting
1720 public static class Dependencies {
1721 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001722 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001723 *
1724 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001725 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001726 */
1727 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001728 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001729 MDNS_DISCOVERY_MANAGER_VERSION);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001730 }
1731
1732 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001733 * Check whether the MdnsAdvertiser feature is enabled.
1734 *
1735 * @param context The global context information about an app environment.
1736 * @return true if the MdnsAdvertiser feature is enabled.
1737 */
1738 public boolean isMdnsAdvertiserEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001739 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001740 MDNS_ADVERTISER_VERSION);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001741 }
1742
1743 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001744 * Get the type allowlist flag value.
1745 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1746 */
1747 @Nullable
1748 public String getTypeAllowlistFlags() {
1749 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1750 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1751 }
1752
1753 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001754 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001755 */
1756 public boolean isFeatureEnabled(Context context, String feature) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001757 return DeviceConfigUtils.isTetheringFeatureEnabled(context, feature);
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001758 }
1759
1760 /**
Yuyang Huangb96a0712023-09-07 15:13:15 +09001761 * @see DeviceConfigUtils#isTetheringFeatureNotChickenedOut
1762 */
1763 public boolean isTetheringFeatureNotChickenedOut(String feature) {
1764 return DeviceConfigUtils.isTetheringFeatureNotChickenedOut(feature);
1765 }
1766
1767 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001768 * @see MdnsDiscoveryManager
1769 */
1770 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
Paul Hu14667de2023-04-17 22:42:47 +08001771 @NonNull ExecutorProvider executorProvider,
Yuyang Huang243d1a52023-05-23 17:26:52 +09001772 @NonNull MdnsMultinetworkSocketClient socketClient, @NonNull SharedLog sharedLog) {
1773 return new MdnsDiscoveryManager(executorProvider, socketClient, sharedLog);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001774 }
1775
1776 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001777 * @see MdnsAdvertiser
1778 */
1779 public MdnsAdvertiser makeMdnsAdvertiser(
1780 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
Yuyang Huangb96a0712023-09-07 15:13:15 +09001781 @NonNull MdnsAdvertiser.AdvertiserCallback cb, @NonNull SharedLog sharedLog,
1782 MdnsFeatureFlags featureFlags) {
1783 return new MdnsAdvertiser(looper, socketProvider, cb, sharedLog, featureFlags);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001784 }
1785
1786 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001787 * @see MdnsSocketProvider
1788 */
Paul Hu14667de2023-04-17 22:42:47 +08001789 public MdnsSocketProvider makeMdnsSocketProvider(@NonNull Context context,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001790 @NonNull Looper looper, @NonNull SharedLog sharedLog,
1791 @NonNull MdnsSocketProvider.SocketRequestMonitor socketCreationCallback) {
1792 return new MdnsSocketProvider(context, looper, sharedLog, socketCreationCallback);
1793 }
1794
1795 /**
1796 * @see DeviceConfig#getInt(String, String, int)
1797 */
1798 public int getDeviceConfigInt(@NonNull String config, int defaultValue) {
1799 return DeviceConfig.getInt(NAMESPACE_TETHERING, config, defaultValue);
1800 }
1801
1802 /**
1803 * @see Binder#getCallingUid()
1804 */
1805 public int getCallingUid() {
1806 return Binder.getCallingUid();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001807 }
Paul Hu777ed052023-06-19 13:35:15 +00001808
1809 /**
1810 * @see NetworkNsdReportedMetrics
1811 */
Paul Hu508a0122023-09-11 15:31:33 +08001812 public NetworkNsdReportedMetrics makeNetworkNsdReportedMetrics(int clientId) {
1813 return new NetworkNsdReportedMetrics(clientId);
Paul Hu777ed052023-06-19 13:35:15 +00001814 }
1815
1816 /**
1817 * @see MdnsUtils.Clock
1818 */
1819 public Clock makeClock() {
1820 return new Clock();
1821 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001822 }
1823
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001824 /**
1825 * Return whether a type is allowlisted to use the Java backend.
1826 * @param type The service type
1827 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1828 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1829 */
1830 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1831 @NonNull String flagPrefix) {
1832 if (type == null) return false;
1833 final String typesConfig = mDeps.getTypeAllowlistFlags();
1834 if (TextUtils.isEmpty(typesConfig)) return false;
1835
1836 final String mappingPrefix = type + ":";
1837 String mappedFlag = null;
1838 for (String mapping : TextUtils.split(typesConfig, ",")) {
1839 if (mapping.startsWith(mappingPrefix)) {
1840 mappedFlag = mapping.substring(mappingPrefix.length());
1841 break;
1842 }
1843 }
1844
1845 if (mappedFlag == null) return false;
1846
1847 return mDeps.isFeatureEnabled(mContext,
1848 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1849 }
1850
1851 private boolean useDiscoveryManagerForType(@Nullable String type) {
1852 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1853 }
1854
1855 private boolean useAdvertiserForType(@Nullable String type) {
1856 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1857 }
1858
paulhu1b35e822022-04-08 14:48:41 +08001859 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001860 HandlerThread thread = new HandlerThread(TAG);
1861 thread.start();
1862 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001863 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001864 return service;
1865 }
1866
paulhu2b9ed952022-02-10 21:58:32 +08001867 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1868 private final StateMachine mStateMachine;
1869
1870 MDnsEventCallback(StateMachine sm) {
1871 mStateMachine = sm;
1872 }
1873
1874 @Override
1875 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1876 mStateMachine.sendMessage(
1877 MDNS_SERVICE_EVENT, status.result, status.id, status);
1878 }
1879
1880 @Override
1881 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1882 mStateMachine.sendMessage(
1883 MDNS_SERVICE_EVENT, status.result, status.id, status);
1884 }
1885
1886 @Override
1887 public void onServiceResolutionStatus(final ResolutionInfo status) {
1888 mStateMachine.sendMessage(
1889 MDNS_SERVICE_EVENT, status.result, status.id, status);
1890 }
1891
1892 @Override
1893 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1894 mStateMachine.sendMessage(
1895 MDNS_SERVICE_EVENT, status.result, status.id, status);
1896 }
1897
1898 @Override
1899 public int getInterfaceVersion() throws RemoteException {
1900 return this.VERSION;
1901 }
1902
1903 @Override
1904 public String getInterfaceHash() throws RemoteException {
1905 return this.HASH;
1906 }
1907 }
1908
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001909 private void sendAllOffloadServiceInfos(@NonNull OffloadEngineInfo offloadEngineInfo) {
1910 final String targetInterface = offloadEngineInfo.mInterfaceName;
1911 final IOffloadEngine offloadEngine = offloadEngineInfo.mOffloadEngine;
1912 final List<MdnsAdvertiser.OffloadServiceInfoWrapper> offloadWrappers =
1913 mAdvertiser.getAllInterfaceOffloadServiceInfos(targetInterface);
1914 for (MdnsAdvertiser.OffloadServiceInfoWrapper wrapper : offloadWrappers) {
1915 try {
1916 offloadEngine.onOffloadServiceUpdated(wrapper.mOffloadServiceInfo);
1917 } catch (RemoteException e) {
1918 // Can happen in regular cases, do not log a stacktrace
1919 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
1920 }
1921 }
1922 }
1923
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001924 private void sendOffloadServiceInfosUpdate(@NonNull String targetInterfaceName,
1925 @NonNull OffloadServiceInfo offloadServiceInfo, boolean isRemove) {
1926 final int count = mOffloadEngines.beginBroadcast();
1927 try {
1928 for (int i = 0; i < count; i++) {
1929 final OffloadEngineInfo offloadEngineInfo =
1930 (OffloadEngineInfo) mOffloadEngines.getBroadcastCookie(i);
1931 final String interfaceName = offloadEngineInfo.mInterfaceName;
1932 if (!targetInterfaceName.equals(interfaceName)
1933 || ((offloadEngineInfo.mOffloadType
1934 & offloadServiceInfo.getOffloadType()) == 0)) {
1935 continue;
1936 }
1937 try {
1938 if (isRemove) {
1939 mOffloadEngines.getBroadcastItem(i).onOffloadServiceRemoved(
1940 offloadServiceInfo);
1941 } else {
1942 mOffloadEngines.getBroadcastItem(i).onOffloadServiceUpdated(
1943 offloadServiceInfo);
1944 }
1945 } catch (RemoteException e) {
1946 // Can happen in regular cases, do not log a stacktrace
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001947 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001948 }
1949 }
1950 } finally {
1951 mOffloadEngines.finishBroadcast();
1952 }
1953 }
1954
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001955 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001956 // TODO: add a callback to notify when a service is being added on each interface (as soon
1957 // as probing starts), and call mOffloadCallbacks. This callback is for
1958 // OFFLOAD_CAPABILITY_FILTER_REPLIES offload type.
1959
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001960 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001961 public void onRegisterServiceSucceeded(int transactionId, NsdServiceInfo registeredInfo) {
1962 mServiceLogs.log("onRegisterServiceSucceeded: transactionId " + transactionId);
1963 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001964 if (clientInfo == null) return;
1965
Paul Hud44e1b72023-06-16 02:07:42 +00001966 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1967 if (clientRequestId < 0) return;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001968
1969 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1970 // historical behavior.
1971 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
Paul Hu777ed052023-06-19 13:35:15 +00001972 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu508a0122023-09-11 15:31:33 +08001973 clientInfo.onRegisterServiceSucceeded(clientRequestId, cbInfo, request);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001974 }
1975
1976 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001977 public void onRegisterServiceFailed(int transactionId, int errorCode) {
1978 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001979 if (clientInfo == null) return;
1980
Paul Hud44e1b72023-06-16 02:07:42 +00001981 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1982 if (clientRequestId < 0) return;
Paul Hu777ed052023-06-19 13:35:15 +00001983 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu508a0122023-09-11 15:31:33 +08001984 clientInfo.onRegisterServiceFailed(clientRequestId, errorCode, false /* isLegacy */,
1985 transactionId, request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001986 }
1987
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001988 @Override
1989 public void onOffloadStartOrUpdate(@NonNull String interfaceName,
1990 @NonNull OffloadServiceInfo offloadServiceInfo) {
1991 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, false /* isRemove */);
1992 }
1993
1994 @Override
1995 public void onOffloadStop(@NonNull String interfaceName,
1996 @NonNull OffloadServiceInfo offloadServiceInfo) {
1997 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, true /* isRemove */);
1998 }
1999
Paul Hud44e1b72023-06-16 02:07:42 +00002000 private ClientInfo getClientInfoOrLog(int transactionId) {
2001 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002002 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00002003 Log.e(TAG, String.format("Callback for service %d has no client", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002004 }
2005 return clientInfo;
2006 }
2007
Paul Hud44e1b72023-06-16 02:07:42 +00002008 private int getClientRequestIdOrLog(@NonNull ClientInfo info, int transactionId) {
2009 final int clientRequestId = info.getClientRequestId(transactionId);
2010 if (clientRequestId < 0) {
2011 Log.e(TAG, String.format(
2012 "Client request ID not found for service %d", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002013 }
Paul Hud44e1b72023-06-16 02:07:42 +00002014 return clientRequestId;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002015 }
2016 }
2017
Paul Hu2e0a88c2023-03-09 16:05:01 +08002018 private static class ConnectorArgs {
2019 @NonNull public final NsdServiceConnector connector;
2020 @NonNull public final INsdManagerCallback callback;
2021 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002022 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002023
2024 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00002025 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08002026 this.connector = connector;
2027 this.callback = callback;
2028 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002029 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002030 }
2031 }
2032
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002033 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08002034 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09002035 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu101dbf52023-08-09 16:05:20 +08002036 final int uid = mDeps.getCallingUid();
2037 if (cb == null) {
2038 throw new IllegalArgumentException("Unknown client callback from uid=" + uid);
2039 }
Paul Hu2e0a88c2023-03-09 16:05:01 +08002040 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002041 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00002042 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
Paul Hu101dbf52023-08-09 16:05:20 +08002043 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend, uid)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002044 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07002045 }
2046
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002047 private static class ListenerArgs {
2048 public final NsdServiceConnector connector;
2049 public final NsdServiceInfo serviceInfo;
2050 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
2051 this.connector = connector;
2052 this.serviceInfo = serviceInfo;
2053 }
2054 }
2055
2056 private class NsdServiceConnector extends INsdServiceConnector.Stub
2057 implements IBinder.DeathRecipient {
2058 @Override
2059 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
2060 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2061 NsdManager.REGISTER_SERVICE, 0, listenerKey,
2062 new ListenerArgs(this, serviceInfo)));
2063 }
2064
2065 @Override
2066 public void unregisterService(int listenerKey) {
2067 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2068 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
2069 new ListenerArgs(this, null)));
2070 }
2071
2072 @Override
2073 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
2074 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2075 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
2076 new ListenerArgs(this, serviceInfo)));
2077 }
2078
2079 @Override
2080 public void stopDiscovery(int listenerKey) {
2081 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2082 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
2083 }
2084
2085 @Override
2086 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
2087 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2088 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
2089 new ListenerArgs(this, serviceInfo)));
2090 }
2091
2092 @Override
Paul Hub58deb72022-12-26 09:24:42 +00002093 public void stopResolution(int listenerKey) {
2094 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2095 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
2096 }
2097
2098 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00002099 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
2100 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2101 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
2102 new ListenerArgs(this, serviceInfo)));
2103 }
2104
2105 @Override
2106 public void unregisterServiceInfoCallback(int listenerKey) {
2107 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2108 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
2109 new ListenerArgs(this, null)));
2110 }
2111
2112 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002113 public void startDaemon() {
2114 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2115 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
2116 }
2117
2118 @Override
2119 public void binderDied() {
2120 mNsdStateMachine.sendMessage(
2121 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002122
2123 }
2124
2125 @Override
2126 public void registerOffloadEngine(String ifaceName, IOffloadEngine cb,
2127 @OffloadEngine.OffloadCapability long offloadCapabilities,
2128 @OffloadEngine.OffloadType long offloadTypes) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002129 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002130 Objects.requireNonNull(ifaceName);
2131 Objects.requireNonNull(cb);
2132 mNsdStateMachine.sendMessage(
2133 mNsdStateMachine.obtainMessage(NsdManager.REGISTER_OFFLOAD_ENGINE,
2134 new OffloadEngineInfo(cb, ifaceName, offloadCapabilities,
2135 offloadTypes)));
2136 }
2137
2138 @Override
2139 public void unregisterOffloadEngine(IOffloadEngine cb) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002140 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002141 Objects.requireNonNull(cb);
2142 mNsdStateMachine.sendMessage(
2143 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_OFFLOAD_ENGINE, cb));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002144 }
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002145
2146 private static void checkOffloadEnginePermission(Context context) {
2147 if (!SdkLevel.isAtLeastT()) {
2148 throw new SecurityException("API is not available in before API level 33");
2149 }
2150 // REGISTER_NSD_OFFLOAD_ENGINE was only added to the SDK in V, but may
2151 // be back ported to older builds: accept it as long as it's signature-protected
2152 if (PermissionUtils.checkAnyPermissionOf(context, REGISTER_NSD_OFFLOAD_ENGINE)
2153 && (SdkLevel.isAtLeastV() || PermissionUtils.isSystemSignaturePermission(
2154 context, REGISTER_NSD_OFFLOAD_ENGINE))) {
2155 return;
2156 }
2157 if (PermissionUtils.checkAnyPermissionOf(context, NETWORK_STACK,
2158 PERMISSION_MAINLINE_NETWORK_STACK, NETWORK_SETTINGS)) {
2159 return;
2160 }
2161 throw new SecurityException("Requires one of the following permissions: "
2162 + String.join(", ", List.of(REGISTER_NSD_OFFLOAD_ENGINE, NETWORK_STACK,
2163 PERMISSION_MAINLINE_NETWORK_STACK, NETWORK_SETTINGS)) + ".");
2164 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002165 }
2166
Hugo Benichi912db992017-04-24 16:41:03 +09002167 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07002168 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07002169 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09002170 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
2171 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07002172 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07002173 }
2174
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002175 private int getUniqueId() {
2176 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
2177 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002178 }
2179
Paul Hud44e1b72023-06-16 02:07:42 +00002180 private boolean registerService(int transactionId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09002181 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002182 Log.d(TAG, "registerService: " + transactionId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002183 }
Hugo Benichi6d706442017-04-24 16:19:58 +09002184 String name = service.getServiceName();
2185 String type = service.getServiceType();
2186 int port = service.getPort();
2187 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002188 final int registerInterface = getNetworkInterfaceIndex(service);
2189 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08002190 Log.e(TAG, "Interface to register service on not found");
2191 return false;
2192 }
Paul Hud44e1b72023-06-16 02:07:42 +00002193 return mMDnsManager.registerService(
2194 transactionId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002195 }
2196
Paul Hud44e1b72023-06-16 02:07:42 +00002197 private boolean unregisterService(int transactionId) {
2198 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002199 }
2200
Paul Hud44e1b72023-06-16 02:07:42 +00002201 private boolean discoverServices(int transactionId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08002202 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002203 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
2204 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002205 Log.e(TAG, "Interface to discover service on not found");
2206 return false;
2207 }
Paul Hud44e1b72023-06-16 02:07:42 +00002208 return mMDnsManager.discover(transactionId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002209 }
2210
Paul Hud44e1b72023-06-16 02:07:42 +00002211 private boolean stopServiceDiscovery(int transactionId) {
2212 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002213 }
2214
Paul Hud44e1b72023-06-16 02:07:42 +00002215 private boolean resolveService(int transactionId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002216 final String name = service.getServiceName();
2217 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002218 final int resolveInterface = getNetworkInterfaceIndex(service);
2219 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002220 Log.e(TAG, "Interface to resolve service on not found");
2221 return false;
2222 }
Paul Hud44e1b72023-06-16 02:07:42 +00002223 return mMDnsManager.resolve(transactionId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002224 }
2225
2226 /**
2227 * Guess the interface to use to resolve or discover a service on a specific network.
2228 *
2229 * This is an imperfect guess, as for example the network may be gone or not yet fully
2230 * registered. This is fine as failing is correct if the network is gone, and a client
2231 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
2232 * this is to support the legacy mdnsresponder implementation, which historically resolved
2233 * services on an unspecified network.
2234 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002235 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
2236 final Network network = serviceInfo.getNetwork();
2237 if (network == null) {
2238 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
2239 // provided by NsdService from discovery results, and the service was found on an
2240 // interface that has no app-usable Network).
2241 if (serviceInfo.getInterfaceIndex() != 0) {
2242 return serviceInfo.getInterfaceIndex();
2243 }
2244 return IFACE_IDX_ANY;
2245 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002246
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002247 String interfaceName = getNetworkInterfaceName(network);
2248 if (interfaceName == null) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002249 return IFACE_IDX_ANY;
2250 }
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002251 return getNetworkInterfaceIndexByName(interfaceName);
2252 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002253
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002254 private String getNetworkInterfaceName(@Nullable Network network) {
2255 if (network == null) {
2256 return null;
2257 }
2258 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
2259 if (cm == null) {
2260 Log.wtf(TAG, "No ConnectivityManager");
2261 return null;
2262 }
2263 final LinkProperties lp = cm.getLinkProperties(network);
2264 if (lp == null) {
2265 return null;
2266 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002267 // Only resolve on non-stacked interfaces
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002268 return lp.getInterfaceName();
2269 }
2270
2271 private int getNetworkInterfaceIndexByName(final String ifaceName) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002272 final NetworkInterface iface;
2273 try {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002274 iface = NetworkInterface.getByName(ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002275 } catch (SocketException e) {
2276 Log.e(TAG, "Error querying interface", e);
2277 return IFACE_IDX_ANY;
2278 }
2279
2280 if (iface == null) {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002281 Log.e(TAG, "Interface not found: " + ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002282 return IFACE_IDX_ANY;
2283 }
2284
2285 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002286 }
2287
Paul Hud44e1b72023-06-16 02:07:42 +00002288 private boolean stopResolveService(int transactionId) {
2289 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002290 }
2291
Paul Hud44e1b72023-06-16 02:07:42 +00002292 private boolean getAddrInfo(int transactionId, String hostname, int interfaceIdx) {
2293 return mMDnsManager.getServiceAddress(transactionId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002294 }
2295
Paul Hud44e1b72023-06-16 02:07:42 +00002296 private boolean stopGetAddrInfo(int transactionId) {
2297 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002298 }
2299
2300 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00002301 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2302 if (!PermissionUtils.checkDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002303
Paul Hub2e67d32023-04-18 05:50:14 +00002304 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
2305 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07002306 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00002307
2308 // Dump service and clients logs
2309 pw.println();
Paul Hu14667de2023-04-17 22:42:47 +08002310 pw.println("Logs:");
Paul Hub2e67d32023-04-18 05:50:14 +00002311 pw.increaseIndent();
2312 mServiceLogs.reverseDump(pw);
2313 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002314 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002315
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002316 private abstract static class ClientRequest {
Paul Hud44e1b72023-06-16 02:07:42 +00002317 private final int mTransactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002318 private final long mStartTimeMs;
Paul Hu812e9212023-06-20 06:24:53 +00002319 private int mFoundServiceCount = 0;
2320 private int mLostServiceCount = 0;
2321 private final Set<String> mServices = new ArraySet<>();
Paul Hua6bc4632023-06-26 01:18:29 +00002322 private boolean mIsServiceFromCache = false;
Paul Hubad6fe92023-07-24 21:25:22 +08002323 private int mSentQueryCount = NO_SENT_QUERY_COUNT;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002324
Paul Hu812e9212023-06-20 06:24:53 +00002325 private ClientRequest(int transactionId, long startTimeMs) {
Paul Hud44e1b72023-06-16 02:07:42 +00002326 mTransactionId = transactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002327 mStartTimeMs = startTimeMs;
2328 }
2329
Paul Hu812e9212023-06-20 06:24:53 +00002330 public long calculateRequestDurationMs(long stopTimeMs) {
Paul Hu777ed052023-06-19 13:35:15 +00002331 return stopTimeMs - mStartTimeMs;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002332 }
Paul Hu812e9212023-06-20 06:24:53 +00002333
2334 public void onServiceFound(String serviceName) {
2335 mFoundServiceCount++;
2336 if (mServices.size() <= MAX_SERVICES_COUNT_METRIC_PER_CLIENT) {
2337 mServices.add(serviceName);
2338 }
2339 }
2340
2341 public void onServiceLost() {
2342 mLostServiceCount++;
2343 }
2344
2345 public int getFoundServiceCount() {
2346 return mFoundServiceCount;
2347 }
2348
2349 public int getLostServiceCount() {
2350 return mLostServiceCount;
2351 }
2352
2353 public int getServicesCount() {
2354 return mServices.size();
2355 }
Paul Hua6bc4632023-06-26 01:18:29 +00002356
2357 public void setServiceFromCache(boolean isServiceFromCache) {
2358 mIsServiceFromCache = isServiceFromCache;
2359 }
2360
2361 public boolean isServiceFromCache() {
2362 return mIsServiceFromCache;
2363 }
Paul Hubad6fe92023-07-24 21:25:22 +08002364
2365 public void onQuerySent() {
2366 mSentQueryCount++;
2367 }
2368
2369 public int getSentQueryCount() {
2370 return mSentQueryCount;
2371 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002372 }
2373
2374 private static class LegacyClientRequest extends ClientRequest {
2375 private final int mRequestCode;
2376
Paul Hu812e9212023-06-20 06:24:53 +00002377 private LegacyClientRequest(int transactionId, int requestCode, long startTimeMs) {
2378 super(transactionId, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002379 mRequestCode = requestCode;
2380 }
2381 }
2382
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002383 private abstract static class JavaBackendClientRequest extends ClientRequest {
2384 @Nullable
2385 private final Network mRequestedNetwork;
2386
Paul Hu777ed052023-06-19 13:35:15 +00002387 private JavaBackendClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002388 long startTimeMs) {
2389 super(transactionId, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002390 mRequestedNetwork = requestedNetwork;
2391 }
2392
2393 @Nullable
2394 public Network getRequestedNetwork() {
2395 return mRequestedNetwork;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002396 }
2397 }
2398
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002399 private static class AdvertiserClientRequest extends JavaBackendClientRequest {
Paul Hu777ed052023-06-19 13:35:15 +00002400 private AdvertiserClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002401 long startTimeMs) {
2402 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002403 }
2404 }
2405
2406 private static class DiscoveryManagerRequest extends JavaBackendClientRequest {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002407 @NonNull
2408 private final MdnsListener mListener;
2409
Paul Hud44e1b72023-06-16 02:07:42 +00002410 private DiscoveryManagerRequest(int transactionId, @NonNull MdnsListener listener,
Paul Hu812e9212023-06-20 06:24:53 +00002411 @Nullable Network requestedNetwork, long startTimeMs) {
2412 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002413 mListener = listener;
2414 }
2415 }
2416
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002417 /* Information tracked per client */
2418 private class ClientInfo {
2419
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002420 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002421 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002422 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002423 private NsdServiceInfo mResolvedService;
2424
Paul Hud44e1b72023-06-16 02:07:42 +00002425 /* A map from client request ID (listenerKey) to the request */
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002426 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08002427
Luke Huangf7277ed2021-07-12 21:15:10 +08002428 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002429 private boolean mIsPreSClient = false;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002430 private final int mUid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002431 // The flag of using java backend if the client's target SDK >= U
2432 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002433 // Store client logs
2434 private final SharedLog mClientLogs;
Paul Hucdef3532023-06-18 14:47:35 +00002435 // Report the nsd metrics data
2436 private final NetworkNsdReportedMetrics mMetrics;
Luke Huangf7277ed2021-07-12 21:15:10 +08002437
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002438 private ClientInfo(INsdManagerCallback cb, int uid, boolean useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +00002439 SharedLog sharedLog, NetworkNsdReportedMetrics metrics) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002440 mCb = cb;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002441 mUid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002442 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002443 mClientLogs = sharedLog;
2444 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Paul Hucdef3532023-06-18 14:47:35 +00002445 mMetrics = metrics;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002446 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002447
2448 @Override
2449 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06002450 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07002451 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002452 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002453 sb.append("mUseJavaBackend ").append(mUseJavaBackend).append("\n");
2454 sb.append("mUid ").append(mUid).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002455 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002456 int clientRequestId = mClientRequests.keyAt(i);
2457 sb.append("clientRequestId ")
2458 .append(clientRequestId)
2459 .append(" transactionId ").append(mClientRequests.valueAt(i).mTransactionId)
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002460 .append(" type ").append(
2461 mClientRequests.valueAt(i).getClass().getSimpleName())
2462 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07002463 }
2464 return sb.toString();
2465 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002466
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002467 private boolean isPreSClient() {
2468 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08002469 }
2470
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002471 private void setPreSClient() {
2472 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08002473 }
2474
Paul Hu812e9212023-06-20 06:24:53 +00002475 private MdnsListener unregisterMdnsListenerFromRequest(ClientRequest request) {
Paul Hue4f5f252023-02-16 21:13:47 +08002476 final MdnsListener listener =
2477 ((DiscoveryManagerRequest) request).mListener;
2478 mMdnsDiscoveryManager.unregisterListener(
2479 listener.getListenedServiceType(), listener);
Paul Hu812e9212023-06-20 06:24:53 +00002480 return listener;
Paul Hue4f5f252023-02-16 21:13:47 +08002481 }
2482
Dave Plattfeff2af2014-03-07 14:48:22 -08002483 // Remove any pending requests from the global map when we get rid of a client,
2484 // and send cancellations to the daemon.
2485 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00002486 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09002487 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002488 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002489 final int clientRequestId = mClientRequests.keyAt(i);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002490 final ClientRequest request = mClientRequests.valueAt(i);
Paul Hud44e1b72023-06-16 02:07:42 +00002491 final int transactionId = request.mTransactionId;
2492 mTransactionIdToClientInfoMap.remove(transactionId);
paulhub2225702021-11-17 09:35:33 +08002493 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002494 Log.d(TAG, "Terminating clientRequestId " + clientRequestId
2495 + " transactionId " + transactionId
2496 + " type " + mClientRequests.get(clientRequestId));
paulhub2225702021-11-17 09:35:33 +08002497 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002498
2499 if (request instanceof DiscoveryManagerRequest) {
Paul Hu812e9212023-06-20 06:24:53 +00002500 final MdnsListener listener = unregisterMdnsListenerFromRequest(request);
2501 if (listener instanceof DiscoveryListener) {
Paul Hu508a0122023-09-11 15:31:33 +08002502 mMetrics.reportServiceDiscoveryStop(false /* isLegacy */, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00002503 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2504 request.getFoundServiceCount(),
2505 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002506 request.getServicesCount(),
2507 request.getSentQueryCount());
Paul Hu60149052023-07-31 14:26:08 +08002508 } else if (listener instanceof ResolutionListener) {
Paul Hu508a0122023-09-11 15:31:33 +08002509 mMetrics.reportServiceResolutionStop(false /* isLegacy */, transactionId,
Paul Hu60149052023-07-31 14:26:08 +08002510 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Huddce5912023-08-01 10:26:49 +08002511 } else if (listener instanceof ServiceInfoListener) {
2512 mMetrics.reportServiceInfoCallbackUnregistered(transactionId,
2513 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2514 request.getFoundServiceCount(),
2515 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002516 request.isServiceFromCache(),
2517 request.getSentQueryCount());
Paul Hu812e9212023-06-20 06:24:53 +00002518 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002519 continue;
2520 }
2521
2522 if (request instanceof AdvertiserClientRequest) {
Paul Hu043bcd42023-07-14 16:38:25 +08002523 final AdvertiserMetrics metrics =
2524 mAdvertiser.getAdvertiserMetrics(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00002525 mAdvertiser.removeService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002526 mMetrics.reportServiceUnregistration(false /* isLegacy */, transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002527 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2528 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2529 metrics.mConflictDuringProbingCount,
2530 metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002531 continue;
2532 }
2533
2534 if (!(request instanceof LegacyClientRequest)) {
2535 throw new IllegalStateException("Unknown request type: " + request.getClass());
2536 }
2537
2538 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08002539 case NsdManager.DISCOVER_SERVICES:
Paul Hud44e1b72023-06-16 02:07:42 +00002540 stopServiceDiscovery(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002541 mMetrics.reportServiceDiscoveryStop(true /* isLegacy */, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00002542 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2543 request.getFoundServiceCount(),
2544 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002545 request.getServicesCount(),
2546 NO_SENT_QUERY_COUNT);
Dave Plattfeff2af2014-03-07 14:48:22 -08002547 break;
2548 case NsdManager.RESOLVE_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002549 stopResolveService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002550 mMetrics.reportServiceResolutionStop(true /* isLegacy */, transactionId,
Paul Hu60149052023-07-31 14:26:08 +08002551 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Dave Plattfeff2af2014-03-07 14:48:22 -08002552 break;
2553 case NsdManager.REGISTER_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002554 unregisterService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002555 mMetrics.reportServiceUnregistration(true /* isLegacy */, transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002556 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2557 NO_PACKET /* repliedRequestsCount */,
2558 NO_PACKET /* sentPacketCount */,
2559 0 /* conflictDuringProbingCount */,
2560 0 /* conflictAfterProbingCount */);
Dave Plattfeff2af2014-03-07 14:48:22 -08002561 break;
2562 default:
2563 break;
2564 }
2565 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002566 mClientRequests.clear();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002567 updateMulticastLock();
2568 }
2569
2570 /**
2571 * Returns true if this client has any Java backend request that requests one of the given
2572 * networks.
2573 */
2574 boolean hasAnyJavaBackendRequestForNetworks(@NonNull ArraySet<Network> networks) {
2575 for (int i = 0; i < mClientRequests.size(); i++) {
2576 final ClientRequest req = mClientRequests.valueAt(i);
2577 if (!(req instanceof JavaBackendClientRequest)) {
2578 continue;
2579 }
2580 final Network reqNetwork = ((JavaBackendClientRequest) mClientRequests.valueAt(i))
2581 .getRequestedNetwork();
2582 if (MdnsUtils.isAnyNetworkMatched(reqNetwork, networks)) {
2583 return true;
2584 }
2585 }
2586 return false;
Dave Plattfeff2af2014-03-07 14:48:22 -08002587 }
2588
Paul Hud44e1b72023-06-16 02:07:42 +00002589 // mClientRequests is a sparse array of client request id -> ClientRequest. For a given
2590 // transaction id, return the corresponding client request id.
2591 private int getClientRequestId(final int transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002592 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002593 if (mClientRequests.valueAt(i).mTransactionId == transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002594 return mClientRequests.keyAt(i);
2595 }
Christopher Lane74411222014-04-25 18:39:07 -07002596 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002597 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07002598 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002599
Paul Hub2e67d32023-04-18 05:50:14 +00002600 private void log(String message) {
2601 mClientLogs.log(message);
2602 }
2603
Paul Hu508a0122023-09-11 15:31:33 +08002604 private static boolean isLegacyClientRequest(@NonNull ClientRequest request) {
2605 return !(request instanceof DiscoveryManagerRequest)
2606 && !(request instanceof AdvertiserClientRequest);
2607 }
2608
2609 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info,
2610 ClientRequest request) {
2611 mMetrics.reportServiceDiscoveryStarted(
2612 isLegacyClientRequest(request), request.mTransactionId);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002613 try {
2614 mCb.onDiscoverServicesStarted(listenerKey, info);
2615 } catch (RemoteException e) {
2616 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
2617 }
2618 }
Paul Hu508a0122023-09-11 15:31:33 +08002619 void onDiscoverServicesFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2620 onDiscoverServicesFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2621 0L /* durationMs */);
Paul Hu812e9212023-06-20 06:24:53 +00002622 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002623
Paul Hu508a0122023-09-11 15:31:33 +08002624 void onDiscoverServicesFailed(int listenerKey, int error, boolean isLegacy,
2625 int transactionId, long durationMs) {
2626 mMetrics.reportServiceDiscoveryFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002627 try {
2628 mCb.onDiscoverServicesFailed(listenerKey, error);
2629 } catch (RemoteException e) {
2630 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
2631 }
2632 }
2633
Paul Hu812e9212023-06-20 06:24:53 +00002634 void onServiceFound(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2635 request.onServiceFound(info.getServiceName());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002636 try {
2637 mCb.onServiceFound(listenerKey, info);
2638 } catch (RemoteException e) {
2639 Log.e(TAG, "Error calling onServiceFound(", e);
2640 }
2641 }
2642
Paul Hu812e9212023-06-20 06:24:53 +00002643 void onServiceLost(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2644 request.onServiceLost();
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002645 try {
2646 mCb.onServiceLost(listenerKey, info);
2647 } catch (RemoteException e) {
2648 Log.e(TAG, "Error calling onServiceLost(", e);
2649 }
2650 }
2651
2652 void onStopDiscoveryFailed(int listenerKey, int error) {
2653 try {
2654 mCb.onStopDiscoveryFailed(listenerKey, error);
2655 } catch (RemoteException e) {
2656 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
2657 }
2658 }
2659
Paul Hu812e9212023-06-20 06:24:53 +00002660 void onStopDiscoverySucceeded(int listenerKey, ClientRequest request) {
2661 mMetrics.reportServiceDiscoveryStop(
Paul Hu508a0122023-09-11 15:31:33 +08002662 isLegacyClientRequest(request),
Paul Hu812e9212023-06-20 06:24:53 +00002663 request.mTransactionId,
2664 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2665 request.getFoundServiceCount(),
2666 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002667 request.getServicesCount(),
2668 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002669 try {
2670 mCb.onStopDiscoverySucceeded(listenerKey);
2671 } catch (RemoteException e) {
2672 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
2673 }
2674 }
2675
Paul Hu508a0122023-09-11 15:31:33 +08002676 void onRegisterServiceFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2677 onRegisterServiceFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2678 0L /* durationMs */);
Paul Hu777ed052023-06-19 13:35:15 +00002679 }
2680
Paul Hu508a0122023-09-11 15:31:33 +08002681 void onRegisterServiceFailed(int listenerKey, int error, boolean isLegacy,
2682 int transactionId, long durationMs) {
2683 mMetrics.reportServiceRegistrationFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002684 try {
2685 mCb.onRegisterServiceFailed(listenerKey, error);
2686 } catch (RemoteException e) {
2687 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2688 }
2689 }
2690
Paul Hu508a0122023-09-11 15:31:33 +08002691 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info,
2692 ClientRequest request) {
2693 mMetrics.reportServiceRegistrationSucceeded(isLegacyClientRequest(request),
2694 request.mTransactionId,
2695 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002696 try {
2697 mCb.onRegisterServiceSucceeded(listenerKey, info);
2698 } catch (RemoteException e) {
2699 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2700 }
2701 }
2702
2703 void onUnregisterServiceFailed(int listenerKey, int error) {
2704 try {
2705 mCb.onUnregisterServiceFailed(listenerKey, error);
2706 } catch (RemoteException e) {
2707 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2708 }
2709 }
2710
Paul Hu508a0122023-09-11 15:31:33 +08002711 void onUnregisterServiceSucceeded(int listenerKey, ClientRequest request,
Paul Hu043bcd42023-07-14 16:38:25 +08002712 AdvertiserMetrics metrics) {
Paul Hu508a0122023-09-11 15:31:33 +08002713 mMetrics.reportServiceUnregistration(isLegacyClientRequest(request),
2714 request.mTransactionId,
2715 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hu043bcd42023-07-14 16:38:25 +08002716 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2717 metrics.mConflictDuringProbingCount, metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002718 try {
2719 mCb.onUnregisterServiceSucceeded(listenerKey);
2720 } catch (RemoteException e) {
2721 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2722 }
2723 }
2724
Paul Hu508a0122023-09-11 15:31:33 +08002725 void onResolveServiceFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2726 onResolveServiceFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2727 0L /* durationMs */);
Paul Hua6bc4632023-06-26 01:18:29 +00002728 }
2729
Paul Hu508a0122023-09-11 15:31:33 +08002730 void onResolveServiceFailed(int listenerKey, int error, boolean isLegacy,
2731 int transactionId, long durationMs) {
2732 mMetrics.reportServiceResolutionFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002733 try {
2734 mCb.onResolveServiceFailed(listenerKey, error);
2735 } catch (RemoteException e) {
2736 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2737 }
2738 }
2739
Paul Hua6bc4632023-06-26 01:18:29 +00002740 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info,
2741 ClientRequest request) {
2742 mMetrics.reportServiceResolved(
Paul Hu508a0122023-09-11 15:31:33 +08002743 isLegacyClientRequest(request),
Paul Hua6bc4632023-06-26 01:18:29 +00002744 request.mTransactionId,
2745 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hubad6fe92023-07-24 21:25:22 +08002746 request.isServiceFromCache(),
2747 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002748 try {
2749 mCb.onResolveServiceSucceeded(listenerKey, info);
2750 } catch (RemoteException e) {
2751 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2752 }
2753 }
Paul Hub58deb72022-12-26 09:24:42 +00002754
2755 void onStopResolutionFailed(int listenerKey, int error) {
2756 try {
2757 mCb.onStopResolutionFailed(listenerKey, error);
2758 } catch (RemoteException e) {
2759 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2760 }
2761 }
2762
Paul Hu60149052023-07-31 14:26:08 +08002763 void onStopResolutionSucceeded(int listenerKey, ClientRequest request) {
2764 mMetrics.reportServiceResolutionStop(
Paul Hu508a0122023-09-11 15:31:33 +08002765 isLegacyClientRequest(request),
Paul Hu60149052023-07-31 14:26:08 +08002766 request.mTransactionId,
2767 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hub58deb72022-12-26 09:24:42 +00002768 try {
2769 mCb.onStopResolutionSucceeded(listenerKey);
2770 } catch (RemoteException e) {
2771 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2772 }
2773 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002774
2775 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
Paul Huddce5912023-08-01 10:26:49 +08002776 mMetrics.reportServiceInfoCallbackRegistrationFailed(NO_TRANSACTION);
Paul Hu18aeccc2022-12-27 08:48:48 +00002777 try {
2778 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2779 } catch (RemoteException e) {
2780 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2781 }
2782 }
2783
Paul Huddce5912023-08-01 10:26:49 +08002784 void onServiceInfoCallbackRegistered(int transactionId) {
2785 mMetrics.reportServiceInfoCallbackRegistered(transactionId);
2786 }
2787
2788 void onServiceUpdated(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2789 request.onServiceFound(info.getServiceName());
Paul Hu18aeccc2022-12-27 08:48:48 +00002790 try {
2791 mCb.onServiceUpdated(listenerKey, info);
2792 } catch (RemoteException e) {
2793 Log.e(TAG, "Error calling onServiceUpdated", e);
2794 }
2795 }
2796
Paul Huddce5912023-08-01 10:26:49 +08002797 void onServiceUpdatedLost(int listenerKey, ClientRequest request) {
2798 request.onServiceLost();
Paul Hu18aeccc2022-12-27 08:48:48 +00002799 try {
2800 mCb.onServiceUpdatedLost(listenerKey);
2801 } catch (RemoteException e) {
2802 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2803 }
2804 }
2805
Paul Huddce5912023-08-01 10:26:49 +08002806 void onServiceInfoCallbackUnregistered(int listenerKey, ClientRequest request) {
2807 mMetrics.reportServiceInfoCallbackUnregistered(
2808 request.mTransactionId,
2809 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2810 request.getFoundServiceCount(),
2811 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002812 request.isServiceFromCache(),
2813 request.getSentQueryCount());
Paul Hu18aeccc2022-12-27 08:48:48 +00002814 try {
2815 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2816 } catch (RemoteException e) {
2817 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2818 }
2819 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002820 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002821}