blob: 1a05d4605783c02e88910fa019c20d32234e3264 [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 =
1611 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider);
Paul Hu14667de2023-04-17 22:42:47 +08001612 mMdnsDiscoveryManager = deps.makeMdnsDiscoveryManager(new ExecutorProvider(),
Yuyang Huang243d1a52023-05-23 17:26:52 +09001613 mMdnsSocketClient, LOGGER.forSubComponent("MdnsDiscoveryManager"));
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001614 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1615 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
Paul Hu14667de2023-04-17 22:42:47 +08001616 new AdvertiserCallback(), LOGGER.forSubComponent("MdnsAdvertiser"));
Paul Hu777ed052023-06-19 13:35:15 +00001617 mClock = deps.makeClock();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001618 }
1619
1620 /**
1621 * Dependencies of NsdService, for injection in tests.
1622 */
1623 @VisibleForTesting
1624 public static class Dependencies {
1625 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001626 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001627 *
1628 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001629 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001630 */
1631 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Motomu Utsumi278db582023-04-21 12:35:22 +09001632 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1633 MDNS_DISCOVERY_MANAGER_VERSION, DeviceConfigUtils.TETHERING_MODULE_NAME,
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +09001634 false /* defaultEnabled */);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001635 }
1636
1637 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001638 * Check whether the MdnsAdvertiser feature is enabled.
1639 *
1640 * @param context The global context information about an app environment.
1641 * @return true if the MdnsAdvertiser feature is enabled.
1642 */
1643 public boolean isMdnsAdvertiserEnabled(Context context) {
Motomu Utsumi278db582023-04-21 12:35:22 +09001644 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1645 MDNS_ADVERTISER_VERSION, DeviceConfigUtils.TETHERING_MODULE_NAME,
1646 false /* defaultEnabled */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001647 }
1648
1649 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001650 * Get the type allowlist flag value.
1651 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1652 */
1653 @Nullable
1654 public String getTypeAllowlistFlags() {
1655 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1656 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1657 }
1658
1659 /**
1660 * @see DeviceConfigUtils#isFeatureEnabled(Context, String, String, String, boolean)
1661 */
1662 public boolean isFeatureEnabled(Context context, String feature) {
1663 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1664 feature, DeviceConfigUtils.TETHERING_MODULE_NAME, false /* defaultEnabled */);
1665 }
1666
1667 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001668 * @see MdnsDiscoveryManager
1669 */
1670 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
Paul Hu14667de2023-04-17 22:42:47 +08001671 @NonNull ExecutorProvider executorProvider,
Yuyang Huang243d1a52023-05-23 17:26:52 +09001672 @NonNull MdnsMultinetworkSocketClient socketClient, @NonNull SharedLog sharedLog) {
1673 return new MdnsDiscoveryManager(executorProvider, socketClient, sharedLog);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001674 }
1675
1676 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001677 * @see MdnsAdvertiser
1678 */
1679 public MdnsAdvertiser makeMdnsAdvertiser(
1680 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
Paul Hu14667de2023-04-17 22:42:47 +08001681 @NonNull MdnsAdvertiser.AdvertiserCallback cb, @NonNull SharedLog sharedLog) {
1682 return new MdnsAdvertiser(looper, socketProvider, cb, sharedLog);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001683 }
1684
1685 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001686 * @see MdnsSocketProvider
1687 */
Paul Hu14667de2023-04-17 22:42:47 +08001688 public MdnsSocketProvider makeMdnsSocketProvider(@NonNull Context context,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001689 @NonNull Looper looper, @NonNull SharedLog sharedLog,
1690 @NonNull MdnsSocketProvider.SocketRequestMonitor socketCreationCallback) {
1691 return new MdnsSocketProvider(context, looper, sharedLog, socketCreationCallback);
1692 }
1693
1694 /**
1695 * @see DeviceConfig#getInt(String, String, int)
1696 */
1697 public int getDeviceConfigInt(@NonNull String config, int defaultValue) {
1698 return DeviceConfig.getInt(NAMESPACE_TETHERING, config, defaultValue);
1699 }
1700
1701 /**
1702 * @see Binder#getCallingUid()
1703 */
1704 public int getCallingUid() {
1705 return Binder.getCallingUid();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001706 }
Paul Hu777ed052023-06-19 13:35:15 +00001707
1708 /**
1709 * @see NetworkNsdReportedMetrics
1710 */
1711 public NetworkNsdReportedMetrics makeNetworkNsdReportedMetrics(
1712 boolean isLegacy, int clientId) {
1713 return new NetworkNsdReportedMetrics(isLegacy, clientId);
1714 }
1715
1716 /**
1717 * @see MdnsUtils.Clock
1718 */
1719 public Clock makeClock() {
1720 return new Clock();
1721 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001722 }
1723
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001724 /**
1725 * Return whether a type is allowlisted to use the Java backend.
1726 * @param type The service type
1727 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1728 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1729 */
1730 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1731 @NonNull String flagPrefix) {
1732 if (type == null) return false;
1733 final String typesConfig = mDeps.getTypeAllowlistFlags();
1734 if (TextUtils.isEmpty(typesConfig)) return false;
1735
1736 final String mappingPrefix = type + ":";
1737 String mappedFlag = null;
1738 for (String mapping : TextUtils.split(typesConfig, ",")) {
1739 if (mapping.startsWith(mappingPrefix)) {
1740 mappedFlag = mapping.substring(mappingPrefix.length());
1741 break;
1742 }
1743 }
1744
1745 if (mappedFlag == null) return false;
1746
1747 return mDeps.isFeatureEnabled(mContext,
1748 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1749 }
1750
1751 private boolean useDiscoveryManagerForType(@Nullable String type) {
1752 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1753 }
1754
1755 private boolean useAdvertiserForType(@Nullable String type) {
1756 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1757 }
1758
paulhu1b35e822022-04-08 14:48:41 +08001759 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001760 HandlerThread thread = new HandlerThread(TAG);
1761 thread.start();
1762 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001763 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001764 return service;
1765 }
1766
paulhu2b9ed952022-02-10 21:58:32 +08001767 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1768 private final StateMachine mStateMachine;
1769
1770 MDnsEventCallback(StateMachine sm) {
1771 mStateMachine = sm;
1772 }
1773
1774 @Override
1775 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1776 mStateMachine.sendMessage(
1777 MDNS_SERVICE_EVENT, status.result, status.id, status);
1778 }
1779
1780 @Override
1781 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1782 mStateMachine.sendMessage(
1783 MDNS_SERVICE_EVENT, status.result, status.id, status);
1784 }
1785
1786 @Override
1787 public void onServiceResolutionStatus(final ResolutionInfo status) {
1788 mStateMachine.sendMessage(
1789 MDNS_SERVICE_EVENT, status.result, status.id, status);
1790 }
1791
1792 @Override
1793 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1794 mStateMachine.sendMessage(
1795 MDNS_SERVICE_EVENT, status.result, status.id, status);
1796 }
1797
1798 @Override
1799 public int getInterfaceVersion() throws RemoteException {
1800 return this.VERSION;
1801 }
1802
1803 @Override
1804 public String getInterfaceHash() throws RemoteException {
1805 return this.HASH;
1806 }
1807 }
1808
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001809 private void sendOffloadServiceInfosUpdate(@NonNull String targetInterfaceName,
1810 @NonNull OffloadServiceInfo offloadServiceInfo, boolean isRemove) {
1811 final int count = mOffloadEngines.beginBroadcast();
1812 try {
1813 for (int i = 0; i < count; i++) {
1814 final OffloadEngineInfo offloadEngineInfo =
1815 (OffloadEngineInfo) mOffloadEngines.getBroadcastCookie(i);
1816 final String interfaceName = offloadEngineInfo.mInterfaceName;
1817 if (!targetInterfaceName.equals(interfaceName)
1818 || ((offloadEngineInfo.mOffloadType
1819 & offloadServiceInfo.getOffloadType()) == 0)) {
1820 continue;
1821 }
1822 try {
1823 if (isRemove) {
1824 mOffloadEngines.getBroadcastItem(i).onOffloadServiceRemoved(
1825 offloadServiceInfo);
1826 } else {
1827 mOffloadEngines.getBroadcastItem(i).onOffloadServiceUpdated(
1828 offloadServiceInfo);
1829 }
1830 } catch (RemoteException e) {
1831 // Can happen in regular cases, do not log a stacktrace
1832 Log.i(TAG, "Failed to send offload callback, remote died", e);
1833 }
1834 }
1835 } finally {
1836 mOffloadEngines.finishBroadcast();
1837 }
1838 }
1839
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001840 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001841 // TODO: add a callback to notify when a service is being added on each interface (as soon
1842 // as probing starts), and call mOffloadCallbacks. This callback is for
1843 // OFFLOAD_CAPABILITY_FILTER_REPLIES offload type.
1844
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001845 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001846 public void onRegisterServiceSucceeded(int transactionId, NsdServiceInfo registeredInfo) {
1847 mServiceLogs.log("onRegisterServiceSucceeded: transactionId " + transactionId);
1848 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001849 if (clientInfo == null) return;
1850
Paul Hud44e1b72023-06-16 02:07:42 +00001851 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1852 if (clientRequestId < 0) return;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001853
1854 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1855 // historical behavior.
1856 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
Paul Hu777ed052023-06-19 13:35:15 +00001857 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1858 clientInfo.onRegisterServiceSucceeded(
1859 clientRequestId, cbInfo, transactionId, request.calculateRequestDurationMs());
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001860 }
1861
1862 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001863 public void onRegisterServiceFailed(int transactionId, int errorCode) {
1864 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001865 if (clientInfo == null) return;
1866
Paul Hud44e1b72023-06-16 02:07:42 +00001867 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1868 if (clientRequestId < 0) return;
Paul Hu777ed052023-06-19 13:35:15 +00001869 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1870 clientInfo.onRegisterServiceFailed(clientRequestId, errorCode, transactionId,
1871 request.calculateRequestDurationMs());
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001872 }
1873
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001874 @Override
1875 public void onOffloadStartOrUpdate(@NonNull String interfaceName,
1876 @NonNull OffloadServiceInfo offloadServiceInfo) {
1877 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, false /* isRemove */);
1878 }
1879
1880 @Override
1881 public void onOffloadStop(@NonNull String interfaceName,
1882 @NonNull OffloadServiceInfo offloadServiceInfo) {
1883 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, true /* isRemove */);
1884 }
1885
Paul Hud44e1b72023-06-16 02:07:42 +00001886 private ClientInfo getClientInfoOrLog(int transactionId) {
1887 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001888 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001889 Log.e(TAG, String.format("Callback for service %d has no client", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001890 }
1891 return clientInfo;
1892 }
1893
Paul Hud44e1b72023-06-16 02:07:42 +00001894 private int getClientRequestIdOrLog(@NonNull ClientInfo info, int transactionId) {
1895 final int clientRequestId = info.getClientRequestId(transactionId);
1896 if (clientRequestId < 0) {
1897 Log.e(TAG, String.format(
1898 "Client request ID not found for service %d", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001899 }
Paul Hud44e1b72023-06-16 02:07:42 +00001900 return clientRequestId;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001901 }
1902 }
1903
Paul Hu2e0a88c2023-03-09 16:05:01 +08001904 private static class ConnectorArgs {
1905 @NonNull public final NsdServiceConnector connector;
1906 @NonNull public final INsdManagerCallback callback;
1907 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001908 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001909
1910 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00001911 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08001912 this.connector = connector;
1913 this.callback = callback;
1914 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001915 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001916 }
1917 }
1918
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001919 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08001920 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001921 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu2e0a88c2023-03-09 16:05:01 +08001922 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001923 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00001924 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
1925 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001926 mDeps.getCallingUid())));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001927 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07001928 }
1929
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001930 private static class ListenerArgs {
1931 public final NsdServiceConnector connector;
1932 public final NsdServiceInfo serviceInfo;
1933 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
1934 this.connector = connector;
1935 this.serviceInfo = serviceInfo;
1936 }
1937 }
1938
1939 private class NsdServiceConnector extends INsdServiceConnector.Stub
1940 implements IBinder.DeathRecipient {
1941 @Override
1942 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
1943 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1944 NsdManager.REGISTER_SERVICE, 0, listenerKey,
1945 new ListenerArgs(this, serviceInfo)));
1946 }
1947
1948 @Override
1949 public void unregisterService(int listenerKey) {
1950 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1951 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
1952 new ListenerArgs(this, null)));
1953 }
1954
1955 @Override
1956 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
1957 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1958 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
1959 new ListenerArgs(this, serviceInfo)));
1960 }
1961
1962 @Override
1963 public void stopDiscovery(int listenerKey) {
1964 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1965 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
1966 }
1967
1968 @Override
1969 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
1970 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1971 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
1972 new ListenerArgs(this, serviceInfo)));
1973 }
1974
1975 @Override
Paul Hub58deb72022-12-26 09:24:42 +00001976 public void stopResolution(int listenerKey) {
1977 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1978 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
1979 }
1980
1981 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00001982 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
1983 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1984 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
1985 new ListenerArgs(this, serviceInfo)));
1986 }
1987
1988 @Override
1989 public void unregisterServiceInfoCallback(int listenerKey) {
1990 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1991 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
1992 new ListenerArgs(this, null)));
1993 }
1994
1995 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001996 public void startDaemon() {
1997 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1998 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
1999 }
2000
2001 @Override
2002 public void binderDied() {
2003 mNsdStateMachine.sendMessage(
2004 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002005
2006 }
2007
2008 @Override
2009 public void registerOffloadEngine(String ifaceName, IOffloadEngine cb,
2010 @OffloadEngine.OffloadCapability long offloadCapabilities,
2011 @OffloadEngine.OffloadType long offloadTypes) {
2012 // TODO: Relax the permission because NETWORK_SETTINGS is a signature permission, and
2013 // it may not be possible for all the callers of this API to have it.
2014 PermissionUtils.enforceNetworkStackPermissionOr(mContext, NETWORK_SETTINGS);
2015 Objects.requireNonNull(ifaceName);
2016 Objects.requireNonNull(cb);
2017 mNsdStateMachine.sendMessage(
2018 mNsdStateMachine.obtainMessage(NsdManager.REGISTER_OFFLOAD_ENGINE,
2019 new OffloadEngineInfo(cb, ifaceName, offloadCapabilities,
2020 offloadTypes)));
2021 }
2022
2023 @Override
2024 public void unregisterOffloadEngine(IOffloadEngine cb) {
2025 // TODO: Relax the permission because NETWORK_SETTINGS is a signature permission, and
2026 // it may not be possible for all the callers of this API to have it.
2027 PermissionUtils.enforceNetworkStackPermissionOr(mContext, NETWORK_SETTINGS);
2028 Objects.requireNonNull(cb);
2029 mNsdStateMachine.sendMessage(
2030 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_OFFLOAD_ENGINE, cb));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002031 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002032 }
2033
Hugo Benichi912db992017-04-24 16:41:03 +09002034 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07002035 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07002036 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09002037 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
2038 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07002039 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07002040 }
2041
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002042 private int getUniqueId() {
2043 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
2044 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002045 }
2046
Paul Hud44e1b72023-06-16 02:07:42 +00002047 private boolean registerService(int transactionId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09002048 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002049 Log.d(TAG, "registerService: " + transactionId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002050 }
Hugo Benichi6d706442017-04-24 16:19:58 +09002051 String name = service.getServiceName();
2052 String type = service.getServiceType();
2053 int port = service.getPort();
2054 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002055 final int registerInterface = getNetworkInterfaceIndex(service);
2056 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08002057 Log.e(TAG, "Interface to register service on not found");
2058 return false;
2059 }
Paul Hud44e1b72023-06-16 02:07:42 +00002060 return mMDnsManager.registerService(
2061 transactionId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002062 }
2063
Paul Hud44e1b72023-06-16 02:07:42 +00002064 private boolean unregisterService(int transactionId) {
2065 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002066 }
2067
Paul Hud44e1b72023-06-16 02:07:42 +00002068 private boolean discoverServices(int transactionId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08002069 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002070 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
2071 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002072 Log.e(TAG, "Interface to discover service on not found");
2073 return false;
2074 }
Paul Hud44e1b72023-06-16 02:07:42 +00002075 return mMDnsManager.discover(transactionId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002076 }
2077
Paul Hud44e1b72023-06-16 02:07:42 +00002078 private boolean stopServiceDiscovery(int transactionId) {
2079 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002080 }
2081
Paul Hud44e1b72023-06-16 02:07:42 +00002082 private boolean resolveService(int transactionId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002083 final String name = service.getServiceName();
2084 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002085 final int resolveInterface = getNetworkInterfaceIndex(service);
2086 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002087 Log.e(TAG, "Interface to resolve service on not found");
2088 return false;
2089 }
Paul Hud44e1b72023-06-16 02:07:42 +00002090 return mMDnsManager.resolve(transactionId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002091 }
2092
2093 /**
2094 * Guess the interface to use to resolve or discover a service on a specific network.
2095 *
2096 * This is an imperfect guess, as for example the network may be gone or not yet fully
2097 * registered. This is fine as failing is correct if the network is gone, and a client
2098 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
2099 * this is to support the legacy mdnsresponder implementation, which historically resolved
2100 * services on an unspecified network.
2101 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002102 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
2103 final Network network = serviceInfo.getNetwork();
2104 if (network == null) {
2105 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
2106 // provided by NsdService from discovery results, and the service was found on an
2107 // interface that has no app-usable Network).
2108 if (serviceInfo.getInterfaceIndex() != 0) {
2109 return serviceInfo.getInterfaceIndex();
2110 }
2111 return IFACE_IDX_ANY;
2112 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002113
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002114 String interfaceName = getNetworkInterfaceName(network);
2115 if (interfaceName == null) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002116 return IFACE_IDX_ANY;
2117 }
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002118 return getNetworkInterfaceIndexByName(interfaceName);
2119 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002120
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002121 private String getNetworkInterfaceName(@Nullable Network network) {
2122 if (network == null) {
2123 return null;
2124 }
2125 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
2126 if (cm == null) {
2127 Log.wtf(TAG, "No ConnectivityManager");
2128 return null;
2129 }
2130 final LinkProperties lp = cm.getLinkProperties(network);
2131 if (lp == null) {
2132 return null;
2133 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002134 // Only resolve on non-stacked interfaces
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002135 return lp.getInterfaceName();
2136 }
2137
2138 private int getNetworkInterfaceIndexByName(final String ifaceName) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002139 final NetworkInterface iface;
2140 try {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002141 iface = NetworkInterface.getByName(ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002142 } catch (SocketException e) {
2143 Log.e(TAG, "Error querying interface", e);
2144 return IFACE_IDX_ANY;
2145 }
2146
2147 if (iface == null) {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002148 Log.e(TAG, "Interface not found: " + ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002149 return IFACE_IDX_ANY;
2150 }
2151
2152 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002153 }
2154
Paul Hud44e1b72023-06-16 02:07:42 +00002155 private boolean stopResolveService(int transactionId) {
2156 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002157 }
2158
Paul Hud44e1b72023-06-16 02:07:42 +00002159 private boolean getAddrInfo(int transactionId, String hostname, int interfaceIdx) {
2160 return mMDnsManager.getServiceAddress(transactionId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002161 }
2162
Paul Hud44e1b72023-06-16 02:07:42 +00002163 private boolean stopGetAddrInfo(int transactionId) {
2164 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002165 }
2166
2167 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00002168 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2169 if (!PermissionUtils.checkDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002170
Paul Hub2e67d32023-04-18 05:50:14 +00002171 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
2172 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07002173 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00002174
2175 // Dump service and clients logs
2176 pw.println();
Paul Hu14667de2023-04-17 22:42:47 +08002177 pw.println("Logs:");
Paul Hub2e67d32023-04-18 05:50:14 +00002178 pw.increaseIndent();
2179 mServiceLogs.reverseDump(pw);
2180 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002181 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002182
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002183 private abstract static class ClientRequest {
Paul Hud44e1b72023-06-16 02:07:42 +00002184 private final int mTransactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002185 private final Clock mClock;
2186 private final long mStartTimeMs;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002187
Paul Hu777ed052023-06-19 13:35:15 +00002188 private ClientRequest(int transactionId, @NonNull Clock clock, long startTimeMs) {
Paul Hud44e1b72023-06-16 02:07:42 +00002189 mTransactionId = transactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002190 mClock = clock;
2191 mStartTimeMs = startTimeMs;
2192 }
2193
2194 public long calculateRequestDurationMs() {
2195 final long stopTimeMs = mClock.elapsedRealtime();
2196 return stopTimeMs - mStartTimeMs;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002197 }
2198 }
2199
2200 private static class LegacyClientRequest extends ClientRequest {
2201 private final int mRequestCode;
2202
Paul Hu777ed052023-06-19 13:35:15 +00002203 private LegacyClientRequest(int transactionId, int requestCode, @NonNull Clock clock,
2204 long startTimeMs) {
2205 super(transactionId, clock, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002206 mRequestCode = requestCode;
2207 }
2208 }
2209
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002210 private abstract static class JavaBackendClientRequest extends ClientRequest {
2211 @Nullable
2212 private final Network mRequestedNetwork;
2213
Paul Hu777ed052023-06-19 13:35:15 +00002214 private JavaBackendClientRequest(int transactionId, @Nullable Network requestedNetwork,
2215 @NonNull Clock clock, long startTimeMs) {
2216 super(transactionId, clock, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002217 mRequestedNetwork = requestedNetwork;
2218 }
2219
2220 @Nullable
2221 public Network getRequestedNetwork() {
2222 return mRequestedNetwork;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002223 }
2224 }
2225
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002226 private static class AdvertiserClientRequest extends JavaBackendClientRequest {
Paul Hu777ed052023-06-19 13:35:15 +00002227 private AdvertiserClientRequest(int transactionId, @Nullable Network requestedNetwork,
2228 @NonNull Clock clock, long startTimeMs) {
2229 super(transactionId, requestedNetwork, clock, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002230 }
2231 }
2232
2233 private static class DiscoveryManagerRequest extends JavaBackendClientRequest {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002234 @NonNull
2235 private final MdnsListener mListener;
2236
Paul Hud44e1b72023-06-16 02:07:42 +00002237 private DiscoveryManagerRequest(int transactionId, @NonNull MdnsListener listener,
Paul Hu777ed052023-06-19 13:35:15 +00002238 @Nullable Network requestedNetwork, @NonNull Clock clock, long startTimeMs) {
2239 super(transactionId, requestedNetwork, clock, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002240 mListener = listener;
2241 }
2242 }
2243
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002244 /* Information tracked per client */
2245 private class ClientInfo {
2246
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002247 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002248 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002249 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002250 private NsdServiceInfo mResolvedService;
2251
Paul Hud44e1b72023-06-16 02:07:42 +00002252 /* A map from client request ID (listenerKey) to the request */
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002253 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08002254
Luke Huangf7277ed2021-07-12 21:15:10 +08002255 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002256 private boolean mIsPreSClient = false;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002257 private final int mUid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002258 // The flag of using java backend if the client's target SDK >= U
2259 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002260 // Store client logs
2261 private final SharedLog mClientLogs;
Paul Hucdef3532023-06-18 14:47:35 +00002262 // Report the nsd metrics data
2263 private final NetworkNsdReportedMetrics mMetrics;
Luke Huangf7277ed2021-07-12 21:15:10 +08002264
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002265 private ClientInfo(INsdManagerCallback cb, int uid, boolean useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +00002266 SharedLog sharedLog, NetworkNsdReportedMetrics metrics) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002267 mCb = cb;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002268 mUid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002269 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002270 mClientLogs = sharedLog;
2271 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Paul Hucdef3532023-06-18 14:47:35 +00002272 mMetrics = metrics;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002273 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002274
2275 @Override
2276 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06002277 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07002278 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002279 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002280 sb.append("mUseJavaBackend ").append(mUseJavaBackend).append("\n");
2281 sb.append("mUid ").append(mUid).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002282 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002283 int clientRequestId = mClientRequests.keyAt(i);
2284 sb.append("clientRequestId ")
2285 .append(clientRequestId)
2286 .append(" transactionId ").append(mClientRequests.valueAt(i).mTransactionId)
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002287 .append(" type ").append(
2288 mClientRequests.valueAt(i).getClass().getSimpleName())
2289 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07002290 }
2291 return sb.toString();
2292 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002293
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002294 private boolean isPreSClient() {
2295 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08002296 }
2297
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002298 private void setPreSClient() {
2299 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08002300 }
2301
Paul Hue4f5f252023-02-16 21:13:47 +08002302 private void unregisterMdnsListenerFromRequest(ClientRequest request) {
2303 final MdnsListener listener =
2304 ((DiscoveryManagerRequest) request).mListener;
2305 mMdnsDiscoveryManager.unregisterListener(
2306 listener.getListenedServiceType(), listener);
2307 }
2308
Dave Plattfeff2af2014-03-07 14:48:22 -08002309 // Remove any pending requests from the global map when we get rid of a client,
2310 // and send cancellations to the daemon.
2311 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00002312 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09002313 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002314 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002315 final int clientRequestId = mClientRequests.keyAt(i);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002316 final ClientRequest request = mClientRequests.valueAt(i);
Paul Hud44e1b72023-06-16 02:07:42 +00002317 final int transactionId = request.mTransactionId;
2318 mTransactionIdToClientInfoMap.remove(transactionId);
paulhub2225702021-11-17 09:35:33 +08002319 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002320 Log.d(TAG, "Terminating clientRequestId " + clientRequestId
2321 + " transactionId " + transactionId
2322 + " type " + mClientRequests.get(clientRequestId));
paulhub2225702021-11-17 09:35:33 +08002323 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002324
2325 if (request instanceof DiscoveryManagerRequest) {
Paul Hue4f5f252023-02-16 21:13:47 +08002326 unregisterMdnsListenerFromRequest(request);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002327 continue;
2328 }
2329
2330 if (request instanceof AdvertiserClientRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00002331 mAdvertiser.removeService(transactionId);
Paul Hu777ed052023-06-19 13:35:15 +00002332 mMetrics.reportServiceUnregistration(
2333 transactionId, request.calculateRequestDurationMs());
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002334 continue;
2335 }
2336
2337 if (!(request instanceof LegacyClientRequest)) {
2338 throw new IllegalStateException("Unknown request type: " + request.getClass());
2339 }
2340
2341 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08002342 case NsdManager.DISCOVER_SERVICES:
Paul Hud44e1b72023-06-16 02:07:42 +00002343 stopServiceDiscovery(transactionId);
Dave Plattfeff2af2014-03-07 14:48:22 -08002344 break;
2345 case NsdManager.RESOLVE_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002346 stopResolveService(transactionId);
Dave Plattfeff2af2014-03-07 14:48:22 -08002347 break;
2348 case NsdManager.REGISTER_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002349 unregisterService(transactionId);
Paul Hu777ed052023-06-19 13:35:15 +00002350 mMetrics.reportServiceUnregistration(
2351 transactionId, request.calculateRequestDurationMs());
Dave Plattfeff2af2014-03-07 14:48:22 -08002352 break;
2353 default:
2354 break;
2355 }
2356 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002357 mClientRequests.clear();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002358 updateMulticastLock();
2359 }
2360
2361 /**
2362 * Returns true if this client has any Java backend request that requests one of the given
2363 * networks.
2364 */
2365 boolean hasAnyJavaBackendRequestForNetworks(@NonNull ArraySet<Network> networks) {
2366 for (int i = 0; i < mClientRequests.size(); i++) {
2367 final ClientRequest req = mClientRequests.valueAt(i);
2368 if (!(req instanceof JavaBackendClientRequest)) {
2369 continue;
2370 }
2371 final Network reqNetwork = ((JavaBackendClientRequest) mClientRequests.valueAt(i))
2372 .getRequestedNetwork();
2373 if (MdnsUtils.isAnyNetworkMatched(reqNetwork, networks)) {
2374 return true;
2375 }
2376 }
2377 return false;
Dave Plattfeff2af2014-03-07 14:48:22 -08002378 }
2379
Paul Hud44e1b72023-06-16 02:07:42 +00002380 // mClientRequests is a sparse array of client request id -> ClientRequest. For a given
2381 // transaction id, return the corresponding client request id.
2382 private int getClientRequestId(final int transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002383 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002384 if (mClientRequests.valueAt(i).mTransactionId == transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002385 return mClientRequests.keyAt(i);
2386 }
Christopher Lane74411222014-04-25 18:39:07 -07002387 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002388 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07002389 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002390
Paul Hub2e67d32023-04-18 05:50:14 +00002391 private void log(String message) {
2392 mClientLogs.log(message);
2393 }
2394
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002395 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info) {
2396 try {
2397 mCb.onDiscoverServicesStarted(listenerKey, info);
2398 } catch (RemoteException e) {
2399 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
2400 }
2401 }
2402
2403 void onDiscoverServicesFailed(int listenerKey, int error) {
2404 try {
2405 mCb.onDiscoverServicesFailed(listenerKey, error);
2406 } catch (RemoteException e) {
2407 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
2408 }
2409 }
2410
2411 void onServiceFound(int listenerKey, NsdServiceInfo info) {
2412 try {
2413 mCb.onServiceFound(listenerKey, info);
2414 } catch (RemoteException e) {
2415 Log.e(TAG, "Error calling onServiceFound(", e);
2416 }
2417 }
2418
2419 void onServiceLost(int listenerKey, NsdServiceInfo info) {
2420 try {
2421 mCb.onServiceLost(listenerKey, info);
2422 } catch (RemoteException e) {
2423 Log.e(TAG, "Error calling onServiceLost(", e);
2424 }
2425 }
2426
2427 void onStopDiscoveryFailed(int listenerKey, int error) {
2428 try {
2429 mCb.onStopDiscoveryFailed(listenerKey, error);
2430 } catch (RemoteException e) {
2431 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
2432 }
2433 }
2434
2435 void onStopDiscoverySucceeded(int listenerKey) {
2436 try {
2437 mCb.onStopDiscoverySucceeded(listenerKey);
2438 } catch (RemoteException e) {
2439 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
2440 }
2441 }
2442
Paul Hu777ed052023-06-19 13:35:15 +00002443 void onRegisterServiceFailedImmediately(int listenerKey, int error) {
2444 onRegisterServiceFailed(listenerKey, error, NO_TRANSACTION, 0 /* durationMs */);
2445 }
2446
2447 void onRegisterServiceFailed(int listenerKey, int error, int transactionId,
2448 long durationMs) {
2449 mMetrics.reportServiceRegistrationFailed(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002450 try {
2451 mCb.onRegisterServiceFailed(listenerKey, error);
2452 } catch (RemoteException e) {
2453 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2454 }
2455 }
2456
Paul Hu777ed052023-06-19 13:35:15 +00002457 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info, int transactionId,
2458 long durationMs) {
2459 mMetrics.reportServiceRegistrationSucceeded(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002460 try {
2461 mCb.onRegisterServiceSucceeded(listenerKey, info);
2462 } catch (RemoteException e) {
2463 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2464 }
2465 }
2466
2467 void onUnregisterServiceFailed(int listenerKey, int error) {
2468 try {
2469 mCb.onUnregisterServiceFailed(listenerKey, error);
2470 } catch (RemoteException e) {
2471 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2472 }
2473 }
2474
Paul Hu777ed052023-06-19 13:35:15 +00002475 void onUnregisterServiceSucceeded(int listenerKey, int transactionId, long durationMs) {
2476 mMetrics.reportServiceUnregistration(transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002477 try {
2478 mCb.onUnregisterServiceSucceeded(listenerKey);
2479 } catch (RemoteException e) {
2480 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2481 }
2482 }
2483
2484 void onResolveServiceFailed(int listenerKey, int error) {
2485 try {
2486 mCb.onResolveServiceFailed(listenerKey, error);
2487 } catch (RemoteException e) {
2488 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2489 }
2490 }
2491
2492 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info) {
2493 try {
2494 mCb.onResolveServiceSucceeded(listenerKey, info);
2495 } catch (RemoteException e) {
2496 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2497 }
2498 }
Paul Hub58deb72022-12-26 09:24:42 +00002499
2500 void onStopResolutionFailed(int listenerKey, int error) {
2501 try {
2502 mCb.onStopResolutionFailed(listenerKey, error);
2503 } catch (RemoteException e) {
2504 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2505 }
2506 }
2507
2508 void onStopResolutionSucceeded(int listenerKey) {
2509 try {
2510 mCb.onStopResolutionSucceeded(listenerKey);
2511 } catch (RemoteException e) {
2512 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2513 }
2514 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002515
2516 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
2517 try {
2518 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2519 } catch (RemoteException e) {
2520 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2521 }
2522 }
2523
2524 void onServiceUpdated(int listenerKey, NsdServiceInfo info) {
2525 try {
2526 mCb.onServiceUpdated(listenerKey, info);
2527 } catch (RemoteException e) {
2528 Log.e(TAG, "Error calling onServiceUpdated", e);
2529 }
2530 }
2531
2532 void onServiceUpdatedLost(int listenerKey) {
2533 try {
2534 mCb.onServiceUpdatedLost(listenerKey);
2535 } catch (RemoteException e) {
2536 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2537 }
2538 }
2539
2540 void onServiceInfoCallbackUnregistered(int listenerKey) {
2541 try {
2542 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2543 } catch (RemoteException e) {
2544 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2545 }
2546 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002547 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002548}