blob: f7edbe4ecf2490ff83dd8a55923c1bfe6b57179d [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;
paulhu2b9ed952022-02-10 21:58:32 +080020import static android.net.ConnectivityManager.NETID_UNSET;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090021import static android.net.NetworkCapabilities.TRANSPORT_VPN;
22import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
Paul Hu019621e2023-01-13 23:26:49 +080023import static android.net.nsd.NsdManager.MDNS_DISCOVERY_MANAGER_EVENT;
paulhu2b9ed952022-02-10 21:58:32 +080024import static android.net.nsd.NsdManager.MDNS_SERVICE_EVENT;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +090025import static android.net.nsd.NsdManager.RESOLVE_SERVICE_SUCCEEDED;
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +090026import static android.provider.DeviceConfig.NAMESPACE_TETHERING;
paulhu2b9ed952022-02-10 21:58:32 +080027
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090028import static com.android.modules.utils.build.SdkLevel.isAtLeastU;
Yuyang Huangde802c82023-05-02 17:14:22 +090029import static com.android.server.connectivity.mdns.MdnsRecord.MAX_LABEL_LENGTH;
Paul Hucdef3532023-06-18 14:47:35 +000030import static com.android.server.connectivity.mdns.util.MdnsUtils.Clock;
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090031
Paul Hu23fa2022023-01-13 22:57:24 +080032import android.annotation.NonNull;
Paul Hu4bd98ef2023-01-12 13:42:07 +080033import android.annotation.Nullable;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090034import android.app.ActivityManager;
paulhua262cc12019-08-12 16:25:11 +080035import android.content.Context;
Irfan Sheriff75006652012-04-17 23:15:29 -070036import android.content.Intent;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090037import android.net.ConnectivityManager;
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +090038import android.net.INetd;
Paul Hu75069ed2023-01-14 00:31:09 +080039import android.net.InetAddresses;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090040import android.net.LinkProperties;
41import android.net.Network;
paulhu2b9ed952022-02-10 21:58:32 +080042import android.net.mdns.aidl.DiscoveryInfo;
43import android.net.mdns.aidl.GetAddressInfo;
44import android.net.mdns.aidl.IMDnsEventListener;
45import android.net.mdns.aidl.RegistrationInfo;
46import android.net.mdns.aidl.ResolutionInfo;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070047import android.net.nsd.INsdManager;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090048import android.net.nsd.INsdManagerCallback;
49import android.net.nsd.INsdServiceConnector;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090050import android.net.nsd.IOffloadEngine;
paulhu2b9ed952022-02-10 21:58:32 +080051import android.net.nsd.MDnsManager;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070052import android.net.nsd.NsdManager;
paulhua262cc12019-08-12 16:25:11 +080053import android.net.nsd.NsdServiceInfo;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090054import android.net.nsd.OffloadEngine;
55import android.net.nsd.OffloadServiceInfo;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090056import android.net.wifi.WifiManager;
Paul Hub2e67d32023-04-18 05:50:14 +000057import android.os.Binder;
Hugo Benichi803a2f02017-04-24 11:35:06 +090058import android.os.Handler;
paulhua262cc12019-08-12 16:25:11 +080059import android.os.HandlerThread;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090060import android.os.IBinder;
Paul Hu4bd98ef2023-01-12 13:42:07 +080061import android.os.Looper;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070062import android.os.Message;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090063import android.os.RemoteCallbackList;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090064import android.os.RemoteException;
Dianne Hackborn692107e2012-08-29 18:32:08 -070065import android.os.UserHandle;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090066import android.provider.DeviceConfig;
Paul Hu23fa2022023-01-13 22:57:24 +080067import android.text.TextUtils;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090068import android.util.ArraySet;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090069import android.util.Log;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +090070import android.util.Pair;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070071import android.util.SparseArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070072
paulhua262cc12019-08-12 16:25:11 +080073import com.android.internal.annotations.VisibleForTesting;
Paul Hub2e67d32023-04-18 05:50:14 +000074import com.android.internal.util.IndentingPrintWriter;
paulhua262cc12019-08-12 16:25:11 +080075import com.android.internal.util.State;
76import com.android.internal.util.StateMachine;
Paul Hucdef3532023-06-18 14:47:35 +000077import com.android.metrics.NetworkNsdReportedMetrics;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090078import com.android.net.module.util.CollectionUtils;
Paul Hu4bd98ef2023-01-12 13:42:07 +080079import com.android.net.module.util.DeviceConfigUtils;
Yuyang Huanga6a6ff92023-04-24 13:33:34 +090080import com.android.net.module.util.InetAddressUtils;
paulhu3ffffe72021-09-16 10:15:22 +080081import com.android.net.module.util.PermissionUtils;
Paul Hub2e67d32023-04-18 05:50:14 +000082import com.android.net.module.util.SharedLog;
Paul Hu4bd98ef2023-01-12 13:42:07 +080083import com.android.server.connectivity.mdns.ExecutorProvider;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090084import com.android.server.connectivity.mdns.MdnsAdvertiser;
Paul Hu4bd98ef2023-01-12 13:42:07 +080085import com.android.server.connectivity.mdns.MdnsDiscoveryManager;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090086import com.android.server.connectivity.mdns.MdnsInterfaceSocket;
Paul Hu4bd98ef2023-01-12 13:42:07 +080087import com.android.server.connectivity.mdns.MdnsMultinetworkSocketClient;
Paul Hu23fa2022023-01-13 22:57:24 +080088import com.android.server.connectivity.mdns.MdnsSearchOptions;
89import com.android.server.connectivity.mdns.MdnsServiceBrowserListener;
90import com.android.server.connectivity.mdns.MdnsServiceInfo;
Paul Hu4bd98ef2023-01-12 13:42:07 +080091import com.android.server.connectivity.mdns.MdnsSocketProvider;
Yuyang Huangde802c82023-05-02 17:14:22 +090092import com.android.server.connectivity.mdns.util.MdnsUtils;
paulhua262cc12019-08-12 16:25:11 +080093
Irfan Sheriff77ec5582012-03-22 17:01:39 -070094import java.io.FileDescriptor;
95import java.io.PrintWriter;
Yuyang Huangaa0e9602023-03-17 12:43:09 +090096import java.net.Inet6Address;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070097import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090098import java.net.NetworkInterface;
99import java.net.SocketException;
100import java.net.UnknownHostException;
Paul Hu2b865912023-03-06 14:27:53 +0800101import java.util.ArrayList;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900102import java.util.Arrays;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700103import java.util.HashMap;
Paul Hu23fa2022023-01-13 22:57:24 +0800104import java.util.List;
Paul Hu75069ed2023-01-14 00:31:09 +0800105import java.util.Map;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900106import java.util.Objects;
Paul Hu23fa2022023-01-13 22:57:24 +0800107import java.util.regex.Matcher;
108import java.util.regex.Pattern;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700109
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700110/**
111 * Network Service Discovery Service handles remote service discovery operation requests by
112 * implementing the INsdManager interface.
113 *
114 * @hide
115 */
116public class NsdService extends INsdManager.Stub {
117 private static final String TAG = "NsdService";
118 private static final String MDNS_TAG = "mDnsConnector";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900119 /**
120 * Enable discovery using the Java DiscoveryManager, instead of the legacy mdnsresponder
121 * implementation.
122 */
Paul Hu4bd98ef2023-01-12 13:42:07 +0800123 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Paul Hu23fa2022023-01-13 22:57:24 +0800124 private static final String LOCAL_DOMAIN_NAME = "local";
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700125
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900126 /**
127 * Enable advertising using the Java MdnsAdvertiser, instead of the legacy mdnsresponder
128 * implementation.
129 */
130 private static final String MDNS_ADVERTISER_VERSION = "mdns_advertiser_version";
131
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900132 /**
133 * Comma-separated list of type:flag mappings indicating the flags to use to allowlist
134 * discovery/advertising using MdnsDiscoveryManager / MdnsAdvertiser for a given type.
135 *
136 * For example _mytype._tcp.local and _othertype._tcp.local would be configured with:
137 * _mytype._tcp:mytype,_othertype._tcp.local:othertype
138 *
139 * In which case the flags:
140 * "mdns_discovery_manager_allowlist_mytype_version",
141 * "mdns_advertiser_allowlist_mytype_version",
142 * "mdns_discovery_manager_allowlist_othertype_version",
143 * "mdns_advertiser_allowlist_othertype_version"
144 * would be used to toggle MdnsDiscoveryManager / MdnsAdvertiser for each type. The flags will
145 * be read with
146 * {@link DeviceConfigUtils#isFeatureEnabled(Context, String, String, String, boolean)}.
147 *
148 * @see #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX
149 * @see #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX
150 * @see #MDNS_ALLOWLIST_FLAG_SUFFIX
151 */
152 private static final String MDNS_TYPE_ALLOWLIST_FLAGS = "mdns_type_allowlist_flags";
153
154 private static final String MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX =
155 "mdns_discovery_manager_allowlist_";
156 private static final String MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX =
157 "mdns_advertiser_allowlist_";
158 private static final String MDNS_ALLOWLIST_FLAG_SUFFIX = "_version";
159
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900160 @VisibleForTesting
161 static final String MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
162 "mdns_config_running_app_active_importance_cutoff";
163 @VisibleForTesting
164 static final int DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
165 ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
166 private final int mRunningAppActiveImportanceCutoff;
167
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900168 public static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +0000169 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900170 private static final int IFACE_IDX_ANY = 0;
Paul Hu777ed052023-06-19 13:35:15 +0000171 private static final int NO_TRANSACTION = -1;
Paul Hu14667de2023-04-17 22:42:47 +0800172 private static final SharedLog LOGGER = new SharedLog("serviceDiscovery");
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700173
Hugo Benichi32be63d2017-04-05 14:06:11 +0900174 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900175 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +0800176 private final MDnsManager mMDnsManager;
177 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900178 @NonNull
179 private final Dependencies mDeps;
180 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800181 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900182 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800183 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900184 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800185 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900186 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900187 private final MdnsAdvertiser mAdvertiser;
Paul Hu777ed052023-06-19 13:35:15 +0000188 @NonNull
189 private final Clock mClock;
Paul Hu14667de2023-04-17 22:42:47 +0800190 private final SharedLog mServiceLogs = LOGGER.forSubComponent(TAG);
Paul Hu23fa2022023-01-13 22:57:24 +0800191 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800192 // state machine thread. If change this outside state machine, it will need to introduce
193 // synchronization.
194 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800195 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700196
197 /**
198 * Clients receiving asynchronous messages
199 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900200 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700201
Paul Hud44e1b72023-06-16 02:07:42 +0000202 /* A map from transaction(unique) id to client info */
203 private final SparseArray<ClientInfo> mTransactionIdToClientInfoMap = new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700204
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900205 // Note this is not final to avoid depending on the Wi-Fi service starting before NsdService
206 @Nullable
207 private WifiManager.MulticastLock mHeldMulticastLock;
208 // Fulfilled network requests that require the Wi-Fi lock: key is the obtained Network
209 // (non-null), value is the requested Network (nullable)
210 @NonNull
211 private final ArraySet<Network> mWifiLockRequiredNetworks = new ArraySet<>();
212 @NonNull
213 private final ArraySet<Integer> mRunningAppActiveUids = new ArraySet<>();
214
Luke Huang05298582021-06-13 16:52:05 +0000215 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700216
Hugo Benichi32be63d2017-04-05 14:06:11 +0900217 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700218 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800219 // The count of the connected legacy clients.
220 private int mLegacyClientCount = 0;
Paul Hub2e67d32023-04-18 05:50:14 +0000221 // The number of client that ever connected.
222 private int mClientNumberId = 1;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700223
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900224 private final RemoteCallbackList<IOffloadEngine> mOffloadEngines =
225 new RemoteCallbackList<>();
226
227 private static class OffloadEngineInfo {
228 @NonNull final String mInterfaceName;
229 final long mOffloadCapabilities;
230 final long mOffloadType;
231 @NonNull final IOffloadEngine mOffloadEngine;
232
233 OffloadEngineInfo(@NonNull IOffloadEngine offloadEngine,
234 @NonNull String interfaceName, long capabilities, long offloadType) {
235 this.mOffloadEngine = offloadEngine;
236 this.mInterfaceName = interfaceName;
237 this.mOffloadCapabilities = capabilities;
238 this.mOffloadType = offloadType;
239 }
240 }
241
Paul Hu23fa2022023-01-13 22:57:24 +0800242 private static class MdnsListener implements MdnsServiceBrowserListener {
Paul Hud44e1b72023-06-16 02:07:42 +0000243 protected final int mClientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800244 protected final int mTransactionId;
245 @NonNull
246 protected final NsdServiceInfo mReqServiceInfo;
247 @NonNull
248 protected final String mListenedServiceType;
249
Paul Hud44e1b72023-06-16 02:07:42 +0000250 MdnsListener(int clientRequestId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
Paul Hu23fa2022023-01-13 22:57:24 +0800251 @NonNull String listenedServiceType) {
Paul Hud44e1b72023-06-16 02:07:42 +0000252 mClientRequestId = clientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800253 mTransactionId = transactionId;
254 mReqServiceInfo = reqServiceInfo;
255 mListenedServiceType = listenedServiceType;
256 }
257
258 @NonNull
259 public String getListenedServiceType() {
260 return mListenedServiceType;
261 }
262
263 @Override
264 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo) { }
265
266 @Override
267 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
268
269 @Override
270 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
271
272 @Override
273 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) { }
274
275 @Override
276 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
277
278 @Override
279 public void onSearchStoppedWithError(int error) { }
280
281 @Override
282 public void onSearchFailedToStart() { }
283
284 @Override
285 public void onDiscoveryQuerySent(@NonNull List<String> subtypes, int transactionId) { }
286
287 @Override
288 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
289 }
290
291 private class DiscoveryListener extends MdnsListener {
292
Paul Hud44e1b72023-06-16 02:07:42 +0000293 DiscoveryListener(int clientRequestId, int transactionId,
294 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
295 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800296 }
297
298 @Override
299 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu019621e2023-01-13 23:26:49 +0800300 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
301 NsdManager.SERVICE_FOUND,
Paul Hud44e1b72023-06-16 02:07:42 +0000302 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800303 }
304
305 @Override
306 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800307 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
308 NsdManager.SERVICE_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000309 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800310 }
311 }
312
Paul Hu75069ed2023-01-14 00:31:09 +0800313 private class ResolutionListener extends MdnsListener {
314
Paul Hud44e1b72023-06-16 02:07:42 +0000315 ResolutionListener(int clientRequestId, int transactionId,
316 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
317 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800318 }
319
320 @Override
321 public void onServiceFound(MdnsServiceInfo serviceInfo) {
322 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
323 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
Paul Hud44e1b72023-06-16 02:07:42 +0000324 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu75069ed2023-01-14 00:31:09 +0800325 }
326 }
327
Paul Hu30bd70d2023-02-07 13:20:56 +0000328 private class ServiceInfoListener extends MdnsListener {
329
Paul Hud44e1b72023-06-16 02:07:42 +0000330 ServiceInfoListener(int clientRequestId, int transactionId,
331 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
332 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +0000333 }
334
335 @Override
336 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo) {
337 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
338 NsdManager.SERVICE_UPDATED,
Paul Hud44e1b72023-06-16 02:07:42 +0000339 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000340 }
341
342 @Override
343 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) {
344 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
345 NsdManager.SERVICE_UPDATED,
Paul Hud44e1b72023-06-16 02:07:42 +0000346 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000347 }
348
349 @Override
350 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) {
351 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
352 NsdManager.SERVICE_UPDATED_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000353 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000354 }
355 }
356
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900357 private class SocketRequestMonitor implements MdnsSocketProvider.SocketRequestMonitor {
358 @Override
359 public void onSocketRequestFulfilled(@Nullable Network socketNetwork,
360 @NonNull MdnsInterfaceSocket socket, @NonNull int[] transports) {
361 // The network may be null for Wi-Fi SoftAp interfaces (tethering), but there is no APF
362 // filtering on such interfaces, so taking the multicast lock is not necessary to
363 // disable APF filtering of multicast.
364 if (socketNetwork == null
365 || !CollectionUtils.contains(transports, TRANSPORT_WIFI)
366 || CollectionUtils.contains(transports, TRANSPORT_VPN)) {
367 return;
368 }
369
370 if (mWifiLockRequiredNetworks.add(socketNetwork)) {
371 updateMulticastLock();
372 }
373 }
374
375 @Override
376 public void onSocketDestroyed(@Nullable Network socketNetwork,
377 @NonNull MdnsInterfaceSocket socket) {
378 if (mWifiLockRequiredNetworks.remove(socketNetwork)) {
379 updateMulticastLock();
380 }
381 }
382 }
383
384 private class UidImportanceListener implements ActivityManager.OnUidImportanceListener {
385 private final Handler mHandler;
386
387 private UidImportanceListener(Handler handler) {
388 mHandler = handler;
389 }
390
391 @Override
392 public void onUidImportance(int uid, int importance) {
393 mHandler.post(() -> handleUidImportanceChanged(uid, importance));
394 }
395 }
396
397 private void handleUidImportanceChanged(int uid, int importance) {
398 // Lower importance values are more "important"
399 final boolean modified = importance <= mRunningAppActiveImportanceCutoff
400 ? mRunningAppActiveUids.add(uid)
401 : mRunningAppActiveUids.remove(uid);
402 if (modified) {
403 updateMulticastLock();
404 }
405 }
406
407 /**
408 * Take or release the lock based on updated internal state.
409 *
410 * This determines whether the lock needs to be held based on
411 * {@link #mWifiLockRequiredNetworks}, {@link #mRunningAppActiveUids} and
412 * {@link ClientInfo#mClientRequests}, so it must be called after any of the these have been
413 * updated.
414 */
415 private void updateMulticastLock() {
416 final int needsLockUid = getMulticastLockNeededUid();
417 if (needsLockUid >= 0 && mHeldMulticastLock == null) {
418 final WifiManager wm = mContext.getSystemService(WifiManager.class);
419 if (wm == null) {
420 Log.wtf(TAG, "Got a TRANSPORT_WIFI network without WifiManager");
421 return;
422 }
423 mHeldMulticastLock = wm.createMulticastLock(TAG);
424 mHeldMulticastLock.acquire();
425 mServiceLogs.log("Taking multicast lock for uid " + needsLockUid);
426 } else if (needsLockUid < 0 && mHeldMulticastLock != null) {
427 mHeldMulticastLock.release();
428 mHeldMulticastLock = null;
429 mServiceLogs.log("Released multicast lock");
430 }
431 }
432
433 /**
434 * @return The UID of an app requiring the multicast lock, or -1 if none.
435 */
436 private int getMulticastLockNeededUid() {
437 if (mWifiLockRequiredNetworks.size() == 0) {
438 // Return early if NSD is not active, or not on any relevant network
439 return -1;
440 }
Paul Hud44e1b72023-06-16 02:07:42 +0000441 for (int i = 0; i < mTransactionIdToClientInfoMap.size(); i++) {
442 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.valueAt(i);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900443 if (!mRunningAppActiveUids.contains(clientInfo.mUid)) {
444 // Ignore non-active UIDs
445 continue;
446 }
447
448 if (clientInfo.hasAnyJavaBackendRequestForNetworks(mWifiLockRequiredNetworks)) {
449 return clientInfo.mUid;
450 }
451 }
452 return -1;
453 }
454
Paul Hu019621e2023-01-13 23:26:49 +0800455 /**
456 * Data class of mdns service callback information.
457 */
458 private static class MdnsEvent {
Paul Hud44e1b72023-06-16 02:07:42 +0000459 final int mClientRequestId;
Paul Hu019621e2023-01-13 23:26:49 +0800460 @NonNull
Paul Hu019621e2023-01-13 23:26:49 +0800461 final MdnsServiceInfo mMdnsServiceInfo;
462
Paul Hud44e1b72023-06-16 02:07:42 +0000463 MdnsEvent(int clientRequestId, @NonNull MdnsServiceInfo mdnsServiceInfo) {
464 mClientRequestId = clientRequestId;
Paul Hu019621e2023-01-13 23:26:49 +0800465 mMdnsServiceInfo = mdnsServiceInfo;
466 }
467 }
468
Irfan Sheriff75006652012-04-17 23:15:29 -0700469 private class NsdStateMachine extends StateMachine {
470
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700471 private final DefaultState mDefaultState = new DefaultState();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700472 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700473
474 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700475 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900476 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700477 }
478
Luke Huang92860f92021-06-23 06:29:30 +0000479 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800480 if (mIsDaemonStarted) {
481 if (DBG) Log.d(TAG, "Daemon is already started.");
482 return;
483 }
484 mMDnsManager.registerEventListener(mMDnsEventCallback);
485 mMDnsManager.startDaemon();
486 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000487 maybeScheduleStop();
Paul Hub2e67d32023-04-18 05:50:14 +0000488 mServiceLogs.log("Start mdns_responder daemon");
Luke Huang05298582021-06-13 16:52:05 +0000489 }
490
paulhu2b9ed952022-02-10 21:58:32 +0800491 private void maybeStopDaemon() {
492 if (!mIsDaemonStarted) {
493 if (DBG) Log.d(TAG, "Daemon has not been started.");
494 return;
495 }
496 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
497 mMDnsManager.stopDaemon();
498 mIsDaemonStarted = false;
Paul Hub2e67d32023-04-18 05:50:14 +0000499 mServiceLogs.log("Stop mdns_responder daemon");
paulhu2b9ed952022-02-10 21:58:32 +0800500 }
501
Luke Huang92860f92021-06-23 06:29:30 +0000502 private boolean isAnyRequestActive() {
Paul Hud44e1b72023-06-16 02:07:42 +0000503 return mTransactionIdToClientInfoMap.size() != 0;
Luke Huang92860f92021-06-23 06:29:30 +0000504 }
505
506 private void scheduleStop() {
507 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
508 }
509 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800510 // The native daemon should stay alive and can't be cleanup
511 // if any legacy client connected.
512 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000513 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000514 }
515 }
516
Luke Huang92860f92021-06-23 06:29:30 +0000517 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000518 this.removeMessages(NsdManager.DAEMON_CLEANUP);
519 }
520
Paul Hu23fa2022023-01-13 22:57:24 +0800521 private void maybeStartMonitoringSockets() {
522 if (mIsMonitoringSocketsStarted) {
523 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
524 return;
525 }
526
527 mMdnsSocketProvider.startMonitoringSockets();
528 mIsMonitoringSocketsStarted = true;
529 }
530
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900531 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
532 if (!mIsMonitoringSocketsStarted) return;
533 if (isAnyRequestActive()) return;
534
Paul Hu58f20602023-02-18 11:41:07 +0800535 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800536 mIsMonitoringSocketsStarted = false;
537 }
538
Hugo Benichi803a2f02017-04-24 11:35:06 +0900539 NsdStateMachine(String name, Handler handler) {
540 super(name, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -0700541 addState(mDefaultState);
Irfan Sheriff75006652012-04-17 23:15:29 -0700542 addState(mEnabledState, mDefaultState);
paulhu5568f452021-11-30 13:31:29 +0800543 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900544 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700545 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700546 }
547
548 class DefaultState extends State {
549 @Override
550 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900551 final ClientInfo cInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000552 final int clientRequestId = msg.arg2;
Irfan Sheriff75006652012-04-17 23:15:29 -0700553 switch (msg.what) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900554 case NsdManager.REGISTER_CLIENT:
Paul Hu2e0a88c2023-03-09 16:05:01 +0800555 final ConnectorArgs arg = (ConnectorArgs) msg.obj;
556 final INsdManagerCallback cb = arg.callback;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900557 try {
Paul Hu2e0a88c2023-03-09 16:05:01 +0800558 cb.asBinder().linkToDeath(arg.connector, 0);
Paul Hub2e67d32023-04-18 05:50:14 +0000559 final String tag = "Client" + arg.uid + "-" + mClientNumberId++;
Paul Hu777ed052023-06-19 13:35:15 +0000560 final NetworkNsdReportedMetrics metrics =
561 mDeps.makeNetworkNsdReportedMetrics(
562 !arg.useJavaBackend, (int) mClock.elapsedRealtime());
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900563 cInfo = new ClientInfo(cb, arg.uid, arg.useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +0000564 mServiceLogs.forSubComponent(tag), metrics);
Paul Hu2e0a88c2023-03-09 16:05:01 +0800565 mClients.put(arg.connector, cInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900566 } catch (RemoteException e) {
Paul Hud44e1b72023-06-16 02:07:42 +0000567 Log.w(TAG, "Client request id " + clientRequestId
568 + " has already died");
Irfan Sheriff75006652012-04-17 23:15:29 -0700569 }
570 break;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900571 case NsdManager.UNREGISTER_CLIENT:
572 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
573 cInfo = mClients.remove(connector);
Dave Plattfeff2af2014-03-07 14:48:22 -0800574 if (cInfo != null) {
575 cInfo.expungeAllRequests();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900576 if (cInfo.isPreSClient()) {
Luke Huangf7277ed2021-07-12 21:15:10 +0800577 mLegacyClientCount -= 1;
578 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800579 }
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900580 maybeStopMonitoringSocketsIfNoActiveRequest();
Luke Huangf7277ed2021-07-12 21:15:10 +0800581 maybeScheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700582 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700583 case NsdManager.DISCOVER_SERVICES:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900584 cInfo = getClientInfoForReply(msg);
585 if (cInfo != null) {
586 cInfo.onDiscoverServicesFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000587 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900588 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700589 break;
590 case NsdManager.STOP_DISCOVERY:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900591 cInfo = getClientInfoForReply(msg);
592 if (cInfo != null) {
593 cInfo.onStopDiscoveryFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000594 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900595 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700596 break;
597 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900598 cInfo = getClientInfoForReply(msg);
599 if (cInfo != null) {
Paul Hu777ed052023-06-19 13:35:15 +0000600 cInfo.onRegisterServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000601 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900602 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700603 break;
604 case NsdManager.UNREGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900605 cInfo = getClientInfoForReply(msg);
606 if (cInfo != null) {
607 cInfo.onUnregisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000608 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900609 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700610 break;
611 case NsdManager.RESOLVE_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900612 cInfo = getClientInfoForReply(msg);
613 if (cInfo != null) {
614 cInfo.onResolveServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000615 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900616 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700617 break;
Paul Hub58deb72022-12-26 09:24:42 +0000618 case NsdManager.STOP_RESOLUTION:
619 cInfo = getClientInfoForReply(msg);
620 if (cInfo != null) {
621 cInfo.onStopResolutionFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000622 clientRequestId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hub58deb72022-12-26 09:24:42 +0000623 }
624 break;
Paul Hu18aeccc2022-12-27 08:48:48 +0000625 case NsdManager.REGISTER_SERVICE_CALLBACK:
626 cInfo = getClientInfoForReply(msg);
627 if (cInfo != null) {
628 cInfo.onServiceInfoCallbackRegistrationFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000629 clientRequestId, NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +0000630 }
631 break;
Luke Huang05298582021-06-13 16:52:05 +0000632 case NsdManager.DAEMON_CLEANUP:
paulhu2b9ed952022-02-10 21:58:32 +0800633 maybeStopDaemon();
Luke Huang05298582021-06-13 16:52:05 +0000634 break;
Luke Huangf7277ed2021-07-12 21:15:10 +0800635 // This event should be only sent by the legacy (target SDK < S) clients.
636 // Mark the sending client as legacy.
637 case NsdManager.DAEMON_STARTUP:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900638 cInfo = getClientInfoForReply(msg);
Luke Huangf7277ed2021-07-12 21:15:10 +0800639 if (cInfo != null) {
640 cancelStop();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900641 cInfo.setPreSClient();
Luke Huangf7277ed2021-07-12 21:15:10 +0800642 mLegacyClientCount += 1;
643 maybeStartDaemon();
644 }
645 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700646 default:
paulhub2225702021-11-17 09:35:33 +0800647 Log.e(TAG, "Unhandled " + msg);
Irfan Sheriff75006652012-04-17 23:15:29 -0700648 return NOT_HANDLED;
649 }
650 return HANDLED;
651 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900652
653 private ClientInfo getClientInfoForReply(Message msg) {
654 final ListenerArgs args = (ListenerArgs) msg.obj;
655 return mClients.get(args.connector);
656 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700657 }
658
Irfan Sheriff75006652012-04-17 23:15:29 -0700659 class EnabledState extends State {
660 @Override
661 public void enter() {
662 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700663 }
664
665 @Override
666 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000667 // TODO: it is incorrect to stop the daemon without expunging all requests
668 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000669 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700670 }
671
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700672 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900673 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800674 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700675 return true;
676 }
677 return false;
678 }
679
Paul Hud44e1b72023-06-16 02:07:42 +0000680 private void storeLegacyRequestMap(int clientRequestId, int transactionId,
681 ClientInfo clientInfo, int what) {
Paul Hu777ed052023-06-19 13:35:15 +0000682 clientInfo.mClientRequests.put(clientRequestId, new LegacyClientRequest(
683 transactionId, what, mClock, mClock.elapsedRealtime()));
Paul Hud44e1b72023-06-16 02:07:42 +0000684 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000685 // Remove the cleanup event because here comes a new request.
686 cancelStop();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700687 }
688
Paul Hud44e1b72023-06-16 02:07:42 +0000689 private void storeAdvertiserRequestMap(int clientRequestId, int transactionId,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900690 ClientInfo clientInfo, @Nullable Network requestedNetwork) {
Paul Hu777ed052023-06-19 13:35:15 +0000691 clientInfo.mClientRequests.put(clientRequestId, new AdvertiserClientRequest(
692 transactionId, requestedNetwork, mClock, mClock.elapsedRealtime()));
Paul Hud44e1b72023-06-16 02:07:42 +0000693 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900694 updateMulticastLock();
Paul Hu23fa2022023-01-13 22:57:24 +0800695 }
696
Paul Hud44e1b72023-06-16 02:07:42 +0000697 private void removeRequestMap(
698 int clientRequestId, int transactionId, ClientInfo clientInfo) {
699 final ClientRequest existing = clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900700 if (existing == null) return;
Paul Hud44e1b72023-06-16 02:07:42 +0000701 clientInfo.mClientRequests.remove(clientRequestId);
702 mTransactionIdToClientInfoMap.remove(transactionId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900703
704 if (existing instanceof LegacyClientRequest) {
705 maybeScheduleStop();
706 } else {
707 maybeStopMonitoringSocketsIfNoActiveRequest();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900708 updateMulticastLock();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900709 }
710 }
711
Paul Hud44e1b72023-06-16 02:07:42 +0000712 private void storeDiscoveryManagerRequestMap(int clientRequestId, int transactionId,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900713 MdnsListener listener, ClientInfo clientInfo,
714 @Nullable Network requestedNetwork) {
Paul Hu777ed052023-06-19 13:35:15 +0000715 clientInfo.mClientRequests.put(clientRequestId, new DiscoveryManagerRequest(
716 transactionId, listener, requestedNetwork, mClock,
717 mClock.elapsedRealtime()));
Paul Hud44e1b72023-06-16 02:07:42 +0000718 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900719 updateMulticastLock();
Paul Hu23fa2022023-01-13 22:57:24 +0800720 }
721
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900722 /**
723 * Truncate a service name to up to 63 UTF-8 bytes.
724 *
725 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
726 * names used in registerService follows historical behavior (see mdnsresponder
727 * handle_regservice_request).
728 */
729 @NonNull
730 private String truncateServiceName(@NonNull String originalName) {
Yuyang Huangde802c82023-05-02 17:14:22 +0900731 return MdnsUtils.truncateServiceName(originalName, MAX_LABEL_LENGTH);
Paul Hu23fa2022023-01-13 22:57:24 +0800732 }
733
Paul Hud44e1b72023-06-16 02:07:42 +0000734 private void stopDiscoveryManagerRequest(ClientRequest request, int clientRequestId,
735 int transactionId, ClientInfo clientInfo) {
Paul Hue4f5f252023-02-16 21:13:47 +0800736 clientInfo.unregisterMdnsListenerFromRequest(request);
Paul Hud44e1b72023-06-16 02:07:42 +0000737 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hue4f5f252023-02-16 21:13:47 +0800738 }
739
Irfan Sheriff75006652012-04-17 23:15:29 -0700740 @Override
741 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900742 final ClientInfo clientInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000743 final int transactionId;
744 final int clientRequestId = msg.arg2;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900745 final ListenerArgs args;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900746 final OffloadEngineInfo offloadEngineInfo;
Irfan Sheriff75006652012-04-17 23:15:29 -0700747 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800748 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800749 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900750 args = (ListenerArgs) msg.obj;
751 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000752 // If the binder death notification for a INsdManagerCallback was received
753 // before any calls are received by NsdService, the clientInfo would be
754 // cleared and cause NPE. Add a null check here to prevent this corner case.
755 if (clientInfo == null) {
756 Log.e(TAG, "Unknown connector in discovery");
757 break;
758 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700759
760 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900761 clientInfo.onDiscoverServicesFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000762 clientRequestId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriff75006652012-04-17 23:15:29 -0700763 break;
764 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700765
Paul Hu23fa2022023-01-13 22:57:24 +0800766 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000767 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900768 final Pair<String, String> typeAndSubtype =
769 parseTypeAndSubtype(info.getServiceType());
770 final String serviceType = typeAndSubtype == null
771 ? null : typeAndSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800772 if (clientInfo.mUseJavaBackend
773 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900774 || useDiscoveryManagerForType(serviceType)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800775 if (serviceType == null) {
Paul Hud44e1b72023-06-16 02:07:42 +0000776 clientInfo.onDiscoverServicesFailed(clientRequestId,
Paul Hu23fa2022023-01-13 22:57:24 +0800777 NsdManager.FAILURE_INTERNAL_ERROR);
778 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700779 }
Paul Hu23fa2022023-01-13 22:57:24 +0800780
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900781 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800782 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +0000783 final MdnsListener listener = new DiscoveryListener(clientRequestId,
784 transactionId, info, listenServiceType);
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900785 final MdnsSearchOptions.Builder optionsBuilder =
786 MdnsSearchOptions.newBuilder()
787 .setNetwork(info.getNetwork())
Yuyang Huangff963222023-06-01 18:42:42 +0900788 .setRemoveExpiredService(true)
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900789 .setIsPassiveMode(true);
790 if (typeAndSubtype.second != null) {
791 // The parsing ensures subtype starts with an underscore.
792 // MdnsSearchOptions expects the underscore to not be present.
793 optionsBuilder.addSubtype(typeAndSubtype.second.substring(1));
794 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900795 mMdnsDiscoveryManager.registerListener(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900796 listenServiceType, listener, optionsBuilder.build());
Paul Hud44e1b72023-06-16 02:07:42 +0000797 storeDiscoveryManagerRequestMap(clientRequestId, transactionId,
798 listener, clientInfo, info.getNetwork());
799 clientInfo.onDiscoverServicesStarted(clientRequestId, info);
800 clientInfo.log("Register a DiscoveryListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +0000801 + " for service type:" + listenServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700802 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800803 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000804 if (discoverServices(transactionId, info)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800805 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +0000806 Log.d(TAG, "Discover " + msg.arg2 + " " + transactionId
Paul Hu23fa2022023-01-13 22:57:24 +0800807 + info.getServiceType());
808 }
Paul Hud44e1b72023-06-16 02:07:42 +0000809 storeLegacyRequestMap(
810 clientRequestId, transactionId, clientInfo, msg.what);
811 clientInfo.onDiscoverServicesStarted(clientRequestId, info);
Paul Hu23fa2022023-01-13 22:57:24 +0800812 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000813 stopServiceDiscovery(transactionId);
814 clientInfo.onDiscoverServicesFailed(clientRequestId,
Paul Hu23fa2022023-01-13 22:57:24 +0800815 NsdManager.FAILURE_INTERNAL_ERROR);
816 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700817 }
818 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800819 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900820 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800821 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900822 args = (ListenerArgs) msg.obj;
823 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000824 // If the binder death notification for a INsdManagerCallback was received
825 // before any calls are received by NsdService, the clientInfo would be
826 // cleared and cause NPE. Add a null check here to prevent this corner case.
827 if (clientInfo == null) {
828 Log.e(TAG, "Unknown connector in stop discovery");
829 break;
830 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700831
Paul Hud44e1b72023-06-16 02:07:42 +0000832 final ClientRequest request =
833 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900834 if (request == null) {
835 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700836 break;
837 }
Paul Hud44e1b72023-06-16 02:07:42 +0000838 transactionId = request.mTransactionId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900839 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
840 // point, so this needs to check the type of the original request to
841 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900842 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +0000843 stopDiscoveryManagerRequest(
844 request, clientRequestId, transactionId, clientInfo);
845 clientInfo.onStopDiscoverySucceeded(clientRequestId);
846 clientInfo.log("Unregister the DiscoveryListener " + transactionId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700847 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000848 removeRequestMap(clientRequestId, transactionId, clientInfo);
849 if (stopServiceDiscovery(transactionId)) {
850 clientInfo.onStopDiscoverySucceeded(clientRequestId);
Paul Hu23fa2022023-01-13 22:57:24 +0800851 } else {
852 clientInfo.onStopDiscoveryFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000853 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu23fa2022023-01-13 22:57:24 +0800854 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700855 }
856 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900857 }
858 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800859 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900860 args = (ListenerArgs) msg.obj;
861 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000862 // If the binder death notification for a INsdManagerCallback was received
863 // before any calls are received by NsdService, the clientInfo would be
864 // cleared and cause NPE. Add a null check here to prevent this corner case.
865 if (clientInfo == null) {
866 Log.e(TAG, "Unknown connector in registration");
867 break;
868 }
869
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700870 if (requestLimitReached(clientInfo)) {
Paul Hu777ed052023-06-19 13:35:15 +0000871 clientInfo.onRegisterServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000872 clientRequestId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700873 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700874 }
875
Paul Hud44e1b72023-06-16 02:07:42 +0000876 transactionId = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900877 final NsdServiceInfo serviceInfo = args.serviceInfo;
878 final String serviceType = serviceInfo.getServiceType();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900879 final Pair<String, String> typeSubtype = parseTypeAndSubtype(serviceType);
880 final String registerServiceType = typeSubtype == null
881 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800882 if (clientInfo.mUseJavaBackend
883 || mDeps.isMdnsAdvertiserEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900884 || useAdvertiserForType(registerServiceType)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900885 if (registerServiceType == null) {
886 Log.e(TAG, "Invalid service type: " + serviceType);
Paul Hu777ed052023-06-19 13:35:15 +0000887 clientInfo.onRegisterServiceFailedImmediately(
888 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900889 break;
890 }
891 serviceInfo.setServiceType(registerServiceType);
892 serviceInfo.setServiceName(truncateServiceName(
893 serviceInfo.getServiceName()));
894
895 maybeStartMonitoringSockets();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900896 // TODO: pass in the subtype as well. Including the subtype in the
897 // service type would generate service instance names like
898 // Name._subtype._sub._type._tcp, which is incorrect
899 // (it should be Name._type._tcp).
Paul Hud44e1b72023-06-16 02:07:42 +0000900 mAdvertiser.addService(transactionId, serviceInfo, typeSubtype.second);
901 storeAdvertiserRequestMap(clientRequestId, transactionId, clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900902 serviceInfo.getNetwork());
Irfan Sheriff75006652012-04-17 23:15:29 -0700903 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900904 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000905 if (registerService(transactionId, serviceInfo)) {
906 if (DBG) {
907 Log.d(TAG, "Register " + clientRequestId
908 + " " + transactionId);
909 }
910 storeLegacyRequestMap(
911 clientRequestId, transactionId, clientInfo, msg.what);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900912 // Return success after mDns reports success
913 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000914 unregisterService(transactionId);
Paul Hu777ed052023-06-19 13:35:15 +0000915 clientInfo.onRegisterServiceFailedImmediately(
Paul Hud44e1b72023-06-16 02:07:42 +0000916 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900917 }
918
Irfan Sheriff75006652012-04-17 23:15:29 -0700919 }
920 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900921 }
922 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800923 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900924 args = (ListenerArgs) msg.obj;
925 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000926 // If the binder death notification for a INsdManagerCallback was received
927 // before any calls are received by NsdService, the clientInfo would be
928 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900929 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800930 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700931 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700932 }
Paul Hud44e1b72023-06-16 02:07:42 +0000933 final ClientRequest request =
934 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900935 if (request == null) {
936 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
937 break;
938 }
Paul Hud44e1b72023-06-16 02:07:42 +0000939 transactionId = request.mTransactionId;
940 removeRequestMap(clientRequestId, transactionId, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900941
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900942 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
943 // so this needs to check the type of the original request to unregister
944 // instead of looking at the flag value.
945 if (request instanceof AdvertiserClientRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +0000946 mAdvertiser.removeService(transactionId);
Paul Hu777ed052023-06-19 13:35:15 +0000947 clientInfo.onUnregisterServiceSucceeded(clientRequestId, transactionId,
948 request.calculateRequestDurationMs());
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700949 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000950 if (unregisterService(transactionId)) {
Paul Hu777ed052023-06-19 13:35:15 +0000951 clientInfo.onUnregisterServiceSucceeded(clientRequestId,
952 transactionId, request.calculateRequestDurationMs());
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900953 } else {
954 clientInfo.onUnregisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000955 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900956 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700957 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700958 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900959 }
Paul Hu75069ed2023-01-14 00:31:09 +0800960 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800961 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900962 args = (ListenerArgs) msg.obj;
963 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000964 // If the binder death notification for a INsdManagerCallback was received
965 // before any calls are received by NsdService, the clientInfo would be
966 // cleared and cause NPE. Add a null check here to prevent this corner case.
967 if (clientInfo == null) {
968 Log.e(TAG, "Unknown connector in resolution");
969 break;
970 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700971
Paul Hu75069ed2023-01-14 00:31:09 +0800972 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000973 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900974 final Pair<String, String> typeSubtype =
975 parseTypeAndSubtype(info.getServiceType());
976 final String serviceType = typeSubtype == null
977 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800978 if (clientInfo.mUseJavaBackend
979 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900980 || useDiscoveryManagerForType(serviceType)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800981 if (serviceType == null) {
Paul Hud44e1b72023-06-16 02:07:42 +0000982 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu75069ed2023-01-14 00:31:09 +0800983 NsdManager.FAILURE_INTERNAL_ERROR);
984 break;
985 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900986 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +0800987
988 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +0000989 final MdnsListener listener = new ResolutionListener(clientRequestId,
990 transactionId, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800991 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
992 .setNetwork(info.getNetwork())
993 .setIsPassiveMode(true)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900994 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +0900995 .setRemoveExpiredService(true)
Paul Hu75069ed2023-01-14 00:31:09 +0800996 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900997 mMdnsDiscoveryManager.registerListener(
998 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +0000999 storeDiscoveryManagerRequestMap(clientRequestId, transactionId,
1000 listener, clientInfo, info.getNetwork());
1001 clientInfo.log("Register a ResolutionListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001002 + " for service type:" + resolveServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -07001003 } else {
Paul Hu75069ed2023-01-14 00:31:09 +08001004 if (clientInfo.mResolvedService != null) {
1005 clientInfo.onResolveServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001006 clientRequestId, NsdManager.FAILURE_ALREADY_ACTIVE);
Paul Hu75069ed2023-01-14 00:31:09 +08001007 break;
1008 }
1009
1010 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +00001011 if (resolveService(transactionId, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +08001012 clientInfo.mResolvedService = new NsdServiceInfo();
Paul Hud44e1b72023-06-16 02:07:42 +00001013 storeLegacyRequestMap(
1014 clientRequestId, transactionId, clientInfo, msg.what);
Paul Hu75069ed2023-01-14 00:31:09 +08001015 } else {
1016 clientInfo.onResolveServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001017 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu75069ed2023-01-14 00:31:09 +08001018 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001019 }
1020 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001021 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001022 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +00001023 if (DBG) Log.d(TAG, "Stop service resolution");
1024 args = (ListenerArgs) msg.obj;
1025 clientInfo = mClients.get(args.connector);
1026 // If the binder death notification for a INsdManagerCallback was received
1027 // before any calls are received by NsdService, the clientInfo would be
1028 // cleared and cause NPE. Add a null check here to prevent this corner case.
1029 if (clientInfo == null) {
1030 Log.e(TAG, "Unknown connector in stop resolution");
1031 break;
1032 }
1033
Paul Hud44e1b72023-06-16 02:07:42 +00001034 final ClientRequest request =
1035 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001036 if (request == null) {
1037 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
1038 break;
1039 }
Paul Hud44e1b72023-06-16 02:07:42 +00001040 transactionId = request.mTransactionId;
Paul Hue4f5f252023-02-16 21:13:47 +08001041 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
1042 // point, so this needs to check the type of the original request to
1043 // unregister instead of looking at the flag value.
1044 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001045 stopDiscoveryManagerRequest(
1046 request, clientRequestId, transactionId, clientInfo);
1047 clientInfo.onStopResolutionSucceeded(clientRequestId);
1048 clientInfo.log("Unregister the ResolutionListener " + transactionId);
Paul Hub58deb72022-12-26 09:24:42 +00001049 } else {
Paul Hud44e1b72023-06-16 02:07:42 +00001050 removeRequestMap(clientRequestId, transactionId, clientInfo);
1051 if (stopResolveService(transactionId)) {
1052 clientInfo.onStopResolutionSucceeded(clientRequestId);
Paul Hue4f5f252023-02-16 21:13:47 +08001053 } else {
1054 clientInfo.onStopResolutionFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001055 clientRequestId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hue4f5f252023-02-16 21:13:47 +08001056 }
1057 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +00001058 }
Paul Hub58deb72022-12-26 09:24:42 +00001059 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001060 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001061 case NsdManager.REGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001062 if (DBG) Log.d(TAG, "Register a service callback");
1063 args = (ListenerArgs) msg.obj;
1064 clientInfo = mClients.get(args.connector);
1065 // If the binder death notification for a INsdManagerCallback was received
1066 // before any calls are received by NsdService, the clientInfo would be
1067 // cleared and cause NPE. Add a null check here to prevent this corner case.
1068 if (clientInfo == null) {
1069 Log.e(TAG, "Unknown connector in callback registration");
1070 break;
1071 }
1072
Paul Hu30bd70d2023-02-07 13:20:56 +00001073 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001074 transactionId = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001075 final Pair<String, String> typeAndSubtype =
1076 parseTypeAndSubtype(info.getServiceType());
1077 final String serviceType = typeAndSubtype == null
1078 ? null : typeAndSubtype.first;
Paul Hu30bd70d2023-02-07 13:20:56 +00001079 if (serviceType == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001080 clientInfo.onServiceInfoCallbackRegistrationFailed(clientRequestId,
Paul Hu30bd70d2023-02-07 13:20:56 +00001081 NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +00001082 break;
1083 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001084 final String resolveServiceType = serviceType + ".local";
Paul Hu18aeccc2022-12-27 08:48:48 +00001085
Paul Hu30bd70d2023-02-07 13:20:56 +00001086 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001087 final MdnsListener listener = new ServiceInfoListener(clientRequestId,
1088 transactionId, info, resolveServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +00001089 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1090 .setNetwork(info.getNetwork())
1091 .setIsPassiveMode(true)
1092 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001093 .setRemoveExpiredService(true)
Paul Hu30bd70d2023-02-07 13:20:56 +00001094 .build();
1095 mMdnsDiscoveryManager.registerListener(
1096 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001097 storeDiscoveryManagerRequestMap(clientRequestId, transactionId, listener,
1098 clientInfo, info.getNetwork());
1099 clientInfo.log("Register a ServiceInfoListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001100 + " for service type:" + resolveServiceType);
Paul Hu18aeccc2022-12-27 08:48:48 +00001101 break;
Paul Hu30bd70d2023-02-07 13:20:56 +00001102 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001103 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001104 if (DBG) Log.d(TAG, "Unregister a service callback");
1105 args = (ListenerArgs) msg.obj;
1106 clientInfo = mClients.get(args.connector);
1107 // If the binder death notification for a INsdManagerCallback was received
1108 // before any calls are received by NsdService, the clientInfo would be
1109 // cleared and cause NPE. Add a null check here to prevent this corner case.
1110 if (clientInfo == null) {
1111 Log.e(TAG, "Unknown connector in callback unregistration");
1112 break;
1113 }
1114
Paul Hud44e1b72023-06-16 02:07:42 +00001115 final ClientRequest request =
1116 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001117 if (request == null) {
Paul Hu30bd70d2023-02-07 13:20:56 +00001118 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE_CALLBACK");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001119 break;
1120 }
Paul Hud44e1b72023-06-16 02:07:42 +00001121 transactionId = request.mTransactionId;
Paul Hu30bd70d2023-02-07 13:20:56 +00001122 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001123 stopDiscoveryManagerRequest(
1124 request, clientRequestId, transactionId, clientInfo);
1125 clientInfo.onServiceInfoCallbackUnregistered(clientRequestId);
1126 clientInfo.log("Unregister the ServiceInfoListener " + transactionId);
Paul Hu18aeccc2022-12-27 08:48:48 +00001127 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001128 loge("Unregister failed with non-DiscoveryManagerRequest.");
Paul Hu18aeccc2022-12-27 08:48:48 +00001129 }
Paul Hu18aeccc2022-12-27 08:48:48 +00001130 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001131 }
paulhu2b9ed952022-02-10 21:58:32 +08001132 case MDNS_SERVICE_EVENT:
1133 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +09001134 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001135 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001136 break;
Paul Hu019621e2023-01-13 23:26:49 +08001137 case MDNS_DISCOVERY_MANAGER_EVENT:
1138 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
1139 return NOT_HANDLED;
1140 }
1141 break;
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001142 case NsdManager.REGISTER_OFFLOAD_ENGINE:
1143 offloadEngineInfo = (OffloadEngineInfo) msg.obj;
1144 // TODO: Limits the number of registrations created by a given class.
1145 mOffloadEngines.register(offloadEngineInfo.mOffloadEngine,
1146 offloadEngineInfo);
1147 // TODO: Sends all the existing OffloadServiceInfos back.
1148 break;
1149 case NsdManager.UNREGISTER_OFFLOAD_ENGINE:
1150 mOffloadEngines.unregister((IOffloadEngine) msg.obj);
1151 break;
Irfan Sheriff75006652012-04-17 23:15:29 -07001152 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001153 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001154 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001155 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001156 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001157
Paul Hud44e1b72023-06-16 02:07:42 +00001158 private boolean handleMDnsServiceEvent(int code, int transactionId, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001159 NsdServiceInfo servInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001160 ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001161 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001162 Log.e(TAG, String.format(
1163 "transactionId %d for %d has no client mapping", transactionId, code));
Hugo Benichif0c84092017-04-05 14:43:29 +09001164 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001165 }
1166
1167 /* This goes in response as msg.arg2 */
Paul Hud44e1b72023-06-16 02:07:42 +00001168 int clientRequestId = clientInfo.getClientRequestId(transactionId);
1169 if (clientRequestId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -07001170 // This can happen because of race conditions. For example,
1171 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
1172 // and we may get in this situation.
Paul Hud44e1b72023-06-16 02:07:42 +00001173 Log.d(TAG, String.format("%d for transactionId %d that is no longer active",
1174 code, transactionId));
Hugo Benichif0c84092017-04-05 14:43:29 +09001175 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001176 }
Hugo Benichi32be63d2017-04-05 14:06:11 +09001177 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00001178 Log.d(TAG, String.format(
1179 "MDns service event code:%d transactionId=%d", code, transactionId));
Hugo Benichi32be63d2017-04-05 14:06:11 +09001180 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001181 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +08001182 case IMDnsEventListener.SERVICE_FOUND: {
1183 final DiscoveryInfo info = (DiscoveryInfo) obj;
1184 final String name = info.serviceName;
1185 final String type = info.registrationType;
1186 servInfo = new NsdServiceInfo(name, type);
1187 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001188 if (foundNetId == 0L) {
1189 // Ignore services that do not have a Network: they are not usable
1190 // by apps, as they would need privileged permissions to use
1191 // interfaces that do not have an associated Network.
1192 break;
1193 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +09001194 if (foundNetId == INetd.DUMMY_NET_ID) {
1195 // Ignore services on the dummy0 interface: they are only seen when
1196 // discovering locally advertised services, and are not reachable
1197 // through that interface.
1198 break;
1199 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001200 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Paul Hud44e1b72023-06-16 02:07:42 +00001201 clientInfo.onServiceFound(clientRequestId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001202 break;
paulhu2b9ed952022-02-10 21:58:32 +08001203 }
1204 case IMDnsEventListener.SERVICE_LOST: {
1205 final DiscoveryInfo info = (DiscoveryInfo) obj;
1206 final String name = info.serviceName;
1207 final String type = info.registrationType;
1208 final int lostNetId = info.netId;
1209 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001210 // The network could be set to null (netId 0) if it was torn down when the
1211 // service is lost
1212 // TODO: avoid returning null in that case, possibly by remembering
1213 // found services on the same interface index and their network at the time
1214 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Paul Hud44e1b72023-06-16 02:07:42 +00001215 clientInfo.onServiceLost(clientRequestId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001216 break;
paulhu2b9ed952022-02-10 21:58:32 +08001217 }
1218 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001219 clientInfo.onDiscoverServicesFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001220 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001221 break;
paulhu2b9ed952022-02-10 21:58:32 +08001222 case IMDnsEventListener.SERVICE_REGISTERED: {
1223 final RegistrationInfo info = (RegistrationInfo) obj;
1224 final String name = info.serviceName;
1225 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Paul Hu777ed052023-06-19 13:35:15 +00001226 final ClientRequest request =
1227 clientInfo.mClientRequests.get(clientRequestId);
1228 clientInfo.onRegisterServiceSucceeded(clientRequestId, servInfo,
1229 transactionId, request.calculateRequestDurationMs());
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001230 break;
paulhu2b9ed952022-02-10 21:58:32 +08001231 }
1232 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Paul Hu777ed052023-06-19 13:35:15 +00001233 final ClientRequest request =
1234 clientInfo.mClientRequests.get(clientRequestId);
1235 clientInfo.onRegisterServiceFailed(clientRequestId,
1236 NsdManager.FAILURE_INTERNAL_ERROR, transactionId,
1237 request.calculateRequestDurationMs());
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001238 break;
paulhu2b9ed952022-02-10 21:58:32 +08001239 case IMDnsEventListener.SERVICE_RESOLVED: {
1240 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001241 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +08001242 final String fullName = info.serviceFullName;
1243 while (index < fullName.length() && fullName.charAt(index) != '.') {
1244 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001245 ++index;
1246 }
1247 ++index;
1248 }
paulhu2b9ed952022-02-10 21:58:32 +08001249 if (index >= fullName.length()) {
1250 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001251 break;
1252 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001253
paulhube186602022-04-12 07:18:23 +00001254 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001255 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001256 String type = rest.replace(".local.", "");
1257
Paul Hu30bd70d2023-02-07 13:20:56 +00001258 final NsdServiceInfo serviceInfo = clientInfo.mResolvedService;
Paul Hu18aeccc2022-12-27 08:48:48 +00001259 serviceInfo.setServiceName(name);
1260 serviceInfo.setServiceType(type);
1261 serviceInfo.setPort(info.port);
1262 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001263 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001264
Paul Hud44e1b72023-06-16 02:07:42 +00001265 stopResolveService(transactionId);
1266 removeRequestMap(clientRequestId, transactionId, clientInfo);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001267
Paul Hud44e1b72023-06-16 02:07:42 +00001268 final int transactionId2 = getUniqueId();
1269 if (getAddrInfo(transactionId2, info.hostname, info.interfaceIdx)) {
1270 storeLegacyRequestMap(clientRequestId, transactionId2, clientInfo,
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001271 NsdManager.RESOLVE_SERVICE);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001272 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001273 clientInfo.onResolveServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001274 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu30bd70d2023-02-07 13:20:56 +00001275 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001276 }
1277 break;
paulhu2b9ed952022-02-10 21:58:32 +08001278 }
1279 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001280 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001281 stopResolveService(transactionId);
1282 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001283 clientInfo.onResolveServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001284 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu30bd70d2023-02-07 13:20:56 +00001285 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001286 break;
paulhu2b9ed952022-02-10 21:58:32 +08001287 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001288 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001289 stopGetAddrInfo(transactionId);
1290 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001291 clientInfo.onResolveServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001292 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu30bd70d2023-02-07 13:20:56 +00001293 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001294 break;
paulhu2b9ed952022-02-10 21:58:32 +08001295 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001296 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001297 final GetAddressInfo info = (GetAddressInfo) obj;
1298 final String address = info.address;
1299 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001300 InetAddress serviceHost = null;
1301 try {
paulhu2b9ed952022-02-10 21:58:32 +08001302 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001303 } catch (UnknownHostException e) {
1304 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1305 }
1306
1307 // If the resolved service is on an interface without a network, consider it
1308 // as a failure: it would not be usable by apps as they would need
1309 // privileged permissions.
Paul Hu30bd70d2023-02-07 13:20:56 +00001310 if (netId != NETID_UNSET && serviceHost != null) {
1311 clientInfo.mResolvedService.setHost(serviceHost);
1312 setServiceNetworkForCallback(clientInfo.mResolvedService,
1313 netId, info.interfaceIdx);
1314 clientInfo.onResolveServiceSucceeded(
Paul Hud44e1b72023-06-16 02:07:42 +00001315 clientRequestId, clientInfo.mResolvedService);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001316 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001317 clientInfo.onResolveServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001318 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001319 }
Paul Hud44e1b72023-06-16 02:07:42 +00001320 stopGetAddrInfo(transactionId);
1321 removeRequestMap(clientRequestId, transactionId, clientInfo);
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 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001325 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001326 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001327 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001328 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001329 }
Paul Hu019621e2023-01-13 23:26:49 +08001330
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001331 @Nullable
1332 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(
1333 final MdnsEvent event, int code) {
Paul Hu019621e2023-01-13 23:26:49 +08001334 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001335 final String[] typeArray = serviceInfo.getServiceType();
1336 final String joinedType;
1337 if (typeArray.length == 0
1338 || !typeArray[typeArray.length - 1].equals(LOCAL_DOMAIN_NAME)) {
1339 Log.wtf(TAG, "MdnsServiceInfo type does not end in .local: "
1340 + Arrays.toString(typeArray));
1341 return null;
1342 } else {
1343 joinedType = TextUtils.join(".",
1344 Arrays.copyOfRange(typeArray, 0, typeArray.length - 1));
1345 }
1346 final String serviceType;
1347 switch (code) {
1348 case NsdManager.SERVICE_FOUND:
1349 case NsdManager.SERVICE_LOST:
1350 // For consistency with historical behavior, discovered service types have
1351 // a dot at the end.
1352 serviceType = joinedType + ".";
1353 break;
1354 case RESOLVE_SERVICE_SUCCEEDED:
1355 // For consistency with historical behavior, resolved service types have
1356 // a dot at the beginning.
1357 serviceType = "." + joinedType;
1358 break;
1359 default:
1360 serviceType = joinedType;
1361 break;
1362 }
Paul Hu019621e2023-01-13 23:26:49 +08001363 final String serviceName = serviceInfo.getServiceInstanceName();
1364 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1365 final Network network = serviceInfo.getNetwork();
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001366 // In MdnsDiscoveryManagerEvent, the Network can be null which means it is a
1367 // network for Tethering interface. In other words, the network == null means the
1368 // network has netId = INetd.LOCAL_NET_ID.
Paul Hu019621e2023-01-13 23:26:49 +08001369 setServiceNetworkForCallback(
1370 servInfo,
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001371 network == null ? INetd.LOCAL_NET_ID : network.netId,
Paul Hu019621e2023-01-13 23:26:49 +08001372 serviceInfo.getInterfaceIndex());
1373 return servInfo;
1374 }
1375
1376 private boolean handleMdnsDiscoveryManagerEvent(
1377 int transactionId, int code, Object obj) {
Paul Hud44e1b72023-06-16 02:07:42 +00001378 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Paul Hu019621e2023-01-13 23:26:49 +08001379 if (clientInfo == null) {
1380 Log.e(TAG, String.format(
1381 "id %d for %d has no client mapping", transactionId, code));
1382 return false;
1383 }
1384
1385 final MdnsEvent event = (MdnsEvent) obj;
Paul Hud44e1b72023-06-16 02:07:42 +00001386 final int clientRequestId = event.mClientRequestId;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001387 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event, code);
1388 // Errors are already logged if null
1389 if (info == null) return false;
Paul Hu83ec7f42023-06-07 18:04:09 +08001390 mServiceLogs.log(String.format(
1391 "MdnsDiscoveryManager event code=%s transactionId=%d",
1392 NsdManager.nameOf(code), transactionId));
Paul Hu019621e2023-01-13 23:26:49 +08001393 switch (code) {
1394 case NsdManager.SERVICE_FOUND:
Paul Hud44e1b72023-06-16 02:07:42 +00001395 clientInfo.onServiceFound(clientRequestId, info);
Paul Hu319751a2023-01-13 23:56:34 +08001396 break;
1397 case NsdManager.SERVICE_LOST:
Paul Hud44e1b72023-06-16 02:07:42 +00001398 clientInfo.onServiceLost(clientRequestId, info);
Paul Hu019621e2023-01-13 23:26:49 +08001399 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001400 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
Paul Hud44e1b72023-06-16 02:07:42 +00001401 final ClientRequest request =
1402 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001403 if (request == null) {
1404 Log.e(TAG, "Unknown client request in RESOLVE_SERVICE_SUCCEEDED");
1405 break;
1406 }
Paul Hu75069ed2023-01-14 00:31:09 +08001407 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Paul Hu75069ed2023-01-14 00:31:09 +08001408 info.setPort(serviceInfo.getPort());
1409
1410 Map<String, String> attrs = serviceInfo.getAttributes();
1411 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1412 final String key = kv.getKey();
1413 try {
1414 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1415 } catch (IllegalArgumentException e) {
1416 Log.e(TAG, "Invalid attribute", e);
1417 }
1418 }
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001419 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu2b865912023-03-06 14:27:53 +08001420 if (addresses.size() != 0) {
1421 info.setHostAddresses(addresses);
Paul Hud44e1b72023-06-16 02:07:42 +00001422 clientInfo.onResolveServiceSucceeded(clientRequestId, info);
Paul Hu2b865912023-03-06 14:27:53 +08001423 } else {
1424 // No address. Notify resolution failure.
Paul Hu75069ed2023-01-14 00:31:09 +08001425 clientInfo.onResolveServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001426 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu75069ed2023-01-14 00:31:09 +08001427 }
1428
1429 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001430 if (!(request instanceof DiscoveryManagerRequest)) {
1431 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1432 break;
1433 }
Paul Hud44e1b72023-06-16 02:07:42 +00001434 stopDiscoveryManagerRequest(
1435 request, clientRequestId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001436 break;
1437 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001438 case NsdManager.SERVICE_UPDATED: {
1439 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1440 info.setPort(serviceInfo.getPort());
1441
1442 Map<String, String> attrs = serviceInfo.getAttributes();
1443 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1444 final String key = kv.getKey();
1445 try {
1446 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1447 } catch (IllegalArgumentException e) {
1448 Log.e(TAG, "Invalid attribute", e);
1449 }
1450 }
1451
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001452 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001453 info.setHostAddresses(addresses);
Paul Hud44e1b72023-06-16 02:07:42 +00001454 clientInfo.onServiceUpdated(clientRequestId, info);
Paul Hu30bd70d2023-02-07 13:20:56 +00001455 break;
1456 }
1457 case NsdManager.SERVICE_UPDATED_LOST:
Paul Hud44e1b72023-06-16 02:07:42 +00001458 clientInfo.onServiceUpdatedLost(clientRequestId);
Paul Hu30bd70d2023-02-07 13:20:56 +00001459 break;
Paul Hu019621e2023-01-13 23:26:49 +08001460 default:
1461 return false;
1462 }
1463 return true;
1464 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001465 }
1466 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001467
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001468 @NonNull
1469 private static List<InetAddress> getInetAddresses(@NonNull MdnsServiceInfo serviceInfo) {
1470 final List<String> v4Addrs = serviceInfo.getIpv4Addresses();
1471 final List<String> v6Addrs = serviceInfo.getIpv6Addresses();
1472 final List<InetAddress> addresses = new ArrayList<>(v4Addrs.size() + v6Addrs.size());
1473 for (String ipv4Address : v4Addrs) {
1474 try {
1475 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1476 } catch (IllegalArgumentException e) {
1477 Log.wtf(TAG, "Invalid ipv4 address", e);
1478 }
1479 }
1480 for (String ipv6Address : v6Addrs) {
1481 try {
Yuyang Huanga6a6ff92023-04-24 13:33:34 +09001482 final Inet6Address addr = (Inet6Address) InetAddresses.parseNumericAddress(
1483 ipv6Address);
1484 addresses.add(InetAddressUtils.withScopeId(addr, serviceInfo.getInterfaceIndex()));
1485 } catch (IllegalArgumentException e) {
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001486 Log.wtf(TAG, "Invalid ipv6 address", e);
1487 }
1488 }
1489 return addresses;
1490 }
1491
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001492 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1493 switch (netId) {
1494 case NETID_UNSET:
1495 info.setNetwork(null);
1496 break;
1497 case INetd.LOCAL_NET_ID:
1498 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1499 // visible / usable for apps, so do not return it. Store the interface
1500 // index instead, so at least if the client tries to resolve the service
1501 // with that NsdServiceInfo, it will be done on the same interface.
1502 // If they recreate the NsdServiceInfo themselves, resolution would be
1503 // done on all interfaces as before T, which should also work.
1504 info.setNetwork(null);
1505 info.setInterfaceIndex(ifaceIdx);
1506 break;
1507 default:
1508 info.setNetwork(new Network(netId));
1509 }
1510 }
1511
paulhube186602022-04-12 07:18:23 +00001512 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1513 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1514 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1515 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1516 private String unescape(String s) {
1517 StringBuilder sb = new StringBuilder(s.length());
1518 for (int i = 0; i < s.length(); ++i) {
1519 char c = s.charAt(i);
1520 if (c == '\\') {
1521 if (++i >= s.length()) {
1522 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1523 break;
1524 }
1525 c = s.charAt(i);
1526 if (c != '.' && c != '\\') {
1527 if (i + 2 >= s.length()) {
1528 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1529 break;
1530 }
1531 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1532 + (s.charAt(i + 2) - '0'));
1533 i += 2;
1534 }
1535 }
1536 sb.append(c);
1537 }
1538 return sb.toString();
1539 }
1540
Paul Hu7445e3d2023-03-03 15:14:00 +08001541 /**
1542 * Check the given service type is valid and construct it to a service type
1543 * which can use for discovery / resolution service.
1544 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001545 * <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 +08001546 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1547 * underscore; they are alphanumerical characters or dashes or underscore, except the
1548 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1549 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001550 * <p>The subtype may also be specified with a comma after the service type, for example
1551 * _type._tcp,_subtype.
1552 *
Paul Hu7445e3d2023-03-03 15:14:00 +08001553 * @param serviceType the request service type for discovery / resolution service
1554 * @return constructed service type or null if the given service type is invalid.
1555 */
1556 @Nullable
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001557 public static Pair<String, String> parseTypeAndSubtype(String serviceType) {
Paul Hu7445e3d2023-03-03 15:14:00 +08001558 if (TextUtils.isEmpty(serviceType)) return null;
1559
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001560 final String typeOrSubtypePattern = "_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]";
Paul Hu7445e3d2023-03-03 15:14:00 +08001561 final Pattern serviceTypePattern = Pattern.compile(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001562 // Optional leading subtype (_subtype._type._tcp)
1563 // (?: xxx) is a non-capturing parenthesis, don't capture the dot
1564 "^(?:(" + typeOrSubtypePattern + ")\\.)?"
1565 // Actual type (_type._tcp.local)
1566 + "(" + typeOrSubtypePattern + "\\._(?:tcp|udp))"
Paul Hu7445e3d2023-03-03 15:14:00 +08001567 // Drop '.' at the end of service type that is compatible with old backend.
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001568 // e.g. allow "_type._tcp.local."
1569 + "\\.?"
1570 // Optional subtype after comma, for "_type._tcp,_subtype" format
1571 + "(?:,(" + typeOrSubtypePattern + "))?"
1572 + "$");
Paul Hu7445e3d2023-03-03 15:14:00 +08001573 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1574 if (!matcher.matches()) return null;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001575 // Use the subtype either at the beginning or after the comma
1576 final String subtype = matcher.group(1) != null ? matcher.group(1) : matcher.group(3);
1577 return new Pair<>(matcher.group(2), subtype);
Paul Hu7445e3d2023-03-03 15:14:00 +08001578 }
1579
Hugo Benichi803a2f02017-04-24 11:35:06 +09001580 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001581 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001582 this(ctx, handler, cleanupDelayMs, new Dependencies());
1583 }
1584
1585 @VisibleForTesting
1586 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001587 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001588 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001589 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001590 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001591 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1592 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001593 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001594
Paul Hu14667de2023-04-17 22:42:47 +08001595 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper(),
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001596 LOGGER.forSubComponent("MdnsSocketProvider"), new SocketRequestMonitor());
Yuyang Huang700778b2023-03-08 16:17:05 +09001597 // Netlink monitor starts on boot, and intentionally never stopped, to ensure that all
1598 // address events are received.
1599 handler.post(mMdnsSocketProvider::startNetLinkMonitor);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001600
1601 // NsdService is started after ActivityManager (startOtherServices in SystemServer, vs.
1602 // startBootstrapServices).
1603 mRunningAppActiveImportanceCutoff = mDeps.getDeviceConfigInt(
1604 MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF,
1605 DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF);
1606 final ActivityManager am = ctx.getSystemService(ActivityManager.class);
1607 am.addOnUidImportanceListener(new UidImportanceListener(handler),
1608 mRunningAppActiveImportanceCutoff);
1609
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001610 mMdnsSocketClient =
Yuyang Huang7ddf2932023-08-01 18:16:30 +09001611 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider,
1612 LOGGER.forSubComponent("MdnsMultinetworkSocketClient"));
Paul Hu14667de2023-04-17 22:42:47 +08001613 mMdnsDiscoveryManager = deps.makeMdnsDiscoveryManager(new ExecutorProvider(),
Yuyang Huang243d1a52023-05-23 17:26:52 +09001614 mMdnsSocketClient, LOGGER.forSubComponent("MdnsDiscoveryManager"));
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001615 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1616 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
Paul Hu14667de2023-04-17 22:42:47 +08001617 new AdvertiserCallback(), LOGGER.forSubComponent("MdnsAdvertiser"));
Paul Hu777ed052023-06-19 13:35:15 +00001618 mClock = deps.makeClock();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001619 }
1620
1621 /**
1622 * Dependencies of NsdService, for injection in tests.
1623 */
1624 @VisibleForTesting
1625 public static class Dependencies {
1626 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001627 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001628 *
1629 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001630 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001631 */
1632 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Motomu Utsumi278db582023-04-21 12:35:22 +09001633 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1634 MDNS_DISCOVERY_MANAGER_VERSION, DeviceConfigUtils.TETHERING_MODULE_NAME,
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +09001635 false /* defaultEnabled */);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001636 }
1637
1638 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001639 * Check whether the MdnsAdvertiser feature is enabled.
1640 *
1641 * @param context The global context information about an app environment.
1642 * @return true if the MdnsAdvertiser feature is enabled.
1643 */
1644 public boolean isMdnsAdvertiserEnabled(Context context) {
Motomu Utsumi278db582023-04-21 12:35:22 +09001645 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1646 MDNS_ADVERTISER_VERSION, DeviceConfigUtils.TETHERING_MODULE_NAME,
1647 false /* defaultEnabled */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001648 }
1649
1650 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001651 * Get the type allowlist flag value.
1652 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1653 */
1654 @Nullable
1655 public String getTypeAllowlistFlags() {
1656 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1657 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1658 }
1659
1660 /**
1661 * @see DeviceConfigUtils#isFeatureEnabled(Context, String, String, String, boolean)
1662 */
1663 public boolean isFeatureEnabled(Context context, String feature) {
1664 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1665 feature, DeviceConfigUtils.TETHERING_MODULE_NAME, false /* defaultEnabled */);
1666 }
1667
1668 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001669 * @see MdnsDiscoveryManager
1670 */
1671 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
Paul Hu14667de2023-04-17 22:42:47 +08001672 @NonNull ExecutorProvider executorProvider,
Yuyang Huang243d1a52023-05-23 17:26:52 +09001673 @NonNull MdnsMultinetworkSocketClient socketClient, @NonNull SharedLog sharedLog) {
1674 return new MdnsDiscoveryManager(executorProvider, socketClient, sharedLog);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001675 }
1676
1677 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001678 * @see MdnsAdvertiser
1679 */
1680 public MdnsAdvertiser makeMdnsAdvertiser(
1681 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
Paul Hu14667de2023-04-17 22:42:47 +08001682 @NonNull MdnsAdvertiser.AdvertiserCallback cb, @NonNull SharedLog sharedLog) {
1683 return new MdnsAdvertiser(looper, socketProvider, cb, sharedLog);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001684 }
1685
1686 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001687 * @see MdnsSocketProvider
1688 */
Paul Hu14667de2023-04-17 22:42:47 +08001689 public MdnsSocketProvider makeMdnsSocketProvider(@NonNull Context context,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001690 @NonNull Looper looper, @NonNull SharedLog sharedLog,
1691 @NonNull MdnsSocketProvider.SocketRequestMonitor socketCreationCallback) {
1692 return new MdnsSocketProvider(context, looper, sharedLog, socketCreationCallback);
1693 }
1694
1695 /**
1696 * @see DeviceConfig#getInt(String, String, int)
1697 */
1698 public int getDeviceConfigInt(@NonNull String config, int defaultValue) {
1699 return DeviceConfig.getInt(NAMESPACE_TETHERING, config, defaultValue);
1700 }
1701
1702 /**
1703 * @see Binder#getCallingUid()
1704 */
1705 public int getCallingUid() {
1706 return Binder.getCallingUid();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001707 }
Paul Hu777ed052023-06-19 13:35:15 +00001708
1709 /**
1710 * @see NetworkNsdReportedMetrics
1711 */
1712 public NetworkNsdReportedMetrics makeNetworkNsdReportedMetrics(
1713 boolean isLegacy, int clientId) {
1714 return new NetworkNsdReportedMetrics(isLegacy, clientId);
1715 }
1716
1717 /**
1718 * @see MdnsUtils.Clock
1719 */
1720 public Clock makeClock() {
1721 return new Clock();
1722 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001723 }
1724
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001725 /**
1726 * Return whether a type is allowlisted to use the Java backend.
1727 * @param type The service type
1728 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1729 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1730 */
1731 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1732 @NonNull String flagPrefix) {
1733 if (type == null) return false;
1734 final String typesConfig = mDeps.getTypeAllowlistFlags();
1735 if (TextUtils.isEmpty(typesConfig)) return false;
1736
1737 final String mappingPrefix = type + ":";
1738 String mappedFlag = null;
1739 for (String mapping : TextUtils.split(typesConfig, ",")) {
1740 if (mapping.startsWith(mappingPrefix)) {
1741 mappedFlag = mapping.substring(mappingPrefix.length());
1742 break;
1743 }
1744 }
1745
1746 if (mappedFlag == null) return false;
1747
1748 return mDeps.isFeatureEnabled(mContext,
1749 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1750 }
1751
1752 private boolean useDiscoveryManagerForType(@Nullable String type) {
1753 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1754 }
1755
1756 private boolean useAdvertiserForType(@Nullable String type) {
1757 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1758 }
1759
paulhu1b35e822022-04-08 14:48:41 +08001760 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001761 HandlerThread thread = new HandlerThread(TAG);
1762 thread.start();
1763 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001764 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001765 return service;
1766 }
1767
paulhu2b9ed952022-02-10 21:58:32 +08001768 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1769 private final StateMachine mStateMachine;
1770
1771 MDnsEventCallback(StateMachine sm) {
1772 mStateMachine = sm;
1773 }
1774
1775 @Override
1776 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1777 mStateMachine.sendMessage(
1778 MDNS_SERVICE_EVENT, status.result, status.id, status);
1779 }
1780
1781 @Override
1782 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1783 mStateMachine.sendMessage(
1784 MDNS_SERVICE_EVENT, status.result, status.id, status);
1785 }
1786
1787 @Override
1788 public void onServiceResolutionStatus(final ResolutionInfo status) {
1789 mStateMachine.sendMessage(
1790 MDNS_SERVICE_EVENT, status.result, status.id, status);
1791 }
1792
1793 @Override
1794 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1795 mStateMachine.sendMessage(
1796 MDNS_SERVICE_EVENT, status.result, status.id, status);
1797 }
1798
1799 @Override
1800 public int getInterfaceVersion() throws RemoteException {
1801 return this.VERSION;
1802 }
1803
1804 @Override
1805 public String getInterfaceHash() throws RemoteException {
1806 return this.HASH;
1807 }
1808 }
1809
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001810 private void sendOffloadServiceInfosUpdate(@NonNull String targetInterfaceName,
1811 @NonNull OffloadServiceInfo offloadServiceInfo, boolean isRemove) {
1812 final int count = mOffloadEngines.beginBroadcast();
1813 try {
1814 for (int i = 0; i < count; i++) {
1815 final OffloadEngineInfo offloadEngineInfo =
1816 (OffloadEngineInfo) mOffloadEngines.getBroadcastCookie(i);
1817 final String interfaceName = offloadEngineInfo.mInterfaceName;
1818 if (!targetInterfaceName.equals(interfaceName)
1819 || ((offloadEngineInfo.mOffloadType
1820 & offloadServiceInfo.getOffloadType()) == 0)) {
1821 continue;
1822 }
1823 try {
1824 if (isRemove) {
1825 mOffloadEngines.getBroadcastItem(i).onOffloadServiceRemoved(
1826 offloadServiceInfo);
1827 } else {
1828 mOffloadEngines.getBroadcastItem(i).onOffloadServiceUpdated(
1829 offloadServiceInfo);
1830 }
1831 } catch (RemoteException e) {
1832 // Can happen in regular cases, do not log a stacktrace
1833 Log.i(TAG, "Failed to send offload callback, remote died", e);
1834 }
1835 }
1836 } finally {
1837 mOffloadEngines.finishBroadcast();
1838 }
1839 }
1840
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001841 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001842 // TODO: add a callback to notify when a service is being added on each interface (as soon
1843 // as probing starts), and call mOffloadCallbacks. This callback is for
1844 // OFFLOAD_CAPABILITY_FILTER_REPLIES offload type.
1845
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001846 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001847 public void onRegisterServiceSucceeded(int transactionId, NsdServiceInfo registeredInfo) {
1848 mServiceLogs.log("onRegisterServiceSucceeded: transactionId " + transactionId);
1849 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001850 if (clientInfo == null) return;
1851
Paul Hud44e1b72023-06-16 02:07:42 +00001852 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1853 if (clientRequestId < 0) return;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001854
1855 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1856 // historical behavior.
1857 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
Paul Hu777ed052023-06-19 13:35:15 +00001858 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1859 clientInfo.onRegisterServiceSucceeded(
1860 clientRequestId, cbInfo, transactionId, request.calculateRequestDurationMs());
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001861 }
1862
1863 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001864 public void onRegisterServiceFailed(int transactionId, int errorCode) {
1865 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001866 if (clientInfo == null) return;
1867
Paul Hud44e1b72023-06-16 02:07:42 +00001868 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1869 if (clientRequestId < 0) return;
Paul Hu777ed052023-06-19 13:35:15 +00001870 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1871 clientInfo.onRegisterServiceFailed(clientRequestId, errorCode, transactionId,
1872 request.calculateRequestDurationMs());
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001873 }
1874
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001875 @Override
1876 public void onOffloadStartOrUpdate(@NonNull String interfaceName,
1877 @NonNull OffloadServiceInfo offloadServiceInfo) {
1878 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, false /* isRemove */);
1879 }
1880
1881 @Override
1882 public void onOffloadStop(@NonNull String interfaceName,
1883 @NonNull OffloadServiceInfo offloadServiceInfo) {
1884 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, true /* isRemove */);
1885 }
1886
Paul Hud44e1b72023-06-16 02:07:42 +00001887 private ClientInfo getClientInfoOrLog(int transactionId) {
1888 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001889 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001890 Log.e(TAG, String.format("Callback for service %d has no client", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001891 }
1892 return clientInfo;
1893 }
1894
Paul Hud44e1b72023-06-16 02:07:42 +00001895 private int getClientRequestIdOrLog(@NonNull ClientInfo info, int transactionId) {
1896 final int clientRequestId = info.getClientRequestId(transactionId);
1897 if (clientRequestId < 0) {
1898 Log.e(TAG, String.format(
1899 "Client request ID not found for service %d", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001900 }
Paul Hud44e1b72023-06-16 02:07:42 +00001901 return clientRequestId;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001902 }
1903 }
1904
Paul Hu2e0a88c2023-03-09 16:05:01 +08001905 private static class ConnectorArgs {
1906 @NonNull public final NsdServiceConnector connector;
1907 @NonNull public final INsdManagerCallback callback;
1908 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001909 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001910
1911 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00001912 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08001913 this.connector = connector;
1914 this.callback = callback;
1915 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001916 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001917 }
1918 }
1919
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001920 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08001921 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001922 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu101dbf52023-08-09 16:05:20 +08001923 final int uid = mDeps.getCallingUid();
1924 if (cb == null) {
1925 throw new IllegalArgumentException("Unknown client callback from uid=" + uid);
1926 }
Paul Hu2e0a88c2023-03-09 16:05:01 +08001927 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001928 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00001929 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
Paul Hu101dbf52023-08-09 16:05:20 +08001930 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend, uid)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001931 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07001932 }
1933
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001934 private static class ListenerArgs {
1935 public final NsdServiceConnector connector;
1936 public final NsdServiceInfo serviceInfo;
1937 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
1938 this.connector = connector;
1939 this.serviceInfo = serviceInfo;
1940 }
1941 }
1942
1943 private class NsdServiceConnector extends INsdServiceConnector.Stub
1944 implements IBinder.DeathRecipient {
1945 @Override
1946 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
1947 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1948 NsdManager.REGISTER_SERVICE, 0, listenerKey,
1949 new ListenerArgs(this, serviceInfo)));
1950 }
1951
1952 @Override
1953 public void unregisterService(int listenerKey) {
1954 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1955 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
1956 new ListenerArgs(this, null)));
1957 }
1958
1959 @Override
1960 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
1961 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1962 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
1963 new ListenerArgs(this, serviceInfo)));
1964 }
1965
1966 @Override
1967 public void stopDiscovery(int listenerKey) {
1968 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1969 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
1970 }
1971
1972 @Override
1973 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
1974 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1975 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
1976 new ListenerArgs(this, serviceInfo)));
1977 }
1978
1979 @Override
Paul Hub58deb72022-12-26 09:24:42 +00001980 public void stopResolution(int listenerKey) {
1981 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1982 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
1983 }
1984
1985 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00001986 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
1987 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1988 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
1989 new ListenerArgs(this, serviceInfo)));
1990 }
1991
1992 @Override
1993 public void unregisterServiceInfoCallback(int listenerKey) {
1994 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1995 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
1996 new ListenerArgs(this, null)));
1997 }
1998
1999 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002000 public void startDaemon() {
2001 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2002 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
2003 }
2004
2005 @Override
2006 public void binderDied() {
2007 mNsdStateMachine.sendMessage(
2008 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002009
2010 }
2011
2012 @Override
2013 public void registerOffloadEngine(String ifaceName, IOffloadEngine cb,
2014 @OffloadEngine.OffloadCapability long offloadCapabilities,
2015 @OffloadEngine.OffloadType long offloadTypes) {
2016 // TODO: Relax the permission because NETWORK_SETTINGS is a signature permission, and
2017 // it may not be possible for all the callers of this API to have it.
2018 PermissionUtils.enforceNetworkStackPermissionOr(mContext, NETWORK_SETTINGS);
2019 Objects.requireNonNull(ifaceName);
2020 Objects.requireNonNull(cb);
2021 mNsdStateMachine.sendMessage(
2022 mNsdStateMachine.obtainMessage(NsdManager.REGISTER_OFFLOAD_ENGINE,
2023 new OffloadEngineInfo(cb, ifaceName, offloadCapabilities,
2024 offloadTypes)));
2025 }
2026
2027 @Override
2028 public void unregisterOffloadEngine(IOffloadEngine cb) {
2029 // TODO: Relax the permission because NETWORK_SETTINGS is a signature permission, and
2030 // it may not be possible for all the callers of this API to have it.
2031 PermissionUtils.enforceNetworkStackPermissionOr(mContext, NETWORK_SETTINGS);
2032 Objects.requireNonNull(cb);
2033 mNsdStateMachine.sendMessage(
2034 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_OFFLOAD_ENGINE, cb));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002035 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002036 }
2037
Hugo Benichi912db992017-04-24 16:41:03 +09002038 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07002039 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07002040 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09002041 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
2042 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07002043 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07002044 }
2045
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002046 private int getUniqueId() {
2047 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
2048 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002049 }
2050
Paul Hud44e1b72023-06-16 02:07:42 +00002051 private boolean registerService(int transactionId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09002052 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002053 Log.d(TAG, "registerService: " + transactionId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002054 }
Hugo Benichi6d706442017-04-24 16:19:58 +09002055 String name = service.getServiceName();
2056 String type = service.getServiceType();
2057 int port = service.getPort();
2058 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002059 final int registerInterface = getNetworkInterfaceIndex(service);
2060 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08002061 Log.e(TAG, "Interface to register service on not found");
2062 return false;
2063 }
Paul Hud44e1b72023-06-16 02:07:42 +00002064 return mMDnsManager.registerService(
2065 transactionId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002066 }
2067
Paul Hud44e1b72023-06-16 02:07:42 +00002068 private boolean unregisterService(int transactionId) {
2069 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002070 }
2071
Paul Hud44e1b72023-06-16 02:07:42 +00002072 private boolean discoverServices(int transactionId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08002073 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002074 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
2075 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002076 Log.e(TAG, "Interface to discover service on not found");
2077 return false;
2078 }
Paul Hud44e1b72023-06-16 02:07:42 +00002079 return mMDnsManager.discover(transactionId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002080 }
2081
Paul Hud44e1b72023-06-16 02:07:42 +00002082 private boolean stopServiceDiscovery(int transactionId) {
2083 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002084 }
2085
Paul Hud44e1b72023-06-16 02:07:42 +00002086 private boolean resolveService(int transactionId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002087 final String name = service.getServiceName();
2088 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002089 final int resolveInterface = getNetworkInterfaceIndex(service);
2090 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002091 Log.e(TAG, "Interface to resolve service on not found");
2092 return false;
2093 }
Paul Hud44e1b72023-06-16 02:07:42 +00002094 return mMDnsManager.resolve(transactionId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002095 }
2096
2097 /**
2098 * Guess the interface to use to resolve or discover a service on a specific network.
2099 *
2100 * This is an imperfect guess, as for example the network may be gone or not yet fully
2101 * registered. This is fine as failing is correct if the network is gone, and a client
2102 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
2103 * this is to support the legacy mdnsresponder implementation, which historically resolved
2104 * services on an unspecified network.
2105 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002106 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
2107 final Network network = serviceInfo.getNetwork();
2108 if (network == null) {
2109 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
2110 // provided by NsdService from discovery results, and the service was found on an
2111 // interface that has no app-usable Network).
2112 if (serviceInfo.getInterfaceIndex() != 0) {
2113 return serviceInfo.getInterfaceIndex();
2114 }
2115 return IFACE_IDX_ANY;
2116 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002117
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002118 String interfaceName = getNetworkInterfaceName(network);
2119 if (interfaceName == null) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002120 return IFACE_IDX_ANY;
2121 }
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002122 return getNetworkInterfaceIndexByName(interfaceName);
2123 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002124
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002125 private String getNetworkInterfaceName(@Nullable Network network) {
2126 if (network == null) {
2127 return null;
2128 }
2129 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
2130 if (cm == null) {
2131 Log.wtf(TAG, "No ConnectivityManager");
2132 return null;
2133 }
2134 final LinkProperties lp = cm.getLinkProperties(network);
2135 if (lp == null) {
2136 return null;
2137 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002138 // Only resolve on non-stacked interfaces
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002139 return lp.getInterfaceName();
2140 }
2141
2142 private int getNetworkInterfaceIndexByName(final String ifaceName) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002143 final NetworkInterface iface;
2144 try {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002145 iface = NetworkInterface.getByName(ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002146 } catch (SocketException e) {
2147 Log.e(TAG, "Error querying interface", e);
2148 return IFACE_IDX_ANY;
2149 }
2150
2151 if (iface == null) {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002152 Log.e(TAG, "Interface not found: " + ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002153 return IFACE_IDX_ANY;
2154 }
2155
2156 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002157 }
2158
Paul Hud44e1b72023-06-16 02:07:42 +00002159 private boolean stopResolveService(int transactionId) {
2160 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002161 }
2162
Paul Hud44e1b72023-06-16 02:07:42 +00002163 private boolean getAddrInfo(int transactionId, String hostname, int interfaceIdx) {
2164 return mMDnsManager.getServiceAddress(transactionId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002165 }
2166
Paul Hud44e1b72023-06-16 02:07:42 +00002167 private boolean stopGetAddrInfo(int transactionId) {
2168 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002169 }
2170
2171 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00002172 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2173 if (!PermissionUtils.checkDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002174
Paul Hub2e67d32023-04-18 05:50:14 +00002175 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
2176 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07002177 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00002178
2179 // Dump service and clients logs
2180 pw.println();
Paul Hu14667de2023-04-17 22:42:47 +08002181 pw.println("Logs:");
Paul Hub2e67d32023-04-18 05:50:14 +00002182 pw.increaseIndent();
2183 mServiceLogs.reverseDump(pw);
2184 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002185 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002186
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002187 private abstract static class ClientRequest {
Paul Hud44e1b72023-06-16 02:07:42 +00002188 private final int mTransactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002189 private final Clock mClock;
2190 private final long mStartTimeMs;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002191
Paul Hu777ed052023-06-19 13:35:15 +00002192 private ClientRequest(int transactionId, @NonNull Clock clock, long startTimeMs) {
Paul Hud44e1b72023-06-16 02:07:42 +00002193 mTransactionId = transactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002194 mClock = clock;
2195 mStartTimeMs = startTimeMs;
2196 }
2197
2198 public long calculateRequestDurationMs() {
2199 final long stopTimeMs = mClock.elapsedRealtime();
2200 return stopTimeMs - mStartTimeMs;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002201 }
2202 }
2203
2204 private static class LegacyClientRequest extends ClientRequest {
2205 private final int mRequestCode;
2206
Paul Hu777ed052023-06-19 13:35:15 +00002207 private LegacyClientRequest(int transactionId, int requestCode, @NonNull Clock clock,
2208 long startTimeMs) {
2209 super(transactionId, clock, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002210 mRequestCode = requestCode;
2211 }
2212 }
2213
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002214 private abstract static class JavaBackendClientRequest extends ClientRequest {
2215 @Nullable
2216 private final Network mRequestedNetwork;
2217
Paul Hu777ed052023-06-19 13:35:15 +00002218 private JavaBackendClientRequest(int transactionId, @Nullable Network requestedNetwork,
2219 @NonNull Clock clock, long startTimeMs) {
2220 super(transactionId, clock, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002221 mRequestedNetwork = requestedNetwork;
2222 }
2223
2224 @Nullable
2225 public Network getRequestedNetwork() {
2226 return mRequestedNetwork;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002227 }
2228 }
2229
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002230 private static class AdvertiserClientRequest extends JavaBackendClientRequest {
Paul Hu777ed052023-06-19 13:35:15 +00002231 private AdvertiserClientRequest(int transactionId, @Nullable Network requestedNetwork,
2232 @NonNull Clock clock, long startTimeMs) {
2233 super(transactionId, requestedNetwork, clock, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002234 }
2235 }
2236
2237 private static class DiscoveryManagerRequest extends JavaBackendClientRequest {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002238 @NonNull
2239 private final MdnsListener mListener;
2240
Paul Hud44e1b72023-06-16 02:07:42 +00002241 private DiscoveryManagerRequest(int transactionId, @NonNull MdnsListener listener,
Paul Hu777ed052023-06-19 13:35:15 +00002242 @Nullable Network requestedNetwork, @NonNull Clock clock, long startTimeMs) {
2243 super(transactionId, requestedNetwork, clock, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002244 mListener = listener;
2245 }
2246 }
2247
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002248 /* Information tracked per client */
2249 private class ClientInfo {
2250
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002251 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002252 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002253 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002254 private NsdServiceInfo mResolvedService;
2255
Paul Hud44e1b72023-06-16 02:07:42 +00002256 /* A map from client request ID (listenerKey) to the request */
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002257 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08002258
Luke Huangf7277ed2021-07-12 21:15:10 +08002259 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002260 private boolean mIsPreSClient = false;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002261 private final int mUid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002262 // The flag of using java backend if the client's target SDK >= U
2263 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002264 // Store client logs
2265 private final SharedLog mClientLogs;
Paul Hucdef3532023-06-18 14:47:35 +00002266 // Report the nsd metrics data
2267 private final NetworkNsdReportedMetrics mMetrics;
Luke Huangf7277ed2021-07-12 21:15:10 +08002268
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002269 private ClientInfo(INsdManagerCallback cb, int uid, boolean useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +00002270 SharedLog sharedLog, NetworkNsdReportedMetrics metrics) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002271 mCb = cb;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002272 mUid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002273 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002274 mClientLogs = sharedLog;
2275 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Paul Hucdef3532023-06-18 14:47:35 +00002276 mMetrics = metrics;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002277 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002278
2279 @Override
2280 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06002281 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07002282 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002283 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002284 sb.append("mUseJavaBackend ").append(mUseJavaBackend).append("\n");
2285 sb.append("mUid ").append(mUid).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002286 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002287 int clientRequestId = mClientRequests.keyAt(i);
2288 sb.append("clientRequestId ")
2289 .append(clientRequestId)
2290 .append(" transactionId ").append(mClientRequests.valueAt(i).mTransactionId)
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002291 .append(" type ").append(
2292 mClientRequests.valueAt(i).getClass().getSimpleName())
2293 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07002294 }
2295 return sb.toString();
2296 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002297
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002298 private boolean isPreSClient() {
2299 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08002300 }
2301
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002302 private void setPreSClient() {
2303 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08002304 }
2305
Paul Hue4f5f252023-02-16 21:13:47 +08002306 private void unregisterMdnsListenerFromRequest(ClientRequest request) {
2307 final MdnsListener listener =
2308 ((DiscoveryManagerRequest) request).mListener;
2309 mMdnsDiscoveryManager.unregisterListener(
2310 listener.getListenedServiceType(), listener);
2311 }
2312
Dave Plattfeff2af2014-03-07 14:48:22 -08002313 // Remove any pending requests from the global map when we get rid of a client,
2314 // and send cancellations to the daemon.
2315 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00002316 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09002317 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002318 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002319 final int clientRequestId = mClientRequests.keyAt(i);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002320 final ClientRequest request = mClientRequests.valueAt(i);
Paul Hud44e1b72023-06-16 02:07:42 +00002321 final int transactionId = request.mTransactionId;
2322 mTransactionIdToClientInfoMap.remove(transactionId);
paulhub2225702021-11-17 09:35:33 +08002323 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002324 Log.d(TAG, "Terminating clientRequestId " + clientRequestId
2325 + " transactionId " + transactionId
2326 + " type " + mClientRequests.get(clientRequestId));
paulhub2225702021-11-17 09:35:33 +08002327 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002328
2329 if (request instanceof DiscoveryManagerRequest) {
Paul Hue4f5f252023-02-16 21:13:47 +08002330 unregisterMdnsListenerFromRequest(request);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002331 continue;
2332 }
2333
2334 if (request instanceof AdvertiserClientRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00002335 mAdvertiser.removeService(transactionId);
Paul Hu777ed052023-06-19 13:35:15 +00002336 mMetrics.reportServiceUnregistration(
2337 transactionId, request.calculateRequestDurationMs());
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002338 continue;
2339 }
2340
2341 if (!(request instanceof LegacyClientRequest)) {
2342 throw new IllegalStateException("Unknown request type: " + request.getClass());
2343 }
2344
2345 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08002346 case NsdManager.DISCOVER_SERVICES:
Paul Hud44e1b72023-06-16 02:07:42 +00002347 stopServiceDiscovery(transactionId);
Dave Plattfeff2af2014-03-07 14:48:22 -08002348 break;
2349 case NsdManager.RESOLVE_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002350 stopResolveService(transactionId);
Dave Plattfeff2af2014-03-07 14:48:22 -08002351 break;
2352 case NsdManager.REGISTER_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002353 unregisterService(transactionId);
Paul Hu777ed052023-06-19 13:35:15 +00002354 mMetrics.reportServiceUnregistration(
2355 transactionId, request.calculateRequestDurationMs());
Dave Plattfeff2af2014-03-07 14:48:22 -08002356 break;
2357 default:
2358 break;
2359 }
2360 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002361 mClientRequests.clear();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002362 updateMulticastLock();
2363 }
2364
2365 /**
2366 * Returns true if this client has any Java backend request that requests one of the given
2367 * networks.
2368 */
2369 boolean hasAnyJavaBackendRequestForNetworks(@NonNull ArraySet<Network> networks) {
2370 for (int i = 0; i < mClientRequests.size(); i++) {
2371 final ClientRequest req = mClientRequests.valueAt(i);
2372 if (!(req instanceof JavaBackendClientRequest)) {
2373 continue;
2374 }
2375 final Network reqNetwork = ((JavaBackendClientRequest) mClientRequests.valueAt(i))
2376 .getRequestedNetwork();
2377 if (MdnsUtils.isAnyNetworkMatched(reqNetwork, networks)) {
2378 return true;
2379 }
2380 }
2381 return false;
Dave Plattfeff2af2014-03-07 14:48:22 -08002382 }
2383
Paul Hud44e1b72023-06-16 02:07:42 +00002384 // mClientRequests is a sparse array of client request id -> ClientRequest. For a given
2385 // transaction id, return the corresponding client request id.
2386 private int getClientRequestId(final int transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002387 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002388 if (mClientRequests.valueAt(i).mTransactionId == transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002389 return mClientRequests.keyAt(i);
2390 }
Christopher Lane74411222014-04-25 18:39:07 -07002391 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002392 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07002393 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002394
Paul Hub2e67d32023-04-18 05:50:14 +00002395 private void log(String message) {
2396 mClientLogs.log(message);
2397 }
2398
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002399 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info) {
2400 try {
2401 mCb.onDiscoverServicesStarted(listenerKey, info);
2402 } catch (RemoteException e) {
2403 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
2404 }
2405 }
2406
2407 void onDiscoverServicesFailed(int listenerKey, int error) {
2408 try {
2409 mCb.onDiscoverServicesFailed(listenerKey, error);
2410 } catch (RemoteException e) {
2411 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
2412 }
2413 }
2414
2415 void onServiceFound(int listenerKey, NsdServiceInfo info) {
2416 try {
2417 mCb.onServiceFound(listenerKey, info);
2418 } catch (RemoteException e) {
2419 Log.e(TAG, "Error calling onServiceFound(", e);
2420 }
2421 }
2422
2423 void onServiceLost(int listenerKey, NsdServiceInfo info) {
2424 try {
2425 mCb.onServiceLost(listenerKey, info);
2426 } catch (RemoteException e) {
2427 Log.e(TAG, "Error calling onServiceLost(", e);
2428 }
2429 }
2430
2431 void onStopDiscoveryFailed(int listenerKey, int error) {
2432 try {
2433 mCb.onStopDiscoveryFailed(listenerKey, error);
2434 } catch (RemoteException e) {
2435 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
2436 }
2437 }
2438
2439 void onStopDiscoverySucceeded(int listenerKey) {
2440 try {
2441 mCb.onStopDiscoverySucceeded(listenerKey);
2442 } catch (RemoteException e) {
2443 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
2444 }
2445 }
2446
Paul Hu777ed052023-06-19 13:35:15 +00002447 void onRegisterServiceFailedImmediately(int listenerKey, int error) {
2448 onRegisterServiceFailed(listenerKey, error, NO_TRANSACTION, 0 /* durationMs */);
2449 }
2450
2451 void onRegisterServiceFailed(int listenerKey, int error, int transactionId,
2452 long durationMs) {
2453 mMetrics.reportServiceRegistrationFailed(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002454 try {
2455 mCb.onRegisterServiceFailed(listenerKey, error);
2456 } catch (RemoteException e) {
2457 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2458 }
2459 }
2460
Paul Hu777ed052023-06-19 13:35:15 +00002461 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info, int transactionId,
2462 long durationMs) {
2463 mMetrics.reportServiceRegistrationSucceeded(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002464 try {
2465 mCb.onRegisterServiceSucceeded(listenerKey, info);
2466 } catch (RemoteException e) {
2467 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2468 }
2469 }
2470
2471 void onUnregisterServiceFailed(int listenerKey, int error) {
2472 try {
2473 mCb.onUnregisterServiceFailed(listenerKey, error);
2474 } catch (RemoteException e) {
2475 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2476 }
2477 }
2478
Paul Hu777ed052023-06-19 13:35:15 +00002479 void onUnregisterServiceSucceeded(int listenerKey, int transactionId, long durationMs) {
2480 mMetrics.reportServiceUnregistration(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002481 try {
2482 mCb.onUnregisterServiceSucceeded(listenerKey);
2483 } catch (RemoteException e) {
2484 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2485 }
2486 }
2487
2488 void onResolveServiceFailed(int listenerKey, int error) {
2489 try {
2490 mCb.onResolveServiceFailed(listenerKey, error);
2491 } catch (RemoteException e) {
2492 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2493 }
2494 }
2495
2496 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info) {
2497 try {
2498 mCb.onResolveServiceSucceeded(listenerKey, info);
2499 } catch (RemoteException e) {
2500 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2501 }
2502 }
Paul Hub58deb72022-12-26 09:24:42 +00002503
2504 void onStopResolutionFailed(int listenerKey, int error) {
2505 try {
2506 mCb.onStopResolutionFailed(listenerKey, error);
2507 } catch (RemoteException e) {
2508 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2509 }
2510 }
2511
2512 void onStopResolutionSucceeded(int listenerKey) {
2513 try {
2514 mCb.onStopResolutionSucceeded(listenerKey);
2515 } catch (RemoteException e) {
2516 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2517 }
2518 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002519
2520 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
2521 try {
2522 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2523 } catch (RemoteException e) {
2524 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2525 }
2526 }
2527
2528 void onServiceUpdated(int listenerKey, NsdServiceInfo info) {
2529 try {
2530 mCb.onServiceUpdated(listenerKey, info);
2531 } catch (RemoteException e) {
2532 Log.e(TAG, "Error calling onServiceUpdated", e);
2533 }
2534 }
2535
2536 void onServiceUpdatedLost(int listenerKey) {
2537 try {
2538 mCb.onServiceUpdatedLost(listenerKey);
2539 } catch (RemoteException e) {
2540 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2541 }
2542 }
2543
2544 void onServiceInfoCallbackUnregistered(int listenerKey) {
2545 try {
2546 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2547 } catch (RemoteException e) {
2548 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2549 }
2550 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002551 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002552}