blob: 415159dcf18c04c4f8614a7adb7dcebec730b227 [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 Hu14667de2023-04-17 22:42:47 +0800179 private static final SharedLog LOGGER = new SharedLog("serviceDiscovery");
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700180
Hugo Benichi32be63d2017-04-05 14:06:11 +0900181 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900182 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +0800183 private final MDnsManager mMDnsManager;
184 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900185 @NonNull
186 private final Dependencies mDeps;
187 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800188 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900189 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800190 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900191 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800192 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900193 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900194 private final MdnsAdvertiser mAdvertiser;
Paul Hu777ed052023-06-19 13:35:15 +0000195 @NonNull
196 private final Clock mClock;
Paul Hu14667de2023-04-17 22:42:47 +0800197 private final SharedLog mServiceLogs = LOGGER.forSubComponent(TAG);
Paul Hu23fa2022023-01-13 22:57:24 +0800198 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800199 // state machine thread. If change this outside state machine, it will need to introduce
200 // synchronization.
201 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800202 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700203
204 /**
205 * Clients receiving asynchronous messages
206 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900207 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700208
Paul Hud44e1b72023-06-16 02:07:42 +0000209 /* A map from transaction(unique) id to client info */
210 private final SparseArray<ClientInfo> mTransactionIdToClientInfoMap = new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700211
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900212 // Note this is not final to avoid depending on the Wi-Fi service starting before NsdService
213 @Nullable
214 private WifiManager.MulticastLock mHeldMulticastLock;
215 // Fulfilled network requests that require the Wi-Fi lock: key is the obtained Network
216 // (non-null), value is the requested Network (nullable)
217 @NonNull
218 private final ArraySet<Network> mWifiLockRequiredNetworks = new ArraySet<>();
219 @NonNull
220 private final ArraySet<Integer> mRunningAppActiveUids = new ArraySet<>();
221
Luke Huang05298582021-06-13 16:52:05 +0000222 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700223
Hugo Benichi32be63d2017-04-05 14:06:11 +0900224 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700225 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800226 // The count of the connected legacy clients.
227 private int mLegacyClientCount = 0;
Paul Hub2e67d32023-04-18 05:50:14 +0000228 // The number of client that ever connected.
229 private int mClientNumberId = 1;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700230
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900231 private final RemoteCallbackList<IOffloadEngine> mOffloadEngines =
232 new RemoteCallbackList<>();
233
234 private static class OffloadEngineInfo {
235 @NonNull final String mInterfaceName;
236 final long mOffloadCapabilities;
237 final long mOffloadType;
238 @NonNull final IOffloadEngine mOffloadEngine;
239
240 OffloadEngineInfo(@NonNull IOffloadEngine offloadEngine,
241 @NonNull String interfaceName, long capabilities, long offloadType) {
242 this.mOffloadEngine = offloadEngine;
243 this.mInterfaceName = interfaceName;
244 this.mOffloadCapabilities = capabilities;
245 this.mOffloadType = offloadType;
246 }
247 }
248
Paul Hu812e9212023-06-20 06:24:53 +0000249 @VisibleForTesting
250 static class MdnsListener implements MdnsServiceBrowserListener {
Paul Hud44e1b72023-06-16 02:07:42 +0000251 protected final int mClientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800252 protected final int mTransactionId;
253 @NonNull
254 protected final NsdServiceInfo mReqServiceInfo;
255 @NonNull
256 protected final String mListenedServiceType;
257
Paul Hud44e1b72023-06-16 02:07:42 +0000258 MdnsListener(int clientRequestId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
Paul Hu23fa2022023-01-13 22:57:24 +0800259 @NonNull String listenedServiceType) {
Paul Hud44e1b72023-06-16 02:07:42 +0000260 mClientRequestId = clientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800261 mTransactionId = transactionId;
262 mReqServiceInfo = reqServiceInfo;
263 mListenedServiceType = listenedServiceType;
264 }
265
266 @NonNull
267 public String getListenedServiceType() {
268 return mListenedServiceType;
269 }
270
271 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000272 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
273 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800274
275 @Override
276 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
277
278 @Override
279 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
280
281 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000282 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
283 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800284
285 @Override
286 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
287
288 @Override
289 public void onSearchStoppedWithError(int error) { }
290
291 @Override
292 public void onSearchFailedToStart() { }
293
294 @Override
295 public void onDiscoveryQuerySent(@NonNull List<String> subtypes, int transactionId) { }
296
297 @Override
298 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
299 }
300
301 private class DiscoveryListener extends MdnsListener {
302
Paul Hud44e1b72023-06-16 02:07:42 +0000303 DiscoveryListener(int clientRequestId, int transactionId,
304 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
305 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800306 }
307
308 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000309 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
310 boolean isServiceFromCache) {
Paul Hu019621e2023-01-13 23:26:49 +0800311 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
312 NsdManager.SERVICE_FOUND,
Paul Hua6bc4632023-06-26 01:18:29 +0000313 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu23fa2022023-01-13 22:57:24 +0800314 }
315
316 @Override
317 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800318 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
319 NsdManager.SERVICE_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000320 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800321 }
322 }
323
Paul Hu75069ed2023-01-14 00:31:09 +0800324 private class ResolutionListener extends MdnsListener {
325
Paul Hud44e1b72023-06-16 02:07:42 +0000326 ResolutionListener(int clientRequestId, int transactionId,
327 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
328 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800329 }
330
331 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000332 public void onServiceFound(MdnsServiceInfo serviceInfo, boolean isServiceFromCache) {
Paul Hu75069ed2023-01-14 00:31:09 +0800333 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
334 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
Paul Hua6bc4632023-06-26 01:18:29 +0000335 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu75069ed2023-01-14 00:31:09 +0800336 }
337 }
338
Paul Hu30bd70d2023-02-07 13:20:56 +0000339 private class ServiceInfoListener extends MdnsListener {
340
Paul Hud44e1b72023-06-16 02:07:42 +0000341 ServiceInfoListener(int clientRequestId, int transactionId,
342 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
343 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +0000344 }
345
346 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000347 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
348 boolean isServiceFromCache) {
Paul Hu30bd70d2023-02-07 13:20:56 +0000349 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
350 NsdManager.SERVICE_UPDATED,
Paul Hua6bc4632023-06-26 01:18:29 +0000351 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu30bd70d2023-02-07 13:20:56 +0000352 }
353
354 @Override
355 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) {
356 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
357 NsdManager.SERVICE_UPDATED,
Paul Hud44e1b72023-06-16 02:07:42 +0000358 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000359 }
360
361 @Override
362 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) {
363 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
364 NsdManager.SERVICE_UPDATED_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000365 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000366 }
367 }
368
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900369 private class SocketRequestMonitor implements MdnsSocketProvider.SocketRequestMonitor {
370 @Override
371 public void onSocketRequestFulfilled(@Nullable Network socketNetwork,
372 @NonNull MdnsInterfaceSocket socket, @NonNull int[] transports) {
373 // The network may be null for Wi-Fi SoftAp interfaces (tethering), but there is no APF
374 // filtering on such interfaces, so taking the multicast lock is not necessary to
375 // disable APF filtering of multicast.
376 if (socketNetwork == null
377 || !CollectionUtils.contains(transports, TRANSPORT_WIFI)
378 || CollectionUtils.contains(transports, TRANSPORT_VPN)) {
379 return;
380 }
381
382 if (mWifiLockRequiredNetworks.add(socketNetwork)) {
383 updateMulticastLock();
384 }
385 }
386
387 @Override
388 public void onSocketDestroyed(@Nullable Network socketNetwork,
389 @NonNull MdnsInterfaceSocket socket) {
390 if (mWifiLockRequiredNetworks.remove(socketNetwork)) {
391 updateMulticastLock();
392 }
393 }
394 }
395
396 private class UidImportanceListener implements ActivityManager.OnUidImportanceListener {
397 private final Handler mHandler;
398
399 private UidImportanceListener(Handler handler) {
400 mHandler = handler;
401 }
402
403 @Override
404 public void onUidImportance(int uid, int importance) {
405 mHandler.post(() -> handleUidImportanceChanged(uid, importance));
406 }
407 }
408
409 private void handleUidImportanceChanged(int uid, int importance) {
410 // Lower importance values are more "important"
411 final boolean modified = importance <= mRunningAppActiveImportanceCutoff
412 ? mRunningAppActiveUids.add(uid)
413 : mRunningAppActiveUids.remove(uid);
414 if (modified) {
415 updateMulticastLock();
416 }
417 }
418
419 /**
420 * Take or release the lock based on updated internal state.
421 *
422 * This determines whether the lock needs to be held based on
423 * {@link #mWifiLockRequiredNetworks}, {@link #mRunningAppActiveUids} and
424 * {@link ClientInfo#mClientRequests}, so it must be called after any of the these have been
425 * updated.
426 */
427 private void updateMulticastLock() {
428 final int needsLockUid = getMulticastLockNeededUid();
429 if (needsLockUid >= 0 && mHeldMulticastLock == null) {
430 final WifiManager wm = mContext.getSystemService(WifiManager.class);
431 if (wm == null) {
432 Log.wtf(TAG, "Got a TRANSPORT_WIFI network without WifiManager");
433 return;
434 }
435 mHeldMulticastLock = wm.createMulticastLock(TAG);
436 mHeldMulticastLock.acquire();
437 mServiceLogs.log("Taking multicast lock for uid " + needsLockUid);
438 } else if (needsLockUid < 0 && mHeldMulticastLock != null) {
439 mHeldMulticastLock.release();
440 mHeldMulticastLock = null;
441 mServiceLogs.log("Released multicast lock");
442 }
443 }
444
445 /**
446 * @return The UID of an app requiring the multicast lock, or -1 if none.
447 */
448 private int getMulticastLockNeededUid() {
449 if (mWifiLockRequiredNetworks.size() == 0) {
450 // Return early if NSD is not active, or not on any relevant network
451 return -1;
452 }
Paul Hud44e1b72023-06-16 02:07:42 +0000453 for (int i = 0; i < mTransactionIdToClientInfoMap.size(); i++) {
454 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.valueAt(i);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900455 if (!mRunningAppActiveUids.contains(clientInfo.mUid)) {
456 // Ignore non-active UIDs
457 continue;
458 }
459
460 if (clientInfo.hasAnyJavaBackendRequestForNetworks(mWifiLockRequiredNetworks)) {
461 return clientInfo.mUid;
462 }
463 }
464 return -1;
465 }
466
Paul Hu019621e2023-01-13 23:26:49 +0800467 /**
468 * Data class of mdns service callback information.
469 */
470 private static class MdnsEvent {
Paul Hud44e1b72023-06-16 02:07:42 +0000471 final int mClientRequestId;
Paul Hu019621e2023-01-13 23:26:49 +0800472 @NonNull
Paul Hu019621e2023-01-13 23:26:49 +0800473 final MdnsServiceInfo mMdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000474 final boolean mIsServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800475
Paul Hud44e1b72023-06-16 02:07:42 +0000476 MdnsEvent(int clientRequestId, @NonNull MdnsServiceInfo mdnsServiceInfo) {
Paul Hua6bc4632023-06-26 01:18:29 +0000477 this(clientRequestId, mdnsServiceInfo, false /* isServiceFromCache */);
478 }
479
480 MdnsEvent(int clientRequestId, @NonNull MdnsServiceInfo mdnsServiceInfo,
481 boolean isServiceFromCache) {
Paul Hud44e1b72023-06-16 02:07:42 +0000482 mClientRequestId = clientRequestId;
Paul Hu019621e2023-01-13 23:26:49 +0800483 mMdnsServiceInfo = mdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000484 mIsServiceFromCache = isServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800485 }
486 }
487
Irfan Sheriff75006652012-04-17 23:15:29 -0700488 private class NsdStateMachine extends StateMachine {
489
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700490 private final DefaultState mDefaultState = new DefaultState();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700491 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700492
493 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700494 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900495 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700496 }
497
Luke Huang92860f92021-06-23 06:29:30 +0000498 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800499 if (mIsDaemonStarted) {
500 if (DBG) Log.d(TAG, "Daemon is already started.");
501 return;
502 }
503 mMDnsManager.registerEventListener(mMDnsEventCallback);
504 mMDnsManager.startDaemon();
505 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000506 maybeScheduleStop();
Paul Hub2e67d32023-04-18 05:50:14 +0000507 mServiceLogs.log("Start mdns_responder daemon");
Luke Huang05298582021-06-13 16:52:05 +0000508 }
509
paulhu2b9ed952022-02-10 21:58:32 +0800510 private void maybeStopDaemon() {
511 if (!mIsDaemonStarted) {
512 if (DBG) Log.d(TAG, "Daemon has not been started.");
513 return;
514 }
515 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
516 mMDnsManager.stopDaemon();
517 mIsDaemonStarted = false;
Paul Hub2e67d32023-04-18 05:50:14 +0000518 mServiceLogs.log("Stop mdns_responder daemon");
paulhu2b9ed952022-02-10 21:58:32 +0800519 }
520
Luke Huang92860f92021-06-23 06:29:30 +0000521 private boolean isAnyRequestActive() {
Paul Hud44e1b72023-06-16 02:07:42 +0000522 return mTransactionIdToClientInfoMap.size() != 0;
Luke Huang92860f92021-06-23 06:29:30 +0000523 }
524
525 private void scheduleStop() {
526 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
527 }
528 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800529 // The native daemon should stay alive and can't be cleanup
530 // if any legacy client connected.
531 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000532 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000533 }
534 }
535
Luke Huang92860f92021-06-23 06:29:30 +0000536 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000537 this.removeMessages(NsdManager.DAEMON_CLEANUP);
538 }
539
Paul Hu23fa2022023-01-13 22:57:24 +0800540 private void maybeStartMonitoringSockets() {
541 if (mIsMonitoringSocketsStarted) {
542 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
543 return;
544 }
545
546 mMdnsSocketProvider.startMonitoringSockets();
547 mIsMonitoringSocketsStarted = true;
548 }
549
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900550 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
551 if (!mIsMonitoringSocketsStarted) return;
552 if (isAnyRequestActive()) return;
553
Paul Hu58f20602023-02-18 11:41:07 +0800554 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800555 mIsMonitoringSocketsStarted = false;
556 }
557
Hugo Benichi803a2f02017-04-24 11:35:06 +0900558 NsdStateMachine(String name, Handler handler) {
559 super(name, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -0700560 addState(mDefaultState);
Irfan Sheriff75006652012-04-17 23:15:29 -0700561 addState(mEnabledState, mDefaultState);
paulhu5568f452021-11-30 13:31:29 +0800562 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900563 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700564 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700565 }
566
567 class DefaultState extends State {
568 @Override
569 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900570 final ClientInfo cInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000571 final int clientRequestId = msg.arg2;
Irfan Sheriff75006652012-04-17 23:15:29 -0700572 switch (msg.what) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900573 case NsdManager.REGISTER_CLIENT:
Paul Hu2e0a88c2023-03-09 16:05:01 +0800574 final ConnectorArgs arg = (ConnectorArgs) msg.obj;
575 final INsdManagerCallback cb = arg.callback;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900576 try {
Paul Hu2e0a88c2023-03-09 16:05:01 +0800577 cb.asBinder().linkToDeath(arg.connector, 0);
Paul Hub2e67d32023-04-18 05:50:14 +0000578 final String tag = "Client" + arg.uid + "-" + mClientNumberId++;
Paul Hu777ed052023-06-19 13:35:15 +0000579 final NetworkNsdReportedMetrics metrics =
580 mDeps.makeNetworkNsdReportedMetrics(
581 !arg.useJavaBackend, (int) mClock.elapsedRealtime());
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900582 cInfo = new ClientInfo(cb, arg.uid, arg.useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +0000583 mServiceLogs.forSubComponent(tag), metrics);
Paul Hu2e0a88c2023-03-09 16:05:01 +0800584 mClients.put(arg.connector, cInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900585 } catch (RemoteException e) {
Paul Hud44e1b72023-06-16 02:07:42 +0000586 Log.w(TAG, "Client request id " + clientRequestId
587 + " has already died");
Irfan Sheriff75006652012-04-17 23:15:29 -0700588 }
589 break;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900590 case NsdManager.UNREGISTER_CLIENT:
591 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
592 cInfo = mClients.remove(connector);
Dave Plattfeff2af2014-03-07 14:48:22 -0800593 if (cInfo != null) {
594 cInfo.expungeAllRequests();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900595 if (cInfo.isPreSClient()) {
Luke Huangf7277ed2021-07-12 21:15:10 +0800596 mLegacyClientCount -= 1;
597 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800598 }
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900599 maybeStopMonitoringSocketsIfNoActiveRequest();
Luke Huangf7277ed2021-07-12 21:15:10 +0800600 maybeScheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700601 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700602 case NsdManager.DISCOVER_SERVICES:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900603 cInfo = getClientInfoForReply(msg);
604 if (cInfo != null) {
Paul Hu812e9212023-06-20 06:24:53 +0000605 cInfo.onDiscoverServicesFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000606 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900607 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700608 break;
609 case NsdManager.STOP_DISCOVERY:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900610 cInfo = getClientInfoForReply(msg);
611 if (cInfo != null) {
612 cInfo.onStopDiscoveryFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000613 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900614 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700615 break;
616 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900617 cInfo = getClientInfoForReply(msg);
618 if (cInfo != null) {
Paul Hu777ed052023-06-19 13:35:15 +0000619 cInfo.onRegisterServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000620 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900621 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700622 break;
623 case NsdManager.UNREGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900624 cInfo = getClientInfoForReply(msg);
625 if (cInfo != null) {
626 cInfo.onUnregisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000627 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900628 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700629 break;
630 case NsdManager.RESOLVE_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900631 cInfo = getClientInfoForReply(msg);
632 if (cInfo != null) {
Paul Hua6bc4632023-06-26 01:18:29 +0000633 cInfo.onResolveServiceFailedImmediately(
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;
Paul Hub58deb72022-12-26 09:24:42 +0000637 case NsdManager.STOP_RESOLUTION:
638 cInfo = getClientInfoForReply(msg);
639 if (cInfo != null) {
640 cInfo.onStopResolutionFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000641 clientRequestId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hub58deb72022-12-26 09:24:42 +0000642 }
643 break;
Paul Hu18aeccc2022-12-27 08:48:48 +0000644 case NsdManager.REGISTER_SERVICE_CALLBACK:
645 cInfo = getClientInfoForReply(msg);
646 if (cInfo != null) {
647 cInfo.onServiceInfoCallbackRegistrationFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000648 clientRequestId, NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +0000649 }
650 break;
Luke Huang05298582021-06-13 16:52:05 +0000651 case NsdManager.DAEMON_CLEANUP:
paulhu2b9ed952022-02-10 21:58:32 +0800652 maybeStopDaemon();
Luke Huang05298582021-06-13 16:52:05 +0000653 break;
Luke Huangf7277ed2021-07-12 21:15:10 +0800654 // This event should be only sent by the legacy (target SDK < S) clients.
655 // Mark the sending client as legacy.
656 case NsdManager.DAEMON_STARTUP:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900657 cInfo = getClientInfoForReply(msg);
Luke Huangf7277ed2021-07-12 21:15:10 +0800658 if (cInfo != null) {
659 cancelStop();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900660 cInfo.setPreSClient();
Luke Huangf7277ed2021-07-12 21:15:10 +0800661 mLegacyClientCount += 1;
662 maybeStartDaemon();
663 }
664 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700665 default:
paulhub2225702021-11-17 09:35:33 +0800666 Log.e(TAG, "Unhandled " + msg);
Irfan Sheriff75006652012-04-17 23:15:29 -0700667 return NOT_HANDLED;
668 }
669 return HANDLED;
670 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900671
672 private ClientInfo getClientInfoForReply(Message msg) {
673 final ListenerArgs args = (ListenerArgs) msg.obj;
674 return mClients.get(args.connector);
675 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700676 }
677
Irfan Sheriff75006652012-04-17 23:15:29 -0700678 class EnabledState extends State {
679 @Override
680 public void enter() {
681 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700682 }
683
684 @Override
685 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000686 // TODO: it is incorrect to stop the daemon without expunging all requests
687 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000688 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700689 }
690
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700691 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900692 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800693 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700694 return true;
695 }
696 return false;
697 }
698
Paul Hud44e1b72023-06-16 02:07:42 +0000699 private void storeLegacyRequestMap(int clientRequestId, int transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +0000700 ClientInfo clientInfo, int what, long startTimeMs) {
701 clientInfo.mClientRequests.put(clientRequestId,
702 new LegacyClientRequest(transactionId, what, startTimeMs));
Paul Hud44e1b72023-06-16 02:07:42 +0000703 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000704 // Remove the cleanup event because here comes a new request.
705 cancelStop();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700706 }
707
Paul Hud44e1b72023-06-16 02:07:42 +0000708 private void storeAdvertiserRequestMap(int clientRequestId, int transactionId,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900709 ClientInfo clientInfo, @Nullable Network requestedNetwork) {
Paul Hu777ed052023-06-19 13:35:15 +0000710 clientInfo.mClientRequests.put(clientRequestId, new AdvertiserClientRequest(
Paul Hu812e9212023-06-20 06:24:53 +0000711 transactionId, requestedNetwork, mClock.elapsedRealtime()));
Paul Hud44e1b72023-06-16 02:07:42 +0000712 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900713 updateMulticastLock();
Paul Hu23fa2022023-01-13 22:57:24 +0800714 }
715
Paul Hud44e1b72023-06-16 02:07:42 +0000716 private void removeRequestMap(
717 int clientRequestId, int transactionId, ClientInfo clientInfo) {
718 final ClientRequest existing = clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900719 if (existing == null) return;
Paul Hud44e1b72023-06-16 02:07:42 +0000720 clientInfo.mClientRequests.remove(clientRequestId);
721 mTransactionIdToClientInfoMap.remove(transactionId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900722
723 if (existing instanceof LegacyClientRequest) {
724 maybeScheduleStop();
725 } else {
726 maybeStopMonitoringSocketsIfNoActiveRequest();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900727 updateMulticastLock();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900728 }
729 }
730
Paul Hud44e1b72023-06-16 02:07:42 +0000731 private void storeDiscoveryManagerRequestMap(int clientRequestId, int transactionId,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900732 MdnsListener listener, ClientInfo clientInfo,
733 @Nullable Network requestedNetwork) {
Paul Hu777ed052023-06-19 13:35:15 +0000734 clientInfo.mClientRequests.put(clientRequestId, new DiscoveryManagerRequest(
Paul Hu812e9212023-06-20 06:24:53 +0000735 transactionId, listener, requestedNetwork, mClock.elapsedRealtime()));
Paul Hud44e1b72023-06-16 02:07:42 +0000736 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900737 updateMulticastLock();
Paul Hu23fa2022023-01-13 22:57:24 +0800738 }
739
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900740 /**
741 * Truncate a service name to up to 63 UTF-8 bytes.
742 *
743 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
744 * names used in registerService follows historical behavior (see mdnsresponder
745 * handle_regservice_request).
746 */
747 @NonNull
748 private String truncateServiceName(@NonNull String originalName) {
Yuyang Huangde802c82023-05-02 17:14:22 +0900749 return MdnsUtils.truncateServiceName(originalName, MAX_LABEL_LENGTH);
Paul Hu23fa2022023-01-13 22:57:24 +0800750 }
751
Paul Hud44e1b72023-06-16 02:07:42 +0000752 private void stopDiscoveryManagerRequest(ClientRequest request, int clientRequestId,
753 int transactionId, ClientInfo clientInfo) {
Paul Hue4f5f252023-02-16 21:13:47 +0800754 clientInfo.unregisterMdnsListenerFromRequest(request);
Paul Hud44e1b72023-06-16 02:07:42 +0000755 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hue4f5f252023-02-16 21:13:47 +0800756 }
757
Irfan Sheriff75006652012-04-17 23:15:29 -0700758 @Override
759 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900760 final ClientInfo clientInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000761 final int transactionId;
762 final int clientRequestId = msg.arg2;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900763 final ListenerArgs args;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900764 final OffloadEngineInfo offloadEngineInfo;
Irfan Sheriff75006652012-04-17 23:15:29 -0700765 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800766 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800767 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900768 args = (ListenerArgs) msg.obj;
769 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000770 // If the binder death notification for a INsdManagerCallback was received
771 // before any calls are received by NsdService, the clientInfo would be
772 // cleared and cause NPE. Add a null check here to prevent this corner case.
773 if (clientInfo == null) {
774 Log.e(TAG, "Unknown connector in discovery");
775 break;
776 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700777
778 if (requestLimitReached(clientInfo)) {
Paul Hu812e9212023-06-20 06:24:53 +0000779 clientInfo.onDiscoverServicesFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000780 clientRequestId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriff75006652012-04-17 23:15:29 -0700781 break;
782 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700783
Paul Hu23fa2022023-01-13 22:57:24 +0800784 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000785 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900786 final Pair<String, String> typeAndSubtype =
787 parseTypeAndSubtype(info.getServiceType());
788 final String serviceType = typeAndSubtype == null
789 ? null : typeAndSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800790 if (clientInfo.mUseJavaBackend
791 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900792 || useDiscoveryManagerForType(serviceType)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800793 if (serviceType == null) {
Paul Hu812e9212023-06-20 06:24:53 +0000794 clientInfo.onDiscoverServicesFailedImmediately(
795 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu23fa2022023-01-13 22:57:24 +0800796 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700797 }
Paul Hu23fa2022023-01-13 22:57:24 +0800798
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900799 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800800 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +0000801 final MdnsListener listener = new DiscoveryListener(clientRequestId,
802 transactionId, info, listenServiceType);
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900803 final MdnsSearchOptions.Builder optionsBuilder =
804 MdnsSearchOptions.newBuilder()
805 .setNetwork(info.getNetwork())
Yuyang Huangff963222023-06-01 18:42:42 +0900806 .setRemoveExpiredService(true)
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900807 .setIsPassiveMode(true);
808 if (typeAndSubtype.second != null) {
809 // The parsing ensures subtype starts with an underscore.
810 // MdnsSearchOptions expects the underscore to not be present.
811 optionsBuilder.addSubtype(typeAndSubtype.second.substring(1));
812 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900813 mMdnsDiscoveryManager.registerListener(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900814 listenServiceType, listener, optionsBuilder.build());
Paul Hud44e1b72023-06-16 02:07:42 +0000815 storeDiscoveryManagerRequestMap(clientRequestId, transactionId,
816 listener, clientInfo, info.getNetwork());
Paul Hu812e9212023-06-20 06:24:53 +0000817 clientInfo.onDiscoverServicesStarted(
818 clientRequestId, info, transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +0000819 clientInfo.log("Register a DiscoveryListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +0000820 + " for service type:" + listenServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700821 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800822 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000823 if (discoverServices(transactionId, info)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800824 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +0000825 Log.d(TAG, "Discover " + msg.arg2 + " " + transactionId
Paul Hu23fa2022023-01-13 22:57:24 +0800826 + info.getServiceType());
827 }
Paul Hua6bc4632023-06-26 01:18:29 +0000828 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
829 msg.what, mClock.elapsedRealtime());
Paul Hu812e9212023-06-20 06:24:53 +0000830 clientInfo.onDiscoverServicesStarted(
831 clientRequestId, info, transactionId);
Paul Hu23fa2022023-01-13 22:57:24 +0800832 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000833 stopServiceDiscovery(transactionId);
Paul Hu812e9212023-06-20 06:24:53 +0000834 clientInfo.onDiscoverServicesFailedImmediately(
835 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu23fa2022023-01-13 22:57:24 +0800836 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700837 }
838 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800839 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900840 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800841 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900842 args = (ListenerArgs) msg.obj;
843 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000844 // If the binder death notification for a INsdManagerCallback was received
845 // before any calls are received by NsdService, the clientInfo would be
846 // cleared and cause NPE. Add a null check here to prevent this corner case.
847 if (clientInfo == null) {
848 Log.e(TAG, "Unknown connector in stop discovery");
849 break;
850 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700851
Paul Hud44e1b72023-06-16 02:07:42 +0000852 final ClientRequest request =
853 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900854 if (request == null) {
855 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700856 break;
857 }
Paul Hud44e1b72023-06-16 02:07:42 +0000858 transactionId = request.mTransactionId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900859 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
860 // point, so this needs to check the type of the original request to
861 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900862 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +0000863 stopDiscoveryManagerRequest(
864 request, clientRequestId, transactionId, clientInfo);
Paul Hu812e9212023-06-20 06:24:53 +0000865 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000866 clientInfo.log("Unregister the DiscoveryListener " + transactionId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700867 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000868 removeRequestMap(clientRequestId, transactionId, clientInfo);
869 if (stopServiceDiscovery(transactionId)) {
Paul Hu812e9212023-06-20 06:24:53 +0000870 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hu23fa2022023-01-13 22:57:24 +0800871 } else {
872 clientInfo.onStopDiscoveryFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000873 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu23fa2022023-01-13 22:57:24 +0800874 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700875 }
876 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900877 }
878 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800879 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900880 args = (ListenerArgs) msg.obj;
881 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000882 // If the binder death notification for a INsdManagerCallback was received
883 // before any calls are received by NsdService, the clientInfo would be
884 // cleared and cause NPE. Add a null check here to prevent this corner case.
885 if (clientInfo == null) {
886 Log.e(TAG, "Unknown connector in registration");
887 break;
888 }
889
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700890 if (requestLimitReached(clientInfo)) {
Paul Hu777ed052023-06-19 13:35:15 +0000891 clientInfo.onRegisterServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000892 clientRequestId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700893 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700894 }
895
Paul Hud44e1b72023-06-16 02:07:42 +0000896 transactionId = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900897 final NsdServiceInfo serviceInfo = args.serviceInfo;
898 final String serviceType = serviceInfo.getServiceType();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900899 final Pair<String, String> typeSubtype = parseTypeAndSubtype(serviceType);
900 final String registerServiceType = typeSubtype == null
901 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800902 if (clientInfo.mUseJavaBackend
903 || mDeps.isMdnsAdvertiserEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900904 || useAdvertiserForType(registerServiceType)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900905 if (registerServiceType == null) {
906 Log.e(TAG, "Invalid service type: " + serviceType);
Paul Hu777ed052023-06-19 13:35:15 +0000907 clientInfo.onRegisterServiceFailedImmediately(
908 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900909 break;
910 }
911 serviceInfo.setServiceType(registerServiceType);
912 serviceInfo.setServiceName(truncateServiceName(
913 serviceInfo.getServiceName()));
914
915 maybeStartMonitoringSockets();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900916 // TODO: pass in the subtype as well. Including the subtype in the
917 // service type would generate service instance names like
918 // Name._subtype._sub._type._tcp, which is incorrect
919 // (it should be Name._type._tcp).
Paul Hud44e1b72023-06-16 02:07:42 +0000920 mAdvertiser.addService(transactionId, serviceInfo, typeSubtype.second);
921 storeAdvertiserRequestMap(clientRequestId, transactionId, clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900922 serviceInfo.getNetwork());
Irfan Sheriff75006652012-04-17 23:15:29 -0700923 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900924 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000925 if (registerService(transactionId, serviceInfo)) {
926 if (DBG) {
927 Log.d(TAG, "Register " + clientRequestId
928 + " " + transactionId);
929 }
Paul Hua6bc4632023-06-26 01:18:29 +0000930 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
931 msg.what, mClock.elapsedRealtime());
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900932 // Return success after mDns reports success
933 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000934 unregisterService(transactionId);
Paul Hu777ed052023-06-19 13:35:15 +0000935 clientInfo.onRegisterServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000936 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900937 }
938
Irfan Sheriff75006652012-04-17 23:15:29 -0700939 }
940 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900941 }
942 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800943 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900944 args = (ListenerArgs) msg.obj;
945 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000946 // If the binder death notification for a INsdManagerCallback was received
947 // before any calls are received by NsdService, the clientInfo would be
948 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900949 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800950 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700951 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700952 }
Paul Hud44e1b72023-06-16 02:07:42 +0000953 final ClientRequest request =
954 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900955 if (request == null) {
956 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
957 break;
958 }
Paul Hud44e1b72023-06-16 02:07:42 +0000959 transactionId = request.mTransactionId;
960 removeRequestMap(clientRequestId, transactionId, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900961
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900962 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
963 // so this needs to check the type of the original request to unregister
964 // instead of looking at the flag value.
Paul Hu812e9212023-06-20 06:24:53 +0000965 final long stopTimeMs = mClock.elapsedRealtime();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900966 if (request instanceof AdvertiserClientRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +0000967 mAdvertiser.removeService(transactionId);
Paul Hu777ed052023-06-19 13:35:15 +0000968 clientInfo.onUnregisterServiceSucceeded(clientRequestId, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +0000969 request.calculateRequestDurationMs(stopTimeMs));
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700970 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000971 if (unregisterService(transactionId)) {
Paul Hu777ed052023-06-19 13:35:15 +0000972 clientInfo.onUnregisterServiceSucceeded(clientRequestId,
Paul Hu812e9212023-06-20 06:24:53 +0000973 transactionId,
974 request.calculateRequestDurationMs(stopTimeMs));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900975 } else {
976 clientInfo.onUnregisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000977 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900978 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700979 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700980 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900981 }
Paul Hu75069ed2023-01-14 00:31:09 +0800982 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800983 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900984 args = (ListenerArgs) msg.obj;
985 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000986 // If the binder death notification for a INsdManagerCallback was received
987 // before any calls are received by NsdService, the clientInfo would be
988 // cleared and cause NPE. Add a null check here to prevent this corner case.
989 if (clientInfo == null) {
990 Log.e(TAG, "Unknown connector in resolution");
991 break;
992 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700993
Paul Hu75069ed2023-01-14 00:31:09 +0800994 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000995 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900996 final Pair<String, String> typeSubtype =
997 parseTypeAndSubtype(info.getServiceType());
998 final String serviceType = typeSubtype == null
999 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001000 if (clientInfo.mUseJavaBackend
1001 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001002 || useDiscoveryManagerForType(serviceType)) {
Paul Hu75069ed2023-01-14 00:31:09 +08001003 if (serviceType == null) {
Paul Hua6bc4632023-06-26 01:18:29 +00001004 clientInfo.onResolveServiceFailedImmediately(
1005 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu75069ed2023-01-14 00:31:09 +08001006 break;
1007 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001008 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +08001009
1010 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001011 final MdnsListener listener = new ResolutionListener(clientRequestId,
1012 transactionId, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +08001013 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1014 .setNetwork(info.getNetwork())
1015 .setIsPassiveMode(true)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +09001016 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001017 .setRemoveExpiredService(true)
Paul Hu75069ed2023-01-14 00:31:09 +08001018 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001019 mMdnsDiscoveryManager.registerListener(
1020 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001021 storeDiscoveryManagerRequestMap(clientRequestId, transactionId,
1022 listener, clientInfo, info.getNetwork());
1023 clientInfo.log("Register a ResolutionListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001024 + " for service type:" + resolveServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -07001025 } else {
Paul Hu75069ed2023-01-14 00:31:09 +08001026 if (clientInfo.mResolvedService != null) {
Paul Hua6bc4632023-06-26 01:18:29 +00001027 clientInfo.onResolveServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +00001028 clientRequestId, NsdManager.FAILURE_ALREADY_ACTIVE);
Paul Hu75069ed2023-01-14 00:31:09 +08001029 break;
1030 }
1031
1032 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +00001033 if (resolveService(transactionId, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +08001034 clientInfo.mResolvedService = new NsdServiceInfo();
Paul Hua6bc4632023-06-26 01:18:29 +00001035 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
1036 msg.what, mClock.elapsedRealtime());
Paul Hu75069ed2023-01-14 00:31:09 +08001037 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001038 clientInfo.onResolveServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +00001039 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu75069ed2023-01-14 00:31:09 +08001040 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001041 }
1042 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001043 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001044 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +00001045 if (DBG) Log.d(TAG, "Stop service resolution");
1046 args = (ListenerArgs) msg.obj;
1047 clientInfo = mClients.get(args.connector);
1048 // If the binder death notification for a INsdManagerCallback was received
1049 // before any calls are received by NsdService, the clientInfo would be
1050 // cleared and cause NPE. Add a null check here to prevent this corner case.
1051 if (clientInfo == null) {
1052 Log.e(TAG, "Unknown connector in stop resolution");
1053 break;
1054 }
1055
Paul Hud44e1b72023-06-16 02:07:42 +00001056 final ClientRequest request =
1057 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001058 if (request == null) {
1059 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
1060 break;
1061 }
Paul Hud44e1b72023-06-16 02:07:42 +00001062 transactionId = request.mTransactionId;
Paul Hue4f5f252023-02-16 21:13:47 +08001063 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
1064 // point, so this needs to check the type of the original request to
1065 // unregister instead of looking at the flag value.
1066 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001067 stopDiscoveryManagerRequest(
1068 request, clientRequestId, transactionId, clientInfo);
Paul Hu60149052023-07-31 14:26:08 +08001069 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001070 clientInfo.log("Unregister the ResolutionListener " + transactionId);
Paul Hub58deb72022-12-26 09:24:42 +00001071 } else {
Paul Hud44e1b72023-06-16 02:07:42 +00001072 removeRequestMap(clientRequestId, transactionId, clientInfo);
1073 if (stopResolveService(transactionId)) {
Paul Hu60149052023-07-31 14:26:08 +08001074 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hue4f5f252023-02-16 21:13:47 +08001075 } else {
1076 clientInfo.onStopResolutionFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001077 clientRequestId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hue4f5f252023-02-16 21:13:47 +08001078 }
1079 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +00001080 }
Paul Hub58deb72022-12-26 09:24:42 +00001081 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001082 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001083 case NsdManager.REGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001084 if (DBG) Log.d(TAG, "Register a service callback");
1085 args = (ListenerArgs) msg.obj;
1086 clientInfo = mClients.get(args.connector);
1087 // If the binder death notification for a INsdManagerCallback was received
1088 // before any calls are received by NsdService, the clientInfo would be
1089 // cleared and cause NPE. Add a null check here to prevent this corner case.
1090 if (clientInfo == null) {
1091 Log.e(TAG, "Unknown connector in callback registration");
1092 break;
1093 }
1094
Paul Hu30bd70d2023-02-07 13:20:56 +00001095 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001096 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001097 final Pair<String, String> typeAndSubtype =
1098 parseTypeAndSubtype(info.getServiceType());
1099 final String serviceType = typeAndSubtype == null
1100 ? null : typeAndSubtype.first;
Paul Hu30bd70d2023-02-07 13:20:56 +00001101 if (serviceType == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001102 clientInfo.onServiceInfoCallbackRegistrationFailed(clientRequestId,
Paul Hu30bd70d2023-02-07 13:20:56 +00001103 NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +00001104 break;
1105 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001106 final String resolveServiceType = serviceType + ".local";
Paul Hu18aeccc2022-12-27 08:48:48 +00001107
Paul Hu30bd70d2023-02-07 13:20:56 +00001108 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001109 final MdnsListener listener = new ServiceInfoListener(clientRequestId,
1110 transactionId, info, resolveServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +00001111 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1112 .setNetwork(info.getNetwork())
1113 .setIsPassiveMode(true)
1114 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001115 .setRemoveExpiredService(true)
Paul Hu30bd70d2023-02-07 13:20:56 +00001116 .build();
1117 mMdnsDiscoveryManager.registerListener(
1118 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001119 storeDiscoveryManagerRequestMap(clientRequestId, transactionId, listener,
1120 clientInfo, info.getNetwork());
1121 clientInfo.log("Register a ServiceInfoListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001122 + " for service type:" + resolveServiceType);
Paul Hu18aeccc2022-12-27 08:48:48 +00001123 break;
Paul Hu30bd70d2023-02-07 13:20:56 +00001124 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001125 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001126 if (DBG) Log.d(TAG, "Unregister a service callback");
1127 args = (ListenerArgs) msg.obj;
1128 clientInfo = mClients.get(args.connector);
1129 // If the binder death notification for a INsdManagerCallback was received
1130 // before any calls are received by NsdService, the clientInfo would be
1131 // cleared and cause NPE. Add a null check here to prevent this corner case.
1132 if (clientInfo == null) {
1133 Log.e(TAG, "Unknown connector in callback unregistration");
1134 break;
1135 }
1136
Paul Hud44e1b72023-06-16 02:07:42 +00001137 final ClientRequest request =
1138 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001139 if (request == null) {
Paul Hu30bd70d2023-02-07 13:20:56 +00001140 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE_CALLBACK");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001141 break;
1142 }
Paul Hud44e1b72023-06-16 02:07:42 +00001143 transactionId = request.mTransactionId;
Paul Hu30bd70d2023-02-07 13:20:56 +00001144 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001145 stopDiscoveryManagerRequest(
1146 request, clientRequestId, transactionId, clientInfo);
1147 clientInfo.onServiceInfoCallbackUnregistered(clientRequestId);
1148 clientInfo.log("Unregister the ServiceInfoListener " + transactionId);
Paul Hu18aeccc2022-12-27 08:48:48 +00001149 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001150 loge("Unregister failed with non-DiscoveryManagerRequest.");
Paul Hu18aeccc2022-12-27 08:48:48 +00001151 }
Paul Hu18aeccc2022-12-27 08:48:48 +00001152 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001153 }
paulhu2b9ed952022-02-10 21:58:32 +08001154 case MDNS_SERVICE_EVENT:
1155 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +09001156 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001157 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001158 break;
Paul Hu019621e2023-01-13 23:26:49 +08001159 case MDNS_DISCOVERY_MANAGER_EVENT:
1160 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
1161 return NOT_HANDLED;
1162 }
1163 break;
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001164 case NsdManager.REGISTER_OFFLOAD_ENGINE:
1165 offloadEngineInfo = (OffloadEngineInfo) msg.obj;
1166 // TODO: Limits the number of registrations created by a given class.
1167 mOffloadEngines.register(offloadEngineInfo.mOffloadEngine,
1168 offloadEngineInfo);
1169 // TODO: Sends all the existing OffloadServiceInfos back.
1170 break;
1171 case NsdManager.UNREGISTER_OFFLOAD_ENGINE:
1172 mOffloadEngines.unregister((IOffloadEngine) msg.obj);
1173 break;
Irfan Sheriff75006652012-04-17 23:15:29 -07001174 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001175 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001176 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001177 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001178 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001179
Paul Hud44e1b72023-06-16 02:07:42 +00001180 private boolean handleMDnsServiceEvent(int code, int transactionId, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001181 NsdServiceInfo servInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001182 ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001183 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001184 Log.e(TAG, String.format(
1185 "transactionId %d for %d has no client mapping", transactionId, code));
Hugo Benichif0c84092017-04-05 14:43:29 +09001186 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001187 }
1188
1189 /* This goes in response as msg.arg2 */
Paul Hud44e1b72023-06-16 02:07:42 +00001190 int clientRequestId = clientInfo.getClientRequestId(transactionId);
1191 if (clientRequestId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -07001192 // This can happen because of race conditions. For example,
1193 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
1194 // and we may get in this situation.
Paul Hud44e1b72023-06-16 02:07:42 +00001195 Log.d(TAG, String.format("%d for transactionId %d that is no longer active",
1196 code, transactionId));
Hugo Benichif0c84092017-04-05 14:43:29 +09001197 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001198 }
Paul Hu812e9212023-06-20 06:24:53 +00001199 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1200 if (request == null) {
1201 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1202 return false;
1203 }
Hugo Benichi32be63d2017-04-05 14:06:11 +09001204 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00001205 Log.d(TAG, String.format(
1206 "MDns service event code:%d transactionId=%d", code, transactionId));
Hugo Benichi32be63d2017-04-05 14:06:11 +09001207 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001208 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +08001209 case IMDnsEventListener.SERVICE_FOUND: {
1210 final DiscoveryInfo info = (DiscoveryInfo) obj;
1211 final String name = info.serviceName;
1212 final String type = info.registrationType;
1213 servInfo = new NsdServiceInfo(name, type);
1214 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001215 if (foundNetId == 0L) {
1216 // Ignore services that do not have a Network: they are not usable
1217 // by apps, as they would need privileged permissions to use
1218 // interfaces that do not have an associated Network.
1219 break;
1220 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +09001221 if (foundNetId == INetd.DUMMY_NET_ID) {
1222 // Ignore services on the dummy0 interface: they are only seen when
1223 // discovering locally advertised services, and are not reachable
1224 // through that interface.
1225 break;
1226 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001227 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001228
1229 clientInfo.onServiceFound(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001230 break;
paulhu2b9ed952022-02-10 21:58:32 +08001231 }
1232 case IMDnsEventListener.SERVICE_LOST: {
1233 final DiscoveryInfo info = (DiscoveryInfo) obj;
1234 final String name = info.serviceName;
1235 final String type = info.registrationType;
1236 final int lostNetId = info.netId;
1237 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001238 // The network could be set to null (netId 0) if it was torn down when the
1239 // service is lost
1240 // TODO: avoid returning null in that case, possibly by remembering
1241 // found services on the same interface index and their network at the time
1242 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001243 clientInfo.onServiceLost(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001244 break;
paulhu2b9ed952022-02-10 21:58:32 +08001245 }
1246 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Paul Hu812e9212023-06-20 06:24:53 +00001247 clientInfo.onDiscoverServicesFailed(clientRequestId,
1248 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1249 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001250 break;
paulhu2b9ed952022-02-10 21:58:32 +08001251 case IMDnsEventListener.SERVICE_REGISTERED: {
1252 final RegistrationInfo info = (RegistrationInfo) obj;
1253 final String name = info.serviceName;
1254 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Paul Hu777ed052023-06-19 13:35:15 +00001255 clientInfo.onRegisterServiceSucceeded(clientRequestId, servInfo,
Paul Hu812e9212023-06-20 06:24:53 +00001256 transactionId,
1257 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001258 break;
paulhu2b9ed952022-02-10 21:58:32 +08001259 }
1260 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Paul Hu777ed052023-06-19 13:35:15 +00001261 clientInfo.onRegisterServiceFailed(clientRequestId,
1262 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001263 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001264 break;
paulhu2b9ed952022-02-10 21:58:32 +08001265 case IMDnsEventListener.SERVICE_RESOLVED: {
1266 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001267 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +08001268 final String fullName = info.serviceFullName;
1269 while (index < fullName.length() && fullName.charAt(index) != '.') {
1270 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001271 ++index;
1272 }
1273 ++index;
1274 }
paulhu2b9ed952022-02-10 21:58:32 +08001275 if (index >= fullName.length()) {
1276 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001277 break;
1278 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001279
paulhube186602022-04-12 07:18:23 +00001280 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001281 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001282 String type = rest.replace(".local.", "");
1283
Paul Hu30bd70d2023-02-07 13:20:56 +00001284 final NsdServiceInfo serviceInfo = clientInfo.mResolvedService;
Paul Hu18aeccc2022-12-27 08:48:48 +00001285 serviceInfo.setServiceName(name);
1286 serviceInfo.setServiceType(type);
1287 serviceInfo.setPort(info.port);
1288 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001289 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001290
Paul Hud44e1b72023-06-16 02:07:42 +00001291 stopResolveService(transactionId);
1292 removeRequestMap(clientRequestId, transactionId, clientInfo);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001293
Paul Hud44e1b72023-06-16 02:07:42 +00001294 final int transactionId2 = getUniqueId();
1295 if (getAddrInfo(transactionId2, info.hostname, info.interfaceIdx)) {
1296 storeLegacyRequestMap(clientRequestId, transactionId2, clientInfo,
Paul Hua6bc4632023-06-26 01:18:29 +00001297 NsdManager.RESOLVE_SERVICE, request.mStartTimeMs);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001298 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001299 clientInfo.onResolveServiceFailed(clientRequestId,
1300 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1301 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001302 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001303 }
1304 break;
paulhu2b9ed952022-02-10 21:58:32 +08001305 }
1306 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001307 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001308 stopResolveService(transactionId);
1309 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001310 clientInfo.onResolveServiceFailed(clientRequestId,
1311 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1312 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001313 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001314 break;
paulhu2b9ed952022-02-10 21:58:32 +08001315 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001316 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001317 stopGetAddrInfo(transactionId);
1318 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001319 clientInfo.onResolveServiceFailed(clientRequestId,
1320 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1321 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001322 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001323 break;
paulhu2b9ed952022-02-10 21:58:32 +08001324 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001325 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001326 final GetAddressInfo info = (GetAddressInfo) obj;
1327 final String address = info.address;
1328 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001329 InetAddress serviceHost = null;
1330 try {
paulhu2b9ed952022-02-10 21:58:32 +08001331 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001332 } catch (UnknownHostException e) {
1333 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1334 }
1335
1336 // If the resolved service is on an interface without a network, consider it
1337 // as a failure: it would not be usable by apps as they would need
1338 // privileged permissions.
Paul Hu30bd70d2023-02-07 13:20:56 +00001339 if (netId != NETID_UNSET && serviceHost != null) {
1340 clientInfo.mResolvedService.setHost(serviceHost);
1341 setServiceNetworkForCallback(clientInfo.mResolvedService,
1342 netId, info.interfaceIdx);
1343 clientInfo.onResolveServiceSucceeded(
Paul Hua6bc4632023-06-26 01:18:29 +00001344 clientRequestId, clientInfo.mResolvedService, request);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001345 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001346 clientInfo.onResolveServiceFailed(clientRequestId,
1347 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1348 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001349 }
Paul Hud44e1b72023-06-16 02:07:42 +00001350 stopGetAddrInfo(transactionId);
1351 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001352 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001353 break;
paulhu2b9ed952022-02-10 21:58:32 +08001354 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001355 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001356 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001357 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001358 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001359 }
Paul Hu019621e2023-01-13 23:26:49 +08001360
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001361 @Nullable
1362 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(
1363 final MdnsEvent event, int code) {
Paul Hu019621e2023-01-13 23:26:49 +08001364 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001365 final String[] typeArray = serviceInfo.getServiceType();
1366 final String joinedType;
1367 if (typeArray.length == 0
1368 || !typeArray[typeArray.length - 1].equals(LOCAL_DOMAIN_NAME)) {
1369 Log.wtf(TAG, "MdnsServiceInfo type does not end in .local: "
1370 + Arrays.toString(typeArray));
1371 return null;
1372 } else {
1373 joinedType = TextUtils.join(".",
1374 Arrays.copyOfRange(typeArray, 0, typeArray.length - 1));
1375 }
1376 final String serviceType;
1377 switch (code) {
1378 case NsdManager.SERVICE_FOUND:
1379 case NsdManager.SERVICE_LOST:
1380 // For consistency with historical behavior, discovered service types have
1381 // a dot at the end.
1382 serviceType = joinedType + ".";
1383 break;
1384 case RESOLVE_SERVICE_SUCCEEDED:
1385 // For consistency with historical behavior, resolved service types have
1386 // a dot at the beginning.
1387 serviceType = "." + joinedType;
1388 break;
1389 default:
1390 serviceType = joinedType;
1391 break;
1392 }
Paul Hu019621e2023-01-13 23:26:49 +08001393 final String serviceName = serviceInfo.getServiceInstanceName();
1394 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1395 final Network network = serviceInfo.getNetwork();
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001396 // In MdnsDiscoveryManagerEvent, the Network can be null which means it is a
1397 // network for Tethering interface. In other words, the network == null means the
1398 // network has netId = INetd.LOCAL_NET_ID.
Paul Hu019621e2023-01-13 23:26:49 +08001399 setServiceNetworkForCallback(
1400 servInfo,
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001401 network == null ? INetd.LOCAL_NET_ID : network.netId,
Paul Hu019621e2023-01-13 23:26:49 +08001402 serviceInfo.getInterfaceIndex());
1403 return servInfo;
1404 }
1405
1406 private boolean handleMdnsDiscoveryManagerEvent(
1407 int transactionId, int code, Object obj) {
Paul Hud44e1b72023-06-16 02:07:42 +00001408 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Paul Hu019621e2023-01-13 23:26:49 +08001409 if (clientInfo == null) {
1410 Log.e(TAG, String.format(
1411 "id %d for %d has no client mapping", transactionId, code));
1412 return false;
1413 }
1414
1415 final MdnsEvent event = (MdnsEvent) obj;
Paul Hud44e1b72023-06-16 02:07:42 +00001416 final int clientRequestId = event.mClientRequestId;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001417 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event, code);
1418 // Errors are already logged if null
1419 if (info == null) return false;
Paul Hu83ec7f42023-06-07 18:04:09 +08001420 mServiceLogs.log(String.format(
1421 "MdnsDiscoveryManager event code=%s transactionId=%d",
1422 NsdManager.nameOf(code), transactionId));
Paul Hu812e9212023-06-20 06:24:53 +00001423 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1424 if (request == null) {
1425 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1426 return false;
1427 }
Paul Hu019621e2023-01-13 23:26:49 +08001428 switch (code) {
1429 case NsdManager.SERVICE_FOUND:
Paul Hu812e9212023-06-20 06:24:53 +00001430 clientInfo.onServiceFound(clientRequestId, info, request);
Paul Hu319751a2023-01-13 23:56:34 +08001431 break;
1432 case NsdManager.SERVICE_LOST:
Paul Hu812e9212023-06-20 06:24:53 +00001433 clientInfo.onServiceLost(clientRequestId, info, request);
Paul Hu019621e2023-01-13 23:26:49 +08001434 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001435 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
1436 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Paul Hu75069ed2023-01-14 00:31:09 +08001437 info.setPort(serviceInfo.getPort());
1438
1439 Map<String, String> attrs = serviceInfo.getAttributes();
1440 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1441 final String key = kv.getKey();
1442 try {
1443 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1444 } catch (IllegalArgumentException e) {
1445 Log.e(TAG, "Invalid attribute", e);
1446 }
1447 }
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001448 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu2b865912023-03-06 14:27:53 +08001449 if (addresses.size() != 0) {
1450 info.setHostAddresses(addresses);
Paul Hua6bc4632023-06-26 01:18:29 +00001451 request.setServiceFromCache(event.mIsServiceFromCache);
1452 clientInfo.onResolveServiceSucceeded(clientRequestId, info, request);
Paul Hu2b865912023-03-06 14:27:53 +08001453 } else {
1454 // No address. Notify resolution failure.
Paul Hua6bc4632023-06-26 01:18:29 +00001455 clientInfo.onResolveServiceFailed(clientRequestId,
1456 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1457 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu75069ed2023-01-14 00:31:09 +08001458 }
1459
1460 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001461 if (!(request instanceof DiscoveryManagerRequest)) {
1462 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1463 break;
1464 }
Paul Hud44e1b72023-06-16 02:07:42 +00001465 stopDiscoveryManagerRequest(
1466 request, clientRequestId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001467 break;
1468 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001469 case NsdManager.SERVICE_UPDATED: {
1470 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1471 info.setPort(serviceInfo.getPort());
1472
1473 Map<String, String> attrs = serviceInfo.getAttributes();
1474 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1475 final String key = kv.getKey();
1476 try {
1477 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1478 } catch (IllegalArgumentException e) {
1479 Log.e(TAG, "Invalid attribute", e);
1480 }
1481 }
1482
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001483 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001484 info.setHostAddresses(addresses);
Paul Hud44e1b72023-06-16 02:07:42 +00001485 clientInfo.onServiceUpdated(clientRequestId, info);
Paul Hu30bd70d2023-02-07 13:20:56 +00001486 break;
1487 }
1488 case NsdManager.SERVICE_UPDATED_LOST:
Paul Hud44e1b72023-06-16 02:07:42 +00001489 clientInfo.onServiceUpdatedLost(clientRequestId);
Paul Hu30bd70d2023-02-07 13:20:56 +00001490 break;
Paul Hu019621e2023-01-13 23:26:49 +08001491 default:
1492 return false;
1493 }
1494 return true;
1495 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001496 }
1497 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001498
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001499 @NonNull
1500 private static List<InetAddress> getInetAddresses(@NonNull MdnsServiceInfo serviceInfo) {
1501 final List<String> v4Addrs = serviceInfo.getIpv4Addresses();
1502 final List<String> v6Addrs = serviceInfo.getIpv6Addresses();
1503 final List<InetAddress> addresses = new ArrayList<>(v4Addrs.size() + v6Addrs.size());
1504 for (String ipv4Address : v4Addrs) {
1505 try {
1506 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1507 } catch (IllegalArgumentException e) {
1508 Log.wtf(TAG, "Invalid ipv4 address", e);
1509 }
1510 }
1511 for (String ipv6Address : v6Addrs) {
1512 try {
Yuyang Huanga6a6ff92023-04-24 13:33:34 +09001513 final Inet6Address addr = (Inet6Address) InetAddresses.parseNumericAddress(
1514 ipv6Address);
1515 addresses.add(InetAddressUtils.withScopeId(addr, serviceInfo.getInterfaceIndex()));
1516 } catch (IllegalArgumentException e) {
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001517 Log.wtf(TAG, "Invalid ipv6 address", e);
1518 }
1519 }
1520 return addresses;
1521 }
1522
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001523 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1524 switch (netId) {
1525 case NETID_UNSET:
1526 info.setNetwork(null);
1527 break;
1528 case INetd.LOCAL_NET_ID:
1529 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1530 // visible / usable for apps, so do not return it. Store the interface
1531 // index instead, so at least if the client tries to resolve the service
1532 // with that NsdServiceInfo, it will be done on the same interface.
1533 // If they recreate the NsdServiceInfo themselves, resolution would be
1534 // done on all interfaces as before T, which should also work.
1535 info.setNetwork(null);
1536 info.setInterfaceIndex(ifaceIdx);
1537 break;
1538 default:
1539 info.setNetwork(new Network(netId));
1540 }
1541 }
1542
paulhube186602022-04-12 07:18:23 +00001543 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1544 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1545 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1546 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1547 private String unescape(String s) {
1548 StringBuilder sb = new StringBuilder(s.length());
1549 for (int i = 0; i < s.length(); ++i) {
1550 char c = s.charAt(i);
1551 if (c == '\\') {
1552 if (++i >= s.length()) {
1553 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1554 break;
1555 }
1556 c = s.charAt(i);
1557 if (c != '.' && c != '\\') {
1558 if (i + 2 >= s.length()) {
1559 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1560 break;
1561 }
1562 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1563 + (s.charAt(i + 2) - '0'));
1564 i += 2;
1565 }
1566 }
1567 sb.append(c);
1568 }
1569 return sb.toString();
1570 }
1571
Paul Hu7445e3d2023-03-03 15:14:00 +08001572 /**
1573 * Check the given service type is valid and construct it to a service type
1574 * which can use for discovery / resolution service.
1575 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001576 * <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 +08001577 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1578 * underscore; they are alphanumerical characters or dashes or underscore, except the
1579 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1580 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001581 * <p>The subtype may also be specified with a comma after the service type, for example
1582 * _type._tcp,_subtype.
1583 *
Paul Hu7445e3d2023-03-03 15:14:00 +08001584 * @param serviceType the request service type for discovery / resolution service
1585 * @return constructed service type or null if the given service type is invalid.
1586 */
1587 @Nullable
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001588 public static Pair<String, String> parseTypeAndSubtype(String serviceType) {
Paul Hu7445e3d2023-03-03 15:14:00 +08001589 if (TextUtils.isEmpty(serviceType)) return null;
1590
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001591 final String typeOrSubtypePattern = "_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]";
Paul Hu7445e3d2023-03-03 15:14:00 +08001592 final Pattern serviceTypePattern = Pattern.compile(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001593 // Optional leading subtype (_subtype._type._tcp)
1594 // (?: xxx) is a non-capturing parenthesis, don't capture the dot
1595 "^(?:(" + typeOrSubtypePattern + ")\\.)?"
1596 // Actual type (_type._tcp.local)
1597 + "(" + typeOrSubtypePattern + "\\._(?:tcp|udp))"
Paul Hu7445e3d2023-03-03 15:14:00 +08001598 // Drop '.' at the end of service type that is compatible with old backend.
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001599 // e.g. allow "_type._tcp.local."
1600 + "\\.?"
1601 // Optional subtype after comma, for "_type._tcp,_subtype" format
1602 + "(?:,(" + typeOrSubtypePattern + "))?"
1603 + "$");
Paul Hu7445e3d2023-03-03 15:14:00 +08001604 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1605 if (!matcher.matches()) return null;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001606 // Use the subtype either at the beginning or after the comma
1607 final String subtype = matcher.group(1) != null ? matcher.group(1) : matcher.group(3);
1608 return new Pair<>(matcher.group(2), subtype);
Paul Hu7445e3d2023-03-03 15:14:00 +08001609 }
1610
Hugo Benichi803a2f02017-04-24 11:35:06 +09001611 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001612 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001613 this(ctx, handler, cleanupDelayMs, new Dependencies());
1614 }
1615
1616 @VisibleForTesting
1617 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001618 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001619 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001620 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001621 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001622 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1623 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001624 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001625
Paul Hu14667de2023-04-17 22:42:47 +08001626 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper(),
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001627 LOGGER.forSubComponent("MdnsSocketProvider"), new SocketRequestMonitor());
Yuyang Huang700778b2023-03-08 16:17:05 +09001628 // Netlink monitor starts on boot, and intentionally never stopped, to ensure that all
1629 // address events are received.
1630 handler.post(mMdnsSocketProvider::startNetLinkMonitor);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001631
1632 // NsdService is started after ActivityManager (startOtherServices in SystemServer, vs.
1633 // startBootstrapServices).
1634 mRunningAppActiveImportanceCutoff = mDeps.getDeviceConfigInt(
1635 MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF,
1636 DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF);
1637 final ActivityManager am = ctx.getSystemService(ActivityManager.class);
1638 am.addOnUidImportanceListener(new UidImportanceListener(handler),
1639 mRunningAppActiveImportanceCutoff);
1640
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001641 mMdnsSocketClient =
Yuyang Huang7ddf2932023-08-01 18:16:30 +09001642 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider,
1643 LOGGER.forSubComponent("MdnsMultinetworkSocketClient"));
Paul Hu14667de2023-04-17 22:42:47 +08001644 mMdnsDiscoveryManager = deps.makeMdnsDiscoveryManager(new ExecutorProvider(),
Yuyang Huang243d1a52023-05-23 17:26:52 +09001645 mMdnsSocketClient, LOGGER.forSubComponent("MdnsDiscoveryManager"));
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001646 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1647 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
Paul Hu14667de2023-04-17 22:42:47 +08001648 new AdvertiserCallback(), LOGGER.forSubComponent("MdnsAdvertiser"));
Paul Hu777ed052023-06-19 13:35:15 +00001649 mClock = deps.makeClock();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001650 }
1651
1652 /**
1653 * Dependencies of NsdService, for injection in tests.
1654 */
1655 @VisibleForTesting
1656 public static class Dependencies {
1657 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001658 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001659 *
1660 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001661 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001662 */
1663 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001664 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
1665 NAMESPACE_TETHERING, MDNS_DISCOVERY_MANAGER_VERSION,
1666 DeviceConfigUtils.TETHERING_MODULE_NAME, false /* defaultEnabled */);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001667 }
1668
1669 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001670 * Check whether the MdnsAdvertiser feature is enabled.
1671 *
1672 * @param context The global context information about an app environment.
1673 * @return true if the MdnsAdvertiser feature is enabled.
1674 */
1675 public boolean isMdnsAdvertiserEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001676 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
1677 NAMESPACE_TETHERING, MDNS_ADVERTISER_VERSION,
1678 DeviceConfigUtils.TETHERING_MODULE_NAME, false /* defaultEnabled */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001679 }
1680
1681 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001682 * Get the type allowlist flag value.
1683 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1684 */
1685 @Nullable
1686 public String getTypeAllowlistFlags() {
1687 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1688 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1689 }
1690
1691 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001692 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001693 */
1694 public boolean isFeatureEnabled(Context context, String feature) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001695 return DeviceConfigUtils.isTetheringFeatureEnabled(context, NAMESPACE_TETHERING,
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001696 feature, DeviceConfigUtils.TETHERING_MODULE_NAME, false /* defaultEnabled */);
1697 }
1698
1699 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001700 * @see MdnsDiscoveryManager
1701 */
1702 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
Paul Hu14667de2023-04-17 22:42:47 +08001703 @NonNull ExecutorProvider executorProvider,
Yuyang Huang243d1a52023-05-23 17:26:52 +09001704 @NonNull MdnsMultinetworkSocketClient socketClient, @NonNull SharedLog sharedLog) {
1705 return new MdnsDiscoveryManager(executorProvider, socketClient, sharedLog);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001706 }
1707
1708 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001709 * @see MdnsAdvertiser
1710 */
1711 public MdnsAdvertiser makeMdnsAdvertiser(
1712 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
Paul Hu14667de2023-04-17 22:42:47 +08001713 @NonNull MdnsAdvertiser.AdvertiserCallback cb, @NonNull SharedLog sharedLog) {
1714 return new MdnsAdvertiser(looper, socketProvider, cb, sharedLog);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001715 }
1716
1717 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001718 * @see MdnsSocketProvider
1719 */
Paul Hu14667de2023-04-17 22:42:47 +08001720 public MdnsSocketProvider makeMdnsSocketProvider(@NonNull Context context,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001721 @NonNull Looper looper, @NonNull SharedLog sharedLog,
1722 @NonNull MdnsSocketProvider.SocketRequestMonitor socketCreationCallback) {
1723 return new MdnsSocketProvider(context, looper, sharedLog, socketCreationCallback);
1724 }
1725
1726 /**
1727 * @see DeviceConfig#getInt(String, String, int)
1728 */
1729 public int getDeviceConfigInt(@NonNull String config, int defaultValue) {
1730 return DeviceConfig.getInt(NAMESPACE_TETHERING, config, defaultValue);
1731 }
1732
1733 /**
1734 * @see Binder#getCallingUid()
1735 */
1736 public int getCallingUid() {
1737 return Binder.getCallingUid();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001738 }
Paul Hu777ed052023-06-19 13:35:15 +00001739
1740 /**
1741 * @see NetworkNsdReportedMetrics
1742 */
1743 public NetworkNsdReportedMetrics makeNetworkNsdReportedMetrics(
1744 boolean isLegacy, int clientId) {
1745 return new NetworkNsdReportedMetrics(isLegacy, clientId);
1746 }
1747
1748 /**
1749 * @see MdnsUtils.Clock
1750 */
1751 public Clock makeClock() {
1752 return new Clock();
1753 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001754 }
1755
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001756 /**
1757 * Return whether a type is allowlisted to use the Java backend.
1758 * @param type The service type
1759 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1760 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1761 */
1762 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1763 @NonNull String flagPrefix) {
1764 if (type == null) return false;
1765 final String typesConfig = mDeps.getTypeAllowlistFlags();
1766 if (TextUtils.isEmpty(typesConfig)) return false;
1767
1768 final String mappingPrefix = type + ":";
1769 String mappedFlag = null;
1770 for (String mapping : TextUtils.split(typesConfig, ",")) {
1771 if (mapping.startsWith(mappingPrefix)) {
1772 mappedFlag = mapping.substring(mappingPrefix.length());
1773 break;
1774 }
1775 }
1776
1777 if (mappedFlag == null) return false;
1778
1779 return mDeps.isFeatureEnabled(mContext,
1780 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1781 }
1782
1783 private boolean useDiscoveryManagerForType(@Nullable String type) {
1784 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1785 }
1786
1787 private boolean useAdvertiserForType(@Nullable String type) {
1788 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1789 }
1790
paulhu1b35e822022-04-08 14:48:41 +08001791 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001792 HandlerThread thread = new HandlerThread(TAG);
1793 thread.start();
1794 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001795 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001796 return service;
1797 }
1798
paulhu2b9ed952022-02-10 21:58:32 +08001799 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1800 private final StateMachine mStateMachine;
1801
1802 MDnsEventCallback(StateMachine sm) {
1803 mStateMachine = sm;
1804 }
1805
1806 @Override
1807 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1808 mStateMachine.sendMessage(
1809 MDNS_SERVICE_EVENT, status.result, status.id, status);
1810 }
1811
1812 @Override
1813 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1814 mStateMachine.sendMessage(
1815 MDNS_SERVICE_EVENT, status.result, status.id, status);
1816 }
1817
1818 @Override
1819 public void onServiceResolutionStatus(final ResolutionInfo status) {
1820 mStateMachine.sendMessage(
1821 MDNS_SERVICE_EVENT, status.result, status.id, status);
1822 }
1823
1824 @Override
1825 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1826 mStateMachine.sendMessage(
1827 MDNS_SERVICE_EVENT, status.result, status.id, status);
1828 }
1829
1830 @Override
1831 public int getInterfaceVersion() throws RemoteException {
1832 return this.VERSION;
1833 }
1834
1835 @Override
1836 public String getInterfaceHash() throws RemoteException {
1837 return this.HASH;
1838 }
1839 }
1840
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001841 private void sendOffloadServiceInfosUpdate(@NonNull String targetInterfaceName,
1842 @NonNull OffloadServiceInfo offloadServiceInfo, boolean isRemove) {
1843 final int count = mOffloadEngines.beginBroadcast();
1844 try {
1845 for (int i = 0; i < count; i++) {
1846 final OffloadEngineInfo offloadEngineInfo =
1847 (OffloadEngineInfo) mOffloadEngines.getBroadcastCookie(i);
1848 final String interfaceName = offloadEngineInfo.mInterfaceName;
1849 if (!targetInterfaceName.equals(interfaceName)
1850 || ((offloadEngineInfo.mOffloadType
1851 & offloadServiceInfo.getOffloadType()) == 0)) {
1852 continue;
1853 }
1854 try {
1855 if (isRemove) {
1856 mOffloadEngines.getBroadcastItem(i).onOffloadServiceRemoved(
1857 offloadServiceInfo);
1858 } else {
1859 mOffloadEngines.getBroadcastItem(i).onOffloadServiceUpdated(
1860 offloadServiceInfo);
1861 }
1862 } catch (RemoteException e) {
1863 // Can happen in regular cases, do not log a stacktrace
1864 Log.i(TAG, "Failed to send offload callback, remote died", e);
1865 }
1866 }
1867 } finally {
1868 mOffloadEngines.finishBroadcast();
1869 }
1870 }
1871
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001872 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001873 // TODO: add a callback to notify when a service is being added on each interface (as soon
1874 // as probing starts), and call mOffloadCallbacks. This callback is for
1875 // OFFLOAD_CAPABILITY_FILTER_REPLIES offload type.
1876
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001877 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001878 public void onRegisterServiceSucceeded(int transactionId, NsdServiceInfo registeredInfo) {
1879 mServiceLogs.log("onRegisterServiceSucceeded: transactionId " + transactionId);
1880 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001881 if (clientInfo == null) return;
1882
Paul Hud44e1b72023-06-16 02:07:42 +00001883 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1884 if (clientRequestId < 0) return;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001885
1886 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1887 // historical behavior.
1888 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
Paul Hu777ed052023-06-19 13:35:15 +00001889 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu812e9212023-06-20 06:24:53 +00001890 clientInfo.onRegisterServiceSucceeded(clientRequestId, cbInfo, transactionId,
1891 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001892 }
1893
1894 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001895 public void onRegisterServiceFailed(int transactionId, int errorCode) {
1896 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001897 if (clientInfo == null) return;
1898
Paul Hud44e1b72023-06-16 02:07:42 +00001899 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1900 if (clientRequestId < 0) return;
Paul Hu777ed052023-06-19 13:35:15 +00001901 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1902 clientInfo.onRegisterServiceFailed(clientRequestId, errorCode, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001903 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001904 }
1905
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001906 @Override
1907 public void onOffloadStartOrUpdate(@NonNull String interfaceName,
1908 @NonNull OffloadServiceInfo offloadServiceInfo) {
1909 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, false /* isRemove */);
1910 }
1911
1912 @Override
1913 public void onOffloadStop(@NonNull String interfaceName,
1914 @NonNull OffloadServiceInfo offloadServiceInfo) {
1915 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, true /* isRemove */);
1916 }
1917
Paul Hud44e1b72023-06-16 02:07:42 +00001918 private ClientInfo getClientInfoOrLog(int transactionId) {
1919 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001920 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001921 Log.e(TAG, String.format("Callback for service %d has no client", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001922 }
1923 return clientInfo;
1924 }
1925
Paul Hud44e1b72023-06-16 02:07:42 +00001926 private int getClientRequestIdOrLog(@NonNull ClientInfo info, int transactionId) {
1927 final int clientRequestId = info.getClientRequestId(transactionId);
1928 if (clientRequestId < 0) {
1929 Log.e(TAG, String.format(
1930 "Client request ID not found for service %d", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001931 }
Paul Hud44e1b72023-06-16 02:07:42 +00001932 return clientRequestId;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001933 }
1934 }
1935
Paul Hu2e0a88c2023-03-09 16:05:01 +08001936 private static class ConnectorArgs {
1937 @NonNull public final NsdServiceConnector connector;
1938 @NonNull public final INsdManagerCallback callback;
1939 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001940 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001941
1942 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00001943 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08001944 this.connector = connector;
1945 this.callback = callback;
1946 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001947 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001948 }
1949 }
1950
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001951 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08001952 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001953 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu101dbf52023-08-09 16:05:20 +08001954 final int uid = mDeps.getCallingUid();
1955 if (cb == null) {
1956 throw new IllegalArgumentException("Unknown client callback from uid=" + uid);
1957 }
Paul Hu2e0a88c2023-03-09 16:05:01 +08001958 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001959 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00001960 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
Paul Hu101dbf52023-08-09 16:05:20 +08001961 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend, uid)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001962 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07001963 }
1964
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001965 private static class ListenerArgs {
1966 public final NsdServiceConnector connector;
1967 public final NsdServiceInfo serviceInfo;
1968 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
1969 this.connector = connector;
1970 this.serviceInfo = serviceInfo;
1971 }
1972 }
1973
1974 private class NsdServiceConnector extends INsdServiceConnector.Stub
1975 implements IBinder.DeathRecipient {
1976 @Override
1977 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
1978 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1979 NsdManager.REGISTER_SERVICE, 0, listenerKey,
1980 new ListenerArgs(this, serviceInfo)));
1981 }
1982
1983 @Override
1984 public void unregisterService(int listenerKey) {
1985 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1986 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
1987 new ListenerArgs(this, null)));
1988 }
1989
1990 @Override
1991 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
1992 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1993 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
1994 new ListenerArgs(this, serviceInfo)));
1995 }
1996
1997 @Override
1998 public void stopDiscovery(int listenerKey) {
1999 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2000 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
2001 }
2002
2003 @Override
2004 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
2005 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2006 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
2007 new ListenerArgs(this, serviceInfo)));
2008 }
2009
2010 @Override
Paul Hub58deb72022-12-26 09:24:42 +00002011 public void stopResolution(int listenerKey) {
2012 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2013 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
2014 }
2015
2016 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00002017 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
2018 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2019 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
2020 new ListenerArgs(this, serviceInfo)));
2021 }
2022
2023 @Override
2024 public void unregisterServiceInfoCallback(int listenerKey) {
2025 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2026 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
2027 new ListenerArgs(this, null)));
2028 }
2029
2030 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002031 public void startDaemon() {
2032 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2033 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
2034 }
2035
2036 @Override
2037 public void binderDied() {
2038 mNsdStateMachine.sendMessage(
2039 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002040
2041 }
2042
2043 @Override
2044 public void registerOffloadEngine(String ifaceName, IOffloadEngine cb,
2045 @OffloadEngine.OffloadCapability long offloadCapabilities,
2046 @OffloadEngine.OffloadType long offloadTypes) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002047 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002048 Objects.requireNonNull(ifaceName);
2049 Objects.requireNonNull(cb);
2050 mNsdStateMachine.sendMessage(
2051 mNsdStateMachine.obtainMessage(NsdManager.REGISTER_OFFLOAD_ENGINE,
2052 new OffloadEngineInfo(cb, ifaceName, offloadCapabilities,
2053 offloadTypes)));
2054 }
2055
2056 @Override
2057 public void unregisterOffloadEngine(IOffloadEngine cb) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002058 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002059 Objects.requireNonNull(cb);
2060 mNsdStateMachine.sendMessage(
2061 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_OFFLOAD_ENGINE, cb));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002062 }
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002063
2064 private static void checkOffloadEnginePermission(Context context) {
2065 if (!SdkLevel.isAtLeastT()) {
2066 throw new SecurityException("API is not available in before API level 33");
2067 }
2068 // REGISTER_NSD_OFFLOAD_ENGINE was only added to the SDK in V, but may
2069 // be back ported to older builds: accept it as long as it's signature-protected
2070 if (PermissionUtils.checkAnyPermissionOf(context, REGISTER_NSD_OFFLOAD_ENGINE)
2071 && (SdkLevel.isAtLeastV() || PermissionUtils.isSystemSignaturePermission(
2072 context, REGISTER_NSD_OFFLOAD_ENGINE))) {
2073 return;
2074 }
2075 if (PermissionUtils.checkAnyPermissionOf(context, NETWORK_STACK,
2076 PERMISSION_MAINLINE_NETWORK_STACK, NETWORK_SETTINGS)) {
2077 return;
2078 }
2079 throw new SecurityException("Requires one of the following permissions: "
2080 + String.join(", ", List.of(REGISTER_NSD_OFFLOAD_ENGINE, NETWORK_STACK,
2081 PERMISSION_MAINLINE_NETWORK_STACK, NETWORK_SETTINGS)) + ".");
2082 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002083 }
2084
Hugo Benichi912db992017-04-24 16:41:03 +09002085 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07002086 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07002087 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09002088 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
2089 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07002090 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07002091 }
2092
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002093 private int getUniqueId() {
2094 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
2095 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002096 }
2097
Paul Hud44e1b72023-06-16 02:07:42 +00002098 private boolean registerService(int transactionId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09002099 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002100 Log.d(TAG, "registerService: " + transactionId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002101 }
Hugo Benichi6d706442017-04-24 16:19:58 +09002102 String name = service.getServiceName();
2103 String type = service.getServiceType();
2104 int port = service.getPort();
2105 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002106 final int registerInterface = getNetworkInterfaceIndex(service);
2107 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08002108 Log.e(TAG, "Interface to register service on not found");
2109 return false;
2110 }
Paul Hud44e1b72023-06-16 02:07:42 +00002111 return mMDnsManager.registerService(
2112 transactionId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002113 }
2114
Paul Hud44e1b72023-06-16 02:07:42 +00002115 private boolean unregisterService(int transactionId) {
2116 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002117 }
2118
Paul Hud44e1b72023-06-16 02:07:42 +00002119 private boolean discoverServices(int transactionId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08002120 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002121 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
2122 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002123 Log.e(TAG, "Interface to discover service on not found");
2124 return false;
2125 }
Paul Hud44e1b72023-06-16 02:07:42 +00002126 return mMDnsManager.discover(transactionId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002127 }
2128
Paul Hud44e1b72023-06-16 02:07:42 +00002129 private boolean stopServiceDiscovery(int transactionId) {
2130 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002131 }
2132
Paul Hud44e1b72023-06-16 02:07:42 +00002133 private boolean resolveService(int transactionId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002134 final String name = service.getServiceName();
2135 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002136 final int resolveInterface = getNetworkInterfaceIndex(service);
2137 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002138 Log.e(TAG, "Interface to resolve service on not found");
2139 return false;
2140 }
Paul Hud44e1b72023-06-16 02:07:42 +00002141 return mMDnsManager.resolve(transactionId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002142 }
2143
2144 /**
2145 * Guess the interface to use to resolve or discover a service on a specific network.
2146 *
2147 * This is an imperfect guess, as for example the network may be gone or not yet fully
2148 * registered. This is fine as failing is correct if the network is gone, and a client
2149 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
2150 * this is to support the legacy mdnsresponder implementation, which historically resolved
2151 * services on an unspecified network.
2152 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002153 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
2154 final Network network = serviceInfo.getNetwork();
2155 if (network == null) {
2156 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
2157 // provided by NsdService from discovery results, and the service was found on an
2158 // interface that has no app-usable Network).
2159 if (serviceInfo.getInterfaceIndex() != 0) {
2160 return serviceInfo.getInterfaceIndex();
2161 }
2162 return IFACE_IDX_ANY;
2163 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002164
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002165 String interfaceName = getNetworkInterfaceName(network);
2166 if (interfaceName == null) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002167 return IFACE_IDX_ANY;
2168 }
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002169 return getNetworkInterfaceIndexByName(interfaceName);
2170 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002171
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002172 private String getNetworkInterfaceName(@Nullable Network network) {
2173 if (network == null) {
2174 return null;
2175 }
2176 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
2177 if (cm == null) {
2178 Log.wtf(TAG, "No ConnectivityManager");
2179 return null;
2180 }
2181 final LinkProperties lp = cm.getLinkProperties(network);
2182 if (lp == null) {
2183 return null;
2184 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002185 // Only resolve on non-stacked interfaces
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002186 return lp.getInterfaceName();
2187 }
2188
2189 private int getNetworkInterfaceIndexByName(final String ifaceName) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002190 final NetworkInterface iface;
2191 try {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002192 iface = NetworkInterface.getByName(ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002193 } catch (SocketException e) {
2194 Log.e(TAG, "Error querying interface", e);
2195 return IFACE_IDX_ANY;
2196 }
2197
2198 if (iface == null) {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002199 Log.e(TAG, "Interface not found: " + ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002200 return IFACE_IDX_ANY;
2201 }
2202
2203 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002204 }
2205
Paul Hud44e1b72023-06-16 02:07:42 +00002206 private boolean stopResolveService(int transactionId) {
2207 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002208 }
2209
Paul Hud44e1b72023-06-16 02:07:42 +00002210 private boolean getAddrInfo(int transactionId, String hostname, int interfaceIdx) {
2211 return mMDnsManager.getServiceAddress(transactionId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002212 }
2213
Paul Hud44e1b72023-06-16 02:07:42 +00002214 private boolean stopGetAddrInfo(int transactionId) {
2215 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002216 }
2217
2218 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00002219 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2220 if (!PermissionUtils.checkDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002221
Paul Hub2e67d32023-04-18 05:50:14 +00002222 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
2223 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07002224 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00002225
2226 // Dump service and clients logs
2227 pw.println();
Paul Hu14667de2023-04-17 22:42:47 +08002228 pw.println("Logs:");
Paul Hub2e67d32023-04-18 05:50:14 +00002229 pw.increaseIndent();
2230 mServiceLogs.reverseDump(pw);
2231 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002232 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002233
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002234 private abstract static class ClientRequest {
Paul Hud44e1b72023-06-16 02:07:42 +00002235 private final int mTransactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002236 private final long mStartTimeMs;
Paul Hu812e9212023-06-20 06:24:53 +00002237 private int mFoundServiceCount = 0;
2238 private int mLostServiceCount = 0;
2239 private final Set<String> mServices = new ArraySet<>();
Paul Hua6bc4632023-06-26 01:18:29 +00002240 private boolean mIsServiceFromCache = false;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002241
Paul Hu812e9212023-06-20 06:24:53 +00002242 private ClientRequest(int transactionId, long startTimeMs) {
Paul Hud44e1b72023-06-16 02:07:42 +00002243 mTransactionId = transactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002244 mStartTimeMs = startTimeMs;
2245 }
2246
Paul Hu812e9212023-06-20 06:24:53 +00002247 public long calculateRequestDurationMs(long stopTimeMs) {
Paul Hu777ed052023-06-19 13:35:15 +00002248 return stopTimeMs - mStartTimeMs;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002249 }
Paul Hu812e9212023-06-20 06:24:53 +00002250
2251 public void onServiceFound(String serviceName) {
2252 mFoundServiceCount++;
2253 if (mServices.size() <= MAX_SERVICES_COUNT_METRIC_PER_CLIENT) {
2254 mServices.add(serviceName);
2255 }
2256 }
2257
2258 public void onServiceLost() {
2259 mLostServiceCount++;
2260 }
2261
2262 public int getFoundServiceCount() {
2263 return mFoundServiceCount;
2264 }
2265
2266 public int getLostServiceCount() {
2267 return mLostServiceCount;
2268 }
2269
2270 public int getServicesCount() {
2271 return mServices.size();
2272 }
Paul Hua6bc4632023-06-26 01:18:29 +00002273
2274 public void setServiceFromCache(boolean isServiceFromCache) {
2275 mIsServiceFromCache = isServiceFromCache;
2276 }
2277
2278 public boolean isServiceFromCache() {
2279 return mIsServiceFromCache;
2280 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002281 }
2282
2283 private static class LegacyClientRequest extends ClientRequest {
2284 private final int mRequestCode;
2285
Paul Hu812e9212023-06-20 06:24:53 +00002286 private LegacyClientRequest(int transactionId, int requestCode, long startTimeMs) {
2287 super(transactionId, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002288 mRequestCode = requestCode;
2289 }
2290 }
2291
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002292 private abstract static class JavaBackendClientRequest extends ClientRequest {
2293 @Nullable
2294 private final Network mRequestedNetwork;
2295
Paul Hu777ed052023-06-19 13:35:15 +00002296 private JavaBackendClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002297 long startTimeMs) {
2298 super(transactionId, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002299 mRequestedNetwork = requestedNetwork;
2300 }
2301
2302 @Nullable
2303 public Network getRequestedNetwork() {
2304 return mRequestedNetwork;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002305 }
2306 }
2307
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002308 private static class AdvertiserClientRequest extends JavaBackendClientRequest {
Paul Hu777ed052023-06-19 13:35:15 +00002309 private AdvertiserClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002310 long startTimeMs) {
2311 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002312 }
2313 }
2314
2315 private static class DiscoveryManagerRequest extends JavaBackendClientRequest {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002316 @NonNull
2317 private final MdnsListener mListener;
2318
Paul Hud44e1b72023-06-16 02:07:42 +00002319 private DiscoveryManagerRequest(int transactionId, @NonNull MdnsListener listener,
Paul Hu812e9212023-06-20 06:24:53 +00002320 @Nullable Network requestedNetwork, long startTimeMs) {
2321 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002322 mListener = listener;
2323 }
2324 }
2325
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002326 /* Information tracked per client */
2327 private class ClientInfo {
2328
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002329 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002330 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002331 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002332 private NsdServiceInfo mResolvedService;
2333
Paul Hud44e1b72023-06-16 02:07:42 +00002334 /* A map from client request ID (listenerKey) to the request */
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002335 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08002336
Luke Huangf7277ed2021-07-12 21:15:10 +08002337 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002338 private boolean mIsPreSClient = false;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002339 private final int mUid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002340 // The flag of using java backend if the client's target SDK >= U
2341 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002342 // Store client logs
2343 private final SharedLog mClientLogs;
Paul Hucdef3532023-06-18 14:47:35 +00002344 // Report the nsd metrics data
2345 private final NetworkNsdReportedMetrics mMetrics;
Luke Huangf7277ed2021-07-12 21:15:10 +08002346
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002347 private ClientInfo(INsdManagerCallback cb, int uid, boolean useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +00002348 SharedLog sharedLog, NetworkNsdReportedMetrics metrics) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002349 mCb = cb;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002350 mUid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002351 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002352 mClientLogs = sharedLog;
2353 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Paul Hucdef3532023-06-18 14:47:35 +00002354 mMetrics = metrics;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002355 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002356
2357 @Override
2358 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06002359 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07002360 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002361 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002362 sb.append("mUseJavaBackend ").append(mUseJavaBackend).append("\n");
2363 sb.append("mUid ").append(mUid).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002364 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002365 int clientRequestId = mClientRequests.keyAt(i);
2366 sb.append("clientRequestId ")
2367 .append(clientRequestId)
2368 .append(" transactionId ").append(mClientRequests.valueAt(i).mTransactionId)
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002369 .append(" type ").append(
2370 mClientRequests.valueAt(i).getClass().getSimpleName())
2371 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07002372 }
2373 return sb.toString();
2374 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002375
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002376 private boolean isPreSClient() {
2377 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08002378 }
2379
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002380 private void setPreSClient() {
2381 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08002382 }
2383
Paul Hu812e9212023-06-20 06:24:53 +00002384 private MdnsListener unregisterMdnsListenerFromRequest(ClientRequest request) {
Paul Hue4f5f252023-02-16 21:13:47 +08002385 final MdnsListener listener =
2386 ((DiscoveryManagerRequest) request).mListener;
2387 mMdnsDiscoveryManager.unregisterListener(
2388 listener.getListenedServiceType(), listener);
Paul Hu812e9212023-06-20 06:24:53 +00002389 return listener;
Paul Hue4f5f252023-02-16 21:13:47 +08002390 }
2391
Dave Plattfeff2af2014-03-07 14:48:22 -08002392 // Remove any pending requests from the global map when we get rid of a client,
2393 // and send cancellations to the daemon.
2394 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00002395 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09002396 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002397 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002398 final int clientRequestId = mClientRequests.keyAt(i);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002399 final ClientRequest request = mClientRequests.valueAt(i);
Paul Hud44e1b72023-06-16 02:07:42 +00002400 final int transactionId = request.mTransactionId;
2401 mTransactionIdToClientInfoMap.remove(transactionId);
paulhub2225702021-11-17 09:35:33 +08002402 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002403 Log.d(TAG, "Terminating clientRequestId " + clientRequestId
2404 + " transactionId " + transactionId
2405 + " type " + mClientRequests.get(clientRequestId));
paulhub2225702021-11-17 09:35:33 +08002406 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002407
2408 if (request instanceof DiscoveryManagerRequest) {
Paul Hu812e9212023-06-20 06:24:53 +00002409 final MdnsListener listener = unregisterMdnsListenerFromRequest(request);
2410 if (listener instanceof DiscoveryListener) {
2411 mMetrics.reportServiceDiscoveryStop(transactionId,
2412 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2413 request.getFoundServiceCount(),
2414 request.getLostServiceCount(),
2415 request.getServicesCount());
Paul Hu60149052023-07-31 14:26:08 +08002416 } else if (listener instanceof ResolutionListener) {
2417 mMetrics.reportServiceResolutionStop(transactionId,
2418 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu812e9212023-06-20 06:24:53 +00002419 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002420 continue;
2421 }
2422
2423 if (request instanceof AdvertiserClientRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00002424 mAdvertiser.removeService(transactionId);
Paul Hu812e9212023-06-20 06:24:53 +00002425 mMetrics.reportServiceUnregistration(transactionId,
2426 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002427 continue;
2428 }
2429
2430 if (!(request instanceof LegacyClientRequest)) {
2431 throw new IllegalStateException("Unknown request type: " + request.getClass());
2432 }
2433
2434 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08002435 case NsdManager.DISCOVER_SERVICES:
Paul Hud44e1b72023-06-16 02:07:42 +00002436 stopServiceDiscovery(transactionId);
Paul Hu812e9212023-06-20 06:24:53 +00002437 mMetrics.reportServiceDiscoveryStop(transactionId,
2438 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2439 request.getFoundServiceCount(),
2440 request.getLostServiceCount(),
2441 request.getServicesCount());
Dave Plattfeff2af2014-03-07 14:48:22 -08002442 break;
2443 case NsdManager.RESOLVE_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002444 stopResolveService(transactionId);
Paul Hu60149052023-07-31 14:26:08 +08002445 mMetrics.reportServiceResolutionStop(transactionId,
2446 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Dave Plattfeff2af2014-03-07 14:48:22 -08002447 break;
2448 case NsdManager.REGISTER_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002449 unregisterService(transactionId);
Paul Hu812e9212023-06-20 06:24:53 +00002450 mMetrics.reportServiceUnregistration(transactionId,
2451 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Dave Plattfeff2af2014-03-07 14:48:22 -08002452 break;
2453 default:
2454 break;
2455 }
2456 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002457 mClientRequests.clear();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002458 updateMulticastLock();
2459 }
2460
2461 /**
2462 * Returns true if this client has any Java backend request that requests one of the given
2463 * networks.
2464 */
2465 boolean hasAnyJavaBackendRequestForNetworks(@NonNull ArraySet<Network> networks) {
2466 for (int i = 0; i < mClientRequests.size(); i++) {
2467 final ClientRequest req = mClientRequests.valueAt(i);
2468 if (!(req instanceof JavaBackendClientRequest)) {
2469 continue;
2470 }
2471 final Network reqNetwork = ((JavaBackendClientRequest) mClientRequests.valueAt(i))
2472 .getRequestedNetwork();
2473 if (MdnsUtils.isAnyNetworkMatched(reqNetwork, networks)) {
2474 return true;
2475 }
2476 }
2477 return false;
Dave Plattfeff2af2014-03-07 14:48:22 -08002478 }
2479
Paul Hud44e1b72023-06-16 02:07:42 +00002480 // mClientRequests is a sparse array of client request id -> ClientRequest. For a given
2481 // transaction id, return the corresponding client request id.
2482 private int getClientRequestId(final int transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002483 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002484 if (mClientRequests.valueAt(i).mTransactionId == transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002485 return mClientRequests.keyAt(i);
2486 }
Christopher Lane74411222014-04-25 18:39:07 -07002487 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002488 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07002489 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002490
Paul Hub2e67d32023-04-18 05:50:14 +00002491 private void log(String message) {
2492 mClientLogs.log(message);
2493 }
2494
Paul Hu812e9212023-06-20 06:24:53 +00002495 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info, int transactionId) {
2496 mMetrics.reportServiceDiscoveryStarted(transactionId);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002497 try {
2498 mCb.onDiscoverServicesStarted(listenerKey, info);
2499 } catch (RemoteException e) {
2500 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
2501 }
2502 }
Paul Hu812e9212023-06-20 06:24:53 +00002503 void onDiscoverServicesFailedImmediately(int listenerKey, int error) {
2504 onDiscoverServicesFailed(listenerKey, error, NO_TRANSACTION, 0L /* durationMs */);
2505 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002506
Paul Hu812e9212023-06-20 06:24:53 +00002507 void onDiscoverServicesFailed(int listenerKey, int error, int transactionId,
2508 long durationMs) {
2509 mMetrics.reportServiceDiscoveryFailed(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002510 try {
2511 mCb.onDiscoverServicesFailed(listenerKey, error);
2512 } catch (RemoteException e) {
2513 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
2514 }
2515 }
2516
Paul Hu812e9212023-06-20 06:24:53 +00002517 void onServiceFound(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2518 request.onServiceFound(info.getServiceName());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002519 try {
2520 mCb.onServiceFound(listenerKey, info);
2521 } catch (RemoteException e) {
2522 Log.e(TAG, "Error calling onServiceFound(", e);
2523 }
2524 }
2525
Paul Hu812e9212023-06-20 06:24:53 +00002526 void onServiceLost(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2527 request.onServiceLost();
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002528 try {
2529 mCb.onServiceLost(listenerKey, info);
2530 } catch (RemoteException e) {
2531 Log.e(TAG, "Error calling onServiceLost(", e);
2532 }
2533 }
2534
2535 void onStopDiscoveryFailed(int listenerKey, int error) {
2536 try {
2537 mCb.onStopDiscoveryFailed(listenerKey, error);
2538 } catch (RemoteException e) {
2539 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
2540 }
2541 }
2542
Paul Hu812e9212023-06-20 06:24:53 +00002543 void onStopDiscoverySucceeded(int listenerKey, ClientRequest request) {
2544 mMetrics.reportServiceDiscoveryStop(
2545 request.mTransactionId,
2546 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2547 request.getFoundServiceCount(),
2548 request.getLostServiceCount(),
2549 request.getServicesCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002550 try {
2551 mCb.onStopDiscoverySucceeded(listenerKey);
2552 } catch (RemoteException e) {
2553 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
2554 }
2555 }
2556
Paul Hu777ed052023-06-19 13:35:15 +00002557 void onRegisterServiceFailedImmediately(int listenerKey, int error) {
Paul Hu812e9212023-06-20 06:24:53 +00002558 onRegisterServiceFailed(listenerKey, error, NO_TRANSACTION, 0L /* durationMs */);
Paul Hu777ed052023-06-19 13:35:15 +00002559 }
2560
2561 void onRegisterServiceFailed(int listenerKey, int error, int transactionId,
2562 long durationMs) {
2563 mMetrics.reportServiceRegistrationFailed(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002564 try {
2565 mCb.onRegisterServiceFailed(listenerKey, error);
2566 } catch (RemoteException e) {
2567 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2568 }
2569 }
2570
Paul Hu777ed052023-06-19 13:35:15 +00002571 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info, int transactionId,
2572 long durationMs) {
2573 mMetrics.reportServiceRegistrationSucceeded(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002574 try {
2575 mCb.onRegisterServiceSucceeded(listenerKey, info);
2576 } catch (RemoteException e) {
2577 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2578 }
2579 }
2580
2581 void onUnregisterServiceFailed(int listenerKey, int error) {
2582 try {
2583 mCb.onUnregisterServiceFailed(listenerKey, error);
2584 } catch (RemoteException e) {
2585 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2586 }
2587 }
2588
Paul Hu777ed052023-06-19 13:35:15 +00002589 void onUnregisterServiceSucceeded(int listenerKey, int transactionId, long durationMs) {
2590 mMetrics.reportServiceUnregistration(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002591 try {
2592 mCb.onUnregisterServiceSucceeded(listenerKey);
2593 } catch (RemoteException e) {
2594 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2595 }
2596 }
2597
Paul Hua6bc4632023-06-26 01:18:29 +00002598 void onResolveServiceFailedImmediately(int listenerKey, int error) {
2599 onResolveServiceFailed(listenerKey, error, NO_TRANSACTION, 0L /* durationMs */);
2600 }
2601
2602 void onResolveServiceFailed(int listenerKey, int error, int transactionId,
2603 long durationMs) {
2604 mMetrics.reportServiceResolutionFailed(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002605 try {
2606 mCb.onResolveServiceFailed(listenerKey, error);
2607 } catch (RemoteException e) {
2608 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2609 }
2610 }
2611
Paul Hua6bc4632023-06-26 01:18:29 +00002612 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info,
2613 ClientRequest request) {
2614 mMetrics.reportServiceResolved(
2615 request.mTransactionId,
2616 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2617 request.isServiceFromCache());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002618 try {
2619 mCb.onResolveServiceSucceeded(listenerKey, info);
2620 } catch (RemoteException e) {
2621 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2622 }
2623 }
Paul Hub58deb72022-12-26 09:24:42 +00002624
2625 void onStopResolutionFailed(int listenerKey, int error) {
2626 try {
2627 mCb.onStopResolutionFailed(listenerKey, error);
2628 } catch (RemoteException e) {
2629 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2630 }
2631 }
2632
Paul Hu60149052023-07-31 14:26:08 +08002633 void onStopResolutionSucceeded(int listenerKey, ClientRequest request) {
2634 mMetrics.reportServiceResolutionStop(
2635 request.mTransactionId,
2636 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hub58deb72022-12-26 09:24:42 +00002637 try {
2638 mCb.onStopResolutionSucceeded(listenerKey);
2639 } catch (RemoteException e) {
2640 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2641 }
2642 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002643
2644 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
2645 try {
2646 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2647 } catch (RemoteException e) {
2648 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2649 }
2650 }
2651
2652 void onServiceUpdated(int listenerKey, NsdServiceInfo info) {
2653 try {
2654 mCb.onServiceUpdated(listenerKey, info);
2655 } catch (RemoteException e) {
2656 Log.e(TAG, "Error calling onServiceUpdated", e);
2657 }
2658 }
2659
2660 void onServiceUpdatedLost(int listenerKey) {
2661 try {
2662 mCb.onServiceUpdatedLost(listenerKey);
2663 } catch (RemoteException e) {
2664 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2665 }
2666 }
2667
2668 void onServiceInfoCallbackUnregistered(int listenerKey) {
2669 try {
2670 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2671 } catch (RemoteException e) {
2672 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2673 }
2674 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002675 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002676}