blob: 27e97f100f2d8a33341a27dc5d746b28d10939f2 [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;
paulhu2b9ed952022-02-10 21:58:32 +080029
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090030import static com.android.modules.utils.build.SdkLevel.isAtLeastU;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090031import static com.android.networkstack.apishim.ConstantsShim.REGISTER_NSD_OFFLOAD_ENGINE;
Yuyang Huangde802c82023-05-02 17:14:22 +090032import static com.android.server.connectivity.mdns.MdnsRecord.MAX_LABEL_LENGTH;
Paul Hucdef3532023-06-18 14:47:35 +000033import static com.android.server.connectivity.mdns.util.MdnsUtils.Clock;
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090034
Paul Hu23fa2022023-01-13 22:57:24 +080035import android.annotation.NonNull;
Paul Hu4bd98ef2023-01-12 13:42:07 +080036import android.annotation.Nullable;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090037import android.app.ActivityManager;
paulhua262cc12019-08-12 16:25:11 +080038import android.content.Context;
Irfan Sheriff75006652012-04-17 23:15:29 -070039import android.content.Intent;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090040import android.net.ConnectivityManager;
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +090041import android.net.INetd;
Paul Hu75069ed2023-01-14 00:31:09 +080042import android.net.InetAddresses;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090043import android.net.LinkProperties;
44import android.net.Network;
paulhu2b9ed952022-02-10 21:58:32 +080045import android.net.mdns.aidl.DiscoveryInfo;
46import android.net.mdns.aidl.GetAddressInfo;
47import android.net.mdns.aidl.IMDnsEventListener;
48import android.net.mdns.aidl.RegistrationInfo;
49import android.net.mdns.aidl.ResolutionInfo;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070050import android.net.nsd.INsdManager;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090051import android.net.nsd.INsdManagerCallback;
52import android.net.nsd.INsdServiceConnector;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090053import android.net.nsd.IOffloadEngine;
paulhu2b9ed952022-02-10 21:58:32 +080054import android.net.nsd.MDnsManager;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070055import android.net.nsd.NsdManager;
paulhua262cc12019-08-12 16:25:11 +080056import android.net.nsd.NsdServiceInfo;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090057import android.net.nsd.OffloadEngine;
58import android.net.nsd.OffloadServiceInfo;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090059import android.net.wifi.WifiManager;
Paul Hub2e67d32023-04-18 05:50:14 +000060import android.os.Binder;
Hugo Benichi803a2f02017-04-24 11:35:06 +090061import android.os.Handler;
paulhua262cc12019-08-12 16:25:11 +080062import android.os.HandlerThread;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090063import android.os.IBinder;
Paul Hu4bd98ef2023-01-12 13:42:07 +080064import android.os.Looper;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070065import android.os.Message;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090066import android.os.RemoteCallbackList;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090067import android.os.RemoteException;
Dianne Hackborn692107e2012-08-29 18:32:08 -070068import android.os.UserHandle;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090069import android.provider.DeviceConfig;
Paul Hu23fa2022023-01-13 22:57:24 +080070import android.text.TextUtils;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090071import android.util.ArraySet;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090072import android.util.Log;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +090073import android.util.Pair;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070074import android.util.SparseArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070075
paulhua262cc12019-08-12 16:25:11 +080076import com.android.internal.annotations.VisibleForTesting;
Paul Hub2e67d32023-04-18 05:50:14 +000077import com.android.internal.util.IndentingPrintWriter;
paulhua262cc12019-08-12 16:25:11 +080078import com.android.internal.util.State;
79import com.android.internal.util.StateMachine;
Paul Hucdef3532023-06-18 14:47:35 +000080import com.android.metrics.NetworkNsdReportedMetrics;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090081import com.android.modules.utils.build.SdkLevel;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090082import com.android.net.module.util.CollectionUtils;
Paul Hu4bd98ef2023-01-12 13:42:07 +080083import com.android.net.module.util.DeviceConfigUtils;
Yuyang Huanga6a6ff92023-04-24 13:33:34 +090084import com.android.net.module.util.InetAddressUtils;
paulhu3ffffe72021-09-16 10:15:22 +080085import com.android.net.module.util.PermissionUtils;
Paul Hub2e67d32023-04-18 05:50:14 +000086import com.android.net.module.util.SharedLog;
Paul Hu4bd98ef2023-01-12 13:42:07 +080087import com.android.server.connectivity.mdns.ExecutorProvider;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090088import com.android.server.connectivity.mdns.MdnsAdvertiser;
Paul Hu4bd98ef2023-01-12 13:42:07 +080089import com.android.server.connectivity.mdns.MdnsDiscoveryManager;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090090import com.android.server.connectivity.mdns.MdnsInterfaceSocket;
Paul Hu4bd98ef2023-01-12 13:42:07 +080091import com.android.server.connectivity.mdns.MdnsMultinetworkSocketClient;
Paul Hu23fa2022023-01-13 22:57:24 +080092import com.android.server.connectivity.mdns.MdnsSearchOptions;
93import com.android.server.connectivity.mdns.MdnsServiceBrowserListener;
94import com.android.server.connectivity.mdns.MdnsServiceInfo;
Paul Hu4bd98ef2023-01-12 13:42:07 +080095import com.android.server.connectivity.mdns.MdnsSocketProvider;
Yuyang Huangde802c82023-05-02 17:14:22 +090096import com.android.server.connectivity.mdns.util.MdnsUtils;
paulhua262cc12019-08-12 16:25:11 +080097
Irfan Sheriff77ec5582012-03-22 17:01:39 -070098import java.io.FileDescriptor;
99import java.io.PrintWriter;
Yuyang Huangaa0e9602023-03-17 12:43:09 +0900100import java.net.Inet6Address;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700101import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900102import java.net.NetworkInterface;
103import java.net.SocketException;
104import java.net.UnknownHostException;
Paul Hu2b865912023-03-06 14:27:53 +0800105import java.util.ArrayList;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900106import java.util.Arrays;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700107import java.util.HashMap;
Paul Hu23fa2022023-01-13 22:57:24 +0800108import java.util.List;
Paul Hu75069ed2023-01-14 00:31:09 +0800109import java.util.Map;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900110import java.util.Objects;
Paul Hu812e9212023-06-20 06:24:53 +0000111import java.util.Set;
Paul Hu23fa2022023-01-13 22:57:24 +0800112import java.util.regex.Matcher;
113import java.util.regex.Pattern;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700114
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700115/**
116 * Network Service Discovery Service handles remote service discovery operation requests by
117 * implementing the INsdManager interface.
118 *
119 * @hide
120 */
121public class NsdService extends INsdManager.Stub {
122 private static final String TAG = "NsdService";
123 private static final String MDNS_TAG = "mDnsConnector";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900124 /**
125 * Enable discovery using the Java DiscoveryManager, instead of the legacy mdnsresponder
126 * implementation.
127 */
Paul Hu4bd98ef2023-01-12 13:42:07 +0800128 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Paul Hu23fa2022023-01-13 22:57:24 +0800129 private static final String LOCAL_DOMAIN_NAME = "local";
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700130
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900131 /**
132 * Enable advertising using the Java MdnsAdvertiser, instead of the legacy mdnsresponder
133 * implementation.
134 */
135 private static final String MDNS_ADVERTISER_VERSION = "mdns_advertiser_version";
136
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900137 /**
138 * Comma-separated list of type:flag mappings indicating the flags to use to allowlist
139 * discovery/advertising using MdnsDiscoveryManager / MdnsAdvertiser for a given type.
140 *
141 * For example _mytype._tcp.local and _othertype._tcp.local would be configured with:
142 * _mytype._tcp:mytype,_othertype._tcp.local:othertype
143 *
144 * In which case the flags:
145 * "mdns_discovery_manager_allowlist_mytype_version",
146 * "mdns_advertiser_allowlist_mytype_version",
147 * "mdns_discovery_manager_allowlist_othertype_version",
148 * "mdns_advertiser_allowlist_othertype_version"
149 * would be used to toggle MdnsDiscoveryManager / MdnsAdvertiser for each type. The flags will
150 * be read with
Motomu Utsumi624aeb42023-08-15 15:52:27 +0900151 * {@link DeviceConfigUtils#isTetheringFeatureEnabled}
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900152 *
153 * @see #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX
154 * @see #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX
155 * @see #MDNS_ALLOWLIST_FLAG_SUFFIX
156 */
157 private static final String MDNS_TYPE_ALLOWLIST_FLAGS = "mdns_type_allowlist_flags";
158
159 private static final String MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX =
160 "mdns_discovery_manager_allowlist_";
161 private static final String MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX =
162 "mdns_advertiser_allowlist_";
163 private static final String MDNS_ALLOWLIST_FLAG_SUFFIX = "_version";
164
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900165 @VisibleForTesting
166 static final String MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
167 "mdns_config_running_app_active_importance_cutoff";
168 @VisibleForTesting
169 static final int DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
170 ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
171 private final int mRunningAppActiveImportanceCutoff;
172
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900173 public static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +0000174 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900175 private static final int IFACE_IDX_ANY = 0;
Paul Hu812e9212023-06-20 06:24:53 +0000176 private static final int MAX_SERVICES_COUNT_METRIC_PER_CLIENT = 100;
177 @VisibleForTesting
178 static final int NO_TRANSACTION = -1;
Paul Hubad6fe92023-07-24 21:25:22 +0800179 private static final int NO_SENT_QUERY_COUNT = 0;
180 private static final int DISCOVERY_QUERY_SENT_CALLBACK = 1000;
Paul Hu14667de2023-04-17 22:42:47 +0800181 private static final SharedLog LOGGER = new SharedLog("serviceDiscovery");
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700182
Hugo Benichi32be63d2017-04-05 14:06:11 +0900183 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900184 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +0800185 private final MDnsManager mMDnsManager;
186 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900187 @NonNull
188 private final Dependencies mDeps;
189 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800190 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900191 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800192 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900193 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800194 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900195 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900196 private final MdnsAdvertiser mAdvertiser;
Paul Hu777ed052023-06-19 13:35:15 +0000197 @NonNull
198 private final Clock mClock;
Paul Hu14667de2023-04-17 22:42:47 +0800199 private final SharedLog mServiceLogs = LOGGER.forSubComponent(TAG);
Paul Hu23fa2022023-01-13 22:57:24 +0800200 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800201 // state machine thread. If change this outside state machine, it will need to introduce
202 // synchronization.
203 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800204 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700205
206 /**
207 * Clients receiving asynchronous messages
208 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900209 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700210
Paul Hud44e1b72023-06-16 02:07:42 +0000211 /* A map from transaction(unique) id to client info */
212 private final SparseArray<ClientInfo> mTransactionIdToClientInfoMap = new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700213
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900214 // Note this is not final to avoid depending on the Wi-Fi service starting before NsdService
215 @Nullable
216 private WifiManager.MulticastLock mHeldMulticastLock;
217 // Fulfilled network requests that require the Wi-Fi lock: key is the obtained Network
218 // (non-null), value is the requested Network (nullable)
219 @NonNull
220 private final ArraySet<Network> mWifiLockRequiredNetworks = new ArraySet<>();
221 @NonNull
222 private final ArraySet<Integer> mRunningAppActiveUids = new ArraySet<>();
223
Luke Huang05298582021-06-13 16:52:05 +0000224 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700225
Hugo Benichi32be63d2017-04-05 14:06:11 +0900226 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700227 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800228 // The count of the connected legacy clients.
229 private int mLegacyClientCount = 0;
Paul Hub2e67d32023-04-18 05:50:14 +0000230 // The number of client that ever connected.
231 private int mClientNumberId = 1;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700232
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900233 private final RemoteCallbackList<IOffloadEngine> mOffloadEngines =
234 new RemoteCallbackList<>();
235
236 private static class OffloadEngineInfo {
237 @NonNull final String mInterfaceName;
238 final long mOffloadCapabilities;
239 final long mOffloadType;
240 @NonNull final IOffloadEngine mOffloadEngine;
241
242 OffloadEngineInfo(@NonNull IOffloadEngine offloadEngine,
243 @NonNull String interfaceName, long capabilities, long offloadType) {
244 this.mOffloadEngine = offloadEngine;
245 this.mInterfaceName = interfaceName;
246 this.mOffloadCapabilities = capabilities;
247 this.mOffloadType = offloadType;
248 }
249 }
250
Paul Hu812e9212023-06-20 06:24:53 +0000251 @VisibleForTesting
252 static class MdnsListener implements MdnsServiceBrowserListener {
Paul Hud44e1b72023-06-16 02:07:42 +0000253 protected final int mClientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800254 protected final int mTransactionId;
255 @NonNull
256 protected final NsdServiceInfo mReqServiceInfo;
257 @NonNull
258 protected final String mListenedServiceType;
259
Paul Hud44e1b72023-06-16 02:07:42 +0000260 MdnsListener(int clientRequestId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
Paul Hu23fa2022023-01-13 22:57:24 +0800261 @NonNull String listenedServiceType) {
Paul Hud44e1b72023-06-16 02:07:42 +0000262 mClientRequestId = clientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800263 mTransactionId = transactionId;
264 mReqServiceInfo = reqServiceInfo;
265 mListenedServiceType = listenedServiceType;
266 }
267
268 @NonNull
269 public String getListenedServiceType() {
270 return mListenedServiceType;
271 }
272
273 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000274 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
275 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800276
277 @Override
278 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
279
280 @Override
281 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
282
283 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000284 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
285 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800286
287 @Override
288 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
289
290 @Override
291 public void onSearchStoppedWithError(int error) { }
292
293 @Override
294 public void onSearchFailedToStart() { }
295
296 @Override
Paul Hubad6fe92023-07-24 21:25:22 +0800297 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
298 int sentQueryTransactionId) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800299
300 @Override
301 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
302 }
303
304 private class DiscoveryListener extends MdnsListener {
305
Paul Hud44e1b72023-06-16 02:07:42 +0000306 DiscoveryListener(int clientRequestId, int transactionId,
307 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
308 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800309 }
310
311 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000312 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
313 boolean isServiceFromCache) {
Paul Hu019621e2023-01-13 23:26:49 +0800314 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
315 NsdManager.SERVICE_FOUND,
Paul Hua6bc4632023-06-26 01:18:29 +0000316 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu23fa2022023-01-13 22:57:24 +0800317 }
318
319 @Override
320 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800321 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
322 NsdManager.SERVICE_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000323 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800324 }
Paul Hubad6fe92023-07-24 21:25:22 +0800325
326 @Override
327 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
328 int sentQueryTransactionId) {
329 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
330 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
331 }
Paul Hu23fa2022023-01-13 22:57:24 +0800332 }
333
Paul Hu75069ed2023-01-14 00:31:09 +0800334 private class ResolutionListener extends MdnsListener {
335
Paul Hud44e1b72023-06-16 02:07:42 +0000336 ResolutionListener(int clientRequestId, int transactionId,
337 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
338 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800339 }
340
341 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000342 public void onServiceFound(MdnsServiceInfo serviceInfo, boolean isServiceFromCache) {
Paul Hu75069ed2023-01-14 00:31:09 +0800343 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
344 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
Paul Hua6bc4632023-06-26 01:18:29 +0000345 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu75069ed2023-01-14 00:31:09 +0800346 }
Paul Hubad6fe92023-07-24 21:25:22 +0800347
348 @Override
349 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
350 int sentQueryTransactionId) {
351 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
352 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
353 }
Paul Hu75069ed2023-01-14 00:31:09 +0800354 }
355
Paul Hu30bd70d2023-02-07 13:20:56 +0000356 private class ServiceInfoListener extends MdnsListener {
357
Paul Hud44e1b72023-06-16 02:07:42 +0000358 ServiceInfoListener(int clientRequestId, int transactionId,
359 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
360 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +0000361 }
362
363 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000364 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
365 boolean isServiceFromCache) {
Paul Hu30bd70d2023-02-07 13:20:56 +0000366 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
367 NsdManager.SERVICE_UPDATED,
Paul Hua6bc4632023-06-26 01:18:29 +0000368 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu30bd70d2023-02-07 13:20:56 +0000369 }
370
371 @Override
372 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) {
373 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
374 NsdManager.SERVICE_UPDATED,
Paul Hud44e1b72023-06-16 02:07:42 +0000375 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000376 }
377
378 @Override
379 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) {
380 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
381 NsdManager.SERVICE_UPDATED_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000382 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000383 }
Paul Hubad6fe92023-07-24 21:25:22 +0800384
385 @Override
386 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
387 int sentQueryTransactionId) {
388 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
389 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
390 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000391 }
392
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900393 private class SocketRequestMonitor implements MdnsSocketProvider.SocketRequestMonitor {
394 @Override
395 public void onSocketRequestFulfilled(@Nullable Network socketNetwork,
396 @NonNull MdnsInterfaceSocket socket, @NonNull int[] transports) {
397 // The network may be null for Wi-Fi SoftAp interfaces (tethering), but there is no APF
398 // filtering on such interfaces, so taking the multicast lock is not necessary to
399 // disable APF filtering of multicast.
400 if (socketNetwork == null
401 || !CollectionUtils.contains(transports, TRANSPORT_WIFI)
402 || CollectionUtils.contains(transports, TRANSPORT_VPN)) {
403 return;
404 }
405
406 if (mWifiLockRequiredNetworks.add(socketNetwork)) {
407 updateMulticastLock();
408 }
409 }
410
411 @Override
412 public void onSocketDestroyed(@Nullable Network socketNetwork,
413 @NonNull MdnsInterfaceSocket socket) {
414 if (mWifiLockRequiredNetworks.remove(socketNetwork)) {
415 updateMulticastLock();
416 }
417 }
418 }
419
420 private class UidImportanceListener implements ActivityManager.OnUidImportanceListener {
421 private final Handler mHandler;
422
423 private UidImportanceListener(Handler handler) {
424 mHandler = handler;
425 }
426
427 @Override
428 public void onUidImportance(int uid, int importance) {
429 mHandler.post(() -> handleUidImportanceChanged(uid, importance));
430 }
431 }
432
433 private void handleUidImportanceChanged(int uid, int importance) {
434 // Lower importance values are more "important"
435 final boolean modified = importance <= mRunningAppActiveImportanceCutoff
436 ? mRunningAppActiveUids.add(uid)
437 : mRunningAppActiveUids.remove(uid);
438 if (modified) {
439 updateMulticastLock();
440 }
441 }
442
443 /**
444 * Take or release the lock based on updated internal state.
445 *
446 * This determines whether the lock needs to be held based on
447 * {@link #mWifiLockRequiredNetworks}, {@link #mRunningAppActiveUids} and
448 * {@link ClientInfo#mClientRequests}, so it must be called after any of the these have been
449 * updated.
450 */
451 private void updateMulticastLock() {
452 final int needsLockUid = getMulticastLockNeededUid();
453 if (needsLockUid >= 0 && mHeldMulticastLock == null) {
454 final WifiManager wm = mContext.getSystemService(WifiManager.class);
455 if (wm == null) {
456 Log.wtf(TAG, "Got a TRANSPORT_WIFI network without WifiManager");
457 return;
458 }
459 mHeldMulticastLock = wm.createMulticastLock(TAG);
460 mHeldMulticastLock.acquire();
461 mServiceLogs.log("Taking multicast lock for uid " + needsLockUid);
462 } else if (needsLockUid < 0 && mHeldMulticastLock != null) {
463 mHeldMulticastLock.release();
464 mHeldMulticastLock = null;
465 mServiceLogs.log("Released multicast lock");
466 }
467 }
468
469 /**
470 * @return The UID of an app requiring the multicast lock, or -1 if none.
471 */
472 private int getMulticastLockNeededUid() {
473 if (mWifiLockRequiredNetworks.size() == 0) {
474 // Return early if NSD is not active, or not on any relevant network
475 return -1;
476 }
Paul Hud44e1b72023-06-16 02:07:42 +0000477 for (int i = 0; i < mTransactionIdToClientInfoMap.size(); i++) {
478 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.valueAt(i);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900479 if (!mRunningAppActiveUids.contains(clientInfo.mUid)) {
480 // Ignore non-active UIDs
481 continue;
482 }
483
484 if (clientInfo.hasAnyJavaBackendRequestForNetworks(mWifiLockRequiredNetworks)) {
485 return clientInfo.mUid;
486 }
487 }
488 return -1;
489 }
490
Paul Hu019621e2023-01-13 23:26:49 +0800491 /**
492 * Data class of mdns service callback information.
493 */
494 private static class MdnsEvent {
Paul Hud44e1b72023-06-16 02:07:42 +0000495 final int mClientRequestId;
Paul Hubad6fe92023-07-24 21:25:22 +0800496 @Nullable
Paul Hu019621e2023-01-13 23:26:49 +0800497 final MdnsServiceInfo mMdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000498 final boolean mIsServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800499
Paul Hubad6fe92023-07-24 21:25:22 +0800500 MdnsEvent(int clientRequestId) {
501 this(clientRequestId, null /* mdnsServiceInfo */, false /* isServiceFromCache */);
502 }
503
504 MdnsEvent(int clientRequestId, @Nullable MdnsServiceInfo mdnsServiceInfo) {
Paul Hua6bc4632023-06-26 01:18:29 +0000505 this(clientRequestId, mdnsServiceInfo, false /* isServiceFromCache */);
506 }
507
Paul Hubad6fe92023-07-24 21:25:22 +0800508 MdnsEvent(int clientRequestId, @Nullable MdnsServiceInfo mdnsServiceInfo,
Paul Hua6bc4632023-06-26 01:18:29 +0000509 boolean isServiceFromCache) {
Paul Hud44e1b72023-06-16 02:07:42 +0000510 mClientRequestId = clientRequestId;
Paul Hu019621e2023-01-13 23:26:49 +0800511 mMdnsServiceInfo = mdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000512 mIsServiceFromCache = isServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800513 }
514 }
515
Irfan Sheriff75006652012-04-17 23:15:29 -0700516 private class NsdStateMachine extends StateMachine {
517
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700518 private final DefaultState mDefaultState = new DefaultState();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700519 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700520
521 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700522 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900523 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700524 }
525
Luke Huang92860f92021-06-23 06:29:30 +0000526 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800527 if (mIsDaemonStarted) {
528 if (DBG) Log.d(TAG, "Daemon is already started.");
529 return;
530 }
531 mMDnsManager.registerEventListener(mMDnsEventCallback);
532 mMDnsManager.startDaemon();
533 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000534 maybeScheduleStop();
Paul Hub2e67d32023-04-18 05:50:14 +0000535 mServiceLogs.log("Start mdns_responder daemon");
Luke Huang05298582021-06-13 16:52:05 +0000536 }
537
paulhu2b9ed952022-02-10 21:58:32 +0800538 private void maybeStopDaemon() {
539 if (!mIsDaemonStarted) {
540 if (DBG) Log.d(TAG, "Daemon has not been started.");
541 return;
542 }
543 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
544 mMDnsManager.stopDaemon();
545 mIsDaemonStarted = false;
Paul Hub2e67d32023-04-18 05:50:14 +0000546 mServiceLogs.log("Stop mdns_responder daemon");
paulhu2b9ed952022-02-10 21:58:32 +0800547 }
548
Luke Huang92860f92021-06-23 06:29:30 +0000549 private boolean isAnyRequestActive() {
Paul Hud44e1b72023-06-16 02:07:42 +0000550 return mTransactionIdToClientInfoMap.size() != 0;
Luke Huang92860f92021-06-23 06:29:30 +0000551 }
552
553 private void scheduleStop() {
554 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
555 }
556 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800557 // The native daemon should stay alive and can't be cleanup
558 // if any legacy client connected.
559 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000560 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000561 }
562 }
563
Luke Huang92860f92021-06-23 06:29:30 +0000564 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000565 this.removeMessages(NsdManager.DAEMON_CLEANUP);
566 }
567
Paul Hu23fa2022023-01-13 22:57:24 +0800568 private void maybeStartMonitoringSockets() {
569 if (mIsMonitoringSocketsStarted) {
570 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
571 return;
572 }
573
574 mMdnsSocketProvider.startMonitoringSockets();
575 mIsMonitoringSocketsStarted = true;
576 }
577
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900578 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
579 if (!mIsMonitoringSocketsStarted) return;
580 if (isAnyRequestActive()) return;
581
Paul Hu58f20602023-02-18 11:41:07 +0800582 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800583 mIsMonitoringSocketsStarted = false;
584 }
585
Hugo Benichi803a2f02017-04-24 11:35:06 +0900586 NsdStateMachine(String name, Handler handler) {
587 super(name, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -0700588 addState(mDefaultState);
Irfan Sheriff75006652012-04-17 23:15:29 -0700589 addState(mEnabledState, mDefaultState);
paulhu5568f452021-11-30 13:31:29 +0800590 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900591 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700592 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700593 }
594
595 class DefaultState extends State {
596 @Override
597 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900598 final ClientInfo cInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000599 final int clientRequestId = msg.arg2;
Irfan Sheriff75006652012-04-17 23:15:29 -0700600 switch (msg.what) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900601 case NsdManager.REGISTER_CLIENT:
Paul Hu2e0a88c2023-03-09 16:05:01 +0800602 final ConnectorArgs arg = (ConnectorArgs) msg.obj;
603 final INsdManagerCallback cb = arg.callback;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900604 try {
Paul Hu2e0a88c2023-03-09 16:05:01 +0800605 cb.asBinder().linkToDeath(arg.connector, 0);
Paul Hub2e67d32023-04-18 05:50:14 +0000606 final String tag = "Client" + arg.uid + "-" + mClientNumberId++;
Paul Hu777ed052023-06-19 13:35:15 +0000607 final NetworkNsdReportedMetrics metrics =
608 mDeps.makeNetworkNsdReportedMetrics(
609 !arg.useJavaBackend, (int) mClock.elapsedRealtime());
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900610 cInfo = new ClientInfo(cb, arg.uid, arg.useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +0000611 mServiceLogs.forSubComponent(tag), metrics);
Paul Hu2e0a88c2023-03-09 16:05:01 +0800612 mClients.put(arg.connector, cInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900613 } catch (RemoteException e) {
Paul Hud44e1b72023-06-16 02:07:42 +0000614 Log.w(TAG, "Client request id " + clientRequestId
615 + " has already died");
Irfan Sheriff75006652012-04-17 23:15:29 -0700616 }
617 break;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900618 case NsdManager.UNREGISTER_CLIENT:
619 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
620 cInfo = mClients.remove(connector);
Dave Plattfeff2af2014-03-07 14:48:22 -0800621 if (cInfo != null) {
622 cInfo.expungeAllRequests();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900623 if (cInfo.isPreSClient()) {
Luke Huangf7277ed2021-07-12 21:15:10 +0800624 mLegacyClientCount -= 1;
625 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800626 }
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900627 maybeStopMonitoringSocketsIfNoActiveRequest();
Luke Huangf7277ed2021-07-12 21:15:10 +0800628 maybeScheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700629 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700630 case NsdManager.DISCOVER_SERVICES:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900631 cInfo = getClientInfoForReply(msg);
632 if (cInfo != null) {
Paul Hu812e9212023-06-20 06:24:53 +0000633 cInfo.onDiscoverServicesFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000634 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900635 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700636 break;
637 case NsdManager.STOP_DISCOVERY:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900638 cInfo = getClientInfoForReply(msg);
639 if (cInfo != null) {
640 cInfo.onStopDiscoveryFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000641 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900642 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700643 break;
644 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900645 cInfo = getClientInfoForReply(msg);
646 if (cInfo != null) {
Paul Hu777ed052023-06-19 13:35:15 +0000647 cInfo.onRegisterServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000648 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900649 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700650 break;
651 case NsdManager.UNREGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900652 cInfo = getClientInfoForReply(msg);
653 if (cInfo != null) {
654 cInfo.onUnregisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000655 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900656 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700657 break;
658 case NsdManager.RESOLVE_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900659 cInfo = getClientInfoForReply(msg);
660 if (cInfo != null) {
Paul Hua6bc4632023-06-26 01:18:29 +0000661 cInfo.onResolveServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000662 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900663 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700664 break;
Paul Hub58deb72022-12-26 09:24:42 +0000665 case NsdManager.STOP_RESOLUTION:
666 cInfo = getClientInfoForReply(msg);
667 if (cInfo != null) {
668 cInfo.onStopResolutionFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000669 clientRequestId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hub58deb72022-12-26 09:24:42 +0000670 }
671 break;
Paul Hu18aeccc2022-12-27 08:48:48 +0000672 case NsdManager.REGISTER_SERVICE_CALLBACK:
673 cInfo = getClientInfoForReply(msg);
674 if (cInfo != null) {
675 cInfo.onServiceInfoCallbackRegistrationFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000676 clientRequestId, NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +0000677 }
678 break;
Luke Huang05298582021-06-13 16:52:05 +0000679 case NsdManager.DAEMON_CLEANUP:
paulhu2b9ed952022-02-10 21:58:32 +0800680 maybeStopDaemon();
Luke Huang05298582021-06-13 16:52:05 +0000681 break;
Luke Huangf7277ed2021-07-12 21:15:10 +0800682 // This event should be only sent by the legacy (target SDK < S) clients.
683 // Mark the sending client as legacy.
684 case NsdManager.DAEMON_STARTUP:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900685 cInfo = getClientInfoForReply(msg);
Luke Huangf7277ed2021-07-12 21:15:10 +0800686 if (cInfo != null) {
687 cancelStop();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900688 cInfo.setPreSClient();
Luke Huangf7277ed2021-07-12 21:15:10 +0800689 mLegacyClientCount += 1;
690 maybeStartDaemon();
691 }
692 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700693 default:
paulhub2225702021-11-17 09:35:33 +0800694 Log.e(TAG, "Unhandled " + msg);
Irfan Sheriff75006652012-04-17 23:15:29 -0700695 return NOT_HANDLED;
696 }
697 return HANDLED;
698 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900699
700 private ClientInfo getClientInfoForReply(Message msg) {
701 final ListenerArgs args = (ListenerArgs) msg.obj;
702 return mClients.get(args.connector);
703 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700704 }
705
Irfan Sheriff75006652012-04-17 23:15:29 -0700706 class EnabledState extends State {
707 @Override
708 public void enter() {
709 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700710 }
711
712 @Override
713 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000714 // TODO: it is incorrect to stop the daemon without expunging all requests
715 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000716 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700717 }
718
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700719 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900720 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800721 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700722 return true;
723 }
724 return false;
725 }
726
Paul Hud44e1b72023-06-16 02:07:42 +0000727 private void storeLegacyRequestMap(int clientRequestId, int transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +0000728 ClientInfo clientInfo, int what, long startTimeMs) {
729 clientInfo.mClientRequests.put(clientRequestId,
730 new LegacyClientRequest(transactionId, what, startTimeMs));
Paul Hud44e1b72023-06-16 02:07:42 +0000731 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000732 // Remove the cleanup event because here comes a new request.
733 cancelStop();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700734 }
735
Paul Hud44e1b72023-06-16 02:07:42 +0000736 private void storeAdvertiserRequestMap(int clientRequestId, int transactionId,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900737 ClientInfo clientInfo, @Nullable Network requestedNetwork) {
Paul Hu777ed052023-06-19 13:35:15 +0000738 clientInfo.mClientRequests.put(clientRequestId, new AdvertiserClientRequest(
Paul Hu812e9212023-06-20 06:24:53 +0000739 transactionId, requestedNetwork, mClock.elapsedRealtime()));
Paul Hud44e1b72023-06-16 02:07:42 +0000740 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900741 updateMulticastLock();
Paul Hu23fa2022023-01-13 22:57:24 +0800742 }
743
Paul Hud44e1b72023-06-16 02:07:42 +0000744 private void removeRequestMap(
745 int clientRequestId, int transactionId, ClientInfo clientInfo) {
746 final ClientRequest existing = clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900747 if (existing == null) return;
Paul Hud44e1b72023-06-16 02:07:42 +0000748 clientInfo.mClientRequests.remove(clientRequestId);
749 mTransactionIdToClientInfoMap.remove(transactionId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900750
751 if (existing instanceof LegacyClientRequest) {
752 maybeScheduleStop();
753 } else {
754 maybeStopMonitoringSocketsIfNoActiveRequest();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900755 updateMulticastLock();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900756 }
757 }
758
Paul Hud44e1b72023-06-16 02:07:42 +0000759 private void storeDiscoveryManagerRequestMap(int clientRequestId, int transactionId,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900760 MdnsListener listener, ClientInfo clientInfo,
761 @Nullable Network requestedNetwork) {
Paul Hu777ed052023-06-19 13:35:15 +0000762 clientInfo.mClientRequests.put(clientRequestId, new DiscoveryManagerRequest(
Paul Hu812e9212023-06-20 06:24:53 +0000763 transactionId, listener, requestedNetwork, mClock.elapsedRealtime()));
Paul Hud44e1b72023-06-16 02:07:42 +0000764 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900765 updateMulticastLock();
Paul Hu23fa2022023-01-13 22:57:24 +0800766 }
767
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900768 /**
769 * Truncate a service name to up to 63 UTF-8 bytes.
770 *
771 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
772 * names used in registerService follows historical behavior (see mdnsresponder
773 * handle_regservice_request).
774 */
775 @NonNull
776 private String truncateServiceName(@NonNull String originalName) {
Yuyang Huangde802c82023-05-02 17:14:22 +0900777 return MdnsUtils.truncateServiceName(originalName, MAX_LABEL_LENGTH);
Paul Hu23fa2022023-01-13 22:57:24 +0800778 }
779
Paul Hud44e1b72023-06-16 02:07:42 +0000780 private void stopDiscoveryManagerRequest(ClientRequest request, int clientRequestId,
781 int transactionId, ClientInfo clientInfo) {
Paul Hue4f5f252023-02-16 21:13:47 +0800782 clientInfo.unregisterMdnsListenerFromRequest(request);
Paul Hud44e1b72023-06-16 02:07:42 +0000783 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hue4f5f252023-02-16 21:13:47 +0800784 }
785
Irfan Sheriff75006652012-04-17 23:15:29 -0700786 @Override
787 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900788 final ClientInfo clientInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000789 final int transactionId;
790 final int clientRequestId = msg.arg2;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900791 final ListenerArgs args;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900792 final OffloadEngineInfo offloadEngineInfo;
Irfan Sheriff75006652012-04-17 23:15:29 -0700793 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800794 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800795 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900796 args = (ListenerArgs) msg.obj;
797 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000798 // If the binder death notification for a INsdManagerCallback was received
799 // before any calls are received by NsdService, the clientInfo would be
800 // cleared and cause NPE. Add a null check here to prevent this corner case.
801 if (clientInfo == null) {
802 Log.e(TAG, "Unknown connector in discovery");
803 break;
804 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700805
806 if (requestLimitReached(clientInfo)) {
Paul Hu812e9212023-06-20 06:24:53 +0000807 clientInfo.onDiscoverServicesFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000808 clientRequestId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriff75006652012-04-17 23:15:29 -0700809 break;
810 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700811
Paul Hu23fa2022023-01-13 22:57:24 +0800812 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000813 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900814 final Pair<String, String> typeAndSubtype =
815 parseTypeAndSubtype(info.getServiceType());
816 final String serviceType = typeAndSubtype == null
817 ? null : typeAndSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800818 if (clientInfo.mUseJavaBackend
819 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900820 || useDiscoveryManagerForType(serviceType)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800821 if (serviceType == null) {
Paul Hu812e9212023-06-20 06:24:53 +0000822 clientInfo.onDiscoverServicesFailedImmediately(
823 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu23fa2022023-01-13 22:57:24 +0800824 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700825 }
Paul Hu23fa2022023-01-13 22:57:24 +0800826
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900827 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800828 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +0000829 final MdnsListener listener = new DiscoveryListener(clientRequestId,
830 transactionId, info, listenServiceType);
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900831 final MdnsSearchOptions.Builder optionsBuilder =
832 MdnsSearchOptions.newBuilder()
833 .setNetwork(info.getNetwork())
Yuyang Huangff963222023-06-01 18:42:42 +0900834 .setRemoveExpiredService(true)
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900835 .setIsPassiveMode(true);
836 if (typeAndSubtype.second != null) {
837 // The parsing ensures subtype starts with an underscore.
838 // MdnsSearchOptions expects the underscore to not be present.
839 optionsBuilder.addSubtype(typeAndSubtype.second.substring(1));
840 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900841 mMdnsDiscoveryManager.registerListener(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900842 listenServiceType, listener, optionsBuilder.build());
Paul Hud44e1b72023-06-16 02:07:42 +0000843 storeDiscoveryManagerRequestMap(clientRequestId, transactionId,
844 listener, clientInfo, info.getNetwork());
Paul Hu812e9212023-06-20 06:24:53 +0000845 clientInfo.onDiscoverServicesStarted(
846 clientRequestId, info, transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +0000847 clientInfo.log("Register a DiscoveryListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +0000848 + " for service type:" + listenServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700849 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800850 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000851 if (discoverServices(transactionId, info)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800852 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +0000853 Log.d(TAG, "Discover " + msg.arg2 + " " + transactionId
Paul Hu23fa2022023-01-13 22:57:24 +0800854 + info.getServiceType());
855 }
Paul Hua6bc4632023-06-26 01:18:29 +0000856 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
857 msg.what, mClock.elapsedRealtime());
Paul Hu812e9212023-06-20 06:24:53 +0000858 clientInfo.onDiscoverServicesStarted(
859 clientRequestId, info, transactionId);
Paul Hu23fa2022023-01-13 22:57:24 +0800860 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000861 stopServiceDiscovery(transactionId);
Paul Hu812e9212023-06-20 06:24:53 +0000862 clientInfo.onDiscoverServicesFailedImmediately(
863 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu23fa2022023-01-13 22:57:24 +0800864 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700865 }
866 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800867 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900868 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800869 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900870 args = (ListenerArgs) msg.obj;
871 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000872 // If the binder death notification for a INsdManagerCallback was received
873 // before any calls are received by NsdService, the clientInfo would be
874 // cleared and cause NPE. Add a null check here to prevent this corner case.
875 if (clientInfo == null) {
876 Log.e(TAG, "Unknown connector in stop discovery");
877 break;
878 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700879
Paul Hud44e1b72023-06-16 02:07:42 +0000880 final ClientRequest request =
881 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900882 if (request == null) {
883 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700884 break;
885 }
Paul Hud44e1b72023-06-16 02:07:42 +0000886 transactionId = request.mTransactionId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900887 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
888 // point, so this needs to check the type of the original request to
889 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900890 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +0000891 stopDiscoveryManagerRequest(
892 request, clientRequestId, transactionId, clientInfo);
Paul Hu812e9212023-06-20 06:24:53 +0000893 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000894 clientInfo.log("Unregister the DiscoveryListener " + transactionId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700895 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000896 removeRequestMap(clientRequestId, transactionId, clientInfo);
897 if (stopServiceDiscovery(transactionId)) {
Paul Hu812e9212023-06-20 06:24:53 +0000898 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hu23fa2022023-01-13 22:57:24 +0800899 } else {
900 clientInfo.onStopDiscoveryFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000901 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu23fa2022023-01-13 22:57:24 +0800902 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700903 }
904 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900905 }
906 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800907 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900908 args = (ListenerArgs) msg.obj;
909 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000910 // If the binder death notification for a INsdManagerCallback was received
911 // before any calls are received by NsdService, the clientInfo would be
912 // cleared and cause NPE. Add a null check here to prevent this corner case.
913 if (clientInfo == null) {
914 Log.e(TAG, "Unknown connector in registration");
915 break;
916 }
917
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700918 if (requestLimitReached(clientInfo)) {
Paul Hu777ed052023-06-19 13:35:15 +0000919 clientInfo.onRegisterServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000920 clientRequestId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700921 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700922 }
923
Paul Hud44e1b72023-06-16 02:07:42 +0000924 transactionId = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900925 final NsdServiceInfo serviceInfo = args.serviceInfo;
926 final String serviceType = serviceInfo.getServiceType();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900927 final Pair<String, String> typeSubtype = parseTypeAndSubtype(serviceType);
928 final String registerServiceType = typeSubtype == null
929 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800930 if (clientInfo.mUseJavaBackend
931 || mDeps.isMdnsAdvertiserEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900932 || useAdvertiserForType(registerServiceType)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900933 if (registerServiceType == null) {
934 Log.e(TAG, "Invalid service type: " + serviceType);
Paul Hu777ed052023-06-19 13:35:15 +0000935 clientInfo.onRegisterServiceFailedImmediately(
936 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900937 break;
938 }
939 serviceInfo.setServiceType(registerServiceType);
940 serviceInfo.setServiceName(truncateServiceName(
941 serviceInfo.getServiceName()));
942
943 maybeStartMonitoringSockets();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900944 // TODO: pass in the subtype as well. Including the subtype in the
945 // service type would generate service instance names like
946 // Name._subtype._sub._type._tcp, which is incorrect
947 // (it should be Name._type._tcp).
Paul Hud44e1b72023-06-16 02:07:42 +0000948 mAdvertiser.addService(transactionId, serviceInfo, typeSubtype.second);
949 storeAdvertiserRequestMap(clientRequestId, transactionId, clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900950 serviceInfo.getNetwork());
Irfan Sheriff75006652012-04-17 23:15:29 -0700951 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900952 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000953 if (registerService(transactionId, serviceInfo)) {
954 if (DBG) {
955 Log.d(TAG, "Register " + clientRequestId
956 + " " + transactionId);
957 }
Paul Hua6bc4632023-06-26 01:18:29 +0000958 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
959 msg.what, mClock.elapsedRealtime());
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900960 // Return success after mDns reports success
961 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000962 unregisterService(transactionId);
Paul Hu777ed052023-06-19 13:35:15 +0000963 clientInfo.onRegisterServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000964 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900965 }
966
Irfan Sheriff75006652012-04-17 23:15:29 -0700967 }
968 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900969 }
970 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800971 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900972 args = (ListenerArgs) msg.obj;
973 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000974 // If the binder death notification for a INsdManagerCallback was received
975 // before any calls are received by NsdService, the clientInfo would be
976 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900977 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800978 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700979 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700980 }
Paul Hud44e1b72023-06-16 02:07:42 +0000981 final ClientRequest request =
982 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900983 if (request == null) {
984 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
985 break;
986 }
Paul Hud44e1b72023-06-16 02:07:42 +0000987 transactionId = request.mTransactionId;
988 removeRequestMap(clientRequestId, transactionId, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900989
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900990 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
991 // so this needs to check the type of the original request to unregister
992 // instead of looking at the flag value.
Paul Hu812e9212023-06-20 06:24:53 +0000993 final long stopTimeMs = mClock.elapsedRealtime();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900994 if (request instanceof AdvertiserClientRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +0000995 mAdvertiser.removeService(transactionId);
Paul Hu777ed052023-06-19 13:35:15 +0000996 clientInfo.onUnregisterServiceSucceeded(clientRequestId, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +0000997 request.calculateRequestDurationMs(stopTimeMs));
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700998 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000999 if (unregisterService(transactionId)) {
Paul Hu777ed052023-06-19 13:35:15 +00001000 clientInfo.onUnregisterServiceSucceeded(clientRequestId,
Paul Hu812e9212023-06-20 06:24:53 +00001001 transactionId,
1002 request.calculateRequestDurationMs(stopTimeMs));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001003 } else {
1004 clientInfo.onUnregisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001005 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001006 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001007 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001008 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001009 }
Paul Hu75069ed2023-01-14 00:31:09 +08001010 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +08001011 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001012 args = (ListenerArgs) msg.obj;
1013 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +00001014 // If the binder death notification for a INsdManagerCallback was received
1015 // before any calls are received by NsdService, the clientInfo would be
1016 // cleared and cause NPE. Add a null check here to prevent this corner case.
1017 if (clientInfo == null) {
1018 Log.e(TAG, "Unknown connector in resolution");
1019 break;
1020 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001021
Paul Hu75069ed2023-01-14 00:31:09 +08001022 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001023 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001024 final Pair<String, String> typeSubtype =
1025 parseTypeAndSubtype(info.getServiceType());
1026 final String serviceType = typeSubtype == null
1027 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001028 if (clientInfo.mUseJavaBackend
1029 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001030 || useDiscoveryManagerForType(serviceType)) {
Paul Hu75069ed2023-01-14 00:31:09 +08001031 if (serviceType == null) {
Paul Hua6bc4632023-06-26 01:18:29 +00001032 clientInfo.onResolveServiceFailedImmediately(
1033 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu75069ed2023-01-14 00:31:09 +08001034 break;
1035 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001036 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +08001037
1038 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001039 final MdnsListener listener = new ResolutionListener(clientRequestId,
1040 transactionId, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +08001041 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1042 .setNetwork(info.getNetwork())
1043 .setIsPassiveMode(true)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +09001044 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001045 .setRemoveExpiredService(true)
Paul Hu75069ed2023-01-14 00:31:09 +08001046 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001047 mMdnsDiscoveryManager.registerListener(
1048 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001049 storeDiscoveryManagerRequestMap(clientRequestId, transactionId,
1050 listener, clientInfo, info.getNetwork());
1051 clientInfo.log("Register a ResolutionListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001052 + " for service type:" + resolveServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -07001053 } else {
Paul Hu75069ed2023-01-14 00:31:09 +08001054 if (clientInfo.mResolvedService != null) {
Paul Hua6bc4632023-06-26 01:18:29 +00001055 clientInfo.onResolveServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +00001056 clientRequestId, NsdManager.FAILURE_ALREADY_ACTIVE);
Paul Hu75069ed2023-01-14 00:31:09 +08001057 break;
1058 }
1059
1060 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +00001061 if (resolveService(transactionId, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +08001062 clientInfo.mResolvedService = new NsdServiceInfo();
Paul Hua6bc4632023-06-26 01:18:29 +00001063 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
1064 msg.what, mClock.elapsedRealtime());
Paul Hu75069ed2023-01-14 00:31:09 +08001065 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001066 clientInfo.onResolveServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +00001067 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu75069ed2023-01-14 00:31:09 +08001068 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001069 }
1070 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001071 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001072 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +00001073 if (DBG) Log.d(TAG, "Stop service resolution");
1074 args = (ListenerArgs) msg.obj;
1075 clientInfo = mClients.get(args.connector);
1076 // If the binder death notification for a INsdManagerCallback was received
1077 // before any calls are received by NsdService, the clientInfo would be
1078 // cleared and cause NPE. Add a null check here to prevent this corner case.
1079 if (clientInfo == null) {
1080 Log.e(TAG, "Unknown connector in stop resolution");
1081 break;
1082 }
1083
Paul Hud44e1b72023-06-16 02:07:42 +00001084 final ClientRequest request =
1085 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001086 if (request == null) {
1087 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
1088 break;
1089 }
Paul Hud44e1b72023-06-16 02:07:42 +00001090 transactionId = request.mTransactionId;
Paul Hue4f5f252023-02-16 21:13:47 +08001091 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
1092 // point, so this needs to check the type of the original request to
1093 // unregister instead of looking at the flag value.
1094 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001095 stopDiscoveryManagerRequest(
1096 request, clientRequestId, transactionId, clientInfo);
Paul Hu60149052023-07-31 14:26:08 +08001097 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001098 clientInfo.log("Unregister the ResolutionListener " + transactionId);
Paul Hub58deb72022-12-26 09:24:42 +00001099 } else {
Paul Hud44e1b72023-06-16 02:07:42 +00001100 removeRequestMap(clientRequestId, transactionId, clientInfo);
1101 if (stopResolveService(transactionId)) {
Paul Hu60149052023-07-31 14:26:08 +08001102 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hue4f5f252023-02-16 21:13:47 +08001103 } else {
1104 clientInfo.onStopResolutionFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001105 clientRequestId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hue4f5f252023-02-16 21:13:47 +08001106 }
1107 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +00001108 }
Paul Hub58deb72022-12-26 09:24:42 +00001109 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001110 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001111 case NsdManager.REGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001112 if (DBG) Log.d(TAG, "Register a service callback");
1113 args = (ListenerArgs) msg.obj;
1114 clientInfo = mClients.get(args.connector);
1115 // If the binder death notification for a INsdManagerCallback was received
1116 // before any calls are received by NsdService, the clientInfo would be
1117 // cleared and cause NPE. Add a null check here to prevent this corner case.
1118 if (clientInfo == null) {
1119 Log.e(TAG, "Unknown connector in callback registration");
1120 break;
1121 }
1122
Paul Hu30bd70d2023-02-07 13:20:56 +00001123 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001124 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001125 final Pair<String, String> typeAndSubtype =
1126 parseTypeAndSubtype(info.getServiceType());
1127 final String serviceType = typeAndSubtype == null
1128 ? null : typeAndSubtype.first;
Paul Hu30bd70d2023-02-07 13:20:56 +00001129 if (serviceType == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001130 clientInfo.onServiceInfoCallbackRegistrationFailed(clientRequestId,
Paul Hu30bd70d2023-02-07 13:20:56 +00001131 NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +00001132 break;
1133 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001134 final String resolveServiceType = serviceType + ".local";
Paul Hu18aeccc2022-12-27 08:48:48 +00001135
Paul Hu30bd70d2023-02-07 13:20:56 +00001136 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001137 final MdnsListener listener = new ServiceInfoListener(clientRequestId,
1138 transactionId, info, resolveServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +00001139 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1140 .setNetwork(info.getNetwork())
1141 .setIsPassiveMode(true)
1142 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001143 .setRemoveExpiredService(true)
Paul Hu30bd70d2023-02-07 13:20:56 +00001144 .build();
1145 mMdnsDiscoveryManager.registerListener(
1146 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001147 storeDiscoveryManagerRequestMap(clientRequestId, transactionId, listener,
1148 clientInfo, info.getNetwork());
Paul Huddce5912023-08-01 10:26:49 +08001149 clientInfo.onServiceInfoCallbackRegistered(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00001150 clientInfo.log("Register a ServiceInfoListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001151 + " for service type:" + resolveServiceType);
Paul Hu18aeccc2022-12-27 08:48:48 +00001152 break;
Paul Hu30bd70d2023-02-07 13:20:56 +00001153 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001154 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001155 if (DBG) Log.d(TAG, "Unregister a service callback");
1156 args = (ListenerArgs) msg.obj;
1157 clientInfo = mClients.get(args.connector);
1158 // If the binder death notification for a INsdManagerCallback was received
1159 // before any calls are received by NsdService, the clientInfo would be
1160 // cleared and cause NPE. Add a null check here to prevent this corner case.
1161 if (clientInfo == null) {
1162 Log.e(TAG, "Unknown connector in callback unregistration");
1163 break;
1164 }
1165
Paul Hud44e1b72023-06-16 02:07:42 +00001166 final ClientRequest request =
1167 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001168 if (request == null) {
Paul Hu30bd70d2023-02-07 13:20:56 +00001169 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE_CALLBACK");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001170 break;
1171 }
Paul Hud44e1b72023-06-16 02:07:42 +00001172 transactionId = request.mTransactionId;
Paul Hu30bd70d2023-02-07 13:20:56 +00001173 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001174 stopDiscoveryManagerRequest(
1175 request, clientRequestId, transactionId, clientInfo);
Paul Huddce5912023-08-01 10:26:49 +08001176 clientInfo.onServiceInfoCallbackUnregistered(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001177 clientInfo.log("Unregister the ServiceInfoListener " + transactionId);
Paul Hu18aeccc2022-12-27 08:48:48 +00001178 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001179 loge("Unregister failed with non-DiscoveryManagerRequest.");
Paul Hu18aeccc2022-12-27 08:48:48 +00001180 }
Paul Hu18aeccc2022-12-27 08:48:48 +00001181 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001182 }
paulhu2b9ed952022-02-10 21:58:32 +08001183 case MDNS_SERVICE_EVENT:
1184 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +09001185 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001186 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001187 break;
Paul Hu019621e2023-01-13 23:26:49 +08001188 case MDNS_DISCOVERY_MANAGER_EVENT:
1189 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
1190 return NOT_HANDLED;
1191 }
1192 break;
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001193 case NsdManager.REGISTER_OFFLOAD_ENGINE:
1194 offloadEngineInfo = (OffloadEngineInfo) msg.obj;
1195 // TODO: Limits the number of registrations created by a given class.
1196 mOffloadEngines.register(offloadEngineInfo.mOffloadEngine,
1197 offloadEngineInfo);
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001198 sendAllOffloadServiceInfos(offloadEngineInfo);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001199 break;
1200 case NsdManager.UNREGISTER_OFFLOAD_ENGINE:
1201 mOffloadEngines.unregister((IOffloadEngine) msg.obj);
1202 break;
Irfan Sheriff75006652012-04-17 23:15:29 -07001203 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001204 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001205 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001206 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001207 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001208
Paul Hud44e1b72023-06-16 02:07:42 +00001209 private boolean handleMDnsServiceEvent(int code, int transactionId, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001210 NsdServiceInfo servInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001211 ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001212 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001213 Log.e(TAG, String.format(
1214 "transactionId %d for %d has no client mapping", transactionId, code));
Hugo Benichif0c84092017-04-05 14:43:29 +09001215 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001216 }
1217
1218 /* This goes in response as msg.arg2 */
Paul Hud44e1b72023-06-16 02:07:42 +00001219 int clientRequestId = clientInfo.getClientRequestId(transactionId);
1220 if (clientRequestId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -07001221 // This can happen because of race conditions. For example,
1222 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
1223 // and we may get in this situation.
Paul Hud44e1b72023-06-16 02:07:42 +00001224 Log.d(TAG, String.format("%d for transactionId %d that is no longer active",
1225 code, transactionId));
Hugo Benichif0c84092017-04-05 14:43:29 +09001226 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001227 }
Paul Hu812e9212023-06-20 06:24:53 +00001228 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1229 if (request == null) {
1230 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1231 return false;
1232 }
Hugo Benichi32be63d2017-04-05 14:06:11 +09001233 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00001234 Log.d(TAG, String.format(
1235 "MDns service event code:%d transactionId=%d", code, transactionId));
Hugo Benichi32be63d2017-04-05 14:06:11 +09001236 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001237 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +08001238 case IMDnsEventListener.SERVICE_FOUND: {
1239 final DiscoveryInfo info = (DiscoveryInfo) obj;
1240 final String name = info.serviceName;
1241 final String type = info.registrationType;
1242 servInfo = new NsdServiceInfo(name, type);
1243 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001244 if (foundNetId == 0L) {
1245 // Ignore services that do not have a Network: they are not usable
1246 // by apps, as they would need privileged permissions to use
1247 // interfaces that do not have an associated Network.
1248 break;
1249 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +09001250 if (foundNetId == INetd.DUMMY_NET_ID) {
1251 // Ignore services on the dummy0 interface: they are only seen when
1252 // discovering locally advertised services, and are not reachable
1253 // through that interface.
1254 break;
1255 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001256 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001257
1258 clientInfo.onServiceFound(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001259 break;
paulhu2b9ed952022-02-10 21:58:32 +08001260 }
1261 case IMDnsEventListener.SERVICE_LOST: {
1262 final DiscoveryInfo info = (DiscoveryInfo) obj;
1263 final String name = info.serviceName;
1264 final String type = info.registrationType;
1265 final int lostNetId = info.netId;
1266 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001267 // The network could be set to null (netId 0) if it was torn down when the
1268 // service is lost
1269 // TODO: avoid returning null in that case, possibly by remembering
1270 // found services on the same interface index and their network at the time
1271 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001272 clientInfo.onServiceLost(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001273 break;
paulhu2b9ed952022-02-10 21:58:32 +08001274 }
1275 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Paul Hu812e9212023-06-20 06:24:53 +00001276 clientInfo.onDiscoverServicesFailed(clientRequestId,
1277 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1278 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001279 break;
paulhu2b9ed952022-02-10 21:58:32 +08001280 case IMDnsEventListener.SERVICE_REGISTERED: {
1281 final RegistrationInfo info = (RegistrationInfo) obj;
1282 final String name = info.serviceName;
1283 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Paul Hu777ed052023-06-19 13:35:15 +00001284 clientInfo.onRegisterServiceSucceeded(clientRequestId, servInfo,
Paul Hu812e9212023-06-20 06:24:53 +00001285 transactionId,
1286 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001287 break;
paulhu2b9ed952022-02-10 21:58:32 +08001288 }
1289 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Paul Hu777ed052023-06-19 13:35:15 +00001290 clientInfo.onRegisterServiceFailed(clientRequestId,
1291 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001292 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001293 break;
paulhu2b9ed952022-02-10 21:58:32 +08001294 case IMDnsEventListener.SERVICE_RESOLVED: {
1295 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001296 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +08001297 final String fullName = info.serviceFullName;
1298 while (index < fullName.length() && fullName.charAt(index) != '.') {
1299 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001300 ++index;
1301 }
1302 ++index;
1303 }
paulhu2b9ed952022-02-10 21:58:32 +08001304 if (index >= fullName.length()) {
1305 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001306 break;
1307 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001308
paulhube186602022-04-12 07:18:23 +00001309 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001310 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001311 String type = rest.replace(".local.", "");
1312
Paul Hu30bd70d2023-02-07 13:20:56 +00001313 final NsdServiceInfo serviceInfo = clientInfo.mResolvedService;
Paul Hu18aeccc2022-12-27 08:48:48 +00001314 serviceInfo.setServiceName(name);
1315 serviceInfo.setServiceType(type);
1316 serviceInfo.setPort(info.port);
1317 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001318 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001319
Paul Hud44e1b72023-06-16 02:07:42 +00001320 stopResolveService(transactionId);
1321 removeRequestMap(clientRequestId, transactionId, clientInfo);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001322
Paul Hud44e1b72023-06-16 02:07:42 +00001323 final int transactionId2 = getUniqueId();
1324 if (getAddrInfo(transactionId2, info.hostname, info.interfaceIdx)) {
1325 storeLegacyRequestMap(clientRequestId, transactionId2, clientInfo,
Paul Hua6bc4632023-06-26 01:18:29 +00001326 NsdManager.RESOLVE_SERVICE, request.mStartTimeMs);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001327 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001328 clientInfo.onResolveServiceFailed(clientRequestId,
1329 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1330 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001331 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001332 }
1333 break;
paulhu2b9ed952022-02-10 21:58:32 +08001334 }
1335 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001336 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001337 stopResolveService(transactionId);
1338 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001339 clientInfo.onResolveServiceFailed(clientRequestId,
1340 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1341 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001342 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001343 break;
paulhu2b9ed952022-02-10 21:58:32 +08001344 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001345 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001346 stopGetAddrInfo(transactionId);
1347 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001348 clientInfo.onResolveServiceFailed(clientRequestId,
1349 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1350 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001351 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001352 break;
paulhu2b9ed952022-02-10 21:58:32 +08001353 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001354 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001355 final GetAddressInfo info = (GetAddressInfo) obj;
1356 final String address = info.address;
1357 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001358 InetAddress serviceHost = null;
1359 try {
paulhu2b9ed952022-02-10 21:58:32 +08001360 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001361 } catch (UnknownHostException e) {
1362 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1363 }
1364
1365 // If the resolved service is on an interface without a network, consider it
1366 // as a failure: it would not be usable by apps as they would need
1367 // privileged permissions.
Paul Hu30bd70d2023-02-07 13:20:56 +00001368 if (netId != NETID_UNSET && serviceHost != null) {
1369 clientInfo.mResolvedService.setHost(serviceHost);
1370 setServiceNetworkForCallback(clientInfo.mResolvedService,
1371 netId, info.interfaceIdx);
1372 clientInfo.onResolveServiceSucceeded(
Paul Hua6bc4632023-06-26 01:18:29 +00001373 clientRequestId, clientInfo.mResolvedService, request);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001374 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001375 clientInfo.onResolveServiceFailed(clientRequestId,
1376 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1377 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001378 }
Paul Hud44e1b72023-06-16 02:07:42 +00001379 stopGetAddrInfo(transactionId);
1380 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001381 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001382 break;
paulhu2b9ed952022-02-10 21:58:32 +08001383 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001384 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001385 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001386 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001387 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001388 }
Paul Hu019621e2023-01-13 23:26:49 +08001389
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001390 @Nullable
1391 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(
1392 final MdnsEvent event, int code) {
Paul Hu019621e2023-01-13 23:26:49 +08001393 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001394 final String[] typeArray = serviceInfo.getServiceType();
1395 final String joinedType;
1396 if (typeArray.length == 0
1397 || !typeArray[typeArray.length - 1].equals(LOCAL_DOMAIN_NAME)) {
1398 Log.wtf(TAG, "MdnsServiceInfo type does not end in .local: "
1399 + Arrays.toString(typeArray));
1400 return null;
1401 } else {
1402 joinedType = TextUtils.join(".",
1403 Arrays.copyOfRange(typeArray, 0, typeArray.length - 1));
1404 }
1405 final String serviceType;
1406 switch (code) {
1407 case NsdManager.SERVICE_FOUND:
1408 case NsdManager.SERVICE_LOST:
1409 // For consistency with historical behavior, discovered service types have
1410 // a dot at the end.
1411 serviceType = joinedType + ".";
1412 break;
1413 case RESOLVE_SERVICE_SUCCEEDED:
1414 // For consistency with historical behavior, resolved service types have
1415 // a dot at the beginning.
1416 serviceType = "." + joinedType;
1417 break;
1418 default:
1419 serviceType = joinedType;
1420 break;
1421 }
Paul Hu019621e2023-01-13 23:26:49 +08001422 final String serviceName = serviceInfo.getServiceInstanceName();
1423 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1424 final Network network = serviceInfo.getNetwork();
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001425 // In MdnsDiscoveryManagerEvent, the Network can be null which means it is a
1426 // network for Tethering interface. In other words, the network == null means the
1427 // network has netId = INetd.LOCAL_NET_ID.
Paul Hu019621e2023-01-13 23:26:49 +08001428 setServiceNetworkForCallback(
1429 servInfo,
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001430 network == null ? INetd.LOCAL_NET_ID : network.netId,
Paul Hu019621e2023-01-13 23:26:49 +08001431 serviceInfo.getInterfaceIndex());
1432 return servInfo;
1433 }
1434
1435 private boolean handleMdnsDiscoveryManagerEvent(
1436 int transactionId, int code, Object obj) {
Paul Hud44e1b72023-06-16 02:07:42 +00001437 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Paul Hu019621e2023-01-13 23:26:49 +08001438 if (clientInfo == null) {
1439 Log.e(TAG, String.format(
1440 "id %d for %d has no client mapping", transactionId, code));
1441 return false;
1442 }
1443
1444 final MdnsEvent event = (MdnsEvent) obj;
Paul Hud44e1b72023-06-16 02:07:42 +00001445 final int clientRequestId = event.mClientRequestId;
Paul Hubad6fe92023-07-24 21:25:22 +08001446 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1447 if (request == null) {
1448 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1449 return false;
1450 }
1451
1452 // Deal with the discovery sent callback
1453 if (code == DISCOVERY_QUERY_SENT_CALLBACK) {
1454 request.onQuerySent();
1455 return true;
1456 }
1457
1458 // Deal with other callbacks.
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001459 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event, code);
1460 // Errors are already logged if null
1461 if (info == null) return false;
Paul Hu83ec7f42023-06-07 18:04:09 +08001462 mServiceLogs.log(String.format(
1463 "MdnsDiscoveryManager event code=%s transactionId=%d",
1464 NsdManager.nameOf(code), transactionId));
Paul Hu019621e2023-01-13 23:26:49 +08001465 switch (code) {
1466 case NsdManager.SERVICE_FOUND:
Paul Hu812e9212023-06-20 06:24:53 +00001467 clientInfo.onServiceFound(clientRequestId, info, request);
Paul Hu319751a2023-01-13 23:56:34 +08001468 break;
1469 case NsdManager.SERVICE_LOST:
Paul Hu812e9212023-06-20 06:24:53 +00001470 clientInfo.onServiceLost(clientRequestId, info, request);
Paul Hu019621e2023-01-13 23:26:49 +08001471 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001472 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
1473 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Paul Hu75069ed2023-01-14 00:31:09 +08001474 info.setPort(serviceInfo.getPort());
1475
1476 Map<String, String> attrs = serviceInfo.getAttributes();
1477 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1478 final String key = kv.getKey();
1479 try {
1480 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1481 } catch (IllegalArgumentException e) {
1482 Log.e(TAG, "Invalid attribute", e);
1483 }
1484 }
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001485 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu2b865912023-03-06 14:27:53 +08001486 if (addresses.size() != 0) {
1487 info.setHostAddresses(addresses);
Paul Hua6bc4632023-06-26 01:18:29 +00001488 request.setServiceFromCache(event.mIsServiceFromCache);
1489 clientInfo.onResolveServiceSucceeded(clientRequestId, info, request);
Paul Hu2b865912023-03-06 14:27:53 +08001490 } else {
1491 // No address. Notify resolution failure.
Paul Hua6bc4632023-06-26 01:18:29 +00001492 clientInfo.onResolveServiceFailed(clientRequestId,
1493 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1494 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu75069ed2023-01-14 00:31:09 +08001495 }
1496
1497 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001498 if (!(request instanceof DiscoveryManagerRequest)) {
1499 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1500 break;
1501 }
Paul Hud44e1b72023-06-16 02:07:42 +00001502 stopDiscoveryManagerRequest(
1503 request, clientRequestId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001504 break;
1505 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001506 case NsdManager.SERVICE_UPDATED: {
1507 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1508 info.setPort(serviceInfo.getPort());
1509
1510 Map<String, String> attrs = serviceInfo.getAttributes();
1511 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1512 final String key = kv.getKey();
1513 try {
1514 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1515 } catch (IllegalArgumentException e) {
1516 Log.e(TAG, "Invalid attribute", e);
1517 }
1518 }
1519
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001520 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001521 info.setHostAddresses(addresses);
Paul Huddce5912023-08-01 10:26:49 +08001522 clientInfo.onServiceUpdated(clientRequestId, info, request);
1523 // Set the ServiceFromCache flag only if the service is actually being
1524 // retrieved from the cache. This flag should not be overridden by later
1525 // service updates, which may not be cached.
1526 if (event.mIsServiceFromCache) {
1527 request.setServiceFromCache(true);
1528 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001529 break;
1530 }
1531 case NsdManager.SERVICE_UPDATED_LOST:
Paul Huddce5912023-08-01 10:26:49 +08001532 clientInfo.onServiceUpdatedLost(clientRequestId, request);
Paul Hu30bd70d2023-02-07 13:20:56 +00001533 break;
Paul Hu019621e2023-01-13 23:26:49 +08001534 default:
1535 return false;
1536 }
1537 return true;
1538 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001539 }
1540 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001541
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001542 @NonNull
1543 private static List<InetAddress> getInetAddresses(@NonNull MdnsServiceInfo serviceInfo) {
1544 final List<String> v4Addrs = serviceInfo.getIpv4Addresses();
1545 final List<String> v6Addrs = serviceInfo.getIpv6Addresses();
1546 final List<InetAddress> addresses = new ArrayList<>(v4Addrs.size() + v6Addrs.size());
1547 for (String ipv4Address : v4Addrs) {
1548 try {
1549 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1550 } catch (IllegalArgumentException e) {
1551 Log.wtf(TAG, "Invalid ipv4 address", e);
1552 }
1553 }
1554 for (String ipv6Address : v6Addrs) {
1555 try {
Yuyang Huanga6a6ff92023-04-24 13:33:34 +09001556 final Inet6Address addr = (Inet6Address) InetAddresses.parseNumericAddress(
1557 ipv6Address);
1558 addresses.add(InetAddressUtils.withScopeId(addr, serviceInfo.getInterfaceIndex()));
1559 } catch (IllegalArgumentException e) {
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001560 Log.wtf(TAG, "Invalid ipv6 address", e);
1561 }
1562 }
1563 return addresses;
1564 }
1565
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001566 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1567 switch (netId) {
1568 case NETID_UNSET:
1569 info.setNetwork(null);
1570 break;
1571 case INetd.LOCAL_NET_ID:
1572 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1573 // visible / usable for apps, so do not return it. Store the interface
1574 // index instead, so at least if the client tries to resolve the service
1575 // with that NsdServiceInfo, it will be done on the same interface.
1576 // If they recreate the NsdServiceInfo themselves, resolution would be
1577 // done on all interfaces as before T, which should also work.
1578 info.setNetwork(null);
1579 info.setInterfaceIndex(ifaceIdx);
1580 break;
1581 default:
1582 info.setNetwork(new Network(netId));
1583 }
1584 }
1585
paulhube186602022-04-12 07:18:23 +00001586 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1587 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1588 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1589 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1590 private String unescape(String s) {
1591 StringBuilder sb = new StringBuilder(s.length());
1592 for (int i = 0; i < s.length(); ++i) {
1593 char c = s.charAt(i);
1594 if (c == '\\') {
1595 if (++i >= s.length()) {
1596 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1597 break;
1598 }
1599 c = s.charAt(i);
1600 if (c != '.' && c != '\\') {
1601 if (i + 2 >= s.length()) {
1602 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1603 break;
1604 }
1605 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1606 + (s.charAt(i + 2) - '0'));
1607 i += 2;
1608 }
1609 }
1610 sb.append(c);
1611 }
1612 return sb.toString();
1613 }
1614
Paul Hu7445e3d2023-03-03 15:14:00 +08001615 /**
1616 * Check the given service type is valid and construct it to a service type
1617 * which can use for discovery / resolution service.
1618 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001619 * <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 +08001620 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1621 * underscore; they are alphanumerical characters or dashes or underscore, except the
1622 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1623 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001624 * <p>The subtype may also be specified with a comma after the service type, for example
1625 * _type._tcp,_subtype.
1626 *
Paul Hu7445e3d2023-03-03 15:14:00 +08001627 * @param serviceType the request service type for discovery / resolution service
1628 * @return constructed service type or null if the given service type is invalid.
1629 */
1630 @Nullable
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001631 public static Pair<String, String> parseTypeAndSubtype(String serviceType) {
Paul Hu7445e3d2023-03-03 15:14:00 +08001632 if (TextUtils.isEmpty(serviceType)) return null;
1633
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001634 final String typeOrSubtypePattern = "_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]";
Paul Hu7445e3d2023-03-03 15:14:00 +08001635 final Pattern serviceTypePattern = Pattern.compile(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001636 // Optional leading subtype (_subtype._type._tcp)
1637 // (?: xxx) is a non-capturing parenthesis, don't capture the dot
1638 "^(?:(" + typeOrSubtypePattern + ")\\.)?"
1639 // Actual type (_type._tcp.local)
1640 + "(" + typeOrSubtypePattern + "\\._(?:tcp|udp))"
Paul Hu7445e3d2023-03-03 15:14:00 +08001641 // Drop '.' at the end of service type that is compatible with old backend.
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001642 // e.g. allow "_type._tcp.local."
1643 + "\\.?"
1644 // Optional subtype after comma, for "_type._tcp,_subtype" format
1645 + "(?:,(" + typeOrSubtypePattern + "))?"
1646 + "$");
Paul Hu7445e3d2023-03-03 15:14:00 +08001647 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1648 if (!matcher.matches()) return null;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001649 // Use the subtype either at the beginning or after the comma
1650 final String subtype = matcher.group(1) != null ? matcher.group(1) : matcher.group(3);
1651 return new Pair<>(matcher.group(2), subtype);
Paul Hu7445e3d2023-03-03 15:14:00 +08001652 }
1653
Hugo Benichi803a2f02017-04-24 11:35:06 +09001654 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001655 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001656 this(ctx, handler, cleanupDelayMs, new Dependencies());
1657 }
1658
1659 @VisibleForTesting
1660 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001661 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001662 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001663 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001664 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001665 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1666 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001667 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001668
Paul Hu14667de2023-04-17 22:42:47 +08001669 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper(),
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001670 LOGGER.forSubComponent("MdnsSocketProvider"), new SocketRequestMonitor());
Yuyang Huang700778b2023-03-08 16:17:05 +09001671 // Netlink monitor starts on boot, and intentionally never stopped, to ensure that all
1672 // address events are received.
1673 handler.post(mMdnsSocketProvider::startNetLinkMonitor);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001674
1675 // NsdService is started after ActivityManager (startOtherServices in SystemServer, vs.
1676 // startBootstrapServices).
1677 mRunningAppActiveImportanceCutoff = mDeps.getDeviceConfigInt(
1678 MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF,
1679 DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF);
1680 final ActivityManager am = ctx.getSystemService(ActivityManager.class);
1681 am.addOnUidImportanceListener(new UidImportanceListener(handler),
1682 mRunningAppActiveImportanceCutoff);
1683
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001684 mMdnsSocketClient =
Yuyang Huang7ddf2932023-08-01 18:16:30 +09001685 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider,
1686 LOGGER.forSubComponent("MdnsMultinetworkSocketClient"));
Paul Hu14667de2023-04-17 22:42:47 +08001687 mMdnsDiscoveryManager = deps.makeMdnsDiscoveryManager(new ExecutorProvider(),
Yuyang Huang243d1a52023-05-23 17:26:52 +09001688 mMdnsSocketClient, LOGGER.forSubComponent("MdnsDiscoveryManager"));
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001689 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1690 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
Paul Hu14667de2023-04-17 22:42:47 +08001691 new AdvertiserCallback(), LOGGER.forSubComponent("MdnsAdvertiser"));
Paul Hu777ed052023-06-19 13:35:15 +00001692 mClock = deps.makeClock();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001693 }
1694
1695 /**
1696 * Dependencies of NsdService, for injection in tests.
1697 */
1698 @VisibleForTesting
1699 public static class Dependencies {
1700 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001701 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001702 *
1703 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001704 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001705 */
1706 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001707 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
1708 NAMESPACE_TETHERING, MDNS_DISCOVERY_MANAGER_VERSION,
1709 DeviceConfigUtils.TETHERING_MODULE_NAME, false /* defaultEnabled */);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001710 }
1711
1712 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001713 * Check whether the MdnsAdvertiser feature is enabled.
1714 *
1715 * @param context The global context information about an app environment.
1716 * @return true if the MdnsAdvertiser feature is enabled.
1717 */
1718 public boolean isMdnsAdvertiserEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001719 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
1720 NAMESPACE_TETHERING, MDNS_ADVERTISER_VERSION,
1721 DeviceConfigUtils.TETHERING_MODULE_NAME, false /* defaultEnabled */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001722 }
1723
1724 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001725 * Get the type allowlist flag value.
1726 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1727 */
1728 @Nullable
1729 public String getTypeAllowlistFlags() {
1730 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1731 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1732 }
1733
1734 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001735 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001736 */
1737 public boolean isFeatureEnabled(Context context, String feature) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001738 return DeviceConfigUtils.isTetheringFeatureEnabled(context, NAMESPACE_TETHERING,
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001739 feature, DeviceConfigUtils.TETHERING_MODULE_NAME, false /* defaultEnabled */);
1740 }
1741
1742 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001743 * @see MdnsDiscoveryManager
1744 */
1745 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
Paul Hu14667de2023-04-17 22:42:47 +08001746 @NonNull ExecutorProvider executorProvider,
Yuyang Huang243d1a52023-05-23 17:26:52 +09001747 @NonNull MdnsMultinetworkSocketClient socketClient, @NonNull SharedLog sharedLog) {
1748 return new MdnsDiscoveryManager(executorProvider, socketClient, sharedLog);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001749 }
1750
1751 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001752 * @see MdnsAdvertiser
1753 */
1754 public MdnsAdvertiser makeMdnsAdvertiser(
1755 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
Paul Hu14667de2023-04-17 22:42:47 +08001756 @NonNull MdnsAdvertiser.AdvertiserCallback cb, @NonNull SharedLog sharedLog) {
1757 return new MdnsAdvertiser(looper, socketProvider, cb, sharedLog);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001758 }
1759
1760 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001761 * @see MdnsSocketProvider
1762 */
Paul Hu14667de2023-04-17 22:42:47 +08001763 public MdnsSocketProvider makeMdnsSocketProvider(@NonNull Context context,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001764 @NonNull Looper looper, @NonNull SharedLog sharedLog,
1765 @NonNull MdnsSocketProvider.SocketRequestMonitor socketCreationCallback) {
1766 return new MdnsSocketProvider(context, looper, sharedLog, socketCreationCallback);
1767 }
1768
1769 /**
1770 * @see DeviceConfig#getInt(String, String, int)
1771 */
1772 public int getDeviceConfigInt(@NonNull String config, int defaultValue) {
1773 return DeviceConfig.getInt(NAMESPACE_TETHERING, config, defaultValue);
1774 }
1775
1776 /**
1777 * @see Binder#getCallingUid()
1778 */
1779 public int getCallingUid() {
1780 return Binder.getCallingUid();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001781 }
Paul Hu777ed052023-06-19 13:35:15 +00001782
1783 /**
1784 * @see NetworkNsdReportedMetrics
1785 */
1786 public NetworkNsdReportedMetrics makeNetworkNsdReportedMetrics(
1787 boolean isLegacy, int clientId) {
1788 return new NetworkNsdReportedMetrics(isLegacy, clientId);
1789 }
1790
1791 /**
1792 * @see MdnsUtils.Clock
1793 */
1794 public Clock makeClock() {
1795 return new Clock();
1796 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001797 }
1798
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001799 /**
1800 * Return whether a type is allowlisted to use the Java backend.
1801 * @param type The service type
1802 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1803 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1804 */
1805 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1806 @NonNull String flagPrefix) {
1807 if (type == null) return false;
1808 final String typesConfig = mDeps.getTypeAllowlistFlags();
1809 if (TextUtils.isEmpty(typesConfig)) return false;
1810
1811 final String mappingPrefix = type + ":";
1812 String mappedFlag = null;
1813 for (String mapping : TextUtils.split(typesConfig, ",")) {
1814 if (mapping.startsWith(mappingPrefix)) {
1815 mappedFlag = mapping.substring(mappingPrefix.length());
1816 break;
1817 }
1818 }
1819
1820 if (mappedFlag == null) return false;
1821
1822 return mDeps.isFeatureEnabled(mContext,
1823 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1824 }
1825
1826 private boolean useDiscoveryManagerForType(@Nullable String type) {
1827 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1828 }
1829
1830 private boolean useAdvertiserForType(@Nullable String type) {
1831 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1832 }
1833
paulhu1b35e822022-04-08 14:48:41 +08001834 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001835 HandlerThread thread = new HandlerThread(TAG);
1836 thread.start();
1837 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001838 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001839 return service;
1840 }
1841
paulhu2b9ed952022-02-10 21:58:32 +08001842 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1843 private final StateMachine mStateMachine;
1844
1845 MDnsEventCallback(StateMachine sm) {
1846 mStateMachine = sm;
1847 }
1848
1849 @Override
1850 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1851 mStateMachine.sendMessage(
1852 MDNS_SERVICE_EVENT, status.result, status.id, status);
1853 }
1854
1855 @Override
1856 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1857 mStateMachine.sendMessage(
1858 MDNS_SERVICE_EVENT, status.result, status.id, status);
1859 }
1860
1861 @Override
1862 public void onServiceResolutionStatus(final ResolutionInfo status) {
1863 mStateMachine.sendMessage(
1864 MDNS_SERVICE_EVENT, status.result, status.id, status);
1865 }
1866
1867 @Override
1868 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1869 mStateMachine.sendMessage(
1870 MDNS_SERVICE_EVENT, status.result, status.id, status);
1871 }
1872
1873 @Override
1874 public int getInterfaceVersion() throws RemoteException {
1875 return this.VERSION;
1876 }
1877
1878 @Override
1879 public String getInterfaceHash() throws RemoteException {
1880 return this.HASH;
1881 }
1882 }
1883
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001884 private void sendAllOffloadServiceInfos(@NonNull OffloadEngineInfo offloadEngineInfo) {
1885 final String targetInterface = offloadEngineInfo.mInterfaceName;
1886 final IOffloadEngine offloadEngine = offloadEngineInfo.mOffloadEngine;
1887 final List<MdnsAdvertiser.OffloadServiceInfoWrapper> offloadWrappers =
1888 mAdvertiser.getAllInterfaceOffloadServiceInfos(targetInterface);
1889 for (MdnsAdvertiser.OffloadServiceInfoWrapper wrapper : offloadWrappers) {
1890 try {
1891 offloadEngine.onOffloadServiceUpdated(wrapper.mOffloadServiceInfo);
1892 } catch (RemoteException e) {
1893 // Can happen in regular cases, do not log a stacktrace
1894 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
1895 }
1896 }
1897 }
1898
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001899 private void sendOffloadServiceInfosUpdate(@NonNull String targetInterfaceName,
1900 @NonNull OffloadServiceInfo offloadServiceInfo, boolean isRemove) {
1901 final int count = mOffloadEngines.beginBroadcast();
1902 try {
1903 for (int i = 0; i < count; i++) {
1904 final OffloadEngineInfo offloadEngineInfo =
1905 (OffloadEngineInfo) mOffloadEngines.getBroadcastCookie(i);
1906 final String interfaceName = offloadEngineInfo.mInterfaceName;
1907 if (!targetInterfaceName.equals(interfaceName)
1908 || ((offloadEngineInfo.mOffloadType
1909 & offloadServiceInfo.getOffloadType()) == 0)) {
1910 continue;
1911 }
1912 try {
1913 if (isRemove) {
1914 mOffloadEngines.getBroadcastItem(i).onOffloadServiceRemoved(
1915 offloadServiceInfo);
1916 } else {
1917 mOffloadEngines.getBroadcastItem(i).onOffloadServiceUpdated(
1918 offloadServiceInfo);
1919 }
1920 } catch (RemoteException e) {
1921 // Can happen in regular cases, do not log a stacktrace
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001922 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001923 }
1924 }
1925 } finally {
1926 mOffloadEngines.finishBroadcast();
1927 }
1928 }
1929
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001930 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001931 // TODO: add a callback to notify when a service is being added on each interface (as soon
1932 // as probing starts), and call mOffloadCallbacks. This callback is for
1933 // OFFLOAD_CAPABILITY_FILTER_REPLIES offload type.
1934
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001935 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001936 public void onRegisterServiceSucceeded(int transactionId, NsdServiceInfo registeredInfo) {
1937 mServiceLogs.log("onRegisterServiceSucceeded: transactionId " + transactionId);
1938 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001939 if (clientInfo == null) return;
1940
Paul Hud44e1b72023-06-16 02:07:42 +00001941 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1942 if (clientRequestId < 0) return;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001943
1944 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1945 // historical behavior.
1946 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
Paul Hu777ed052023-06-19 13:35:15 +00001947 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu812e9212023-06-20 06:24:53 +00001948 clientInfo.onRegisterServiceSucceeded(clientRequestId, cbInfo, transactionId,
1949 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001950 }
1951
1952 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001953 public void onRegisterServiceFailed(int transactionId, int errorCode) {
1954 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001955 if (clientInfo == null) return;
1956
Paul Hud44e1b72023-06-16 02:07:42 +00001957 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1958 if (clientRequestId < 0) return;
Paul Hu777ed052023-06-19 13:35:15 +00001959 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1960 clientInfo.onRegisterServiceFailed(clientRequestId, errorCode, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001961 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001962 }
1963
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001964 @Override
1965 public void onOffloadStartOrUpdate(@NonNull String interfaceName,
1966 @NonNull OffloadServiceInfo offloadServiceInfo) {
1967 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, false /* isRemove */);
1968 }
1969
1970 @Override
1971 public void onOffloadStop(@NonNull String interfaceName,
1972 @NonNull OffloadServiceInfo offloadServiceInfo) {
1973 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, true /* isRemove */);
1974 }
1975
Paul Hud44e1b72023-06-16 02:07:42 +00001976 private ClientInfo getClientInfoOrLog(int transactionId) {
1977 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001978 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001979 Log.e(TAG, String.format("Callback for service %d has no client", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001980 }
1981 return clientInfo;
1982 }
1983
Paul Hud44e1b72023-06-16 02:07:42 +00001984 private int getClientRequestIdOrLog(@NonNull ClientInfo info, int transactionId) {
1985 final int clientRequestId = info.getClientRequestId(transactionId);
1986 if (clientRequestId < 0) {
1987 Log.e(TAG, String.format(
1988 "Client request ID not found for service %d", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001989 }
Paul Hud44e1b72023-06-16 02:07:42 +00001990 return clientRequestId;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001991 }
1992 }
1993
Paul Hu2e0a88c2023-03-09 16:05:01 +08001994 private static class ConnectorArgs {
1995 @NonNull public final NsdServiceConnector connector;
1996 @NonNull public final INsdManagerCallback callback;
1997 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001998 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001999
2000 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00002001 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08002002 this.connector = connector;
2003 this.callback = callback;
2004 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002005 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002006 }
2007 }
2008
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002009 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08002010 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09002011 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu101dbf52023-08-09 16:05:20 +08002012 final int uid = mDeps.getCallingUid();
2013 if (cb == null) {
2014 throw new IllegalArgumentException("Unknown client callback from uid=" + uid);
2015 }
Paul Hu2e0a88c2023-03-09 16:05:01 +08002016 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002017 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00002018 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
Paul Hu101dbf52023-08-09 16:05:20 +08002019 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend, uid)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002020 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07002021 }
2022
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002023 private static class ListenerArgs {
2024 public final NsdServiceConnector connector;
2025 public final NsdServiceInfo serviceInfo;
2026 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
2027 this.connector = connector;
2028 this.serviceInfo = serviceInfo;
2029 }
2030 }
2031
2032 private class NsdServiceConnector extends INsdServiceConnector.Stub
2033 implements IBinder.DeathRecipient {
2034 @Override
2035 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
2036 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2037 NsdManager.REGISTER_SERVICE, 0, listenerKey,
2038 new ListenerArgs(this, serviceInfo)));
2039 }
2040
2041 @Override
2042 public void unregisterService(int listenerKey) {
2043 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2044 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
2045 new ListenerArgs(this, null)));
2046 }
2047
2048 @Override
2049 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
2050 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2051 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
2052 new ListenerArgs(this, serviceInfo)));
2053 }
2054
2055 @Override
2056 public void stopDiscovery(int listenerKey) {
2057 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2058 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
2059 }
2060
2061 @Override
2062 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
2063 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2064 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
2065 new ListenerArgs(this, serviceInfo)));
2066 }
2067
2068 @Override
Paul Hub58deb72022-12-26 09:24:42 +00002069 public void stopResolution(int listenerKey) {
2070 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2071 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
2072 }
2073
2074 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00002075 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
2076 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2077 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
2078 new ListenerArgs(this, serviceInfo)));
2079 }
2080
2081 @Override
2082 public void unregisterServiceInfoCallback(int listenerKey) {
2083 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2084 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
2085 new ListenerArgs(this, null)));
2086 }
2087
2088 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002089 public void startDaemon() {
2090 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2091 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
2092 }
2093
2094 @Override
2095 public void binderDied() {
2096 mNsdStateMachine.sendMessage(
2097 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002098
2099 }
2100
2101 @Override
2102 public void registerOffloadEngine(String ifaceName, IOffloadEngine cb,
2103 @OffloadEngine.OffloadCapability long offloadCapabilities,
2104 @OffloadEngine.OffloadType long offloadTypes) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002105 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002106 Objects.requireNonNull(ifaceName);
2107 Objects.requireNonNull(cb);
2108 mNsdStateMachine.sendMessage(
2109 mNsdStateMachine.obtainMessage(NsdManager.REGISTER_OFFLOAD_ENGINE,
2110 new OffloadEngineInfo(cb, ifaceName, offloadCapabilities,
2111 offloadTypes)));
2112 }
2113
2114 @Override
2115 public void unregisterOffloadEngine(IOffloadEngine cb) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002116 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002117 Objects.requireNonNull(cb);
2118 mNsdStateMachine.sendMessage(
2119 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_OFFLOAD_ENGINE, cb));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002120 }
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002121
2122 private static void checkOffloadEnginePermission(Context context) {
2123 if (!SdkLevel.isAtLeastT()) {
2124 throw new SecurityException("API is not available in before API level 33");
2125 }
2126 // REGISTER_NSD_OFFLOAD_ENGINE was only added to the SDK in V, but may
2127 // be back ported to older builds: accept it as long as it's signature-protected
2128 if (PermissionUtils.checkAnyPermissionOf(context, REGISTER_NSD_OFFLOAD_ENGINE)
2129 && (SdkLevel.isAtLeastV() || PermissionUtils.isSystemSignaturePermission(
2130 context, REGISTER_NSD_OFFLOAD_ENGINE))) {
2131 return;
2132 }
2133 if (PermissionUtils.checkAnyPermissionOf(context, NETWORK_STACK,
2134 PERMISSION_MAINLINE_NETWORK_STACK, NETWORK_SETTINGS)) {
2135 return;
2136 }
2137 throw new SecurityException("Requires one of the following permissions: "
2138 + String.join(", ", List.of(REGISTER_NSD_OFFLOAD_ENGINE, NETWORK_STACK,
2139 PERMISSION_MAINLINE_NETWORK_STACK, NETWORK_SETTINGS)) + ".");
2140 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002141 }
2142
Hugo Benichi912db992017-04-24 16:41:03 +09002143 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07002144 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07002145 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09002146 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
2147 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07002148 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07002149 }
2150
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002151 private int getUniqueId() {
2152 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
2153 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002154 }
2155
Paul Hud44e1b72023-06-16 02:07:42 +00002156 private boolean registerService(int transactionId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09002157 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002158 Log.d(TAG, "registerService: " + transactionId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002159 }
Hugo Benichi6d706442017-04-24 16:19:58 +09002160 String name = service.getServiceName();
2161 String type = service.getServiceType();
2162 int port = service.getPort();
2163 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002164 final int registerInterface = getNetworkInterfaceIndex(service);
2165 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08002166 Log.e(TAG, "Interface to register service on not found");
2167 return false;
2168 }
Paul Hud44e1b72023-06-16 02:07:42 +00002169 return mMDnsManager.registerService(
2170 transactionId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002171 }
2172
Paul Hud44e1b72023-06-16 02:07:42 +00002173 private boolean unregisterService(int transactionId) {
2174 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002175 }
2176
Paul Hud44e1b72023-06-16 02:07:42 +00002177 private boolean discoverServices(int transactionId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08002178 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002179 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
2180 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002181 Log.e(TAG, "Interface to discover service on not found");
2182 return false;
2183 }
Paul Hud44e1b72023-06-16 02:07:42 +00002184 return mMDnsManager.discover(transactionId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002185 }
2186
Paul Hud44e1b72023-06-16 02:07:42 +00002187 private boolean stopServiceDiscovery(int transactionId) {
2188 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002189 }
2190
Paul Hud44e1b72023-06-16 02:07:42 +00002191 private boolean resolveService(int transactionId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002192 final String name = service.getServiceName();
2193 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002194 final int resolveInterface = getNetworkInterfaceIndex(service);
2195 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002196 Log.e(TAG, "Interface to resolve service on not found");
2197 return false;
2198 }
Paul Hud44e1b72023-06-16 02:07:42 +00002199 return mMDnsManager.resolve(transactionId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002200 }
2201
2202 /**
2203 * Guess the interface to use to resolve or discover a service on a specific network.
2204 *
2205 * This is an imperfect guess, as for example the network may be gone or not yet fully
2206 * registered. This is fine as failing is correct if the network is gone, and a client
2207 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
2208 * this is to support the legacy mdnsresponder implementation, which historically resolved
2209 * services on an unspecified network.
2210 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002211 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
2212 final Network network = serviceInfo.getNetwork();
2213 if (network == null) {
2214 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
2215 // provided by NsdService from discovery results, and the service was found on an
2216 // interface that has no app-usable Network).
2217 if (serviceInfo.getInterfaceIndex() != 0) {
2218 return serviceInfo.getInterfaceIndex();
2219 }
2220 return IFACE_IDX_ANY;
2221 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002222
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002223 String interfaceName = getNetworkInterfaceName(network);
2224 if (interfaceName == null) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002225 return IFACE_IDX_ANY;
2226 }
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002227 return getNetworkInterfaceIndexByName(interfaceName);
2228 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002229
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002230 private String getNetworkInterfaceName(@Nullable Network network) {
2231 if (network == null) {
2232 return null;
2233 }
2234 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
2235 if (cm == null) {
2236 Log.wtf(TAG, "No ConnectivityManager");
2237 return null;
2238 }
2239 final LinkProperties lp = cm.getLinkProperties(network);
2240 if (lp == null) {
2241 return null;
2242 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002243 // Only resolve on non-stacked interfaces
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002244 return lp.getInterfaceName();
2245 }
2246
2247 private int getNetworkInterfaceIndexByName(final String ifaceName) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002248 final NetworkInterface iface;
2249 try {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002250 iface = NetworkInterface.getByName(ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002251 } catch (SocketException e) {
2252 Log.e(TAG, "Error querying interface", e);
2253 return IFACE_IDX_ANY;
2254 }
2255
2256 if (iface == null) {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002257 Log.e(TAG, "Interface not found: " + ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002258 return IFACE_IDX_ANY;
2259 }
2260
2261 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002262 }
2263
Paul Hud44e1b72023-06-16 02:07:42 +00002264 private boolean stopResolveService(int transactionId) {
2265 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002266 }
2267
Paul Hud44e1b72023-06-16 02:07:42 +00002268 private boolean getAddrInfo(int transactionId, String hostname, int interfaceIdx) {
2269 return mMDnsManager.getServiceAddress(transactionId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002270 }
2271
Paul Hud44e1b72023-06-16 02:07:42 +00002272 private boolean stopGetAddrInfo(int transactionId) {
2273 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002274 }
2275
2276 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00002277 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2278 if (!PermissionUtils.checkDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002279
Paul Hub2e67d32023-04-18 05:50:14 +00002280 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
2281 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07002282 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00002283
2284 // Dump service and clients logs
2285 pw.println();
Paul Hu14667de2023-04-17 22:42:47 +08002286 pw.println("Logs:");
Paul Hub2e67d32023-04-18 05:50:14 +00002287 pw.increaseIndent();
2288 mServiceLogs.reverseDump(pw);
2289 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002290 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002291
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002292 private abstract static class ClientRequest {
Paul Hud44e1b72023-06-16 02:07:42 +00002293 private final int mTransactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002294 private final long mStartTimeMs;
Paul Hu812e9212023-06-20 06:24:53 +00002295 private int mFoundServiceCount = 0;
2296 private int mLostServiceCount = 0;
2297 private final Set<String> mServices = new ArraySet<>();
Paul Hua6bc4632023-06-26 01:18:29 +00002298 private boolean mIsServiceFromCache = false;
Paul Hubad6fe92023-07-24 21:25:22 +08002299 private int mSentQueryCount = NO_SENT_QUERY_COUNT;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002300
Paul Hu812e9212023-06-20 06:24:53 +00002301 private ClientRequest(int transactionId, long startTimeMs) {
Paul Hud44e1b72023-06-16 02:07:42 +00002302 mTransactionId = transactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002303 mStartTimeMs = startTimeMs;
2304 }
2305
Paul Hu812e9212023-06-20 06:24:53 +00002306 public long calculateRequestDurationMs(long stopTimeMs) {
Paul Hu777ed052023-06-19 13:35:15 +00002307 return stopTimeMs - mStartTimeMs;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002308 }
Paul Hu812e9212023-06-20 06:24:53 +00002309
2310 public void onServiceFound(String serviceName) {
2311 mFoundServiceCount++;
2312 if (mServices.size() <= MAX_SERVICES_COUNT_METRIC_PER_CLIENT) {
2313 mServices.add(serviceName);
2314 }
2315 }
2316
2317 public void onServiceLost() {
2318 mLostServiceCount++;
2319 }
2320
2321 public int getFoundServiceCount() {
2322 return mFoundServiceCount;
2323 }
2324
2325 public int getLostServiceCount() {
2326 return mLostServiceCount;
2327 }
2328
2329 public int getServicesCount() {
2330 return mServices.size();
2331 }
Paul Hua6bc4632023-06-26 01:18:29 +00002332
2333 public void setServiceFromCache(boolean isServiceFromCache) {
2334 mIsServiceFromCache = isServiceFromCache;
2335 }
2336
2337 public boolean isServiceFromCache() {
2338 return mIsServiceFromCache;
2339 }
Paul Hubad6fe92023-07-24 21:25:22 +08002340
2341 public void onQuerySent() {
2342 mSentQueryCount++;
2343 }
2344
2345 public int getSentQueryCount() {
2346 return mSentQueryCount;
2347 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002348 }
2349
2350 private static class LegacyClientRequest extends ClientRequest {
2351 private final int mRequestCode;
2352
Paul Hu812e9212023-06-20 06:24:53 +00002353 private LegacyClientRequest(int transactionId, int requestCode, long startTimeMs) {
2354 super(transactionId, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002355 mRequestCode = requestCode;
2356 }
2357 }
2358
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002359 private abstract static class JavaBackendClientRequest extends ClientRequest {
2360 @Nullable
2361 private final Network mRequestedNetwork;
2362
Paul Hu777ed052023-06-19 13:35:15 +00002363 private JavaBackendClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002364 long startTimeMs) {
2365 super(transactionId, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002366 mRequestedNetwork = requestedNetwork;
2367 }
2368
2369 @Nullable
2370 public Network getRequestedNetwork() {
2371 return mRequestedNetwork;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002372 }
2373 }
2374
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002375 private static class AdvertiserClientRequest extends JavaBackendClientRequest {
Paul Hu777ed052023-06-19 13:35:15 +00002376 private AdvertiserClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002377 long startTimeMs) {
2378 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002379 }
2380 }
2381
2382 private static class DiscoveryManagerRequest extends JavaBackendClientRequest {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002383 @NonNull
2384 private final MdnsListener mListener;
2385
Paul Hud44e1b72023-06-16 02:07:42 +00002386 private DiscoveryManagerRequest(int transactionId, @NonNull MdnsListener listener,
Paul Hu812e9212023-06-20 06:24:53 +00002387 @Nullable Network requestedNetwork, long startTimeMs) {
2388 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002389 mListener = listener;
2390 }
2391 }
2392
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002393 /* Information tracked per client */
2394 private class ClientInfo {
2395
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002396 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002397 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002398 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002399 private NsdServiceInfo mResolvedService;
2400
Paul Hud44e1b72023-06-16 02:07:42 +00002401 /* A map from client request ID (listenerKey) to the request */
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002402 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08002403
Luke Huangf7277ed2021-07-12 21:15:10 +08002404 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002405 private boolean mIsPreSClient = false;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002406 private final int mUid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002407 // The flag of using java backend if the client's target SDK >= U
2408 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002409 // Store client logs
2410 private final SharedLog mClientLogs;
Paul Hucdef3532023-06-18 14:47:35 +00002411 // Report the nsd metrics data
2412 private final NetworkNsdReportedMetrics mMetrics;
Luke Huangf7277ed2021-07-12 21:15:10 +08002413
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002414 private ClientInfo(INsdManagerCallback cb, int uid, boolean useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +00002415 SharedLog sharedLog, NetworkNsdReportedMetrics metrics) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002416 mCb = cb;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002417 mUid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002418 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002419 mClientLogs = sharedLog;
2420 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Paul Hucdef3532023-06-18 14:47:35 +00002421 mMetrics = metrics;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002422 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002423
2424 @Override
2425 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06002426 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07002427 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002428 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002429 sb.append("mUseJavaBackend ").append(mUseJavaBackend).append("\n");
2430 sb.append("mUid ").append(mUid).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002431 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002432 int clientRequestId = mClientRequests.keyAt(i);
2433 sb.append("clientRequestId ")
2434 .append(clientRequestId)
2435 .append(" transactionId ").append(mClientRequests.valueAt(i).mTransactionId)
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002436 .append(" type ").append(
2437 mClientRequests.valueAt(i).getClass().getSimpleName())
2438 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07002439 }
2440 return sb.toString();
2441 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002442
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002443 private boolean isPreSClient() {
2444 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08002445 }
2446
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002447 private void setPreSClient() {
2448 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08002449 }
2450
Paul Hu812e9212023-06-20 06:24:53 +00002451 private MdnsListener unregisterMdnsListenerFromRequest(ClientRequest request) {
Paul Hue4f5f252023-02-16 21:13:47 +08002452 final MdnsListener listener =
2453 ((DiscoveryManagerRequest) request).mListener;
2454 mMdnsDiscoveryManager.unregisterListener(
2455 listener.getListenedServiceType(), listener);
Paul Hu812e9212023-06-20 06:24:53 +00002456 return listener;
Paul Hue4f5f252023-02-16 21:13:47 +08002457 }
2458
Dave Plattfeff2af2014-03-07 14:48:22 -08002459 // Remove any pending requests from the global map when we get rid of a client,
2460 // and send cancellations to the daemon.
2461 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00002462 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09002463 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002464 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002465 final int clientRequestId = mClientRequests.keyAt(i);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002466 final ClientRequest request = mClientRequests.valueAt(i);
Paul Hud44e1b72023-06-16 02:07:42 +00002467 final int transactionId = request.mTransactionId;
2468 mTransactionIdToClientInfoMap.remove(transactionId);
paulhub2225702021-11-17 09:35:33 +08002469 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002470 Log.d(TAG, "Terminating clientRequestId " + clientRequestId
2471 + " transactionId " + transactionId
2472 + " type " + mClientRequests.get(clientRequestId));
paulhub2225702021-11-17 09:35:33 +08002473 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002474
2475 if (request instanceof DiscoveryManagerRequest) {
Paul Hu812e9212023-06-20 06:24:53 +00002476 final MdnsListener listener = unregisterMdnsListenerFromRequest(request);
2477 if (listener instanceof DiscoveryListener) {
2478 mMetrics.reportServiceDiscoveryStop(transactionId,
2479 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2480 request.getFoundServiceCount(),
2481 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002482 request.getServicesCount(),
2483 request.getSentQueryCount());
Paul Hu60149052023-07-31 14:26:08 +08002484 } else if (listener instanceof ResolutionListener) {
2485 mMetrics.reportServiceResolutionStop(transactionId,
2486 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Huddce5912023-08-01 10:26:49 +08002487 } else if (listener instanceof ServiceInfoListener) {
2488 mMetrics.reportServiceInfoCallbackUnregistered(transactionId,
2489 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2490 request.getFoundServiceCount(),
2491 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002492 request.isServiceFromCache(),
2493 request.getSentQueryCount());
Paul Hu812e9212023-06-20 06:24:53 +00002494 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002495 continue;
2496 }
2497
2498 if (request instanceof AdvertiserClientRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00002499 mAdvertiser.removeService(transactionId);
Paul Hu812e9212023-06-20 06:24:53 +00002500 mMetrics.reportServiceUnregistration(transactionId,
2501 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002502 continue;
2503 }
2504
2505 if (!(request instanceof LegacyClientRequest)) {
2506 throw new IllegalStateException("Unknown request type: " + request.getClass());
2507 }
2508
2509 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08002510 case NsdManager.DISCOVER_SERVICES:
Paul Hud44e1b72023-06-16 02:07:42 +00002511 stopServiceDiscovery(transactionId);
Paul Hu812e9212023-06-20 06:24:53 +00002512 mMetrics.reportServiceDiscoveryStop(transactionId,
2513 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2514 request.getFoundServiceCount(),
2515 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002516 request.getServicesCount(),
2517 NO_SENT_QUERY_COUNT);
Dave Plattfeff2af2014-03-07 14:48:22 -08002518 break;
2519 case NsdManager.RESOLVE_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002520 stopResolveService(transactionId);
Paul Hu60149052023-07-31 14:26:08 +08002521 mMetrics.reportServiceResolutionStop(transactionId,
2522 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Dave Plattfeff2af2014-03-07 14:48:22 -08002523 break;
2524 case NsdManager.REGISTER_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002525 unregisterService(transactionId);
Paul Hu812e9212023-06-20 06:24:53 +00002526 mMetrics.reportServiceUnregistration(transactionId,
2527 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Dave Plattfeff2af2014-03-07 14:48:22 -08002528 break;
2529 default:
2530 break;
2531 }
2532 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002533 mClientRequests.clear();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002534 updateMulticastLock();
2535 }
2536
2537 /**
2538 * Returns true if this client has any Java backend request that requests one of the given
2539 * networks.
2540 */
2541 boolean hasAnyJavaBackendRequestForNetworks(@NonNull ArraySet<Network> networks) {
2542 for (int i = 0; i < mClientRequests.size(); i++) {
2543 final ClientRequest req = mClientRequests.valueAt(i);
2544 if (!(req instanceof JavaBackendClientRequest)) {
2545 continue;
2546 }
2547 final Network reqNetwork = ((JavaBackendClientRequest) mClientRequests.valueAt(i))
2548 .getRequestedNetwork();
2549 if (MdnsUtils.isAnyNetworkMatched(reqNetwork, networks)) {
2550 return true;
2551 }
2552 }
2553 return false;
Dave Plattfeff2af2014-03-07 14:48:22 -08002554 }
2555
Paul Hud44e1b72023-06-16 02:07:42 +00002556 // mClientRequests is a sparse array of client request id -> ClientRequest. For a given
2557 // transaction id, return the corresponding client request id.
2558 private int getClientRequestId(final int transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002559 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002560 if (mClientRequests.valueAt(i).mTransactionId == transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002561 return mClientRequests.keyAt(i);
2562 }
Christopher Lane74411222014-04-25 18:39:07 -07002563 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002564 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07002565 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002566
Paul Hub2e67d32023-04-18 05:50:14 +00002567 private void log(String message) {
2568 mClientLogs.log(message);
2569 }
2570
Paul Hu812e9212023-06-20 06:24:53 +00002571 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info, int transactionId) {
2572 mMetrics.reportServiceDiscoveryStarted(transactionId);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002573 try {
2574 mCb.onDiscoverServicesStarted(listenerKey, info);
2575 } catch (RemoteException e) {
2576 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
2577 }
2578 }
Paul Hu812e9212023-06-20 06:24:53 +00002579 void onDiscoverServicesFailedImmediately(int listenerKey, int error) {
2580 onDiscoverServicesFailed(listenerKey, error, NO_TRANSACTION, 0L /* durationMs */);
2581 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002582
Paul Hu812e9212023-06-20 06:24:53 +00002583 void onDiscoverServicesFailed(int listenerKey, int error, int transactionId,
2584 long durationMs) {
2585 mMetrics.reportServiceDiscoveryFailed(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002586 try {
2587 mCb.onDiscoverServicesFailed(listenerKey, error);
2588 } catch (RemoteException e) {
2589 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
2590 }
2591 }
2592
Paul Hu812e9212023-06-20 06:24:53 +00002593 void onServiceFound(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2594 request.onServiceFound(info.getServiceName());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002595 try {
2596 mCb.onServiceFound(listenerKey, info);
2597 } catch (RemoteException e) {
2598 Log.e(TAG, "Error calling onServiceFound(", e);
2599 }
2600 }
2601
Paul Hu812e9212023-06-20 06:24:53 +00002602 void onServiceLost(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2603 request.onServiceLost();
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002604 try {
2605 mCb.onServiceLost(listenerKey, info);
2606 } catch (RemoteException e) {
2607 Log.e(TAG, "Error calling onServiceLost(", e);
2608 }
2609 }
2610
2611 void onStopDiscoveryFailed(int listenerKey, int error) {
2612 try {
2613 mCb.onStopDiscoveryFailed(listenerKey, error);
2614 } catch (RemoteException e) {
2615 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
2616 }
2617 }
2618
Paul Hu812e9212023-06-20 06:24:53 +00002619 void onStopDiscoverySucceeded(int listenerKey, ClientRequest request) {
2620 mMetrics.reportServiceDiscoveryStop(
2621 request.mTransactionId,
2622 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2623 request.getFoundServiceCount(),
2624 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002625 request.getServicesCount(),
2626 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002627 try {
2628 mCb.onStopDiscoverySucceeded(listenerKey);
2629 } catch (RemoteException e) {
2630 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
2631 }
2632 }
2633
Paul Hu777ed052023-06-19 13:35:15 +00002634 void onRegisterServiceFailedImmediately(int listenerKey, int error) {
Paul Hu812e9212023-06-20 06:24:53 +00002635 onRegisterServiceFailed(listenerKey, error, NO_TRANSACTION, 0L /* durationMs */);
Paul Hu777ed052023-06-19 13:35:15 +00002636 }
2637
2638 void onRegisterServiceFailed(int listenerKey, int error, int transactionId,
2639 long durationMs) {
2640 mMetrics.reportServiceRegistrationFailed(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002641 try {
2642 mCb.onRegisterServiceFailed(listenerKey, error);
2643 } catch (RemoteException e) {
2644 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2645 }
2646 }
2647
Paul Hu777ed052023-06-19 13:35:15 +00002648 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info, int transactionId,
2649 long durationMs) {
2650 mMetrics.reportServiceRegistrationSucceeded(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002651 try {
2652 mCb.onRegisterServiceSucceeded(listenerKey, info);
2653 } catch (RemoteException e) {
2654 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2655 }
2656 }
2657
2658 void onUnregisterServiceFailed(int listenerKey, int error) {
2659 try {
2660 mCb.onUnregisterServiceFailed(listenerKey, error);
2661 } catch (RemoteException e) {
2662 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2663 }
2664 }
2665
Paul Hu777ed052023-06-19 13:35:15 +00002666 void onUnregisterServiceSucceeded(int listenerKey, int transactionId, long durationMs) {
2667 mMetrics.reportServiceUnregistration(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002668 try {
2669 mCb.onUnregisterServiceSucceeded(listenerKey);
2670 } catch (RemoteException e) {
2671 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2672 }
2673 }
2674
Paul Hua6bc4632023-06-26 01:18:29 +00002675 void onResolveServiceFailedImmediately(int listenerKey, int error) {
2676 onResolveServiceFailed(listenerKey, error, NO_TRANSACTION, 0L /* durationMs */);
2677 }
2678
2679 void onResolveServiceFailed(int listenerKey, int error, int transactionId,
2680 long durationMs) {
2681 mMetrics.reportServiceResolutionFailed(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002682 try {
2683 mCb.onResolveServiceFailed(listenerKey, error);
2684 } catch (RemoteException e) {
2685 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2686 }
2687 }
2688
Paul Hua6bc4632023-06-26 01:18:29 +00002689 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info,
2690 ClientRequest request) {
2691 mMetrics.reportServiceResolved(
2692 request.mTransactionId,
2693 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hubad6fe92023-07-24 21:25:22 +08002694 request.isServiceFromCache(),
2695 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002696 try {
2697 mCb.onResolveServiceSucceeded(listenerKey, info);
2698 } catch (RemoteException e) {
2699 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2700 }
2701 }
Paul Hub58deb72022-12-26 09:24:42 +00002702
2703 void onStopResolutionFailed(int listenerKey, int error) {
2704 try {
2705 mCb.onStopResolutionFailed(listenerKey, error);
2706 } catch (RemoteException e) {
2707 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2708 }
2709 }
2710
Paul Hu60149052023-07-31 14:26:08 +08002711 void onStopResolutionSucceeded(int listenerKey, ClientRequest request) {
2712 mMetrics.reportServiceResolutionStop(
2713 request.mTransactionId,
2714 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hub58deb72022-12-26 09:24:42 +00002715 try {
2716 mCb.onStopResolutionSucceeded(listenerKey);
2717 } catch (RemoteException e) {
2718 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2719 }
2720 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002721
2722 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
Paul Huddce5912023-08-01 10:26:49 +08002723 mMetrics.reportServiceInfoCallbackRegistrationFailed(NO_TRANSACTION);
Paul Hu18aeccc2022-12-27 08:48:48 +00002724 try {
2725 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2726 } catch (RemoteException e) {
2727 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2728 }
2729 }
2730
Paul Huddce5912023-08-01 10:26:49 +08002731 void onServiceInfoCallbackRegistered(int transactionId) {
2732 mMetrics.reportServiceInfoCallbackRegistered(transactionId);
2733 }
2734
2735 void onServiceUpdated(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2736 request.onServiceFound(info.getServiceName());
Paul Hu18aeccc2022-12-27 08:48:48 +00002737 try {
2738 mCb.onServiceUpdated(listenerKey, info);
2739 } catch (RemoteException e) {
2740 Log.e(TAG, "Error calling onServiceUpdated", e);
2741 }
2742 }
2743
Paul Huddce5912023-08-01 10:26:49 +08002744 void onServiceUpdatedLost(int listenerKey, ClientRequest request) {
2745 request.onServiceLost();
Paul Hu18aeccc2022-12-27 08:48:48 +00002746 try {
2747 mCb.onServiceUpdatedLost(listenerKey);
2748 } catch (RemoteException e) {
2749 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2750 }
2751 }
2752
Paul Huddce5912023-08-01 10:26:49 +08002753 void onServiceInfoCallbackUnregistered(int listenerKey, ClientRequest request) {
2754 mMetrics.reportServiceInfoCallbackUnregistered(
2755 request.mTransactionId,
2756 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2757 request.getFoundServiceCount(),
2758 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002759 request.isServiceFromCache(),
2760 request.getSentQueryCount());
Paul Hu18aeccc2022-12-27 08:48:48 +00002761 try {
2762 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2763 } catch (RemoteException e) {
2764 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2765 }
2766 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002767 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002768}