blob: 6086207f627baf99d99fc2b5f2aa49e459e371b0 [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 Huangd5896e72023-11-28 13:23:59 +090019import static android.Manifest.permission.DEVICE_POWER;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090020import static android.Manifest.permission.NETWORK_SETTINGS;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090021import static android.Manifest.permission.NETWORK_STACK;
paulhu2b9ed952022-02-10 21:58:32 +080022import static android.net.ConnectivityManager.NETID_UNSET;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090023import static android.net.NetworkCapabilities.TRANSPORT_VPN;
24import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090025import static android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK;
Paul Hu019621e2023-01-13 23:26:49 +080026import static android.net.nsd.NsdManager.MDNS_DISCOVERY_MANAGER_EVENT;
paulhu2b9ed952022-02-10 21:58:32 +080027import static android.net.nsd.NsdManager.MDNS_SERVICE_EVENT;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +090028import static android.net.nsd.NsdManager.RESOLVE_SERVICE_SUCCEEDED;
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +090029import static android.provider.DeviceConfig.NAMESPACE_TETHERING;
Motomu Utsumied4e7ec2023-09-13 14:58:32 +090030
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090031import static com.android.modules.utils.build.SdkLevel.isAtLeastU;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090032import static com.android.networkstack.apishim.ConstantsShim.REGISTER_NSD_OFFLOAD_ENGINE;
Paul Hu043bcd42023-07-14 16:38:25 +080033import static com.android.server.connectivity.mdns.MdnsAdvertiser.AdvertiserMetrics;
34import static com.android.server.connectivity.mdns.MdnsConstants.NO_PACKET;
Yuyang Huangde802c82023-05-02 17:14:22 +090035import static com.android.server.connectivity.mdns.MdnsRecord.MAX_LABEL_LENGTH;
Paul Hucdef3532023-06-18 14:47:35 +000036import static com.android.server.connectivity.mdns.util.MdnsUtils.Clock;
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090037
Paul Hu23fa2022023-01-13 22:57:24 +080038import android.annotation.NonNull;
Paul Hu4bd98ef2023-01-12 13:42:07 +080039import android.annotation.Nullable;
Yuyang Huangfc831702023-08-21 17:48:48 +090040import android.annotation.RequiresApi;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090041import android.app.ActivityManager;
paulhua262cc12019-08-12 16:25:11 +080042import android.content.Context;
Irfan Sheriff75006652012-04-17 23:15:29 -070043import android.content.Intent;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090044import android.net.ConnectivityManager;
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +090045import android.net.INetd;
Paul Hu75069ed2023-01-14 00:31:09 +080046import android.net.InetAddresses;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090047import android.net.LinkProperties;
48import android.net.Network;
paulhu2b9ed952022-02-10 21:58:32 +080049import android.net.mdns.aidl.DiscoveryInfo;
50import android.net.mdns.aidl.GetAddressInfo;
51import android.net.mdns.aidl.IMDnsEventListener;
52import android.net.mdns.aidl.RegistrationInfo;
53import android.net.mdns.aidl.ResolutionInfo;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070054import android.net.nsd.INsdManager;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090055import android.net.nsd.INsdManagerCallback;
56import android.net.nsd.INsdServiceConnector;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090057import android.net.nsd.IOffloadEngine;
paulhu2b9ed952022-02-10 21:58:32 +080058import android.net.nsd.MDnsManager;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070059import android.net.nsd.NsdManager;
paulhua262cc12019-08-12 16:25:11 +080060import android.net.nsd.NsdServiceInfo;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090061import android.net.nsd.OffloadEngine;
62import android.net.nsd.OffloadServiceInfo;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090063import android.net.wifi.WifiManager;
Paul Hub2e67d32023-04-18 05:50:14 +000064import android.os.Binder;
Yuyang Huangfc831702023-08-21 17:48:48 +090065import android.os.Build;
Hugo Benichi803a2f02017-04-24 11:35:06 +090066import android.os.Handler;
paulhua262cc12019-08-12 16:25:11 +080067import android.os.HandlerThread;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090068import android.os.IBinder;
Paul Hu4bd98ef2023-01-12 13:42:07 +080069import android.os.Looper;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070070import android.os.Message;
Yuyang Huang33fa4d22023-02-14 22:59:37 +090071import android.os.RemoteCallbackList;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090072import android.os.RemoteException;
Dianne Hackborn692107e2012-08-29 18:32:08 -070073import android.os.UserHandle;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090074import android.provider.DeviceConfig;
Paul Hu23fa2022023-01-13 22:57:24 +080075import android.text.TextUtils;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090076import android.util.ArraySet;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090077import android.util.Log;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +090078import android.util.Pair;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070079import android.util.SparseArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070080
paulhua262cc12019-08-12 16:25:11 +080081import com.android.internal.annotations.VisibleForTesting;
Paul Hub2e67d32023-04-18 05:50:14 +000082import com.android.internal.util.IndentingPrintWriter;
paulhua262cc12019-08-12 16:25:11 +080083import com.android.internal.util.State;
84import com.android.internal.util.StateMachine;
Paul Hucdef3532023-06-18 14:47:35 +000085import com.android.metrics.NetworkNsdReportedMetrics;
Yuyang Huang8e6fbc82023-08-07 17:46:19 +090086import com.android.modules.utils.build.SdkLevel;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090087import com.android.net.module.util.CollectionUtils;
Paul Hu4bd98ef2023-01-12 13:42:07 +080088import com.android.net.module.util.DeviceConfigUtils;
Yuyang Huanga6a6ff92023-04-24 13:33:34 +090089import com.android.net.module.util.InetAddressUtils;
paulhu3ffffe72021-09-16 10:15:22 +080090import com.android.net.module.util.PermissionUtils;
Paul Hub2e67d32023-04-18 05:50:14 +000091import com.android.net.module.util.SharedLog;
Paul Hu4bd98ef2023-01-12 13:42:07 +080092import com.android.server.connectivity.mdns.ExecutorProvider;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090093import com.android.server.connectivity.mdns.MdnsAdvertiser;
Yuyang Huange5cba9c2023-11-02 18:05:47 +090094import com.android.server.connectivity.mdns.MdnsAdvertisingOptions;
Paul Hu4bd98ef2023-01-12 13:42:07 +080095import com.android.server.connectivity.mdns.MdnsDiscoveryManager;
Yuyang Huangb96a0712023-09-07 15:13:15 +090096import com.android.server.connectivity.mdns.MdnsFeatureFlags;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090097import com.android.server.connectivity.mdns.MdnsInterfaceSocket;
Paul Hu4bd98ef2023-01-12 13:42:07 +080098import com.android.server.connectivity.mdns.MdnsMultinetworkSocketClient;
Paul Hu23fa2022023-01-13 22:57:24 +080099import com.android.server.connectivity.mdns.MdnsSearchOptions;
100import com.android.server.connectivity.mdns.MdnsServiceBrowserListener;
101import com.android.server.connectivity.mdns.MdnsServiceInfo;
Paul Hu4bd98ef2023-01-12 13:42:07 +0800102import com.android.server.connectivity.mdns.MdnsSocketProvider;
Yuyang Huangde802c82023-05-02 17:14:22 +0900103import com.android.server.connectivity.mdns.util.MdnsUtils;
paulhua262cc12019-08-12 16:25:11 +0800104
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700105import java.io.FileDescriptor;
106import java.io.PrintWriter;
Yuyang Huangaa0e9602023-03-17 12:43:09 +0900107import java.net.Inet6Address;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700108import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900109import java.net.NetworkInterface;
110import java.net.SocketException;
111import java.net.UnknownHostException;
Paul Hu2b865912023-03-06 14:27:53 +0800112import java.util.ArrayList;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900113import java.util.Arrays;
Kangping Dong5af24b62023-12-10 21:41:16 +0800114import java.util.Collection;
Yuyang Huang170d42f2023-12-09 15:26:16 +0900115import java.util.Collections;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700116import java.util.HashMap;
Kangping Dong5af24b62023-12-10 21:41:16 +0800117import java.util.LinkedHashMap;
Paul Hu23fa2022023-01-13 22:57:24 +0800118import java.util.List;
Paul Hu75069ed2023-01-14 00:31:09 +0800119import java.util.Map;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900120import java.util.Objects;
Paul Hu812e9212023-06-20 06:24:53 +0000121import java.util.Set;
Paul Hu23fa2022023-01-13 22:57:24 +0800122import java.util.regex.Matcher;
123import java.util.regex.Pattern;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700124
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700125/**
126 * Network Service Discovery Service handles remote service discovery operation requests by
127 * implementing the INsdManager interface.
128 *
129 * @hide
130 */
Yuyang Huangfc831702023-08-21 17:48:48 +0900131@RequiresApi(Build.VERSION_CODES.TIRAMISU)
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700132public class NsdService extends INsdManager.Stub {
133 private static final String TAG = "NsdService";
134 private static final String MDNS_TAG = "mDnsConnector";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900135 /**
136 * Enable discovery using the Java DiscoveryManager, instead of the legacy mdnsresponder
137 * implementation.
138 */
Paul Hu4bd98ef2023-01-12 13:42:07 +0800139 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Paul Hu23fa2022023-01-13 22:57:24 +0800140 private static final String LOCAL_DOMAIN_NAME = "local";
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700141
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900142 /**
143 * Enable advertising using the Java MdnsAdvertiser, instead of the legacy mdnsresponder
144 * implementation.
145 */
146 private static final String MDNS_ADVERTISER_VERSION = "mdns_advertiser_version";
147
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900148 /**
149 * Comma-separated list of type:flag mappings indicating the flags to use to allowlist
150 * discovery/advertising using MdnsDiscoveryManager / MdnsAdvertiser for a given type.
151 *
152 * For example _mytype._tcp.local and _othertype._tcp.local would be configured with:
153 * _mytype._tcp:mytype,_othertype._tcp.local:othertype
154 *
155 * In which case the flags:
156 * "mdns_discovery_manager_allowlist_mytype_version",
157 * "mdns_advertiser_allowlist_mytype_version",
158 * "mdns_discovery_manager_allowlist_othertype_version",
159 * "mdns_advertiser_allowlist_othertype_version"
160 * would be used to toggle MdnsDiscoveryManager / MdnsAdvertiser for each type. The flags will
161 * be read with
Motomu Utsumi624aeb42023-08-15 15:52:27 +0900162 * {@link DeviceConfigUtils#isTetheringFeatureEnabled}
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900163 *
164 * @see #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX
165 * @see #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX
166 * @see #MDNS_ALLOWLIST_FLAG_SUFFIX
167 */
168 private static final String MDNS_TYPE_ALLOWLIST_FLAGS = "mdns_type_allowlist_flags";
169
170 private static final String MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX =
171 "mdns_discovery_manager_allowlist_";
172 private static final String MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX =
173 "mdns_advertiser_allowlist_";
174 private static final String MDNS_ALLOWLIST_FLAG_SUFFIX = "_version";
175
Kangping Dong5af24b62023-12-10 21:41:16 +0800176 private static final String TYPE_SUBTYPE_LABEL_REGEX = "_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]";
177
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900178 @VisibleForTesting
179 static final String MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
180 "mdns_config_running_app_active_importance_cutoff";
181 @VisibleForTesting
182 static final int DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
183 ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
184 private final int mRunningAppActiveImportanceCutoff;
185
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900186 public static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +0000187 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900188 private static final int IFACE_IDX_ANY = 0;
Paul Hu812e9212023-06-20 06:24:53 +0000189 private static final int MAX_SERVICES_COUNT_METRIC_PER_CLIENT = 100;
190 @VisibleForTesting
191 static final int NO_TRANSACTION = -1;
Paul Hubad6fe92023-07-24 21:25:22 +0800192 private static final int NO_SENT_QUERY_COUNT = 0;
193 private static final int DISCOVERY_QUERY_SENT_CALLBACK = 1000;
Kangping Dong5af24b62023-12-10 21:41:16 +0800194 private static final int MAX_SUBTYPE_COUNT = 100;
Paul Hu14667de2023-04-17 22:42:47 +0800195 private static final SharedLog LOGGER = new SharedLog("serviceDiscovery");
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700196
Hugo Benichi32be63d2017-04-05 14:06:11 +0900197 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900198 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +0800199 private final MDnsManager mMDnsManager;
200 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900201 @NonNull
202 private final Dependencies mDeps;
203 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800204 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900205 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800206 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900207 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800208 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900209 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900210 private final MdnsAdvertiser mAdvertiser;
Paul Hu777ed052023-06-19 13:35:15 +0000211 @NonNull
212 private final Clock mClock;
Paul Hu14667de2023-04-17 22:42:47 +0800213 private final SharedLog mServiceLogs = LOGGER.forSubComponent(TAG);
Paul Hu23fa2022023-01-13 22:57:24 +0800214 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800215 // state machine thread. If change this outside state machine, it will need to introduce
216 // synchronization.
217 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800218 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700219
220 /**
221 * Clients receiving asynchronous messages
222 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900223 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700224
Paul Hud44e1b72023-06-16 02:07:42 +0000225 /* A map from transaction(unique) id to client info */
226 private final SparseArray<ClientInfo> mTransactionIdToClientInfoMap = new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700227
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900228 // Note this is not final to avoid depending on the Wi-Fi service starting before NsdService
229 @Nullable
230 private WifiManager.MulticastLock mHeldMulticastLock;
231 // Fulfilled network requests that require the Wi-Fi lock: key is the obtained Network
232 // (non-null), value is the requested Network (nullable)
233 @NonNull
234 private final ArraySet<Network> mWifiLockRequiredNetworks = new ArraySet<>();
235 @NonNull
236 private final ArraySet<Integer> mRunningAppActiveUids = new ArraySet<>();
237
Luke Huang05298582021-06-13 16:52:05 +0000238 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700239
Hugo Benichi32be63d2017-04-05 14:06:11 +0900240 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700241 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800242 // The count of the connected legacy clients.
243 private int mLegacyClientCount = 0;
Paul Hub2e67d32023-04-18 05:50:14 +0000244 // The number of client that ever connected.
245 private int mClientNumberId = 1;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700246
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900247 private final RemoteCallbackList<IOffloadEngine> mOffloadEngines =
248 new RemoteCallbackList<>();
249
250 private static class OffloadEngineInfo {
251 @NonNull final String mInterfaceName;
252 final long mOffloadCapabilities;
253 final long mOffloadType;
254 @NonNull final IOffloadEngine mOffloadEngine;
255
256 OffloadEngineInfo(@NonNull IOffloadEngine offloadEngine,
257 @NonNull String interfaceName, long capabilities, long offloadType) {
258 this.mOffloadEngine = offloadEngine;
259 this.mInterfaceName = interfaceName;
260 this.mOffloadCapabilities = capabilities;
261 this.mOffloadType = offloadType;
262 }
263 }
264
Paul Hu812e9212023-06-20 06:24:53 +0000265 @VisibleForTesting
266 static class MdnsListener implements MdnsServiceBrowserListener {
Paul Hud44e1b72023-06-16 02:07:42 +0000267 protected final int mClientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800268 protected final int mTransactionId;
269 @NonNull
270 protected final NsdServiceInfo mReqServiceInfo;
271 @NonNull
272 protected final String mListenedServiceType;
273
Paul Hud44e1b72023-06-16 02:07:42 +0000274 MdnsListener(int clientRequestId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
Paul Hu23fa2022023-01-13 22:57:24 +0800275 @NonNull String listenedServiceType) {
Paul Hud44e1b72023-06-16 02:07:42 +0000276 mClientRequestId = clientRequestId;
Paul Hu23fa2022023-01-13 22:57:24 +0800277 mTransactionId = transactionId;
278 mReqServiceInfo = reqServiceInfo;
279 mListenedServiceType = listenedServiceType;
280 }
281
282 @NonNull
283 public String getListenedServiceType() {
284 return mListenedServiceType;
285 }
286
287 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000288 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
289 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800290
291 @Override
292 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
293
294 @Override
295 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
296
297 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000298 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
299 boolean isServiceFromCache) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800300
301 @Override
302 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
303
304 @Override
305 public void onSearchStoppedWithError(int error) { }
306
307 @Override
308 public void onSearchFailedToStart() { }
309
310 @Override
Paul Hubad6fe92023-07-24 21:25:22 +0800311 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
312 int sentQueryTransactionId) { }
Paul Hu23fa2022023-01-13 22:57:24 +0800313
314 @Override
315 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
316 }
317
318 private class DiscoveryListener extends MdnsListener {
319
Paul Hud44e1b72023-06-16 02:07:42 +0000320 DiscoveryListener(int clientRequestId, int transactionId,
321 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
322 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800323 }
324
325 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000326 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo,
327 boolean isServiceFromCache) {
Paul Hu019621e2023-01-13 23:26:49 +0800328 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
329 NsdManager.SERVICE_FOUND,
Paul Hua6bc4632023-06-26 01:18:29 +0000330 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu23fa2022023-01-13 22:57:24 +0800331 }
332
333 @Override
334 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800335 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
336 NsdManager.SERVICE_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000337 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800338 }
Paul Hubad6fe92023-07-24 21:25:22 +0800339
340 @Override
341 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
342 int sentQueryTransactionId) {
343 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
344 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
345 }
Paul Hu23fa2022023-01-13 22:57:24 +0800346 }
347
Paul Hu75069ed2023-01-14 00:31:09 +0800348 private class ResolutionListener extends MdnsListener {
349
Paul Hud44e1b72023-06-16 02:07:42 +0000350 ResolutionListener(int clientRequestId, int transactionId,
351 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
352 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800353 }
354
355 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000356 public void onServiceFound(MdnsServiceInfo serviceInfo, boolean isServiceFromCache) {
Paul Hu75069ed2023-01-14 00:31:09 +0800357 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
358 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
Paul Hua6bc4632023-06-26 01:18:29 +0000359 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu75069ed2023-01-14 00:31:09 +0800360 }
Paul Hubad6fe92023-07-24 21:25:22 +0800361
362 @Override
363 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
364 int sentQueryTransactionId) {
365 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
366 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
367 }
Paul Hu75069ed2023-01-14 00:31:09 +0800368 }
369
Paul Hu30bd70d2023-02-07 13:20:56 +0000370 private class ServiceInfoListener extends MdnsListener {
371
Paul Hud44e1b72023-06-16 02:07:42 +0000372 ServiceInfoListener(int clientRequestId, int transactionId,
373 @NonNull NsdServiceInfo reqServiceInfo, @NonNull String listenServiceType) {
374 super(clientRequestId, transactionId, reqServiceInfo, listenServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +0000375 }
376
377 @Override
Paul Hua6bc4632023-06-26 01:18:29 +0000378 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo,
379 boolean isServiceFromCache) {
Paul Hu30bd70d2023-02-07 13:20:56 +0000380 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
381 NsdManager.SERVICE_UPDATED,
Paul Hua6bc4632023-06-26 01:18:29 +0000382 new MdnsEvent(mClientRequestId, serviceInfo, isServiceFromCache));
Paul Hu30bd70d2023-02-07 13:20:56 +0000383 }
384
385 @Override
386 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) {
387 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
388 NsdManager.SERVICE_UPDATED,
Paul Hud44e1b72023-06-16 02:07:42 +0000389 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000390 }
391
392 @Override
393 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) {
394 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
395 NsdManager.SERVICE_UPDATED_LOST,
Paul Hud44e1b72023-06-16 02:07:42 +0000396 new MdnsEvent(mClientRequestId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000397 }
Paul Hubad6fe92023-07-24 21:25:22 +0800398
399 @Override
400 public void onDiscoveryQuerySent(@NonNull List<String> subtypes,
401 int sentQueryTransactionId) {
402 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
403 DISCOVERY_QUERY_SENT_CALLBACK, new MdnsEvent(mClientRequestId));
404 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000405 }
406
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900407 private class SocketRequestMonitor implements MdnsSocketProvider.SocketRequestMonitor {
408 @Override
409 public void onSocketRequestFulfilled(@Nullable Network socketNetwork,
410 @NonNull MdnsInterfaceSocket socket, @NonNull int[] transports) {
411 // The network may be null for Wi-Fi SoftAp interfaces (tethering), but there is no APF
412 // filtering on such interfaces, so taking the multicast lock is not necessary to
413 // disable APF filtering of multicast.
414 if (socketNetwork == null
415 || !CollectionUtils.contains(transports, TRANSPORT_WIFI)
416 || CollectionUtils.contains(transports, TRANSPORT_VPN)) {
417 return;
418 }
419
420 if (mWifiLockRequiredNetworks.add(socketNetwork)) {
421 updateMulticastLock();
422 }
423 }
424
425 @Override
426 public void onSocketDestroyed(@Nullable Network socketNetwork,
427 @NonNull MdnsInterfaceSocket socket) {
428 if (mWifiLockRequiredNetworks.remove(socketNetwork)) {
429 updateMulticastLock();
430 }
431 }
432 }
433
434 private class UidImportanceListener implements ActivityManager.OnUidImportanceListener {
435 private final Handler mHandler;
436
437 private UidImportanceListener(Handler handler) {
438 mHandler = handler;
439 }
440
441 @Override
442 public void onUidImportance(int uid, int importance) {
443 mHandler.post(() -> handleUidImportanceChanged(uid, importance));
444 }
445 }
446
447 private void handleUidImportanceChanged(int uid, int importance) {
448 // Lower importance values are more "important"
449 final boolean modified = importance <= mRunningAppActiveImportanceCutoff
450 ? mRunningAppActiveUids.add(uid)
451 : mRunningAppActiveUids.remove(uid);
452 if (modified) {
453 updateMulticastLock();
454 }
455 }
456
457 /**
458 * Take or release the lock based on updated internal state.
459 *
460 * This determines whether the lock needs to be held based on
461 * {@link #mWifiLockRequiredNetworks}, {@link #mRunningAppActiveUids} and
462 * {@link ClientInfo#mClientRequests}, so it must be called after any of the these have been
463 * updated.
464 */
465 private void updateMulticastLock() {
466 final int needsLockUid = getMulticastLockNeededUid();
467 if (needsLockUid >= 0 && mHeldMulticastLock == null) {
468 final WifiManager wm = mContext.getSystemService(WifiManager.class);
469 if (wm == null) {
470 Log.wtf(TAG, "Got a TRANSPORT_WIFI network without WifiManager");
471 return;
472 }
473 mHeldMulticastLock = wm.createMulticastLock(TAG);
474 mHeldMulticastLock.acquire();
475 mServiceLogs.log("Taking multicast lock for uid " + needsLockUid);
476 } else if (needsLockUid < 0 && mHeldMulticastLock != null) {
477 mHeldMulticastLock.release();
478 mHeldMulticastLock = null;
479 mServiceLogs.log("Released multicast lock");
480 }
481 }
482
483 /**
484 * @return The UID of an app requiring the multicast lock, or -1 if none.
485 */
486 private int getMulticastLockNeededUid() {
487 if (mWifiLockRequiredNetworks.size() == 0) {
488 // Return early if NSD is not active, or not on any relevant network
489 return -1;
490 }
Paul Hud44e1b72023-06-16 02:07:42 +0000491 for (int i = 0; i < mTransactionIdToClientInfoMap.size(); i++) {
492 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.valueAt(i);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900493 if (!mRunningAppActiveUids.contains(clientInfo.mUid)) {
494 // Ignore non-active UIDs
495 continue;
496 }
497
498 if (clientInfo.hasAnyJavaBackendRequestForNetworks(mWifiLockRequiredNetworks)) {
499 return clientInfo.mUid;
500 }
501 }
502 return -1;
503 }
504
Paul Hu019621e2023-01-13 23:26:49 +0800505 /**
506 * Data class of mdns service callback information.
507 */
508 private static class MdnsEvent {
Paul Hud44e1b72023-06-16 02:07:42 +0000509 final int mClientRequestId;
Paul Hubad6fe92023-07-24 21:25:22 +0800510 @Nullable
Paul Hu019621e2023-01-13 23:26:49 +0800511 final MdnsServiceInfo mMdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000512 final boolean mIsServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800513
Paul Hubad6fe92023-07-24 21:25:22 +0800514 MdnsEvent(int clientRequestId) {
515 this(clientRequestId, null /* mdnsServiceInfo */, false /* isServiceFromCache */);
516 }
517
518 MdnsEvent(int clientRequestId, @Nullable MdnsServiceInfo mdnsServiceInfo) {
Paul Hua6bc4632023-06-26 01:18:29 +0000519 this(clientRequestId, mdnsServiceInfo, false /* isServiceFromCache */);
520 }
521
Paul Hubad6fe92023-07-24 21:25:22 +0800522 MdnsEvent(int clientRequestId, @Nullable MdnsServiceInfo mdnsServiceInfo,
Paul Hua6bc4632023-06-26 01:18:29 +0000523 boolean isServiceFromCache) {
Paul Hud44e1b72023-06-16 02:07:42 +0000524 mClientRequestId = clientRequestId;
Paul Hu019621e2023-01-13 23:26:49 +0800525 mMdnsServiceInfo = mdnsServiceInfo;
Paul Hua6bc4632023-06-26 01:18:29 +0000526 mIsServiceFromCache = isServiceFromCache;
Paul Hu019621e2023-01-13 23:26:49 +0800527 }
528 }
529
Paul Hu77c11182023-10-23 16:17:32 +0800530 // TODO: Use a Handler instead of a StateMachine since there are no state changes.
Irfan Sheriff75006652012-04-17 23:15:29 -0700531 private class NsdStateMachine extends StateMachine {
532
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700533 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700534
535 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700536 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900537 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700538 }
539
Luke Huang92860f92021-06-23 06:29:30 +0000540 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800541 if (mIsDaemonStarted) {
542 if (DBG) Log.d(TAG, "Daemon is already started.");
543 return;
544 }
545 mMDnsManager.registerEventListener(mMDnsEventCallback);
546 mMDnsManager.startDaemon();
547 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000548 maybeScheduleStop();
Paul Hub2e67d32023-04-18 05:50:14 +0000549 mServiceLogs.log("Start mdns_responder daemon");
Luke Huang05298582021-06-13 16:52:05 +0000550 }
551
paulhu2b9ed952022-02-10 21:58:32 +0800552 private void maybeStopDaemon() {
553 if (!mIsDaemonStarted) {
554 if (DBG) Log.d(TAG, "Daemon has not been started.");
555 return;
556 }
557 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
558 mMDnsManager.stopDaemon();
559 mIsDaemonStarted = false;
Paul Hub2e67d32023-04-18 05:50:14 +0000560 mServiceLogs.log("Stop mdns_responder daemon");
paulhu2b9ed952022-02-10 21:58:32 +0800561 }
562
Luke Huang92860f92021-06-23 06:29:30 +0000563 private boolean isAnyRequestActive() {
Paul Hud44e1b72023-06-16 02:07:42 +0000564 return mTransactionIdToClientInfoMap.size() != 0;
Luke Huang92860f92021-06-23 06:29:30 +0000565 }
566
567 private void scheduleStop() {
568 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
569 }
570 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800571 // The native daemon should stay alive and can't be cleanup
572 // if any legacy client connected.
573 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000574 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000575 }
576 }
577
Luke Huang92860f92021-06-23 06:29:30 +0000578 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000579 this.removeMessages(NsdManager.DAEMON_CLEANUP);
580 }
581
Paul Hu23fa2022023-01-13 22:57:24 +0800582 private void maybeStartMonitoringSockets() {
583 if (mIsMonitoringSocketsStarted) {
584 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
585 return;
586 }
587
588 mMdnsSocketProvider.startMonitoringSockets();
589 mIsMonitoringSocketsStarted = true;
590 }
591
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900592 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
593 if (!mIsMonitoringSocketsStarted) return;
594 if (isAnyRequestActive()) return;
595
Paul Hu58f20602023-02-18 11:41:07 +0800596 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800597 mIsMonitoringSocketsStarted = false;
598 }
599
Hugo Benichi803a2f02017-04-24 11:35:06 +0900600 NsdStateMachine(String name, Handler handler) {
601 super(name, handler);
Paul Hu77c11182023-10-23 16:17:32 +0800602 addState(mEnabledState);
paulhu5568f452021-11-30 13:31:29 +0800603 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900604 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700605 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700606 }
607
Irfan Sheriff75006652012-04-17 23:15:29 -0700608 class EnabledState extends State {
609 @Override
610 public void enter() {
611 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700612 }
613
614 @Override
615 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000616 // TODO: it is incorrect to stop the daemon without expunging all requests
617 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000618 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700619 }
620
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700621 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900622 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800623 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700624 return true;
625 }
626 return false;
627 }
628
Paul Hu508a0122023-09-11 15:31:33 +0800629 private ClientRequest storeLegacyRequestMap(int clientRequestId, int transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +0000630 ClientInfo clientInfo, int what, long startTimeMs) {
Paul Hu508a0122023-09-11 15:31:33 +0800631 final LegacyClientRequest request =
632 new LegacyClientRequest(transactionId, what, startTimeMs);
633 clientInfo.mClientRequests.put(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000634 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000635 // Remove the cleanup event because here comes a new request.
636 cancelStop();
Paul Hu508a0122023-09-11 15:31:33 +0800637 return request;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700638 }
639
Paul Hud44e1b72023-06-16 02:07:42 +0000640 private void storeAdvertiserRequestMap(int clientRequestId, int transactionId,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900641 ClientInfo clientInfo, @Nullable Network requestedNetwork) {
Paul Hu777ed052023-06-19 13:35:15 +0000642 clientInfo.mClientRequests.put(clientRequestId, new AdvertiserClientRequest(
Paul Hu812e9212023-06-20 06:24:53 +0000643 transactionId, requestedNetwork, mClock.elapsedRealtime()));
Paul Hud44e1b72023-06-16 02:07:42 +0000644 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900645 updateMulticastLock();
Paul Hu23fa2022023-01-13 22:57:24 +0800646 }
647
Paul Hud44e1b72023-06-16 02:07:42 +0000648 private void removeRequestMap(
649 int clientRequestId, int transactionId, ClientInfo clientInfo) {
650 final ClientRequest existing = clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900651 if (existing == null) return;
Paul Hud44e1b72023-06-16 02:07:42 +0000652 clientInfo.mClientRequests.remove(clientRequestId);
653 mTransactionIdToClientInfoMap.remove(transactionId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900654
655 if (existing instanceof LegacyClientRequest) {
656 maybeScheduleStop();
657 } else {
658 maybeStopMonitoringSocketsIfNoActiveRequest();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900659 updateMulticastLock();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900660 }
661 }
662
Paul Hu508a0122023-09-11 15:31:33 +0800663 private ClientRequest storeDiscoveryManagerRequestMap(int clientRequestId,
664 int transactionId, MdnsListener listener, ClientInfo clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900665 @Nullable Network requestedNetwork) {
Paul Hu508a0122023-09-11 15:31:33 +0800666 final DiscoveryManagerRequest request = new DiscoveryManagerRequest(transactionId,
667 listener, requestedNetwork, mClock.elapsedRealtime());
668 clientInfo.mClientRequests.put(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000669 mTransactionIdToClientInfoMap.put(transactionId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900670 updateMulticastLock();
Paul Hu508a0122023-09-11 15:31:33 +0800671 return request;
Paul Hu23fa2022023-01-13 22:57:24 +0800672 }
673
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900674 /**
675 * Truncate a service name to up to 63 UTF-8 bytes.
676 *
677 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
678 * names used in registerService follows historical behavior (see mdnsresponder
679 * handle_regservice_request).
680 */
681 @NonNull
682 private String truncateServiceName(@NonNull String originalName) {
Yuyang Huangde802c82023-05-02 17:14:22 +0900683 return MdnsUtils.truncateServiceName(originalName, MAX_LABEL_LENGTH);
Paul Hu23fa2022023-01-13 22:57:24 +0800684 }
685
Paul Hud44e1b72023-06-16 02:07:42 +0000686 private void stopDiscoveryManagerRequest(ClientRequest request, int clientRequestId,
687 int transactionId, ClientInfo clientInfo) {
Paul Hue4f5f252023-02-16 21:13:47 +0800688 clientInfo.unregisterMdnsListenerFromRequest(request);
Paul Hud44e1b72023-06-16 02:07:42 +0000689 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hue4f5f252023-02-16 21:13:47 +0800690 }
691
Paul Hu77c11182023-10-23 16:17:32 +0800692 private ClientInfo getClientInfoForReply(Message msg) {
693 final ListenerArgs args = (ListenerArgs) msg.obj;
694 return mClients.get(args.connector);
695 }
696
Kangping Dong5af24b62023-12-10 21:41:16 +0800697 /**
698 * Returns {@code false} if {@code subtypes} exceeds the maximum number limit or
699 * contains invalid subtype label.
700 */
701 private boolean checkSubtypeLabels(Set<String> subtypes) {
702 if (subtypes.size() > MAX_SUBTYPE_COUNT) {
703 mServiceLogs.e(
704 "Too many subtypes: " + subtypes.size() + " (max = "
705 + MAX_SUBTYPE_COUNT + ")");
706 return false;
707 }
708
709 for (String subtype : subtypes) {
710 if (!checkSubtypeLabel(subtype)) {
711 mServiceLogs.e("Subtype " + subtype + " is invalid");
712 return false;
713 }
714 }
715 return true;
716 }
717
718 private Set<String> dedupSubtypeLabels(Collection<String> subtypes) {
719 final Map<String, String> subtypeMap = new LinkedHashMap<>(subtypes.size());
720 for (String subtype : subtypes) {
721 subtypeMap.put(MdnsUtils.toDnsLowerCase(subtype), subtype);
722 }
723 return new ArraySet<>(subtypeMap.values());
724 }
725
Irfan Sheriff75006652012-04-17 23:15:29 -0700726 @Override
727 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900728 final ClientInfo clientInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000729 final int transactionId;
730 final int clientRequestId = msg.arg2;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900731 final ListenerArgs args;
Yuyang Huang33fa4d22023-02-14 22:59:37 +0900732 final OffloadEngineInfo offloadEngineInfo;
Irfan Sheriff75006652012-04-17 23:15:29 -0700733 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800734 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800735 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900736 args = (ListenerArgs) msg.obj;
737 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000738 // If the binder death notification for a INsdManagerCallback was received
739 // before any calls are received by NsdService, the clientInfo would be
740 // cleared and cause NPE. Add a null check here to prevent this corner case.
741 if (clientInfo == null) {
742 Log.e(TAG, "Unknown connector in discovery");
743 break;
744 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700745
746 if (requestLimitReached(clientInfo)) {
Paul Hu508a0122023-09-11 15:31:33 +0800747 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
748 NsdManager.FAILURE_MAX_LIMIT, true /* isLegacy */);
Irfan Sheriff75006652012-04-17 23:15:29 -0700749 break;
750 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700751
Paul Hu23fa2022023-01-13 22:57:24 +0800752 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000753 transactionId = getUniqueId();
Yuyang Huang170d42f2023-12-09 15:26:16 +0900754 final Pair<String, List<String>> typeAndSubtype =
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900755 parseTypeAndSubtype(info.getServiceType());
756 final String serviceType = typeAndSubtype == null
757 ? null : typeAndSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800758 if (clientInfo.mUseJavaBackend
759 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900760 || useDiscoveryManagerForType(serviceType)) {
Yuyang Huang170d42f2023-12-09 15:26:16 +0900761 if (serviceType == null || typeAndSubtype.second.size() > 1) {
Paul Hu508a0122023-09-11 15:31:33 +0800762 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
763 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Paul Hu23fa2022023-01-13 22:57:24 +0800764 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700765 }
Paul Hu23fa2022023-01-13 22:57:24 +0800766
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900767 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800768 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +0000769 final MdnsListener listener = new DiscoveryListener(clientRequestId,
770 transactionId, info, listenServiceType);
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900771 final MdnsSearchOptions.Builder optionsBuilder =
772 MdnsSearchOptions.newBuilder()
773 .setNetwork(info.getNetwork())
Yuyang Huangff963222023-06-01 18:42:42 +0900774 .setRemoveExpiredService(true)
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900775 .setIsPassiveMode(true);
Yuyang Huang170d42f2023-12-09 15:26:16 +0900776 if (!typeAndSubtype.second.isEmpty()) {
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900777 // The parsing ensures subtype starts with an underscore.
778 // MdnsSearchOptions expects the underscore to not be present.
Yuyang Huang170d42f2023-12-09 15:26:16 +0900779 optionsBuilder.addSubtype(
780 typeAndSubtype.second.get(0).substring(1));
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900781 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900782 mMdnsDiscoveryManager.registerListener(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900783 listenServiceType, listener, optionsBuilder.build());
Paul Hu508a0122023-09-11 15:31:33 +0800784 final ClientRequest request = storeDiscoveryManagerRequestMap(
785 clientRequestId, transactionId, listener, clientInfo,
786 info.getNetwork());
787 clientInfo.onDiscoverServicesStarted(clientRequestId, info, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000788 clientInfo.log("Register a DiscoveryListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +0000789 + " for service type:" + listenServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700790 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800791 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000792 if (discoverServices(transactionId, info)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800793 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +0000794 Log.d(TAG, "Discover " + msg.arg2 + " " + transactionId
Paul Hu23fa2022023-01-13 22:57:24 +0800795 + info.getServiceType());
796 }
Paul Hu508a0122023-09-11 15:31:33 +0800797 final ClientRequest request = storeLegacyRequestMap(clientRequestId,
798 transactionId, clientInfo, msg.what,
799 mClock.elapsedRealtime());
Paul Hu812e9212023-06-20 06:24:53 +0000800 clientInfo.onDiscoverServicesStarted(
Paul Hu508a0122023-09-11 15:31:33 +0800801 clientRequestId, info, request);
Paul Hu23fa2022023-01-13 22:57:24 +0800802 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000803 stopServiceDiscovery(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +0800804 clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
805 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Paul Hu23fa2022023-01-13 22:57:24 +0800806 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700807 }
808 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800809 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900810 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800811 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900812 args = (ListenerArgs) msg.obj;
813 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000814 // If the binder death notification for a INsdManagerCallback was received
815 // before any calls are received by NsdService, the clientInfo would be
816 // cleared and cause NPE. Add a null check here to prevent this corner case.
817 if (clientInfo == null) {
818 Log.e(TAG, "Unknown connector in stop discovery");
819 break;
820 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700821
Paul Hud44e1b72023-06-16 02:07:42 +0000822 final ClientRequest request =
823 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900824 if (request == null) {
825 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700826 break;
827 }
Paul Hud44e1b72023-06-16 02:07:42 +0000828 transactionId = request.mTransactionId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900829 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
830 // point, so this needs to check the type of the original request to
831 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900832 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +0000833 stopDiscoveryManagerRequest(
834 request, clientRequestId, transactionId, clientInfo);
Paul Hu812e9212023-06-20 06:24:53 +0000835 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +0000836 clientInfo.log("Unregister the DiscoveryListener " + transactionId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700837 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000838 removeRequestMap(clientRequestId, transactionId, clientInfo);
839 if (stopServiceDiscovery(transactionId)) {
Paul Hu812e9212023-06-20 06:24:53 +0000840 clientInfo.onStopDiscoverySucceeded(clientRequestId, request);
Paul Hu23fa2022023-01-13 22:57:24 +0800841 } else {
842 clientInfo.onStopDiscoveryFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000843 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Paul Hu23fa2022023-01-13 22:57:24 +0800844 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700845 }
846 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900847 }
848 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800849 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900850 args = (ListenerArgs) msg.obj;
851 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000852 // If the binder death notification for a INsdManagerCallback was received
853 // before any calls are received by NsdService, the clientInfo would be
854 // cleared and cause NPE. Add a null check here to prevent this corner case.
855 if (clientInfo == null) {
856 Log.e(TAG, "Unknown connector in registration");
857 break;
858 }
859
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700860 if (requestLimitReached(clientInfo)) {
Paul Hu508a0122023-09-11 15:31:33 +0800861 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
862 NsdManager.FAILURE_MAX_LIMIT, true /* isLegacy */);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700863 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700864 }
865
Paul Hud44e1b72023-06-16 02:07:42 +0000866 transactionId = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900867 final NsdServiceInfo serviceInfo = args.serviceInfo;
868 final String serviceType = serviceInfo.getServiceType();
Yuyang Huang170d42f2023-12-09 15:26:16 +0900869 final Pair<String, List<String>> typeSubtype = parseTypeAndSubtype(
870 serviceType);
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900871 final String registerServiceType = typeSubtype == null
872 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800873 if (clientInfo.mUseJavaBackend
874 || mDeps.isMdnsAdvertiserEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900875 || useAdvertiserForType(registerServiceType)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900876 if (registerServiceType == null) {
877 Log.e(TAG, "Invalid service type: " + serviceType);
Paul Hu508a0122023-09-11 15:31:33 +0800878 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
879 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900880 break;
881 }
882 serviceInfo.setServiceType(registerServiceType);
883 serviceInfo.setServiceName(truncateServiceName(
884 serviceInfo.getServiceName()));
885
Kangping Dong5af24b62023-12-10 21:41:16 +0800886 Set<String> subtypes = new ArraySet<>(serviceInfo.getSubtypes());
Yuyang Huang170d42f2023-12-09 15:26:16 +0900887 for (String subType: typeSubtype.second) {
888 if (!TextUtils.isEmpty(subType)) {
889 subtypes.add(subType);
890 }
Kangping Dong5af24b62023-12-10 21:41:16 +0800891 }
Kangping Dong5af24b62023-12-10 21:41:16 +0800892 subtypes = dedupSubtypeLabels(subtypes);
893
894 if (!checkSubtypeLabels(subtypes)) {
895 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
896 NsdManager.FAILURE_BAD_PARAMETERS, false /* isLegacy */);
897 break;
898 }
899
900 serviceInfo.setSubtypes(subtypes);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900901 maybeStartMonitoringSockets();
Yuyang Huange5cba9c2023-11-02 18:05:47 +0900902 mAdvertiser.addOrUpdateService(transactionId, serviceInfo,
Yuyang Huange5cba9c2023-11-02 18:05:47 +0900903 MdnsAdvertisingOptions.newBuilder().build());
Paul Hud44e1b72023-06-16 02:07:42 +0000904 storeAdvertiserRequestMap(clientRequestId, transactionId, clientInfo,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900905 serviceInfo.getNetwork());
Irfan Sheriff75006652012-04-17 23:15:29 -0700906 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900907 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +0000908 if (registerService(transactionId, serviceInfo)) {
909 if (DBG) {
910 Log.d(TAG, "Register " + clientRequestId
911 + " " + transactionId);
912 }
Paul Hua6bc4632023-06-26 01:18:29 +0000913 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
914 msg.what, mClock.elapsedRealtime());
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900915 // Return success after mDns reports success
916 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000917 unregisterService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +0800918 clientInfo.onRegisterServiceFailedImmediately(clientRequestId,
919 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900920 }
921
Irfan Sheriff75006652012-04-17 23:15:29 -0700922 }
923 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900924 }
925 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800926 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900927 args = (ListenerArgs) msg.obj;
928 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000929 // If the binder death notification for a INsdManagerCallback was received
930 // before any calls are received by NsdService, the clientInfo would be
931 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900932 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800933 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700934 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700935 }
Paul Hud44e1b72023-06-16 02:07:42 +0000936 final ClientRequest request =
937 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900938 if (request == null) {
939 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
940 break;
941 }
Paul Hud44e1b72023-06-16 02:07:42 +0000942 transactionId = request.mTransactionId;
943 removeRequestMap(clientRequestId, transactionId, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900944
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900945 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
946 // so this needs to check the type of the original request to unregister
947 // instead of looking at the flag value.
948 if (request instanceof AdvertiserClientRequest) {
Paul Hu043bcd42023-07-14 16:38:25 +0800949 final AdvertiserMetrics metrics =
950 mAdvertiser.getAdvertiserMetrics(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +0000951 mAdvertiser.removeService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +0800952 clientInfo.onUnregisterServiceSucceeded(
953 clientRequestId, request, metrics);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700954 } else {
Paul Hud44e1b72023-06-16 02:07:42 +0000955 if (unregisterService(transactionId)) {
Paul Hu508a0122023-09-11 15:31:33 +0800956 clientInfo.onUnregisterServiceSucceeded(clientRequestId, request,
Paul Hu043bcd42023-07-14 16:38:25 +0800957 new AdvertiserMetrics(NO_PACKET /* repliedRequestsCount */,
958 NO_PACKET /* sentPacketCount */,
959 0 /* conflictDuringProbingCount */,
960 0 /* conflictAfterProbingCount */));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900961 } else {
962 clientInfo.onUnregisterServiceFailed(
Paul Hud44e1b72023-06-16 02:07:42 +0000963 clientRequestId, NsdManager.FAILURE_INTERNAL_ERROR);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900964 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700965 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700966 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900967 }
Paul Hu75069ed2023-01-14 00:31:09 +0800968 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800969 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900970 args = (ListenerArgs) msg.obj;
971 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000972 // If the binder death notification for a INsdManagerCallback was received
973 // before any calls are received by NsdService, the clientInfo would be
974 // cleared and cause NPE. Add a null check here to prevent this corner case.
975 if (clientInfo == null) {
976 Log.e(TAG, "Unknown connector in resolution");
977 break;
978 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700979
Paul Hu75069ed2023-01-14 00:31:09 +0800980 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +0000981 transactionId = getUniqueId();
Yuyang Huang170d42f2023-12-09 15:26:16 +0900982 final Pair<String, List<String>> typeSubtype =
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900983 parseTypeAndSubtype(info.getServiceType());
984 final String serviceType = typeSubtype == null
985 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800986 if (clientInfo.mUseJavaBackend
987 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900988 || useDiscoveryManagerForType(serviceType)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800989 if (serviceType == null) {
Paul Hu508a0122023-09-11 15:31:33 +0800990 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
991 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +0800992 break;
993 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900994 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +0800995
996 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +0000997 final MdnsListener listener = new ResolutionListener(clientRequestId,
998 transactionId, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800999 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1000 .setNetwork(info.getNetwork())
1001 .setIsPassiveMode(true)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +09001002 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001003 .setRemoveExpiredService(true)
Paul Hu75069ed2023-01-14 00:31:09 +08001004 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001005 mMdnsDiscoveryManager.registerListener(
1006 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001007 storeDiscoveryManagerRequestMap(clientRequestId, transactionId,
1008 listener, clientInfo, info.getNetwork());
1009 clientInfo.log("Register a ResolutionListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001010 + " for service type:" + resolveServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -07001011 } else {
Paul Hu75069ed2023-01-14 00:31:09 +08001012 if (clientInfo.mResolvedService != null) {
Paul Hu508a0122023-09-11 15:31:33 +08001013 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
1014 NsdManager.FAILURE_ALREADY_ACTIVE, true /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +08001015 break;
1016 }
1017
1018 maybeStartDaemon();
Paul Hud44e1b72023-06-16 02:07:42 +00001019 if (resolveService(transactionId, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +08001020 clientInfo.mResolvedService = new NsdServiceInfo();
Paul Hua6bc4632023-06-26 01:18:29 +00001021 storeLegacyRequestMap(clientRequestId, transactionId, clientInfo,
1022 msg.what, mClock.elapsedRealtime());
Paul Hu75069ed2023-01-14 00:31:09 +08001023 } else {
Paul Hu508a0122023-09-11 15:31:33 +08001024 clientInfo.onResolveServiceFailedImmediately(clientRequestId,
1025 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */);
Paul Hu75069ed2023-01-14 00:31:09 +08001026 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001027 }
1028 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001029 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001030 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +00001031 if (DBG) Log.d(TAG, "Stop service resolution");
1032 args = (ListenerArgs) msg.obj;
1033 clientInfo = mClients.get(args.connector);
1034 // If the binder death notification for a INsdManagerCallback was received
1035 // before any calls are received by NsdService, the clientInfo would be
1036 // cleared and cause NPE. Add a null check here to prevent this corner case.
1037 if (clientInfo == null) {
1038 Log.e(TAG, "Unknown connector in stop resolution");
1039 break;
1040 }
1041
Paul Hud44e1b72023-06-16 02:07:42 +00001042 final ClientRequest request =
1043 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001044 if (request == null) {
1045 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
1046 break;
1047 }
Paul Hud44e1b72023-06-16 02:07:42 +00001048 transactionId = request.mTransactionId;
Paul Hue4f5f252023-02-16 21:13:47 +08001049 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
1050 // point, so this needs to check the type of the original request to
1051 // unregister instead of looking at the flag value.
1052 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001053 stopDiscoveryManagerRequest(
1054 request, clientRequestId, transactionId, clientInfo);
Paul Hu60149052023-07-31 14:26:08 +08001055 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001056 clientInfo.log("Unregister the ResolutionListener " + transactionId);
Paul Hub58deb72022-12-26 09:24:42 +00001057 } else {
Paul Hud44e1b72023-06-16 02:07:42 +00001058 removeRequestMap(clientRequestId, transactionId, clientInfo);
1059 if (stopResolveService(transactionId)) {
Paul Hu60149052023-07-31 14:26:08 +08001060 clientInfo.onStopResolutionSucceeded(clientRequestId, request);
Paul Hue4f5f252023-02-16 21:13:47 +08001061 } else {
1062 clientInfo.onStopResolutionFailed(
Paul Hud44e1b72023-06-16 02:07:42 +00001063 clientRequestId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hue4f5f252023-02-16 21:13:47 +08001064 }
1065 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +00001066 }
Paul Hub58deb72022-12-26 09:24:42 +00001067 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001068 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001069 case NsdManager.REGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001070 if (DBG) Log.d(TAG, "Register a service callback");
1071 args = (ListenerArgs) msg.obj;
1072 clientInfo = mClients.get(args.connector);
1073 // If the binder death notification for a INsdManagerCallback was received
1074 // before any calls are received by NsdService, the clientInfo would be
1075 // cleared and cause NPE. Add a null check here to prevent this corner case.
1076 if (clientInfo == null) {
1077 Log.e(TAG, "Unknown connector in callback registration");
1078 break;
1079 }
1080
Paul Hu30bd70d2023-02-07 13:20:56 +00001081 final NsdServiceInfo info = args.serviceInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001082 transactionId = getUniqueId();
Yuyang Huang170d42f2023-12-09 15:26:16 +09001083 final Pair<String, List<String>> typeAndSubtype =
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001084 parseTypeAndSubtype(info.getServiceType());
1085 final String serviceType = typeAndSubtype == null
1086 ? null : typeAndSubtype.first;
Paul Hu30bd70d2023-02-07 13:20:56 +00001087 if (serviceType == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001088 clientInfo.onServiceInfoCallbackRegistrationFailed(clientRequestId,
Paul Hu30bd70d2023-02-07 13:20:56 +00001089 NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +00001090 break;
1091 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001092 final String resolveServiceType = serviceType + ".local";
Paul Hu18aeccc2022-12-27 08:48:48 +00001093
Paul Hu30bd70d2023-02-07 13:20:56 +00001094 maybeStartMonitoringSockets();
Paul Hud44e1b72023-06-16 02:07:42 +00001095 final MdnsListener listener = new ServiceInfoListener(clientRequestId,
1096 transactionId, info, resolveServiceType);
Paul Hu30bd70d2023-02-07 13:20:56 +00001097 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1098 .setNetwork(info.getNetwork())
1099 .setIsPassiveMode(true)
1100 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001101 .setRemoveExpiredService(true)
Paul Hu30bd70d2023-02-07 13:20:56 +00001102 .build();
1103 mMdnsDiscoveryManager.registerListener(
1104 resolveServiceType, listener, options);
Paul Hud44e1b72023-06-16 02:07:42 +00001105 storeDiscoveryManagerRequestMap(clientRequestId, transactionId, listener,
1106 clientInfo, info.getNetwork());
Paul Huddce5912023-08-01 10:26:49 +08001107 clientInfo.onServiceInfoCallbackRegistered(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00001108 clientInfo.log("Register a ServiceInfoListener " + transactionId
Paul Hub2e67d32023-04-18 05:50:14 +00001109 + " for service type:" + resolveServiceType);
Paul Hu18aeccc2022-12-27 08:48:48 +00001110 break;
Paul Hu30bd70d2023-02-07 13:20:56 +00001111 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001112 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001113 if (DBG) Log.d(TAG, "Unregister a service callback");
1114 args = (ListenerArgs) msg.obj;
1115 clientInfo = mClients.get(args.connector);
1116 // If the binder death notification for a INsdManagerCallback was received
1117 // before any calls are received by NsdService, the clientInfo would be
1118 // cleared and cause NPE. Add a null check here to prevent this corner case.
1119 if (clientInfo == null) {
1120 Log.e(TAG, "Unknown connector in callback unregistration");
1121 break;
1122 }
1123
Paul Hud44e1b72023-06-16 02:07:42 +00001124 final ClientRequest request =
1125 clientInfo.mClientRequests.get(clientRequestId);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001126 if (request == null) {
Paul Hu30bd70d2023-02-07 13:20:56 +00001127 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE_CALLBACK");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001128 break;
1129 }
Paul Hud44e1b72023-06-16 02:07:42 +00001130 transactionId = request.mTransactionId;
Paul Hu30bd70d2023-02-07 13:20:56 +00001131 if (request instanceof DiscoveryManagerRequest) {
Paul Hud44e1b72023-06-16 02:07:42 +00001132 stopDiscoveryManagerRequest(
1133 request, clientRequestId, transactionId, clientInfo);
Paul Huddce5912023-08-01 10:26:49 +08001134 clientInfo.onServiceInfoCallbackUnregistered(clientRequestId, request);
Paul Hud44e1b72023-06-16 02:07:42 +00001135 clientInfo.log("Unregister the ServiceInfoListener " + transactionId);
Paul Hu18aeccc2022-12-27 08:48:48 +00001136 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001137 loge("Unregister failed with non-DiscoveryManagerRequest.");
Paul Hu18aeccc2022-12-27 08:48:48 +00001138 }
Paul Hu18aeccc2022-12-27 08:48:48 +00001139 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001140 }
paulhu2b9ed952022-02-10 21:58:32 +08001141 case MDNS_SERVICE_EVENT:
1142 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +09001143 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001144 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001145 break;
Paul Hu019621e2023-01-13 23:26:49 +08001146 case MDNS_DISCOVERY_MANAGER_EVENT:
1147 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
1148 return NOT_HANDLED;
1149 }
1150 break;
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001151 case NsdManager.REGISTER_OFFLOAD_ENGINE:
1152 offloadEngineInfo = (OffloadEngineInfo) msg.obj;
1153 // TODO: Limits the number of registrations created by a given class.
1154 mOffloadEngines.register(offloadEngineInfo.mOffloadEngine,
1155 offloadEngineInfo);
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001156 sendAllOffloadServiceInfos(offloadEngineInfo);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001157 break;
1158 case NsdManager.UNREGISTER_OFFLOAD_ENGINE:
1159 mOffloadEngines.unregister((IOffloadEngine) msg.obj);
1160 break;
Paul Hu77c11182023-10-23 16:17:32 +08001161 case NsdManager.REGISTER_CLIENT:
1162 final ConnectorArgs arg = (ConnectorArgs) msg.obj;
1163 final INsdManagerCallback cb = arg.callback;
1164 try {
1165 cb.asBinder().linkToDeath(arg.connector, 0);
1166 final String tag = "Client" + arg.uid + "-" + mClientNumberId++;
1167 final NetworkNsdReportedMetrics metrics =
1168 mDeps.makeNetworkNsdReportedMetrics(
1169 (int) mClock.elapsedRealtime());
1170 clientInfo = new ClientInfo(cb, arg.uid, arg.useJavaBackend,
1171 mServiceLogs.forSubComponent(tag), metrics);
1172 mClients.put(arg.connector, clientInfo);
1173 } catch (RemoteException e) {
1174 Log.w(TAG, "Client request id " + clientRequestId
1175 + " has already died");
1176 }
1177 break;
1178 case NsdManager.UNREGISTER_CLIENT:
1179 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
1180 clientInfo = mClients.remove(connector);
1181 if (clientInfo != null) {
1182 clientInfo.expungeAllRequests();
1183 if (clientInfo.isPreSClient()) {
1184 mLegacyClientCount -= 1;
1185 }
1186 }
1187 maybeStopMonitoringSocketsIfNoActiveRequest();
1188 maybeScheduleStop();
1189 break;
1190 case NsdManager.DAEMON_CLEANUP:
1191 maybeStopDaemon();
1192 break;
1193 // This event should be only sent by the legacy (target SDK < S) clients.
1194 // Mark the sending client as legacy.
1195 case NsdManager.DAEMON_STARTUP:
1196 clientInfo = getClientInfoForReply(msg);
1197 if (clientInfo != null) {
1198 cancelStop();
1199 clientInfo.setPreSClient();
1200 mLegacyClientCount += 1;
1201 maybeStartDaemon();
1202 }
1203 break;
Irfan Sheriff75006652012-04-17 23:15:29 -07001204 default:
Paul Hu77c11182023-10-23 16:17:32 +08001205 Log.wtf(TAG, "Unhandled " + msg);
Hugo Benichif0c84092017-04-05 14:43:29 +09001206 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001207 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001208 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001209 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001210
Paul Hud44e1b72023-06-16 02:07:42 +00001211 private boolean handleMDnsServiceEvent(int code, int transactionId, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001212 NsdServiceInfo servInfo;
Paul Hud44e1b72023-06-16 02:07:42 +00001213 ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001214 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00001215 Log.e(TAG, String.format(
1216 "transactionId %d for %d has no client mapping", transactionId, code));
Hugo Benichif0c84092017-04-05 14:43:29 +09001217 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001218 }
1219
1220 /* This goes in response as msg.arg2 */
Paul Hud44e1b72023-06-16 02:07:42 +00001221 int clientRequestId = clientInfo.getClientRequestId(transactionId);
1222 if (clientRequestId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -07001223 // This can happen because of race conditions. For example,
1224 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
1225 // and we may get in this situation.
Paul Hud44e1b72023-06-16 02:07:42 +00001226 Log.d(TAG, String.format("%d for transactionId %d that is no longer active",
1227 code, transactionId));
Hugo Benichif0c84092017-04-05 14:43:29 +09001228 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001229 }
Paul Hu812e9212023-06-20 06:24:53 +00001230 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1231 if (request == null) {
1232 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1233 return false;
1234 }
Hugo Benichi32be63d2017-04-05 14:06:11 +09001235 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00001236 Log.d(TAG, String.format(
1237 "MDns service event code:%d transactionId=%d", code, transactionId));
Hugo Benichi32be63d2017-04-05 14:06:11 +09001238 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001239 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +08001240 case IMDnsEventListener.SERVICE_FOUND: {
1241 final DiscoveryInfo info = (DiscoveryInfo) obj;
1242 final String name = info.serviceName;
1243 final String type = info.registrationType;
1244 servInfo = new NsdServiceInfo(name, type);
1245 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001246 if (foundNetId == 0L) {
1247 // Ignore services that do not have a Network: they are not usable
1248 // by apps, as they would need privileged permissions to use
1249 // interfaces that do not have an associated Network.
1250 break;
1251 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +09001252 if (foundNetId == INetd.DUMMY_NET_ID) {
1253 // Ignore services on the dummy0 interface: they are only seen when
1254 // discovering locally advertised services, and are not reachable
1255 // through that interface.
1256 break;
1257 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001258 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001259
1260 clientInfo.onServiceFound(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001261 break;
paulhu2b9ed952022-02-10 21:58:32 +08001262 }
1263 case IMDnsEventListener.SERVICE_LOST: {
1264 final DiscoveryInfo info = (DiscoveryInfo) obj;
1265 final String name = info.serviceName;
1266 final String type = info.registrationType;
1267 final int lostNetId = info.netId;
1268 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001269 // The network could be set to null (netId 0) if it was torn down when the
1270 // service is lost
1271 // TODO: avoid returning null in that case, possibly by remembering
1272 // found services on the same interface index and their network at the time
1273 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Paul Hu812e9212023-06-20 06:24:53 +00001274 clientInfo.onServiceLost(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001275 break;
paulhu2b9ed952022-02-10 21:58:32 +08001276 }
1277 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Paul Hu812e9212023-06-20 06:24:53 +00001278 clientInfo.onDiscoverServicesFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001279 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1280 transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001281 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001282 break;
paulhu2b9ed952022-02-10 21:58:32 +08001283 case IMDnsEventListener.SERVICE_REGISTERED: {
1284 final RegistrationInfo info = (RegistrationInfo) obj;
1285 final String name = info.serviceName;
1286 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Paul Hu508a0122023-09-11 15:31:33 +08001287 clientInfo.onRegisterServiceSucceeded(clientRequestId, servInfo, request);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001288 break;
paulhu2b9ed952022-02-10 21:58:32 +08001289 }
1290 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Paul Hu777ed052023-06-19 13:35:15 +00001291 clientInfo.onRegisterServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001292 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1293 transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00001294 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001295 break;
paulhu2b9ed952022-02-10 21:58:32 +08001296 case IMDnsEventListener.SERVICE_RESOLVED: {
1297 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001298 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +08001299 final String fullName = info.serviceFullName;
1300 while (index < fullName.length() && fullName.charAt(index) != '.') {
1301 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001302 ++index;
1303 }
1304 ++index;
1305 }
paulhu2b9ed952022-02-10 21:58:32 +08001306 if (index >= fullName.length()) {
1307 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001308 break;
1309 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001310
paulhube186602022-04-12 07:18:23 +00001311 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001312 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001313 String type = rest.replace(".local.", "");
1314
Paul Hu30bd70d2023-02-07 13:20:56 +00001315 final NsdServiceInfo serviceInfo = clientInfo.mResolvedService;
Paul Hu18aeccc2022-12-27 08:48:48 +00001316 serviceInfo.setServiceName(name);
1317 serviceInfo.setServiceType(type);
1318 serviceInfo.setPort(info.port);
1319 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001320 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001321
Paul Hud44e1b72023-06-16 02:07:42 +00001322 stopResolveService(transactionId);
1323 removeRequestMap(clientRequestId, transactionId, clientInfo);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001324
Paul Hud44e1b72023-06-16 02:07:42 +00001325 final int transactionId2 = getUniqueId();
1326 if (getAddrInfo(transactionId2, info.hostname, info.interfaceIdx)) {
1327 storeLegacyRequestMap(clientRequestId, transactionId2, clientInfo,
Paul Hua6bc4632023-06-26 01:18:29 +00001328 NsdManager.RESOLVE_SERVICE, request.mStartTimeMs);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001329 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001330 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001331 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1332 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001333 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001334 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001335 }
1336 break;
paulhu2b9ed952022-02-10 21:58:32 +08001337 }
1338 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001339 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001340 stopResolveService(transactionId);
1341 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001342 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001343 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1344 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001345 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001346 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001347 break;
paulhu2b9ed952022-02-10 21:58:32 +08001348 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001349 /* NNN resolveId errorCode */
Paul Hud44e1b72023-06-16 02:07:42 +00001350 stopGetAddrInfo(transactionId);
1351 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hua6bc4632023-06-26 01:18:29 +00001352 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001353 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1354 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001355 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu30bd70d2023-02-07 13:20:56 +00001356 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001357 break;
paulhu2b9ed952022-02-10 21:58:32 +08001358 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001359 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001360 final GetAddressInfo info = (GetAddressInfo) obj;
1361 final String address = info.address;
1362 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001363 InetAddress serviceHost = null;
1364 try {
paulhu2b9ed952022-02-10 21:58:32 +08001365 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001366 } catch (UnknownHostException e) {
1367 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1368 }
1369
1370 // If the resolved service is on an interface without a network, consider it
1371 // as a failure: it would not be usable by apps as they would need
1372 // privileged permissions.
Paul Hu30bd70d2023-02-07 13:20:56 +00001373 if (netId != NETID_UNSET && serviceHost != null) {
1374 clientInfo.mResolvedService.setHost(serviceHost);
1375 setServiceNetworkForCallback(clientInfo.mResolvedService,
1376 netId, info.interfaceIdx);
1377 clientInfo.onResolveServiceSucceeded(
Paul Hua6bc4632023-06-26 01:18:29 +00001378 clientRequestId, clientInfo.mResolvedService, request);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001379 } else {
Paul Hua6bc4632023-06-26 01:18:29 +00001380 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001381 NsdManager.FAILURE_INTERNAL_ERROR, true /* isLegacy */,
1382 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001383 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001384 }
Paul Hud44e1b72023-06-16 02:07:42 +00001385 stopGetAddrInfo(transactionId);
1386 removeRequestMap(clientRequestId, transactionId, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001387 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001388 break;
paulhu2b9ed952022-02-10 21:58:32 +08001389 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001390 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001391 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001392 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001393 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001394 }
Paul Hu019621e2023-01-13 23:26:49 +08001395
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001396 @Nullable
1397 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(
1398 final MdnsEvent event, int code) {
Paul Hu019621e2023-01-13 23:26:49 +08001399 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001400 final String[] typeArray = serviceInfo.getServiceType();
1401 final String joinedType;
1402 if (typeArray.length == 0
1403 || !typeArray[typeArray.length - 1].equals(LOCAL_DOMAIN_NAME)) {
1404 Log.wtf(TAG, "MdnsServiceInfo type does not end in .local: "
1405 + Arrays.toString(typeArray));
1406 return null;
1407 } else {
1408 joinedType = TextUtils.join(".",
1409 Arrays.copyOfRange(typeArray, 0, typeArray.length - 1));
1410 }
1411 final String serviceType;
1412 switch (code) {
1413 case NsdManager.SERVICE_FOUND:
1414 case NsdManager.SERVICE_LOST:
1415 // For consistency with historical behavior, discovered service types have
1416 // a dot at the end.
1417 serviceType = joinedType + ".";
1418 break;
1419 case RESOLVE_SERVICE_SUCCEEDED:
1420 // For consistency with historical behavior, resolved service types have
1421 // a dot at the beginning.
1422 serviceType = "." + joinedType;
1423 break;
1424 default:
1425 serviceType = joinedType;
1426 break;
1427 }
Paul Hu019621e2023-01-13 23:26:49 +08001428 final String serviceName = serviceInfo.getServiceInstanceName();
1429 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1430 final Network network = serviceInfo.getNetwork();
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001431 // In MdnsDiscoveryManagerEvent, the Network can be null which means it is a
1432 // network for Tethering interface. In other words, the network == null means the
1433 // network has netId = INetd.LOCAL_NET_ID.
Paul Hu019621e2023-01-13 23:26:49 +08001434 setServiceNetworkForCallback(
1435 servInfo,
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001436 network == null ? INetd.LOCAL_NET_ID : network.netId,
Paul Hu019621e2023-01-13 23:26:49 +08001437 serviceInfo.getInterfaceIndex());
Kangping Dong5af24b62023-12-10 21:41:16 +08001438 servInfo.setSubtypes(dedupSubtypeLabels(serviceInfo.getSubtypes()));
Paul Hu019621e2023-01-13 23:26:49 +08001439 return servInfo;
1440 }
1441
1442 private boolean handleMdnsDiscoveryManagerEvent(
1443 int transactionId, int code, Object obj) {
Paul Hud44e1b72023-06-16 02:07:42 +00001444 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Paul Hu019621e2023-01-13 23:26:49 +08001445 if (clientInfo == null) {
1446 Log.e(TAG, String.format(
1447 "id %d for %d has no client mapping", transactionId, code));
1448 return false;
1449 }
1450
1451 final MdnsEvent event = (MdnsEvent) obj;
Paul Hud44e1b72023-06-16 02:07:42 +00001452 final int clientRequestId = event.mClientRequestId;
Paul Hubad6fe92023-07-24 21:25:22 +08001453 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
1454 if (request == null) {
1455 Log.e(TAG, "Unknown client request. clientRequestId=" + clientRequestId);
1456 return false;
1457 }
1458
1459 // Deal with the discovery sent callback
1460 if (code == DISCOVERY_QUERY_SENT_CALLBACK) {
1461 request.onQuerySent();
1462 return true;
1463 }
1464
1465 // Deal with other callbacks.
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001466 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event, code);
1467 // Errors are already logged if null
1468 if (info == null) return false;
Paul Hu83ec7f42023-06-07 18:04:09 +08001469 mServiceLogs.log(String.format(
1470 "MdnsDiscoveryManager event code=%s transactionId=%d",
1471 NsdManager.nameOf(code), transactionId));
Paul Hu019621e2023-01-13 23:26:49 +08001472 switch (code) {
1473 case NsdManager.SERVICE_FOUND:
Paul Hu812e9212023-06-20 06:24:53 +00001474 clientInfo.onServiceFound(clientRequestId, info, request);
Paul Hu319751a2023-01-13 23:56:34 +08001475 break;
1476 case NsdManager.SERVICE_LOST:
Paul Hu812e9212023-06-20 06:24:53 +00001477 clientInfo.onServiceLost(clientRequestId, info, request);
Paul Hu019621e2023-01-13 23:26:49 +08001478 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001479 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
1480 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Paul Hu75069ed2023-01-14 00:31:09 +08001481 info.setPort(serviceInfo.getPort());
1482
1483 Map<String, String> attrs = serviceInfo.getAttributes();
1484 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1485 final String key = kv.getKey();
1486 try {
1487 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1488 } catch (IllegalArgumentException e) {
1489 Log.e(TAG, "Invalid attribute", e);
1490 }
1491 }
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001492 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu2b865912023-03-06 14:27:53 +08001493 if (addresses.size() != 0) {
1494 info.setHostAddresses(addresses);
Paul Hua6bc4632023-06-26 01:18:29 +00001495 request.setServiceFromCache(event.mIsServiceFromCache);
1496 clientInfo.onResolveServiceSucceeded(clientRequestId, info, request);
Paul Hu2b865912023-03-06 14:27:53 +08001497 } else {
1498 // No address. Notify resolution failure.
Paul Hua6bc4632023-06-26 01:18:29 +00001499 clientInfo.onResolveServiceFailed(clientRequestId,
Paul Hu508a0122023-09-11 15:31:33 +08001500 NsdManager.FAILURE_INTERNAL_ERROR, false /* isLegacy */,
1501 transactionId,
Paul Hua6bc4632023-06-26 01:18:29 +00001502 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hu75069ed2023-01-14 00:31:09 +08001503 }
1504
1505 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001506 if (!(request instanceof DiscoveryManagerRequest)) {
1507 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1508 break;
1509 }
Paul Hud44e1b72023-06-16 02:07:42 +00001510 stopDiscoveryManagerRequest(
1511 request, clientRequestId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001512 break;
1513 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001514 case NsdManager.SERVICE_UPDATED: {
1515 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1516 info.setPort(serviceInfo.getPort());
1517
1518 Map<String, String> attrs = serviceInfo.getAttributes();
1519 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1520 final String key = kv.getKey();
1521 try {
1522 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1523 } catch (IllegalArgumentException e) {
1524 Log.e(TAG, "Invalid attribute", e);
1525 }
1526 }
1527
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001528 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001529 info.setHostAddresses(addresses);
Paul Huddce5912023-08-01 10:26:49 +08001530 clientInfo.onServiceUpdated(clientRequestId, info, request);
1531 // Set the ServiceFromCache flag only if the service is actually being
1532 // retrieved from the cache. This flag should not be overridden by later
1533 // service updates, which may not be cached.
1534 if (event.mIsServiceFromCache) {
1535 request.setServiceFromCache(true);
1536 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001537 break;
1538 }
1539 case NsdManager.SERVICE_UPDATED_LOST:
Paul Huddce5912023-08-01 10:26:49 +08001540 clientInfo.onServiceUpdatedLost(clientRequestId, request);
Paul Hu30bd70d2023-02-07 13:20:56 +00001541 break;
Paul Hu019621e2023-01-13 23:26:49 +08001542 default:
1543 return false;
1544 }
1545 return true;
1546 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001547 }
1548 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001549
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001550 @NonNull
1551 private static List<InetAddress> getInetAddresses(@NonNull MdnsServiceInfo serviceInfo) {
1552 final List<String> v4Addrs = serviceInfo.getIpv4Addresses();
1553 final List<String> v6Addrs = serviceInfo.getIpv6Addresses();
1554 final List<InetAddress> addresses = new ArrayList<>(v4Addrs.size() + v6Addrs.size());
1555 for (String ipv4Address : v4Addrs) {
1556 try {
1557 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1558 } catch (IllegalArgumentException e) {
1559 Log.wtf(TAG, "Invalid ipv4 address", e);
1560 }
1561 }
1562 for (String ipv6Address : v6Addrs) {
1563 try {
Yuyang Huanga6a6ff92023-04-24 13:33:34 +09001564 final Inet6Address addr = (Inet6Address) InetAddresses.parseNumericAddress(
1565 ipv6Address);
1566 addresses.add(InetAddressUtils.withScopeId(addr, serviceInfo.getInterfaceIndex()));
1567 } catch (IllegalArgumentException e) {
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001568 Log.wtf(TAG, "Invalid ipv6 address", e);
1569 }
1570 }
1571 return addresses;
1572 }
1573
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001574 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1575 switch (netId) {
1576 case NETID_UNSET:
1577 info.setNetwork(null);
1578 break;
1579 case INetd.LOCAL_NET_ID:
1580 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1581 // visible / usable for apps, so do not return it. Store the interface
1582 // index instead, so at least if the client tries to resolve the service
1583 // with that NsdServiceInfo, it will be done on the same interface.
1584 // If they recreate the NsdServiceInfo themselves, resolution would be
1585 // done on all interfaces as before T, which should also work.
1586 info.setNetwork(null);
1587 info.setInterfaceIndex(ifaceIdx);
1588 break;
1589 default:
1590 info.setNetwork(new Network(netId));
1591 }
1592 }
1593
paulhube186602022-04-12 07:18:23 +00001594 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1595 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1596 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1597 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1598 private String unescape(String s) {
1599 StringBuilder sb = new StringBuilder(s.length());
1600 for (int i = 0; i < s.length(); ++i) {
1601 char c = s.charAt(i);
1602 if (c == '\\') {
1603 if (++i >= s.length()) {
1604 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1605 break;
1606 }
1607 c = s.charAt(i);
1608 if (c != '.' && c != '\\') {
1609 if (i + 2 >= s.length()) {
1610 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1611 break;
1612 }
1613 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1614 + (s.charAt(i + 2) - '0'));
1615 i += 2;
1616 }
1617 }
1618 sb.append(c);
1619 }
1620 return sb.toString();
1621 }
1622
Paul Hu7445e3d2023-03-03 15:14:00 +08001623 /**
1624 * Check the given service type is valid and construct it to a service type
1625 * which can use for discovery / resolution service.
1626 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001627 * <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 +08001628 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1629 * underscore; they are alphanumerical characters or dashes or underscore, except the
1630 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1631 *
Yuyang Huang170d42f2023-12-09 15:26:16 +09001632 * <p>The subtypes may also be specified with a comma after the service type, for example
1633 * _type._tcp,_subtype1,_subtype2
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001634 *
Paul Hu7445e3d2023-03-03 15:14:00 +08001635 * @param serviceType the request service type for discovery / resolution service
1636 * @return constructed service type or null if the given service type is invalid.
1637 */
1638 @Nullable
Yuyang Huang170d42f2023-12-09 15:26:16 +09001639 public static Pair<String, List<String>> parseTypeAndSubtype(String serviceType) {
Paul Hu7445e3d2023-03-03 15:14:00 +08001640 if (TextUtils.isEmpty(serviceType)) return null;
1641
Yuyang Huang170d42f2023-12-09 15:26:16 +09001642 final String regexString =
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001643 // Optional leading subtype (_subtype._type._tcp)
1644 // (?: xxx) is a non-capturing parenthesis, don't capture the dot
Kangping Dong5af24b62023-12-10 21:41:16 +08001645 "^(?:(" + TYPE_SUBTYPE_LABEL_REGEX + ")\\.)?"
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001646 // Actual type (_type._tcp.local)
Kangping Dong5af24b62023-12-10 21:41:16 +08001647 + "(" + TYPE_SUBTYPE_LABEL_REGEX + "\\._(?:tcp|udp))"
Paul Hu7445e3d2023-03-03 15:14:00 +08001648 // Drop '.' at the end of service type that is compatible with old backend.
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001649 // e.g. allow "_type._tcp.local."
1650 + "\\.?"
Yuyang Huang170d42f2023-12-09 15:26:16 +09001651 // Optional subtype after comma, for "_type._tcp,_subtype1,_subtype2" format
1652 + "((?:," + TYPE_SUBTYPE_LABEL_REGEX + ")*)"
1653 + "$";
1654 final Pattern serviceTypePattern = Pattern.compile(regexString);
Paul Hu7445e3d2023-03-03 15:14:00 +08001655 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1656 if (!matcher.matches()) return null;
Yuyang Huang170d42f2023-12-09 15:26:16 +09001657 final String queryType = matcher.group(2);
1658 // Use the subtype at the beginning
1659 if (matcher.group(1) != null) {
1660 return new Pair<>(queryType, List.of(matcher.group(1)));
1661 }
1662 // Use the subtypes at the end
1663 final String subTypesStr = matcher.group(3);
1664 if (subTypesStr != null && !subTypesStr.isEmpty()) {
1665 final String[] subTypes = subTypesStr.substring(1).split(",");
1666 return new Pair<>(queryType, List.of(subTypes));
1667 }
1668
1669 return new Pair<>(queryType, Collections.emptyList());
Paul Hu7445e3d2023-03-03 15:14:00 +08001670 }
1671
Kangping Dong5af24b62023-12-10 21:41:16 +08001672 /** Returns {@code true} if {@code subtype} is a valid DNS-SD subtype label. */
1673 private static boolean checkSubtypeLabel(String subtype) {
1674 return Pattern.compile("^" + TYPE_SUBTYPE_LABEL_REGEX + "$").matcher(subtype).matches();
1675 }
1676
Hugo Benichi803a2f02017-04-24 11:35:06 +09001677 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001678 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001679 this(ctx, handler, cleanupDelayMs, new Dependencies());
1680 }
1681
1682 @VisibleForTesting
1683 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001684 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001685 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001686 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001687 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001688 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1689 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001690 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001691
Paul Hu14667de2023-04-17 22:42:47 +08001692 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper(),
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001693 LOGGER.forSubComponent("MdnsSocketProvider"), new SocketRequestMonitor());
Yuyang Huang700778b2023-03-08 16:17:05 +09001694 // Netlink monitor starts on boot, and intentionally never stopped, to ensure that all
Yuyang Huangfca402a2023-05-24 14:45:59 +09001695 // address events are received. When the netlink monitor starts, any IP addresses already
1696 // on the interfaces will not be seen. In practice, the network will not connect at boot
1697 // time As a result, all the netlink message should be observed if the netlink monitor
1698 // starts here.
Yuyang Huang700778b2023-03-08 16:17:05 +09001699 handler.post(mMdnsSocketProvider::startNetLinkMonitor);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001700
1701 // NsdService is started after ActivityManager (startOtherServices in SystemServer, vs.
1702 // startBootstrapServices).
1703 mRunningAppActiveImportanceCutoff = mDeps.getDeviceConfigInt(
1704 MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF,
1705 DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF);
1706 final ActivityManager am = ctx.getSystemService(ActivityManager.class);
1707 am.addOnUidImportanceListener(new UidImportanceListener(handler),
1708 mRunningAppActiveImportanceCutoff);
1709
Paul Huf3fe3332023-10-16 17:13:25 +08001710 final MdnsFeatureFlags flags = new MdnsFeatureFlags.Builder()
1711 .setIsMdnsOffloadFeatureEnabled(mDeps.isTetheringFeatureNotChickenedOut(
1712 mContext, MdnsFeatureFlags.NSD_FORCE_DISABLE_MDNS_OFFLOAD))
1713 .setIncludeInetAddressRecordsInProbing(mDeps.isFeatureEnabled(
1714 mContext, MdnsFeatureFlags.INCLUDE_INET_ADDRESS_RECORDS_IN_PROBING))
Paul Hu596a5002023-10-18 17:07:31 +08001715 .setIsExpiredServicesRemovalEnabled(mDeps.isFeatureEnabled(
1716 mContext, MdnsFeatureFlags.NSD_EXPIRED_SERVICES_REMOVAL))
Paul Hufd357ef2023-11-01 16:32:45 +08001717 .setIsLabelCountLimitEnabled(mDeps.isTetheringFeatureNotChickenedOut(
1718 mContext, MdnsFeatureFlags.NSD_LIMIT_LABEL_COUNT))
Paul Huf3fe3332023-10-16 17:13:25 +08001719 .build();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001720 mMdnsSocketClient =
Yuyang Huang7ddf2932023-08-01 18:16:30 +09001721 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider,
Paul Hufd357ef2023-11-01 16:32:45 +08001722 LOGGER.forSubComponent("MdnsMultinetworkSocketClient"), flags);
Paul Hu14667de2023-04-17 22:42:47 +08001723 mMdnsDiscoveryManager = deps.makeMdnsDiscoveryManager(new ExecutorProvider(),
Paul Huf3fe3332023-10-16 17:13:25 +08001724 mMdnsSocketClient, LOGGER.forSubComponent("MdnsDiscoveryManager"), flags);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001725 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1726 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
Yuyang Huangb96a0712023-09-07 15:13:15 +09001727 new AdvertiserCallback(), LOGGER.forSubComponent("MdnsAdvertiser"), flags);
Paul Hu777ed052023-06-19 13:35:15 +00001728 mClock = deps.makeClock();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001729 }
1730
1731 /**
1732 * Dependencies of NsdService, for injection in tests.
1733 */
1734 @VisibleForTesting
1735 public static class Dependencies {
1736 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001737 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001738 *
1739 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001740 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001741 */
1742 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001743 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001744 MDNS_DISCOVERY_MANAGER_VERSION);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001745 }
1746
1747 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001748 * Check whether the MdnsAdvertiser feature is enabled.
1749 *
1750 * @param context The global context information about an app environment.
1751 * @return true if the MdnsAdvertiser feature is enabled.
1752 */
1753 public boolean isMdnsAdvertiserEnabled(Context context) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001754 return isAtLeastU() || DeviceConfigUtils.isTetheringFeatureEnabled(context,
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001755 MDNS_ADVERTISER_VERSION);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001756 }
1757
1758 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001759 * Get the type allowlist flag value.
1760 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1761 */
1762 @Nullable
1763 public String getTypeAllowlistFlags() {
1764 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1765 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1766 }
1767
1768 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001769 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001770 */
1771 public boolean isFeatureEnabled(Context context, String feature) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001772 return DeviceConfigUtils.isTetheringFeatureEnabled(context, feature);
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001773 }
1774
1775 /**
Yuyang Huangb96a0712023-09-07 15:13:15 +09001776 * @see DeviceConfigUtils#isTetheringFeatureNotChickenedOut
1777 */
Motomu Utsumied4e7ec2023-09-13 14:58:32 +09001778 public boolean isTetheringFeatureNotChickenedOut(Context context, String feature) {
1779 return DeviceConfigUtils.isTetheringFeatureNotChickenedOut(context, feature);
Yuyang Huangb96a0712023-09-07 15:13:15 +09001780 }
1781
1782 /**
Paul Huf3fe3332023-10-16 17:13:25 +08001783 * @see DeviceConfigUtils#isTrunkStableFeatureEnabled
1784 */
1785 public boolean isTrunkStableFeatureEnabled(String feature) {
1786 return DeviceConfigUtils.isTrunkStableFeatureEnabled(feature);
1787 }
1788
1789 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001790 * @see MdnsDiscoveryManager
1791 */
1792 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
Paul Hu14667de2023-04-17 22:42:47 +08001793 @NonNull ExecutorProvider executorProvider,
Paul Huf3fe3332023-10-16 17:13:25 +08001794 @NonNull MdnsMultinetworkSocketClient socketClient, @NonNull SharedLog sharedLog,
1795 @NonNull MdnsFeatureFlags featureFlags) {
1796 return new MdnsDiscoveryManager(
1797 executorProvider, socketClient, sharedLog, featureFlags);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001798 }
1799
1800 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001801 * @see MdnsAdvertiser
1802 */
1803 public MdnsAdvertiser makeMdnsAdvertiser(
1804 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
Yuyang Huangb96a0712023-09-07 15:13:15 +09001805 @NonNull MdnsAdvertiser.AdvertiserCallback cb, @NonNull SharedLog sharedLog,
1806 MdnsFeatureFlags featureFlags) {
1807 return new MdnsAdvertiser(looper, socketProvider, cb, sharedLog, featureFlags);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001808 }
1809
1810 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001811 * @see MdnsSocketProvider
1812 */
Paul Hu14667de2023-04-17 22:42:47 +08001813 public MdnsSocketProvider makeMdnsSocketProvider(@NonNull Context context,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001814 @NonNull Looper looper, @NonNull SharedLog sharedLog,
1815 @NonNull MdnsSocketProvider.SocketRequestMonitor socketCreationCallback) {
1816 return new MdnsSocketProvider(context, looper, sharedLog, socketCreationCallback);
1817 }
1818
1819 /**
1820 * @see DeviceConfig#getInt(String, String, int)
1821 */
1822 public int getDeviceConfigInt(@NonNull String config, int defaultValue) {
1823 return DeviceConfig.getInt(NAMESPACE_TETHERING, config, defaultValue);
1824 }
1825
1826 /**
1827 * @see Binder#getCallingUid()
1828 */
1829 public int getCallingUid() {
1830 return Binder.getCallingUid();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001831 }
Paul Hu777ed052023-06-19 13:35:15 +00001832
1833 /**
1834 * @see NetworkNsdReportedMetrics
1835 */
Paul Hu508a0122023-09-11 15:31:33 +08001836 public NetworkNsdReportedMetrics makeNetworkNsdReportedMetrics(int clientId) {
1837 return new NetworkNsdReportedMetrics(clientId);
Paul Hu777ed052023-06-19 13:35:15 +00001838 }
1839
1840 /**
1841 * @see MdnsUtils.Clock
1842 */
1843 public Clock makeClock() {
1844 return new Clock();
1845 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001846 }
1847
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001848 /**
1849 * Return whether a type is allowlisted to use the Java backend.
1850 * @param type The service type
1851 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1852 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1853 */
1854 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1855 @NonNull String flagPrefix) {
1856 if (type == null) return false;
1857 final String typesConfig = mDeps.getTypeAllowlistFlags();
1858 if (TextUtils.isEmpty(typesConfig)) return false;
1859
1860 final String mappingPrefix = type + ":";
1861 String mappedFlag = null;
1862 for (String mapping : TextUtils.split(typesConfig, ",")) {
1863 if (mapping.startsWith(mappingPrefix)) {
1864 mappedFlag = mapping.substring(mappingPrefix.length());
1865 break;
1866 }
1867 }
1868
1869 if (mappedFlag == null) return false;
1870
1871 return mDeps.isFeatureEnabled(mContext,
1872 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1873 }
1874
1875 private boolean useDiscoveryManagerForType(@Nullable String type) {
1876 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1877 }
1878
1879 private boolean useAdvertiserForType(@Nullable String type) {
1880 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1881 }
1882
paulhu1b35e822022-04-08 14:48:41 +08001883 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001884 HandlerThread thread = new HandlerThread(TAG);
1885 thread.start();
1886 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001887 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001888 return service;
1889 }
1890
paulhu2b9ed952022-02-10 21:58:32 +08001891 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1892 private final StateMachine mStateMachine;
1893
1894 MDnsEventCallback(StateMachine sm) {
1895 mStateMachine = sm;
1896 }
1897
1898 @Override
1899 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1900 mStateMachine.sendMessage(
1901 MDNS_SERVICE_EVENT, status.result, status.id, status);
1902 }
1903
1904 @Override
1905 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1906 mStateMachine.sendMessage(
1907 MDNS_SERVICE_EVENT, status.result, status.id, status);
1908 }
1909
1910 @Override
1911 public void onServiceResolutionStatus(final ResolutionInfo status) {
1912 mStateMachine.sendMessage(
1913 MDNS_SERVICE_EVENT, status.result, status.id, status);
1914 }
1915
1916 @Override
1917 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1918 mStateMachine.sendMessage(
1919 MDNS_SERVICE_EVENT, status.result, status.id, status);
1920 }
1921
1922 @Override
1923 public int getInterfaceVersion() throws RemoteException {
1924 return this.VERSION;
1925 }
1926
1927 @Override
1928 public String getInterfaceHash() throws RemoteException {
1929 return this.HASH;
1930 }
1931 }
1932
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001933 private void sendAllOffloadServiceInfos(@NonNull OffloadEngineInfo offloadEngineInfo) {
1934 final String targetInterface = offloadEngineInfo.mInterfaceName;
1935 final IOffloadEngine offloadEngine = offloadEngineInfo.mOffloadEngine;
1936 final List<MdnsAdvertiser.OffloadServiceInfoWrapper> offloadWrappers =
1937 mAdvertiser.getAllInterfaceOffloadServiceInfos(targetInterface);
1938 for (MdnsAdvertiser.OffloadServiceInfoWrapper wrapper : offloadWrappers) {
1939 try {
1940 offloadEngine.onOffloadServiceUpdated(wrapper.mOffloadServiceInfo);
1941 } catch (RemoteException e) {
1942 // Can happen in regular cases, do not log a stacktrace
1943 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
1944 }
1945 }
1946 }
1947
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001948 private void sendOffloadServiceInfosUpdate(@NonNull String targetInterfaceName,
1949 @NonNull OffloadServiceInfo offloadServiceInfo, boolean isRemove) {
1950 final int count = mOffloadEngines.beginBroadcast();
1951 try {
1952 for (int i = 0; i < count; i++) {
1953 final OffloadEngineInfo offloadEngineInfo =
1954 (OffloadEngineInfo) mOffloadEngines.getBroadcastCookie(i);
1955 final String interfaceName = offloadEngineInfo.mInterfaceName;
1956 if (!targetInterfaceName.equals(interfaceName)
1957 || ((offloadEngineInfo.mOffloadType
1958 & offloadServiceInfo.getOffloadType()) == 0)) {
1959 continue;
1960 }
1961 try {
1962 if (isRemove) {
1963 mOffloadEngines.getBroadcastItem(i).onOffloadServiceRemoved(
1964 offloadServiceInfo);
1965 } else {
1966 mOffloadEngines.getBroadcastItem(i).onOffloadServiceUpdated(
1967 offloadServiceInfo);
1968 }
1969 } catch (RemoteException e) {
1970 // Can happen in regular cases, do not log a stacktrace
Yuyang Huangc275a9e2023-08-25 18:03:22 +09001971 Log.i(TAG, "Failed to send offload callback, remote died: " + e.getMessage());
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001972 }
1973 }
1974 } finally {
1975 mOffloadEngines.finishBroadcast();
1976 }
1977 }
1978
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001979 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09001980 // TODO: add a callback to notify when a service is being added on each interface (as soon
1981 // as probing starts), and call mOffloadCallbacks. This callback is for
1982 // OFFLOAD_CAPABILITY_FILTER_REPLIES offload type.
1983
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001984 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00001985 public void onRegisterServiceSucceeded(int transactionId, NsdServiceInfo registeredInfo) {
1986 mServiceLogs.log("onRegisterServiceSucceeded: transactionId " + transactionId);
1987 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001988 if (clientInfo == null) return;
1989
Paul Hud44e1b72023-06-16 02:07:42 +00001990 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
1991 if (clientRequestId < 0) return;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001992
1993 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1994 // historical behavior.
1995 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
Paul Hu777ed052023-06-19 13:35:15 +00001996 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu508a0122023-09-11 15:31:33 +08001997 clientInfo.onRegisterServiceSucceeded(clientRequestId, cbInfo, request);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001998 }
1999
2000 @Override
Paul Hud44e1b72023-06-16 02:07:42 +00002001 public void onRegisterServiceFailed(int transactionId, int errorCode) {
2002 final ClientInfo clientInfo = getClientInfoOrLog(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002003 if (clientInfo == null) return;
2004
Paul Hud44e1b72023-06-16 02:07:42 +00002005 final int clientRequestId = getClientRequestIdOrLog(clientInfo, transactionId);
2006 if (clientRequestId < 0) return;
Paul Hu777ed052023-06-19 13:35:15 +00002007 final ClientRequest request = clientInfo.mClientRequests.get(clientRequestId);
Paul Hu508a0122023-09-11 15:31:33 +08002008 clientInfo.onRegisterServiceFailed(clientRequestId, errorCode, false /* isLegacy */,
2009 transactionId, request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002010 }
2011
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002012 @Override
2013 public void onOffloadStartOrUpdate(@NonNull String interfaceName,
2014 @NonNull OffloadServiceInfo offloadServiceInfo) {
2015 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, false /* isRemove */);
2016 }
2017
2018 @Override
2019 public void onOffloadStop(@NonNull String interfaceName,
2020 @NonNull OffloadServiceInfo offloadServiceInfo) {
2021 sendOffloadServiceInfosUpdate(interfaceName, offloadServiceInfo, true /* isRemove */);
2022 }
2023
Paul Hud44e1b72023-06-16 02:07:42 +00002024 private ClientInfo getClientInfoOrLog(int transactionId) {
2025 final ClientInfo clientInfo = mTransactionIdToClientInfoMap.get(transactionId);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002026 if (clientInfo == null) {
Paul Hud44e1b72023-06-16 02:07:42 +00002027 Log.e(TAG, String.format("Callback for service %d has no client", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002028 }
2029 return clientInfo;
2030 }
2031
Paul Hud44e1b72023-06-16 02:07:42 +00002032 private int getClientRequestIdOrLog(@NonNull ClientInfo info, int transactionId) {
2033 final int clientRequestId = info.getClientRequestId(transactionId);
2034 if (clientRequestId < 0) {
2035 Log.e(TAG, String.format(
2036 "Client request ID not found for service %d", transactionId));
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002037 }
Paul Hud44e1b72023-06-16 02:07:42 +00002038 return clientRequestId;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09002039 }
2040 }
2041
Paul Hu2e0a88c2023-03-09 16:05:01 +08002042 private static class ConnectorArgs {
2043 @NonNull public final NsdServiceConnector connector;
2044 @NonNull public final INsdManagerCallback callback;
2045 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002046 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002047
2048 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00002049 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08002050 this.connector = connector;
2051 this.callback = callback;
2052 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002053 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002054 }
2055 }
2056
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002057 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08002058 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09002059 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu101dbf52023-08-09 16:05:20 +08002060 final int uid = mDeps.getCallingUid();
2061 if (cb == null) {
2062 throw new IllegalArgumentException("Unknown client callback from uid=" + uid);
2063 }
Paul Hu2e0a88c2023-03-09 16:05:01 +08002064 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002065 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00002066 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
Paul Hu101dbf52023-08-09 16:05:20 +08002067 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend, uid)));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002068 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07002069 }
2070
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002071 private static class ListenerArgs {
2072 public final NsdServiceConnector connector;
2073 public final NsdServiceInfo serviceInfo;
2074 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
2075 this.connector = connector;
2076 this.serviceInfo = serviceInfo;
2077 }
2078 }
2079
2080 private class NsdServiceConnector extends INsdServiceConnector.Stub
2081 implements IBinder.DeathRecipient {
2082 @Override
2083 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
2084 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2085 NsdManager.REGISTER_SERVICE, 0, listenerKey,
2086 new ListenerArgs(this, serviceInfo)));
2087 }
2088
2089 @Override
2090 public void unregisterService(int listenerKey) {
2091 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2092 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
2093 new ListenerArgs(this, null)));
2094 }
2095
2096 @Override
2097 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
2098 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2099 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
2100 new ListenerArgs(this, serviceInfo)));
2101 }
2102
2103 @Override
2104 public void stopDiscovery(int listenerKey) {
2105 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2106 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
2107 }
2108
2109 @Override
2110 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
2111 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2112 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
2113 new ListenerArgs(this, serviceInfo)));
2114 }
2115
2116 @Override
Paul Hub58deb72022-12-26 09:24:42 +00002117 public void stopResolution(int listenerKey) {
2118 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2119 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
2120 }
2121
2122 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00002123 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
2124 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2125 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
2126 new ListenerArgs(this, serviceInfo)));
2127 }
2128
2129 @Override
2130 public void unregisterServiceInfoCallback(int listenerKey) {
2131 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2132 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
2133 new ListenerArgs(this, null)));
2134 }
2135
2136 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002137 public void startDaemon() {
2138 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
2139 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
2140 }
2141
2142 @Override
2143 public void binderDied() {
2144 mNsdStateMachine.sendMessage(
2145 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002146
2147 }
2148
2149 @Override
2150 public void registerOffloadEngine(String ifaceName, IOffloadEngine cb,
2151 @OffloadEngine.OffloadCapability long offloadCapabilities,
2152 @OffloadEngine.OffloadType long offloadTypes) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002153 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002154 Objects.requireNonNull(ifaceName);
2155 Objects.requireNonNull(cb);
2156 mNsdStateMachine.sendMessage(
2157 mNsdStateMachine.obtainMessage(NsdManager.REGISTER_OFFLOAD_ENGINE,
2158 new OffloadEngineInfo(cb, ifaceName, offloadCapabilities,
2159 offloadTypes)));
2160 }
2161
2162 @Override
2163 public void unregisterOffloadEngine(IOffloadEngine cb) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002164 checkOffloadEnginePermission(mContext);
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002165 Objects.requireNonNull(cb);
2166 mNsdStateMachine.sendMessage(
2167 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_OFFLOAD_ENGINE, cb));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002168 }
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002169
2170 private static void checkOffloadEnginePermission(Context context) {
2171 if (!SdkLevel.isAtLeastT()) {
2172 throw new SecurityException("API is not available in before API level 33");
2173 }
Yuyang Huangd5896e72023-11-28 13:23:59 +09002174
2175 // REGISTER_NSD_OFFLOAD_ENGINE was only added to the SDK in V.
2176 if (SdkLevel.isAtLeastV() && PermissionUtils.checkAnyPermissionOf(context,
2177 REGISTER_NSD_OFFLOAD_ENGINE)) {
2178 return;
2179 }
2180
2181 // REGISTER_NSD_OFFLOAD_ENGINE cannot be backport to U. In U, check the DEVICE_POWER
2182 // permission instead.
2183 if (!SdkLevel.isAtLeastV() && SdkLevel.isAtLeastU()
2184 && PermissionUtils.checkAnyPermissionOf(context, DEVICE_POWER)) {
Yuyang Huang8e6fbc82023-08-07 17:46:19 +09002185 return;
2186 }
2187 if (PermissionUtils.checkAnyPermissionOf(context, NETWORK_STACK,
2188 PERMISSION_MAINLINE_NETWORK_STACK, NETWORK_SETTINGS)) {
2189 return;
2190 }
2191 throw new SecurityException("Requires one of the following permissions: "
2192 + String.join(", ", List.of(REGISTER_NSD_OFFLOAD_ENGINE, NETWORK_STACK,
2193 PERMISSION_MAINLINE_NETWORK_STACK, NETWORK_SETTINGS)) + ".");
2194 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002195 }
2196
Hugo Benichi912db992017-04-24 16:41:03 +09002197 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07002198 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07002199 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09002200 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
2201 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07002202 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07002203 }
2204
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002205 private int getUniqueId() {
2206 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
2207 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002208 }
2209
Paul Hud44e1b72023-06-16 02:07:42 +00002210 private boolean registerService(int transactionId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09002211 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002212 Log.d(TAG, "registerService: " + transactionId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002213 }
Hugo Benichi6d706442017-04-24 16:19:58 +09002214 String name = service.getServiceName();
2215 String type = service.getServiceType();
2216 int port = service.getPort();
2217 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002218 final int registerInterface = getNetworkInterfaceIndex(service);
2219 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08002220 Log.e(TAG, "Interface to register service on not found");
2221 return false;
2222 }
Paul Hud44e1b72023-06-16 02:07:42 +00002223 return mMDnsManager.registerService(
2224 transactionId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002225 }
2226
Paul Hud44e1b72023-06-16 02:07:42 +00002227 private boolean unregisterService(int transactionId) {
2228 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002229 }
2230
Paul Hud44e1b72023-06-16 02:07:42 +00002231 private boolean discoverServices(int transactionId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08002232 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002233 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
2234 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002235 Log.e(TAG, "Interface to discover service on not found");
2236 return false;
2237 }
Paul Hud44e1b72023-06-16 02:07:42 +00002238 return mMDnsManager.discover(transactionId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002239 }
2240
Paul Hud44e1b72023-06-16 02:07:42 +00002241 private boolean stopServiceDiscovery(int transactionId) {
2242 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002243 }
2244
Paul Hud44e1b72023-06-16 02:07:42 +00002245 private boolean resolveService(int transactionId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002246 final String name = service.getServiceName();
2247 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002248 final int resolveInterface = getNetworkInterfaceIndex(service);
2249 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002250 Log.e(TAG, "Interface to resolve service on not found");
2251 return false;
2252 }
Paul Hud44e1b72023-06-16 02:07:42 +00002253 return mMDnsManager.resolve(transactionId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002254 }
2255
2256 /**
2257 * Guess the interface to use to resolve or discover a service on a specific network.
2258 *
2259 * This is an imperfect guess, as for example the network may be gone or not yet fully
2260 * registered. This is fine as failing is correct if the network is gone, and a client
2261 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
2262 * this is to support the legacy mdnsresponder implementation, which historically resolved
2263 * services on an unspecified network.
2264 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09002265 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
2266 final Network network = serviceInfo.getNetwork();
2267 if (network == null) {
2268 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
2269 // provided by NsdService from discovery results, and the service was found on an
2270 // interface that has no app-usable Network).
2271 if (serviceInfo.getInterfaceIndex() != 0) {
2272 return serviceInfo.getInterfaceIndex();
2273 }
2274 return IFACE_IDX_ANY;
2275 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002276
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002277 String interfaceName = getNetworkInterfaceName(network);
2278 if (interfaceName == null) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002279 return IFACE_IDX_ANY;
2280 }
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002281 return getNetworkInterfaceIndexByName(interfaceName);
2282 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002283
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002284 private String getNetworkInterfaceName(@Nullable Network network) {
2285 if (network == null) {
2286 return null;
2287 }
2288 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
2289 if (cm == null) {
2290 Log.wtf(TAG, "No ConnectivityManager");
2291 return null;
2292 }
2293 final LinkProperties lp = cm.getLinkProperties(network);
2294 if (lp == null) {
2295 return null;
2296 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002297 // Only resolve on non-stacked interfaces
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002298 return lp.getInterfaceName();
2299 }
2300
2301 private int getNetworkInterfaceIndexByName(final String ifaceName) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002302 final NetworkInterface iface;
2303 try {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002304 iface = NetworkInterface.getByName(ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002305 } catch (SocketException e) {
2306 Log.e(TAG, "Error querying interface", e);
2307 return IFACE_IDX_ANY;
2308 }
2309
2310 if (iface == null) {
Yuyang Huang33fa4d22023-02-14 22:59:37 +09002311 Log.e(TAG, "Interface not found: " + ifaceName);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09002312 return IFACE_IDX_ANY;
2313 }
2314
2315 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002316 }
2317
Paul Hud44e1b72023-06-16 02:07:42 +00002318 private boolean stopResolveService(int transactionId) {
2319 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002320 }
2321
Paul Hud44e1b72023-06-16 02:07:42 +00002322 private boolean getAddrInfo(int transactionId, String hostname, int interfaceIdx) {
2323 return mMDnsManager.getServiceAddress(transactionId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002324 }
2325
Paul Hud44e1b72023-06-16 02:07:42 +00002326 private boolean stopGetAddrInfo(int transactionId) {
2327 return mMDnsManager.stopOperation(transactionId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002328 }
2329
2330 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00002331 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2332 if (!PermissionUtils.checkDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002333
Paul Hub2e67d32023-04-18 05:50:14 +00002334 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
2335 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07002336 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00002337
2338 // Dump service and clients logs
2339 pw.println();
Paul Hu14667de2023-04-17 22:42:47 +08002340 pw.println("Logs:");
Paul Hub2e67d32023-04-18 05:50:14 +00002341 pw.increaseIndent();
2342 mServiceLogs.reverseDump(pw);
2343 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002344 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002345
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002346 private abstract static class ClientRequest {
Paul Hud44e1b72023-06-16 02:07:42 +00002347 private final int mTransactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002348 private final long mStartTimeMs;
Paul Hu812e9212023-06-20 06:24:53 +00002349 private int mFoundServiceCount = 0;
2350 private int mLostServiceCount = 0;
2351 private final Set<String> mServices = new ArraySet<>();
Paul Hua6bc4632023-06-26 01:18:29 +00002352 private boolean mIsServiceFromCache = false;
Paul Hubad6fe92023-07-24 21:25:22 +08002353 private int mSentQueryCount = NO_SENT_QUERY_COUNT;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002354
Paul Hu812e9212023-06-20 06:24:53 +00002355 private ClientRequest(int transactionId, long startTimeMs) {
Paul Hud44e1b72023-06-16 02:07:42 +00002356 mTransactionId = transactionId;
Paul Hu777ed052023-06-19 13:35:15 +00002357 mStartTimeMs = startTimeMs;
2358 }
2359
Paul Hu812e9212023-06-20 06:24:53 +00002360 public long calculateRequestDurationMs(long stopTimeMs) {
Paul Hu777ed052023-06-19 13:35:15 +00002361 return stopTimeMs - mStartTimeMs;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002362 }
Paul Hu812e9212023-06-20 06:24:53 +00002363
2364 public void onServiceFound(String serviceName) {
2365 mFoundServiceCount++;
2366 if (mServices.size() <= MAX_SERVICES_COUNT_METRIC_PER_CLIENT) {
2367 mServices.add(serviceName);
2368 }
2369 }
2370
2371 public void onServiceLost() {
2372 mLostServiceCount++;
2373 }
2374
2375 public int getFoundServiceCount() {
2376 return mFoundServiceCount;
2377 }
2378
2379 public int getLostServiceCount() {
2380 return mLostServiceCount;
2381 }
2382
2383 public int getServicesCount() {
2384 return mServices.size();
2385 }
Paul Hua6bc4632023-06-26 01:18:29 +00002386
2387 public void setServiceFromCache(boolean isServiceFromCache) {
2388 mIsServiceFromCache = isServiceFromCache;
2389 }
2390
2391 public boolean isServiceFromCache() {
2392 return mIsServiceFromCache;
2393 }
Paul Hubad6fe92023-07-24 21:25:22 +08002394
2395 public void onQuerySent() {
2396 mSentQueryCount++;
2397 }
2398
2399 public int getSentQueryCount() {
2400 return mSentQueryCount;
2401 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002402 }
2403
2404 private static class LegacyClientRequest extends ClientRequest {
2405 private final int mRequestCode;
2406
Paul Hu812e9212023-06-20 06:24:53 +00002407 private LegacyClientRequest(int transactionId, int requestCode, long startTimeMs) {
2408 super(transactionId, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002409 mRequestCode = requestCode;
2410 }
2411 }
2412
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002413 private abstract static class JavaBackendClientRequest extends ClientRequest {
2414 @Nullable
2415 private final Network mRequestedNetwork;
2416
Paul Hu777ed052023-06-19 13:35:15 +00002417 private JavaBackendClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002418 long startTimeMs) {
2419 super(transactionId, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002420 mRequestedNetwork = requestedNetwork;
2421 }
2422
2423 @Nullable
2424 public Network getRequestedNetwork() {
2425 return mRequestedNetwork;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002426 }
2427 }
2428
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002429 private static class AdvertiserClientRequest extends JavaBackendClientRequest {
Paul Hu777ed052023-06-19 13:35:15 +00002430 private AdvertiserClientRequest(int transactionId, @Nullable Network requestedNetwork,
Paul Hu812e9212023-06-20 06:24:53 +00002431 long startTimeMs) {
2432 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002433 }
2434 }
2435
2436 private static class DiscoveryManagerRequest extends JavaBackendClientRequest {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002437 @NonNull
2438 private final MdnsListener mListener;
2439
Paul Hud44e1b72023-06-16 02:07:42 +00002440 private DiscoveryManagerRequest(int transactionId, @NonNull MdnsListener listener,
Paul Hu812e9212023-06-20 06:24:53 +00002441 @Nullable Network requestedNetwork, long startTimeMs) {
2442 super(transactionId, requestedNetwork, startTimeMs);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002443 mListener = listener;
2444 }
2445 }
2446
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002447 /* Information tracked per client */
2448 private class ClientInfo {
2449
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002450 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002451 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002452 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002453 private NsdServiceInfo mResolvedService;
2454
Paul Hud44e1b72023-06-16 02:07:42 +00002455 /* A map from client request ID (listenerKey) to the request */
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002456 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08002457
Luke Huangf7277ed2021-07-12 21:15:10 +08002458 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002459 private boolean mIsPreSClient = false;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002460 private final int mUid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002461 // The flag of using java backend if the client's target SDK >= U
2462 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002463 // Store client logs
2464 private final SharedLog mClientLogs;
Paul Hucdef3532023-06-18 14:47:35 +00002465 // Report the nsd metrics data
2466 private final NetworkNsdReportedMetrics mMetrics;
Luke Huangf7277ed2021-07-12 21:15:10 +08002467
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002468 private ClientInfo(INsdManagerCallback cb, int uid, boolean useJavaBackend,
Paul Hucdef3532023-06-18 14:47:35 +00002469 SharedLog sharedLog, NetworkNsdReportedMetrics metrics) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002470 mCb = cb;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002471 mUid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002472 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002473 mClientLogs = sharedLog;
2474 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Paul Hucdef3532023-06-18 14:47:35 +00002475 mMetrics = metrics;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002476 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002477
2478 @Override
2479 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06002480 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07002481 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002482 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002483 sb.append("mUseJavaBackend ").append(mUseJavaBackend).append("\n");
2484 sb.append("mUid ").append(mUid).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002485 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002486 int clientRequestId = mClientRequests.keyAt(i);
2487 sb.append("clientRequestId ")
2488 .append(clientRequestId)
2489 .append(" transactionId ").append(mClientRequests.valueAt(i).mTransactionId)
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002490 .append(" type ").append(
2491 mClientRequests.valueAt(i).getClass().getSimpleName())
2492 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07002493 }
2494 return sb.toString();
2495 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002496
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002497 private boolean isPreSClient() {
2498 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08002499 }
2500
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002501 private void setPreSClient() {
2502 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08002503 }
2504
Paul Hu812e9212023-06-20 06:24:53 +00002505 private MdnsListener unregisterMdnsListenerFromRequest(ClientRequest request) {
Paul Hue4f5f252023-02-16 21:13:47 +08002506 final MdnsListener listener =
2507 ((DiscoveryManagerRequest) request).mListener;
2508 mMdnsDiscoveryManager.unregisterListener(
2509 listener.getListenedServiceType(), listener);
Paul Hu812e9212023-06-20 06:24:53 +00002510 return listener;
Paul Hue4f5f252023-02-16 21:13:47 +08002511 }
2512
Dave Plattfeff2af2014-03-07 14:48:22 -08002513 // Remove any pending requests from the global map when we get rid of a client,
2514 // and send cancellations to the daemon.
2515 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00002516 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09002517 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002518 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002519 final int clientRequestId = mClientRequests.keyAt(i);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002520 final ClientRequest request = mClientRequests.valueAt(i);
Paul Hud44e1b72023-06-16 02:07:42 +00002521 final int transactionId = request.mTransactionId;
2522 mTransactionIdToClientInfoMap.remove(transactionId);
paulhub2225702021-11-17 09:35:33 +08002523 if (DBG) {
Paul Hud44e1b72023-06-16 02:07:42 +00002524 Log.d(TAG, "Terminating clientRequestId " + clientRequestId
2525 + " transactionId " + transactionId
2526 + " type " + mClientRequests.get(clientRequestId));
paulhub2225702021-11-17 09:35:33 +08002527 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002528
2529 if (request instanceof DiscoveryManagerRequest) {
Paul Hu812e9212023-06-20 06:24:53 +00002530 final MdnsListener listener = unregisterMdnsListenerFromRequest(request);
2531 if (listener instanceof DiscoveryListener) {
Paul Hu508a0122023-09-11 15:31:33 +08002532 mMetrics.reportServiceDiscoveryStop(false /* isLegacy */, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00002533 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2534 request.getFoundServiceCount(),
2535 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002536 request.getServicesCount(),
2537 request.getSentQueryCount());
Paul Hu60149052023-07-31 14:26:08 +08002538 } else if (listener instanceof ResolutionListener) {
Paul Hu508a0122023-09-11 15:31:33 +08002539 mMetrics.reportServiceResolutionStop(false /* isLegacy */, transactionId,
Paul Hu60149052023-07-31 14:26:08 +08002540 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Huddce5912023-08-01 10:26:49 +08002541 } else if (listener instanceof ServiceInfoListener) {
2542 mMetrics.reportServiceInfoCallbackUnregistered(transactionId,
2543 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2544 request.getFoundServiceCount(),
2545 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002546 request.isServiceFromCache(),
2547 request.getSentQueryCount());
Paul Hu812e9212023-06-20 06:24:53 +00002548 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002549 continue;
2550 }
2551
2552 if (request instanceof AdvertiserClientRequest) {
Paul Hu043bcd42023-07-14 16:38:25 +08002553 final AdvertiserMetrics metrics =
2554 mAdvertiser.getAdvertiserMetrics(transactionId);
Paul Hud44e1b72023-06-16 02:07:42 +00002555 mAdvertiser.removeService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002556 mMetrics.reportServiceUnregistration(false /* isLegacy */, transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002557 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2558 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2559 metrics.mConflictDuringProbingCount,
2560 metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002561 continue;
2562 }
2563
2564 if (!(request instanceof LegacyClientRequest)) {
2565 throw new IllegalStateException("Unknown request type: " + request.getClass());
2566 }
2567
2568 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08002569 case NsdManager.DISCOVER_SERVICES:
Paul Hud44e1b72023-06-16 02:07:42 +00002570 stopServiceDiscovery(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002571 mMetrics.reportServiceDiscoveryStop(true /* isLegacy */, transactionId,
Paul Hu812e9212023-06-20 06:24:53 +00002572 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2573 request.getFoundServiceCount(),
2574 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002575 request.getServicesCount(),
2576 NO_SENT_QUERY_COUNT);
Dave Plattfeff2af2014-03-07 14:48:22 -08002577 break;
2578 case NsdManager.RESOLVE_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002579 stopResolveService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002580 mMetrics.reportServiceResolutionStop(true /* isLegacy */, transactionId,
Paul Hu60149052023-07-31 14:26:08 +08002581 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Dave Plattfeff2af2014-03-07 14:48:22 -08002582 break;
2583 case NsdManager.REGISTER_SERVICE:
Paul Hud44e1b72023-06-16 02:07:42 +00002584 unregisterService(transactionId);
Paul Hu508a0122023-09-11 15:31:33 +08002585 mMetrics.reportServiceUnregistration(true /* isLegacy */, transactionId,
Paul Hu043bcd42023-07-14 16:38:25 +08002586 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2587 NO_PACKET /* repliedRequestsCount */,
2588 NO_PACKET /* sentPacketCount */,
2589 0 /* conflictDuringProbingCount */,
2590 0 /* conflictAfterProbingCount */);
Dave Plattfeff2af2014-03-07 14:48:22 -08002591 break;
2592 default:
2593 break;
2594 }
2595 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002596 mClientRequests.clear();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002597 updateMulticastLock();
2598 }
2599
2600 /**
2601 * Returns true if this client has any Java backend request that requests one of the given
2602 * networks.
2603 */
2604 boolean hasAnyJavaBackendRequestForNetworks(@NonNull ArraySet<Network> networks) {
2605 for (int i = 0; i < mClientRequests.size(); i++) {
2606 final ClientRequest req = mClientRequests.valueAt(i);
2607 if (!(req instanceof JavaBackendClientRequest)) {
2608 continue;
2609 }
2610 final Network reqNetwork = ((JavaBackendClientRequest) mClientRequests.valueAt(i))
2611 .getRequestedNetwork();
2612 if (MdnsUtils.isAnyNetworkMatched(reqNetwork, networks)) {
2613 return true;
2614 }
2615 }
2616 return false;
Dave Plattfeff2af2014-03-07 14:48:22 -08002617 }
2618
Paul Hud44e1b72023-06-16 02:07:42 +00002619 // mClientRequests is a sparse array of client request id -> ClientRequest. For a given
2620 // transaction id, return the corresponding client request id.
2621 private int getClientRequestId(final int transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002622 for (int i = 0; i < mClientRequests.size(); i++) {
Paul Hud44e1b72023-06-16 02:07:42 +00002623 if (mClientRequests.valueAt(i).mTransactionId == transactionId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002624 return mClientRequests.keyAt(i);
2625 }
Christopher Lane74411222014-04-25 18:39:07 -07002626 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002627 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07002628 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002629
Paul Hub2e67d32023-04-18 05:50:14 +00002630 private void log(String message) {
2631 mClientLogs.log(message);
2632 }
2633
Paul Hu508a0122023-09-11 15:31:33 +08002634 private static boolean isLegacyClientRequest(@NonNull ClientRequest request) {
2635 return !(request instanceof DiscoveryManagerRequest)
2636 && !(request instanceof AdvertiserClientRequest);
2637 }
2638
2639 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info,
2640 ClientRequest request) {
2641 mMetrics.reportServiceDiscoveryStarted(
2642 isLegacyClientRequest(request), request.mTransactionId);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002643 try {
2644 mCb.onDiscoverServicesStarted(listenerKey, info);
2645 } catch (RemoteException e) {
2646 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
2647 }
2648 }
Paul Hu508a0122023-09-11 15:31:33 +08002649 void onDiscoverServicesFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2650 onDiscoverServicesFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2651 0L /* durationMs */);
Paul Hu812e9212023-06-20 06:24:53 +00002652 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002653
Paul Hu508a0122023-09-11 15:31:33 +08002654 void onDiscoverServicesFailed(int listenerKey, int error, boolean isLegacy,
2655 int transactionId, long durationMs) {
2656 mMetrics.reportServiceDiscoveryFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002657 try {
2658 mCb.onDiscoverServicesFailed(listenerKey, error);
2659 } catch (RemoteException e) {
2660 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
2661 }
2662 }
2663
Paul Hu812e9212023-06-20 06:24:53 +00002664 void onServiceFound(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2665 request.onServiceFound(info.getServiceName());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002666 try {
2667 mCb.onServiceFound(listenerKey, info);
2668 } catch (RemoteException e) {
2669 Log.e(TAG, "Error calling onServiceFound(", e);
2670 }
2671 }
2672
Paul Hu812e9212023-06-20 06:24:53 +00002673 void onServiceLost(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2674 request.onServiceLost();
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002675 try {
2676 mCb.onServiceLost(listenerKey, info);
2677 } catch (RemoteException e) {
2678 Log.e(TAG, "Error calling onServiceLost(", e);
2679 }
2680 }
2681
2682 void onStopDiscoveryFailed(int listenerKey, int error) {
2683 try {
2684 mCb.onStopDiscoveryFailed(listenerKey, error);
2685 } catch (RemoteException e) {
2686 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
2687 }
2688 }
2689
Paul Hu812e9212023-06-20 06:24:53 +00002690 void onStopDiscoverySucceeded(int listenerKey, ClientRequest request) {
2691 mMetrics.reportServiceDiscoveryStop(
Paul Hu508a0122023-09-11 15:31:33 +08002692 isLegacyClientRequest(request),
Paul Hu812e9212023-06-20 06:24:53 +00002693 request.mTransactionId,
2694 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2695 request.getFoundServiceCount(),
2696 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002697 request.getServicesCount(),
2698 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002699 try {
2700 mCb.onStopDiscoverySucceeded(listenerKey);
2701 } catch (RemoteException e) {
2702 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
2703 }
2704 }
2705
Paul Hu508a0122023-09-11 15:31:33 +08002706 void onRegisterServiceFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2707 onRegisterServiceFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2708 0L /* durationMs */);
Paul Hu777ed052023-06-19 13:35:15 +00002709 }
2710
Paul Hu508a0122023-09-11 15:31:33 +08002711 void onRegisterServiceFailed(int listenerKey, int error, boolean isLegacy,
2712 int transactionId, long durationMs) {
2713 mMetrics.reportServiceRegistrationFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002714 try {
2715 mCb.onRegisterServiceFailed(listenerKey, error);
2716 } catch (RemoteException e) {
2717 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2718 }
2719 }
2720
Paul Hu508a0122023-09-11 15:31:33 +08002721 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info,
2722 ClientRequest request) {
2723 mMetrics.reportServiceRegistrationSucceeded(isLegacyClientRequest(request),
2724 request.mTransactionId,
2725 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002726 try {
2727 mCb.onRegisterServiceSucceeded(listenerKey, info);
2728 } catch (RemoteException e) {
2729 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2730 }
2731 }
2732
2733 void onUnregisterServiceFailed(int listenerKey, int error) {
2734 try {
2735 mCb.onUnregisterServiceFailed(listenerKey, error);
2736 } catch (RemoteException e) {
2737 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2738 }
2739 }
2740
Paul Hu508a0122023-09-11 15:31:33 +08002741 void onUnregisterServiceSucceeded(int listenerKey, ClientRequest request,
Paul Hu043bcd42023-07-14 16:38:25 +08002742 AdvertiserMetrics metrics) {
Paul Hu508a0122023-09-11 15:31:33 +08002743 mMetrics.reportServiceUnregistration(isLegacyClientRequest(request),
2744 request.mTransactionId,
2745 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hu043bcd42023-07-14 16:38:25 +08002746 metrics.mRepliedRequestsCount, metrics.mSentPacketCount,
2747 metrics.mConflictDuringProbingCount, metrics.mConflictAfterProbingCount);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002748 try {
2749 mCb.onUnregisterServiceSucceeded(listenerKey);
2750 } catch (RemoteException e) {
2751 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2752 }
2753 }
2754
Paul Hu508a0122023-09-11 15:31:33 +08002755 void onResolveServiceFailedImmediately(int listenerKey, int error, boolean isLegacy) {
2756 onResolveServiceFailed(listenerKey, error, isLegacy, NO_TRANSACTION,
2757 0L /* durationMs */);
Paul Hua6bc4632023-06-26 01:18:29 +00002758 }
2759
Paul Hu508a0122023-09-11 15:31:33 +08002760 void onResolveServiceFailed(int listenerKey, int error, boolean isLegacy,
2761 int transactionId, long durationMs) {
2762 mMetrics.reportServiceResolutionFailed(isLegacy, transactionId, durationMs);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002763 try {
2764 mCb.onResolveServiceFailed(listenerKey, error);
2765 } catch (RemoteException e) {
2766 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2767 }
2768 }
2769
Paul Hua6bc4632023-06-26 01:18:29 +00002770 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info,
2771 ClientRequest request) {
2772 mMetrics.reportServiceResolved(
Paul Hu508a0122023-09-11 15:31:33 +08002773 isLegacyClientRequest(request),
Paul Hua6bc4632023-06-26 01:18:29 +00002774 request.mTransactionId,
2775 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
Paul Hubad6fe92023-07-24 21:25:22 +08002776 request.isServiceFromCache(),
2777 request.getSentQueryCount());
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002778 try {
2779 mCb.onResolveServiceSucceeded(listenerKey, info);
2780 } catch (RemoteException e) {
2781 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2782 }
2783 }
Paul Hub58deb72022-12-26 09:24:42 +00002784
2785 void onStopResolutionFailed(int listenerKey, int error) {
2786 try {
2787 mCb.onStopResolutionFailed(listenerKey, error);
2788 } catch (RemoteException e) {
2789 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2790 }
2791 }
2792
Paul Hu60149052023-07-31 14:26:08 +08002793 void onStopResolutionSucceeded(int listenerKey, ClientRequest request) {
2794 mMetrics.reportServiceResolutionStop(
Paul Hu508a0122023-09-11 15:31:33 +08002795 isLegacyClientRequest(request),
Paul Hu60149052023-07-31 14:26:08 +08002796 request.mTransactionId,
2797 request.calculateRequestDurationMs(mClock.elapsedRealtime()));
Paul Hub58deb72022-12-26 09:24:42 +00002798 try {
2799 mCb.onStopResolutionSucceeded(listenerKey);
2800 } catch (RemoteException e) {
2801 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2802 }
2803 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002804
2805 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
Paul Huddce5912023-08-01 10:26:49 +08002806 mMetrics.reportServiceInfoCallbackRegistrationFailed(NO_TRANSACTION);
Paul Hu18aeccc2022-12-27 08:48:48 +00002807 try {
2808 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2809 } catch (RemoteException e) {
2810 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2811 }
2812 }
2813
Paul Huddce5912023-08-01 10:26:49 +08002814 void onServiceInfoCallbackRegistered(int transactionId) {
2815 mMetrics.reportServiceInfoCallbackRegistered(transactionId);
2816 }
2817
2818 void onServiceUpdated(int listenerKey, NsdServiceInfo info, ClientRequest request) {
2819 request.onServiceFound(info.getServiceName());
Paul Hu18aeccc2022-12-27 08:48:48 +00002820 try {
2821 mCb.onServiceUpdated(listenerKey, info);
2822 } catch (RemoteException e) {
2823 Log.e(TAG, "Error calling onServiceUpdated", e);
2824 }
2825 }
2826
Paul Huddce5912023-08-01 10:26:49 +08002827 void onServiceUpdatedLost(int listenerKey, ClientRequest request) {
2828 request.onServiceLost();
Paul Hu18aeccc2022-12-27 08:48:48 +00002829 try {
2830 mCb.onServiceUpdatedLost(listenerKey);
2831 } catch (RemoteException e) {
2832 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2833 }
2834 }
2835
Paul Huddce5912023-08-01 10:26:49 +08002836 void onServiceInfoCallbackUnregistered(int listenerKey, ClientRequest request) {
2837 mMetrics.reportServiceInfoCallbackUnregistered(
2838 request.mTransactionId,
2839 request.calculateRequestDurationMs(mClock.elapsedRealtime()),
2840 request.getFoundServiceCount(),
2841 request.getLostServiceCount(),
Paul Hubad6fe92023-07-24 21:25:22 +08002842 request.isServiceFromCache(),
2843 request.getSentQueryCount());
Paul Hu18aeccc2022-12-27 08:48:48 +00002844 try {
2845 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2846 } catch (RemoteException e) {
2847 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2848 }
2849 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002850 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002851}