blob: 9a2cc5f6b6cae631a5c4f9bce4eb968cca96dcc1 [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
paulhu2b9ed952022-02-10 21:58:32 +080019import static android.net.ConnectivityManager.NETID_UNSET;
Paul Hu019621e2023-01-13 23:26:49 +080020import static android.net.nsd.NsdManager.MDNS_DISCOVERY_MANAGER_EVENT;
paulhu2b9ed952022-02-10 21:58:32 +080021import static android.net.nsd.NsdManager.MDNS_SERVICE_EVENT;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +090022import static android.net.nsd.NsdManager.RESOLVE_SERVICE_SUCCEEDED;
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +090023import static android.provider.DeviceConfig.NAMESPACE_TETHERING;
paulhu2b9ed952022-02-10 21:58:32 +080024
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090025import static com.android.modules.utils.build.SdkLevel.isAtLeastU;
Yuyang Huangde802c82023-05-02 17:14:22 +090026import static com.android.server.connectivity.mdns.MdnsRecord.MAX_LABEL_LENGTH;
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090027
Paul Hu23fa2022023-01-13 22:57:24 +080028import android.annotation.NonNull;
Paul Hu4bd98ef2023-01-12 13:42:07 +080029import android.annotation.Nullable;
paulhua262cc12019-08-12 16:25:11 +080030import android.content.Context;
Irfan Sheriff75006652012-04-17 23:15:29 -070031import android.content.Intent;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090032import android.net.ConnectivityManager;
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +090033import android.net.INetd;
Paul Hu75069ed2023-01-14 00:31:09 +080034import android.net.InetAddresses;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090035import android.net.LinkProperties;
36import android.net.Network;
paulhu2b9ed952022-02-10 21:58:32 +080037import android.net.mdns.aidl.DiscoveryInfo;
38import android.net.mdns.aidl.GetAddressInfo;
39import android.net.mdns.aidl.IMDnsEventListener;
40import android.net.mdns.aidl.RegistrationInfo;
41import android.net.mdns.aidl.ResolutionInfo;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070042import android.net.nsd.INsdManager;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090043import android.net.nsd.INsdManagerCallback;
44import android.net.nsd.INsdServiceConnector;
paulhu2b9ed952022-02-10 21:58:32 +080045import android.net.nsd.MDnsManager;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070046import android.net.nsd.NsdManager;
paulhua262cc12019-08-12 16:25:11 +080047import android.net.nsd.NsdServiceInfo;
Paul Hub2e67d32023-04-18 05:50:14 +000048import android.os.Binder;
Hugo Benichi803a2f02017-04-24 11:35:06 +090049import android.os.Handler;
paulhua262cc12019-08-12 16:25:11 +080050import android.os.HandlerThread;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090051import android.os.IBinder;
Paul Hu4bd98ef2023-01-12 13:42:07 +080052import android.os.Looper;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070053import android.os.Message;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090054import android.os.RemoteException;
Dianne Hackborn692107e2012-08-29 18:32:08 -070055import android.os.UserHandle;
Paul Hu23fa2022023-01-13 22:57:24 +080056import android.text.TextUtils;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090057import android.util.Log;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +090058import android.util.Pair;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070059import android.util.SparseArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070060
paulhua262cc12019-08-12 16:25:11 +080061import com.android.internal.annotations.VisibleForTesting;
Paul Hub2e67d32023-04-18 05:50:14 +000062import com.android.internal.util.IndentingPrintWriter;
paulhua262cc12019-08-12 16:25:11 +080063import com.android.internal.util.State;
64import com.android.internal.util.StateMachine;
Paul Hu4bd98ef2023-01-12 13:42:07 +080065import com.android.net.module.util.DeviceConfigUtils;
Yuyang Huanga6a6ff92023-04-24 13:33:34 +090066import com.android.net.module.util.InetAddressUtils;
paulhu3ffffe72021-09-16 10:15:22 +080067import com.android.net.module.util.PermissionUtils;
Paul Hub2e67d32023-04-18 05:50:14 +000068import com.android.net.module.util.SharedLog;
Paul Hu4bd98ef2023-01-12 13:42:07 +080069import com.android.server.connectivity.mdns.ExecutorProvider;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090070import com.android.server.connectivity.mdns.MdnsAdvertiser;
Paul Hu4bd98ef2023-01-12 13:42:07 +080071import com.android.server.connectivity.mdns.MdnsDiscoveryManager;
72import com.android.server.connectivity.mdns.MdnsMultinetworkSocketClient;
Paul Hu23fa2022023-01-13 22:57:24 +080073import com.android.server.connectivity.mdns.MdnsSearchOptions;
74import com.android.server.connectivity.mdns.MdnsServiceBrowserListener;
75import com.android.server.connectivity.mdns.MdnsServiceInfo;
Paul Hu4bd98ef2023-01-12 13:42:07 +080076import com.android.server.connectivity.mdns.MdnsSocketClientBase;
77import com.android.server.connectivity.mdns.MdnsSocketProvider;
Yuyang Huangde802c82023-05-02 17:14:22 +090078import com.android.server.connectivity.mdns.util.MdnsUtils;
paulhua262cc12019-08-12 16:25:11 +080079
Irfan Sheriff77ec5582012-03-22 17:01:39 -070080import java.io.FileDescriptor;
81import java.io.PrintWriter;
Yuyang Huangaa0e9602023-03-17 12:43:09 +090082import java.net.Inet6Address;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070083import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090084import java.net.NetworkInterface;
85import java.net.SocketException;
86import java.net.UnknownHostException;
Paul Hu2b865912023-03-06 14:27:53 +080087import java.util.ArrayList;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +090088import java.util.Arrays;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070089import java.util.HashMap;
Paul Hu23fa2022023-01-13 22:57:24 +080090import java.util.List;
Paul Hu75069ed2023-01-14 00:31:09 +080091import java.util.Map;
Paul Hu23fa2022023-01-13 22:57:24 +080092import java.util.regex.Matcher;
93import java.util.regex.Pattern;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070094
Irfan Sheriff77ec5582012-03-22 17:01:39 -070095/**
96 * Network Service Discovery Service handles remote service discovery operation requests by
97 * implementing the INsdManager interface.
98 *
99 * @hide
100 */
101public class NsdService extends INsdManager.Stub {
102 private static final String TAG = "NsdService";
103 private static final String MDNS_TAG = "mDnsConnector";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900104 /**
105 * Enable discovery using the Java DiscoveryManager, instead of the legacy mdnsresponder
106 * implementation.
107 */
Paul Hu4bd98ef2023-01-12 13:42:07 +0800108 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Paul Hu23fa2022023-01-13 22:57:24 +0800109 private static final String LOCAL_DOMAIN_NAME = "local";
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700110
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900111 /**
112 * Enable advertising using the Java MdnsAdvertiser, instead of the legacy mdnsresponder
113 * implementation.
114 */
115 private static final String MDNS_ADVERTISER_VERSION = "mdns_advertiser_version";
116
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900117 /**
118 * Comma-separated list of type:flag mappings indicating the flags to use to allowlist
119 * discovery/advertising using MdnsDiscoveryManager / MdnsAdvertiser for a given type.
120 *
121 * For example _mytype._tcp.local and _othertype._tcp.local would be configured with:
122 * _mytype._tcp:mytype,_othertype._tcp.local:othertype
123 *
124 * In which case the flags:
125 * "mdns_discovery_manager_allowlist_mytype_version",
126 * "mdns_advertiser_allowlist_mytype_version",
127 * "mdns_discovery_manager_allowlist_othertype_version",
128 * "mdns_advertiser_allowlist_othertype_version"
129 * would be used to toggle MdnsDiscoveryManager / MdnsAdvertiser for each type. The flags will
130 * be read with
131 * {@link DeviceConfigUtils#isFeatureEnabled(Context, String, String, String, boolean)}.
132 *
133 * @see #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX
134 * @see #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX
135 * @see #MDNS_ALLOWLIST_FLAG_SUFFIX
136 */
137 private static final String MDNS_TYPE_ALLOWLIST_FLAGS = "mdns_type_allowlist_flags";
138
139 private static final String MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX =
140 "mdns_discovery_manager_allowlist_";
141 private static final String MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX =
142 "mdns_advertiser_allowlist_";
143 private static final String MDNS_ALLOWLIST_FLAG_SUFFIX = "_version";
144
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900145 public static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +0000146 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900147 private static final int IFACE_IDX_ANY = 0;
Paul Hu14667de2023-04-17 22:42:47 +0800148 private static final SharedLog LOGGER = new SharedLog("serviceDiscovery");
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700149
Hugo Benichi32be63d2017-04-05 14:06:11 +0900150 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900151 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +0800152 private final MDnsManager mMDnsManager;
153 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900154 @NonNull
155 private final Dependencies mDeps;
156 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800157 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900158 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800159 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900160 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800161 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900162 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900163 private final MdnsAdvertiser mAdvertiser;
Paul Hu14667de2023-04-17 22:42:47 +0800164 private final SharedLog mServiceLogs = LOGGER.forSubComponent(TAG);
Paul Hu23fa2022023-01-13 22:57:24 +0800165 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800166 // state machine thread. If change this outside state machine, it will need to introduce
167 // synchronization.
168 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800169 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700170
171 /**
172 * Clients receiving asynchronous messages
173 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900174 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700175
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700176 /* A map from unique id to client info */
Hugo Benichi32be63d2017-04-05 14:06:11 +0900177 private final SparseArray<ClientInfo> mIdToClientInfoMap= new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700178
Luke Huang05298582021-06-13 16:52:05 +0000179 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700180
Hugo Benichi32be63d2017-04-05 14:06:11 +0900181 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700182 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800183 // The count of the connected legacy clients.
184 private int mLegacyClientCount = 0;
Paul Hub2e67d32023-04-18 05:50:14 +0000185 // The number of client that ever connected.
186 private int mClientNumberId = 1;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700187
Paul Hu23fa2022023-01-13 22:57:24 +0800188 private static class MdnsListener implements MdnsServiceBrowserListener {
189 protected final int mClientId;
190 protected final int mTransactionId;
191 @NonNull
192 protected final NsdServiceInfo mReqServiceInfo;
193 @NonNull
194 protected final String mListenedServiceType;
195
196 MdnsListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
197 @NonNull String listenedServiceType) {
198 mClientId = clientId;
199 mTransactionId = transactionId;
200 mReqServiceInfo = reqServiceInfo;
201 mListenedServiceType = listenedServiceType;
202 }
203
204 @NonNull
205 public String getListenedServiceType() {
206 return mListenedServiceType;
207 }
208
209 @Override
210 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo) { }
211
212 @Override
213 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
214
215 @Override
216 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
217
218 @Override
219 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) { }
220
221 @Override
222 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
223
224 @Override
225 public void onSearchStoppedWithError(int error) { }
226
227 @Override
228 public void onSearchFailedToStart() { }
229
230 @Override
231 public void onDiscoveryQuerySent(@NonNull List<String> subtypes, int transactionId) { }
232
233 @Override
234 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
235 }
236
237 private class DiscoveryListener extends MdnsListener {
238
239 DiscoveryListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
240 @NonNull String listenServiceType) {
241 super(clientId, transactionId, reqServiceInfo, listenServiceType);
242 }
243
244 @Override
245 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu019621e2023-01-13 23:26:49 +0800246 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
247 NsdManager.SERVICE_FOUND,
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900248 new MdnsEvent(mClientId, serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800249 }
250
251 @Override
252 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800253 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
254 NsdManager.SERVICE_LOST,
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900255 new MdnsEvent(mClientId, serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800256 }
257 }
258
Paul Hu75069ed2023-01-14 00:31:09 +0800259 private class ResolutionListener extends MdnsListener {
260
261 ResolutionListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
262 @NonNull String listenServiceType) {
263 super(clientId, transactionId, reqServiceInfo, listenServiceType);
264 }
265
266 @Override
267 public void onServiceFound(MdnsServiceInfo serviceInfo) {
268 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
269 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900270 new MdnsEvent(mClientId, serviceInfo));
Paul Hu75069ed2023-01-14 00:31:09 +0800271 }
272 }
273
Paul Hu30bd70d2023-02-07 13:20:56 +0000274 private class ServiceInfoListener extends MdnsListener {
275
276 ServiceInfoListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
277 @NonNull String listenServiceType) {
278 super(clientId, transactionId, reqServiceInfo, listenServiceType);
279 }
280
281 @Override
282 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo) {
283 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
284 NsdManager.SERVICE_UPDATED,
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900285 new MdnsEvent(mClientId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000286 }
287
288 @Override
289 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) {
290 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
291 NsdManager.SERVICE_UPDATED,
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900292 new MdnsEvent(mClientId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000293 }
294
295 @Override
296 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) {
297 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
298 NsdManager.SERVICE_UPDATED_LOST,
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900299 new MdnsEvent(mClientId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000300 }
301 }
302
Paul Hu019621e2023-01-13 23:26:49 +0800303 /**
304 * Data class of mdns service callback information.
305 */
306 private static class MdnsEvent {
307 final int mClientId;
308 @NonNull
Paul Hu019621e2023-01-13 23:26:49 +0800309 final MdnsServiceInfo mMdnsServiceInfo;
310
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900311 MdnsEvent(int clientId, @NonNull MdnsServiceInfo mdnsServiceInfo) {
Paul Hu019621e2023-01-13 23:26:49 +0800312 mClientId = clientId;
Paul Hu019621e2023-01-13 23:26:49 +0800313 mMdnsServiceInfo = mdnsServiceInfo;
314 }
315 }
316
Irfan Sheriff75006652012-04-17 23:15:29 -0700317 private class NsdStateMachine extends StateMachine {
318
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700319 private final DefaultState mDefaultState = new DefaultState();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700320 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700321
322 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700323 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900324 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700325 }
326
Luke Huang92860f92021-06-23 06:29:30 +0000327 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800328 if (mIsDaemonStarted) {
329 if (DBG) Log.d(TAG, "Daemon is already started.");
330 return;
331 }
332 mMDnsManager.registerEventListener(mMDnsEventCallback);
333 mMDnsManager.startDaemon();
334 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000335 maybeScheduleStop();
Paul Hub2e67d32023-04-18 05:50:14 +0000336 mServiceLogs.log("Start mdns_responder daemon");
Luke Huang05298582021-06-13 16:52:05 +0000337 }
338
paulhu2b9ed952022-02-10 21:58:32 +0800339 private void maybeStopDaemon() {
340 if (!mIsDaemonStarted) {
341 if (DBG) Log.d(TAG, "Daemon has not been started.");
342 return;
343 }
344 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
345 mMDnsManager.stopDaemon();
346 mIsDaemonStarted = false;
Paul Hub2e67d32023-04-18 05:50:14 +0000347 mServiceLogs.log("Stop mdns_responder daemon");
paulhu2b9ed952022-02-10 21:58:32 +0800348 }
349
Luke Huang92860f92021-06-23 06:29:30 +0000350 private boolean isAnyRequestActive() {
351 return mIdToClientInfoMap.size() != 0;
352 }
353
354 private void scheduleStop() {
355 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
356 }
357 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800358 // The native daemon should stay alive and can't be cleanup
359 // if any legacy client connected.
360 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000361 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000362 }
363 }
364
Luke Huang92860f92021-06-23 06:29:30 +0000365 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000366 this.removeMessages(NsdManager.DAEMON_CLEANUP);
367 }
368
Paul Hu23fa2022023-01-13 22:57:24 +0800369 private void maybeStartMonitoringSockets() {
370 if (mIsMonitoringSocketsStarted) {
371 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
372 return;
373 }
374
375 mMdnsSocketProvider.startMonitoringSockets();
376 mIsMonitoringSocketsStarted = true;
377 }
378
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900379 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
380 if (!mIsMonitoringSocketsStarted) return;
381 if (isAnyRequestActive()) return;
382
Paul Hu58f20602023-02-18 11:41:07 +0800383 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800384 mIsMonitoringSocketsStarted = false;
385 }
386
Hugo Benichi803a2f02017-04-24 11:35:06 +0900387 NsdStateMachine(String name, Handler handler) {
388 super(name, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -0700389 addState(mDefaultState);
Irfan Sheriff75006652012-04-17 23:15:29 -0700390 addState(mEnabledState, mDefaultState);
paulhu5568f452021-11-30 13:31:29 +0800391 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900392 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700393 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700394 }
395
396 class DefaultState extends State {
397 @Override
398 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900399 final ClientInfo cInfo;
400 final int clientId = msg.arg2;
Irfan Sheriff75006652012-04-17 23:15:29 -0700401 switch (msg.what) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900402 case NsdManager.REGISTER_CLIENT:
Paul Hu2e0a88c2023-03-09 16:05:01 +0800403 final ConnectorArgs arg = (ConnectorArgs) msg.obj;
404 final INsdManagerCallback cb = arg.callback;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900405 try {
Paul Hu2e0a88c2023-03-09 16:05:01 +0800406 cb.asBinder().linkToDeath(arg.connector, 0);
Paul Hub2e67d32023-04-18 05:50:14 +0000407 final String tag = "Client" + arg.uid + "-" + mClientNumberId++;
408 cInfo = new ClientInfo(cb, arg.useJavaBackend,
409 mServiceLogs.forSubComponent(tag));
Paul Hu2e0a88c2023-03-09 16:05:01 +0800410 mClients.put(arg.connector, cInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900411 } catch (RemoteException e) {
412 Log.w(TAG, "Client " + clientId + " has already died");
Irfan Sheriff75006652012-04-17 23:15:29 -0700413 }
414 break;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900415 case NsdManager.UNREGISTER_CLIENT:
416 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
417 cInfo = mClients.remove(connector);
Dave Plattfeff2af2014-03-07 14:48:22 -0800418 if (cInfo != null) {
419 cInfo.expungeAllRequests();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900420 if (cInfo.isPreSClient()) {
Luke Huangf7277ed2021-07-12 21:15:10 +0800421 mLegacyClientCount -= 1;
422 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800423 }
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900424 maybeStopMonitoringSocketsIfNoActiveRequest();
Luke Huangf7277ed2021-07-12 21:15:10 +0800425 maybeScheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700426 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700427 case NsdManager.DISCOVER_SERVICES:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900428 cInfo = getClientInfoForReply(msg);
429 if (cInfo != null) {
430 cInfo.onDiscoverServicesFailed(
431 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
432 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700433 break;
434 case NsdManager.STOP_DISCOVERY:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900435 cInfo = getClientInfoForReply(msg);
436 if (cInfo != null) {
437 cInfo.onStopDiscoveryFailed(
438 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
439 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700440 break;
441 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900442 cInfo = getClientInfoForReply(msg);
443 if (cInfo != null) {
444 cInfo.onRegisterServiceFailed(
445 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
446 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700447 break;
448 case NsdManager.UNREGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900449 cInfo = getClientInfoForReply(msg);
450 if (cInfo != null) {
451 cInfo.onUnregisterServiceFailed(
452 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
453 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700454 break;
455 case NsdManager.RESOLVE_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900456 cInfo = getClientInfoForReply(msg);
457 if (cInfo != null) {
458 cInfo.onResolveServiceFailed(
459 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
460 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700461 break;
Paul Hub58deb72022-12-26 09:24:42 +0000462 case NsdManager.STOP_RESOLUTION:
463 cInfo = getClientInfoForReply(msg);
464 if (cInfo != null) {
465 cInfo.onStopResolutionFailed(
466 clientId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
467 }
468 break;
Paul Hu18aeccc2022-12-27 08:48:48 +0000469 case NsdManager.REGISTER_SERVICE_CALLBACK:
470 cInfo = getClientInfoForReply(msg);
471 if (cInfo != null) {
472 cInfo.onServiceInfoCallbackRegistrationFailed(
473 clientId, NsdManager.FAILURE_BAD_PARAMETERS);
474 }
475 break;
Luke Huang05298582021-06-13 16:52:05 +0000476 case NsdManager.DAEMON_CLEANUP:
paulhu2b9ed952022-02-10 21:58:32 +0800477 maybeStopDaemon();
Luke Huang05298582021-06-13 16:52:05 +0000478 break;
Luke Huangf7277ed2021-07-12 21:15:10 +0800479 // This event should be only sent by the legacy (target SDK < S) clients.
480 // Mark the sending client as legacy.
481 case NsdManager.DAEMON_STARTUP:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900482 cInfo = getClientInfoForReply(msg);
Luke Huangf7277ed2021-07-12 21:15:10 +0800483 if (cInfo != null) {
484 cancelStop();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900485 cInfo.setPreSClient();
Luke Huangf7277ed2021-07-12 21:15:10 +0800486 mLegacyClientCount += 1;
487 maybeStartDaemon();
488 }
489 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700490 default:
paulhub2225702021-11-17 09:35:33 +0800491 Log.e(TAG, "Unhandled " + msg);
Irfan Sheriff75006652012-04-17 23:15:29 -0700492 return NOT_HANDLED;
493 }
494 return HANDLED;
495 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900496
497 private ClientInfo getClientInfoForReply(Message msg) {
498 final ListenerArgs args = (ListenerArgs) msg.obj;
499 return mClients.get(args.connector);
500 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700501 }
502
Irfan Sheriff75006652012-04-17 23:15:29 -0700503 class EnabledState extends State {
504 @Override
505 public void enter() {
506 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700507 }
508
509 @Override
510 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000511 // TODO: it is incorrect to stop the daemon without expunging all requests
512 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000513 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700514 }
515
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700516 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900517 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800518 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700519 return true;
520 }
521 return false;
522 }
523
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900524 private void storeLegacyRequestMap(int clientId, int globalId, ClientInfo clientInfo,
525 int what) {
526 clientInfo.mClientRequests.put(clientId, new LegacyClientRequest(globalId, what));
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700527 mIdToClientInfoMap.put(globalId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000528 // Remove the cleanup event because here comes a new request.
529 cancelStop();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700530 }
531
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900532 private void storeAdvertiserRequestMap(int clientId, int globalId,
Paul Hu23fa2022023-01-13 22:57:24 +0800533 ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900534 clientInfo.mClientRequests.put(clientId, new AdvertiserClientRequest(globalId));
535 mIdToClientInfoMap.put(globalId, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800536 }
537
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900538 private void removeRequestMap(int clientId, int globalId, ClientInfo clientInfo) {
539 final ClientRequest existing = clientInfo.mClientRequests.get(clientId);
540 if (existing == null) return;
541 clientInfo.mClientRequests.remove(clientId);
542 mIdToClientInfoMap.remove(globalId);
543
544 if (existing instanceof LegacyClientRequest) {
545 maybeScheduleStop();
546 } else {
547 maybeStopMonitoringSocketsIfNoActiveRequest();
548 }
549 }
550
551 private void storeDiscoveryManagerRequestMap(int clientId, int globalId,
552 MdnsListener listener, ClientInfo clientInfo) {
553 clientInfo.mClientRequests.put(clientId,
554 new DiscoveryManagerRequest(globalId, listener));
555 mIdToClientInfoMap.put(globalId, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800556 }
557
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900558 /**
559 * Truncate a service name to up to 63 UTF-8 bytes.
560 *
561 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
562 * names used in registerService follows historical behavior (see mdnsresponder
563 * handle_regservice_request).
564 */
565 @NonNull
566 private String truncateServiceName(@NonNull String originalName) {
Yuyang Huangde802c82023-05-02 17:14:22 +0900567 return MdnsUtils.truncateServiceName(originalName, MAX_LABEL_LENGTH);
Paul Hu23fa2022023-01-13 22:57:24 +0800568 }
569
Paul Hue4f5f252023-02-16 21:13:47 +0800570 private void stopDiscoveryManagerRequest(ClientRequest request, int clientId, int id,
571 ClientInfo clientInfo) {
572 clientInfo.unregisterMdnsListenerFromRequest(request);
573 removeRequestMap(clientId, id, clientInfo);
574 }
575
Irfan Sheriff75006652012-04-17 23:15:29 -0700576 @Override
577 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900578 final ClientInfo clientInfo;
579 final int id;
580 final int clientId = msg.arg2;
581 final ListenerArgs args;
Irfan Sheriff75006652012-04-17 23:15:29 -0700582 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800583 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800584 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900585 args = (ListenerArgs) msg.obj;
586 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000587 // If the binder death notification for a INsdManagerCallback was received
588 // before any calls are received by NsdService, the clientInfo would be
589 // cleared and cause NPE. Add a null check here to prevent this corner case.
590 if (clientInfo == null) {
591 Log.e(TAG, "Unknown connector in discovery");
592 break;
593 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700594
595 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900596 clientInfo.onDiscoverServicesFailed(
597 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriff75006652012-04-17 23:15:29 -0700598 break;
599 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700600
Paul Hu23fa2022023-01-13 22:57:24 +0800601 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700602 id = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900603 final Pair<String, String> typeAndSubtype =
604 parseTypeAndSubtype(info.getServiceType());
605 final String serviceType = typeAndSubtype == null
606 ? null : typeAndSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800607 if (clientInfo.mUseJavaBackend
608 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900609 || useDiscoveryManagerForType(serviceType)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800610 if (serviceType == null) {
611 clientInfo.onDiscoverServicesFailed(clientId,
612 NsdManager.FAILURE_INTERNAL_ERROR);
613 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700614 }
Paul Hu23fa2022023-01-13 22:57:24 +0800615
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900616 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800617 maybeStartMonitoringSockets();
618 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900619 new DiscoveryListener(clientId, id, info, listenServiceType);
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900620 final MdnsSearchOptions.Builder optionsBuilder =
621 MdnsSearchOptions.newBuilder()
622 .setNetwork(info.getNetwork())
623 .setIsPassiveMode(true);
624 if (typeAndSubtype.second != null) {
625 // The parsing ensures subtype starts with an underscore.
626 // MdnsSearchOptions expects the underscore to not be present.
627 optionsBuilder.addSubtype(typeAndSubtype.second.substring(1));
628 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900629 mMdnsDiscoveryManager.registerListener(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900630 listenServiceType, listener, optionsBuilder.build());
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900631 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800632 clientInfo.onDiscoverServicesStarted(clientId, info);
Paul Hub2e67d32023-04-18 05:50:14 +0000633 clientInfo.log("Register a DiscoveryListener " + id
634 + " for service type:" + listenServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700635 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800636 maybeStartDaemon();
637 if (discoverServices(id, info)) {
638 if (DBG) {
639 Log.d(TAG, "Discover " + msg.arg2 + " " + id
640 + info.getServiceType());
641 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900642 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu23fa2022023-01-13 22:57:24 +0800643 clientInfo.onDiscoverServicesStarted(clientId, info);
644 } else {
645 stopServiceDiscovery(id);
646 clientInfo.onDiscoverServicesFailed(clientId,
647 NsdManager.FAILURE_INTERNAL_ERROR);
648 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700649 }
650 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800651 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900652 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800653 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900654 args = (ListenerArgs) msg.obj;
655 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000656 // If the binder death notification for a INsdManagerCallback was received
657 // before any calls are received by NsdService, the clientInfo would be
658 // cleared and cause NPE. Add a null check here to prevent this corner case.
659 if (clientInfo == null) {
660 Log.e(TAG, "Unknown connector in stop discovery");
661 break;
662 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700663
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900664 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
665 if (request == null) {
666 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700667 break;
668 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900669 id = request.mGlobalId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900670 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
671 // point, so this needs to check the type of the original request to
672 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900673 if (request instanceof DiscoveryManagerRequest) {
Paul Hue4f5f252023-02-16 21:13:47 +0800674 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900675 clientInfo.onStopDiscoverySucceeded(clientId);
Paul Hub2e67d32023-04-18 05:50:14 +0000676 clientInfo.log("Unregister the DiscoveryListener " + id);
Irfan Sheriff75006652012-04-17 23:15:29 -0700677 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800678 removeRequestMap(clientId, id, clientInfo);
679 if (stopServiceDiscovery(id)) {
680 clientInfo.onStopDiscoverySucceeded(clientId);
681 } else {
682 clientInfo.onStopDiscoveryFailed(
683 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
684 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700685 }
686 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900687 }
688 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800689 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900690 args = (ListenerArgs) msg.obj;
691 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000692 // If the binder death notification for a INsdManagerCallback was received
693 // before any calls are received by NsdService, the clientInfo would be
694 // cleared and cause NPE. Add a null check here to prevent this corner case.
695 if (clientInfo == null) {
696 Log.e(TAG, "Unknown connector in registration");
697 break;
698 }
699
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700700 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900701 clientInfo.onRegisterServiceFailed(
702 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700703 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700704 }
705
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700706 id = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900707 final NsdServiceInfo serviceInfo = args.serviceInfo;
708 final String serviceType = serviceInfo.getServiceType();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900709 final Pair<String, String> typeSubtype = parseTypeAndSubtype(serviceType);
710 final String registerServiceType = typeSubtype == null
711 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800712 if (clientInfo.mUseJavaBackend
713 || mDeps.isMdnsAdvertiserEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900714 || useAdvertiserForType(registerServiceType)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900715 if (registerServiceType == null) {
716 Log.e(TAG, "Invalid service type: " + serviceType);
717 clientInfo.onRegisterServiceFailed(clientId,
718 NsdManager.FAILURE_INTERNAL_ERROR);
719 break;
720 }
721 serviceInfo.setServiceType(registerServiceType);
722 serviceInfo.setServiceName(truncateServiceName(
723 serviceInfo.getServiceName()));
724
725 maybeStartMonitoringSockets();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900726 // TODO: pass in the subtype as well. Including the subtype in the
727 // service type would generate service instance names like
728 // Name._subtype._sub._type._tcp, which is incorrect
729 // (it should be Name._type._tcp).
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900730 mAdvertiser.addService(id, serviceInfo);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900731 storeAdvertiserRequestMap(clientId, id, clientInfo);
Irfan Sheriff75006652012-04-17 23:15:29 -0700732 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900733 maybeStartDaemon();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900734 if (registerService(id, serviceInfo)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900735 if (DBG) Log.d(TAG, "Register " + clientId + " " + id);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900736 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900737 // Return success after mDns reports success
738 } else {
739 unregisterService(id);
740 clientInfo.onRegisterServiceFailed(
741 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
742 }
743
Irfan Sheriff75006652012-04-17 23:15:29 -0700744 }
745 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900746 }
747 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800748 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900749 args = (ListenerArgs) msg.obj;
750 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000751 // If the binder death notification for a INsdManagerCallback was received
752 // before any calls are received by NsdService, the clientInfo would be
753 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900754 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800755 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700756 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700757 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900758 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
759 if (request == null) {
760 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
761 break;
762 }
763 id = request.mGlobalId;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900764 removeRequestMap(clientId, id, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900765
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900766 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
767 // so this needs to check the type of the original request to unregister
768 // instead of looking at the flag value.
769 if (request instanceof AdvertiserClientRequest) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900770 mAdvertiser.removeService(id);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900771 clientInfo.onUnregisterServiceSucceeded(clientId);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700772 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900773 if (unregisterService(id)) {
774 clientInfo.onUnregisterServiceSucceeded(clientId);
775 } else {
776 clientInfo.onUnregisterServiceFailed(
777 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
778 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700779 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700780 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900781 }
Paul Hu75069ed2023-01-14 00:31:09 +0800782 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800783 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900784 args = (ListenerArgs) msg.obj;
785 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000786 // If the binder death notification for a INsdManagerCallback was received
787 // before any calls are received by NsdService, the clientInfo would be
788 // cleared and cause NPE. Add a null check here to prevent this corner case.
789 if (clientInfo == null) {
790 Log.e(TAG, "Unknown connector in resolution");
791 break;
792 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700793
Paul Hu75069ed2023-01-14 00:31:09 +0800794 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700795 id = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900796 final Pair<String, String> typeSubtype =
797 parseTypeAndSubtype(info.getServiceType());
798 final String serviceType = typeSubtype == null
799 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800800 if (clientInfo.mUseJavaBackend
801 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900802 || useDiscoveryManagerForType(serviceType)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800803 if (serviceType == null) {
804 clientInfo.onResolveServiceFailed(clientId,
805 NsdManager.FAILURE_INTERNAL_ERROR);
806 break;
807 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900808 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +0800809
810 maybeStartMonitoringSockets();
811 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900812 new ResolutionListener(clientId, id, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800813 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
814 .setNetwork(info.getNetwork())
815 .setIsPassiveMode(true)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900816 .setResolveInstanceName(info.getServiceName())
Paul Hu75069ed2023-01-14 00:31:09 +0800817 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900818 mMdnsDiscoveryManager.registerListener(
819 resolveServiceType, listener, options);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900820 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Paul Hub2e67d32023-04-18 05:50:14 +0000821 clientInfo.log("Register a ResolutionListener " + id
822 + " for service type:" + resolveServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700823 } else {
Paul Hu75069ed2023-01-14 00:31:09 +0800824 if (clientInfo.mResolvedService != null) {
825 clientInfo.onResolveServiceFailed(
826 clientId, NsdManager.FAILURE_ALREADY_ACTIVE);
827 break;
828 }
829
830 maybeStartDaemon();
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900831 if (resolveService(id, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800832 clientInfo.mResolvedService = new NsdServiceInfo();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900833 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu75069ed2023-01-14 00:31:09 +0800834 } else {
835 clientInfo.onResolveServiceFailed(
836 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
837 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700838 }
839 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800840 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900841 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +0000842 if (DBG) Log.d(TAG, "Stop service resolution");
843 args = (ListenerArgs) msg.obj;
844 clientInfo = mClients.get(args.connector);
845 // If the binder death notification for a INsdManagerCallback was received
846 // before any calls are received by NsdService, the clientInfo would be
847 // cleared and cause NPE. Add a null check here to prevent this corner case.
848 if (clientInfo == null) {
849 Log.e(TAG, "Unknown connector in stop resolution");
850 break;
851 }
852
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900853 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
854 if (request == null) {
855 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
856 break;
857 }
858 id = request.mGlobalId;
Paul Hue4f5f252023-02-16 21:13:47 +0800859 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
860 // point, so this needs to check the type of the original request to
861 // unregister instead of looking at the flag value.
862 if (request instanceof DiscoveryManagerRequest) {
863 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Paul Hub58deb72022-12-26 09:24:42 +0000864 clientInfo.onStopResolutionSucceeded(clientId);
Paul Hub2e67d32023-04-18 05:50:14 +0000865 clientInfo.log("Unregister the ResolutionListener " + id);
Paul Hub58deb72022-12-26 09:24:42 +0000866 } else {
Paul Hue4f5f252023-02-16 21:13:47 +0800867 removeRequestMap(clientId, id, clientInfo);
868 if (stopResolveService(id)) {
869 clientInfo.onStopResolutionSucceeded(clientId);
870 } else {
871 clientInfo.onStopResolutionFailed(
872 clientId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
873 }
874 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +0000875 }
Paul Hub58deb72022-12-26 09:24:42 +0000876 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900877 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000878 case NsdManager.REGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +0000879 if (DBG) Log.d(TAG, "Register a service callback");
880 args = (ListenerArgs) msg.obj;
881 clientInfo = mClients.get(args.connector);
882 // If the binder death notification for a INsdManagerCallback was received
883 // before any calls are received by NsdService, the clientInfo would be
884 // cleared and cause NPE. Add a null check here to prevent this corner case.
885 if (clientInfo == null) {
886 Log.e(TAG, "Unknown connector in callback registration");
887 break;
888 }
889
Paul Hu30bd70d2023-02-07 13:20:56 +0000890 final NsdServiceInfo info = args.serviceInfo;
891 id = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900892 final Pair<String, String> typeAndSubtype =
893 parseTypeAndSubtype(info.getServiceType());
894 final String serviceType = typeAndSubtype == null
895 ? null : typeAndSubtype.first;
Paul Hu30bd70d2023-02-07 13:20:56 +0000896 if (serviceType == null) {
897 clientInfo.onServiceInfoCallbackRegistrationFailed(clientId,
898 NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +0000899 break;
900 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000901 final String resolveServiceType = serviceType + ".local";
Paul Hu18aeccc2022-12-27 08:48:48 +0000902
Paul Hu30bd70d2023-02-07 13:20:56 +0000903 maybeStartMonitoringSockets();
904 final MdnsListener listener =
905 new ServiceInfoListener(clientId, id, info, resolveServiceType);
906 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
907 .setNetwork(info.getNetwork())
908 .setIsPassiveMode(true)
909 .setResolveInstanceName(info.getServiceName())
910 .build();
911 mMdnsDiscoveryManager.registerListener(
912 resolveServiceType, listener, options);
913 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Paul Hub2e67d32023-04-18 05:50:14 +0000914 clientInfo.log("Register a ServiceInfoListener " + id
915 + " for service type:" + resolveServiceType);
Paul Hu18aeccc2022-12-27 08:48:48 +0000916 break;
Paul Hu30bd70d2023-02-07 13:20:56 +0000917 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900918 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +0000919 if (DBG) Log.d(TAG, "Unregister a service callback");
920 args = (ListenerArgs) msg.obj;
921 clientInfo = mClients.get(args.connector);
922 // If the binder death notification for a INsdManagerCallback was received
923 // before any calls are received by NsdService, the clientInfo would be
924 // cleared and cause NPE. Add a null check here to prevent this corner case.
925 if (clientInfo == null) {
926 Log.e(TAG, "Unknown connector in callback unregistration");
927 break;
928 }
929
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900930 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
931 if (request == null) {
Paul Hu30bd70d2023-02-07 13:20:56 +0000932 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE_CALLBACK");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900933 break;
934 }
935 id = request.mGlobalId;
Paul Hu30bd70d2023-02-07 13:20:56 +0000936 if (request instanceof DiscoveryManagerRequest) {
937 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Paul Hu18aeccc2022-12-27 08:48:48 +0000938 clientInfo.onServiceInfoCallbackUnregistered(clientId);
Paul Hub2e67d32023-04-18 05:50:14 +0000939 clientInfo.log("Unregister the ServiceInfoListener " + id);
Paul Hu18aeccc2022-12-27 08:48:48 +0000940 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +0000941 loge("Unregister failed with non-DiscoveryManagerRequest.");
Paul Hu18aeccc2022-12-27 08:48:48 +0000942 }
Paul Hu18aeccc2022-12-27 08:48:48 +0000943 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900944 }
paulhu2b9ed952022-02-10 21:58:32 +0800945 case MDNS_SERVICE_EVENT:
946 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +0900947 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700948 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700949 break;
Paul Hu019621e2023-01-13 23:26:49 +0800950 case MDNS_DISCOVERY_MANAGER_EVENT:
951 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
952 return NOT_HANDLED;
953 }
954 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700955 default:
Hugo Benichif0c84092017-04-05 14:43:29 +0900956 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700957 }
Hugo Benichif0c84092017-04-05 14:43:29 +0900958 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700959 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700960
paulhu2b9ed952022-02-10 21:58:32 +0800961 private boolean handleMDnsServiceEvent(int code, int id, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700962 NsdServiceInfo servInfo;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700963 ClientInfo clientInfo = mIdToClientInfoMap.get(id);
964 if (clientInfo == null) {
paulhu2b9ed952022-02-10 21:58:32 +0800965 Log.e(TAG, String.format("id %d for %d has no client mapping", id, code));
Hugo Benichif0c84092017-04-05 14:43:29 +0900966 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700967 }
968
969 /* This goes in response as msg.arg2 */
Christopher Lane74411222014-04-25 18:39:07 -0700970 int clientId = clientInfo.getClientId(id);
971 if (clientId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -0700972 // This can happen because of race conditions. For example,
973 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
974 // and we may get in this situation.
paulhu2b9ed952022-02-10 21:58:32 +0800975 Log.d(TAG, String.format("%d for listener id %d that is no longer active",
976 code, id));
Hugo Benichif0c84092017-04-05 14:43:29 +0900977 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700978 }
Hugo Benichi32be63d2017-04-05 14:06:11 +0900979 if (DBG) {
paulhu2b9ed952022-02-10 21:58:32 +0800980 Log.d(TAG, String.format("MDns service event code:%d id=%d", code, id));
Hugo Benichi32be63d2017-04-05 14:06:11 +0900981 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700982 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +0800983 case IMDnsEventListener.SERVICE_FOUND: {
984 final DiscoveryInfo info = (DiscoveryInfo) obj;
985 final String name = info.serviceName;
986 final String type = info.registrationType;
987 servInfo = new NsdServiceInfo(name, type);
988 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900989 if (foundNetId == 0L) {
990 // Ignore services that do not have a Network: they are not usable
991 // by apps, as they would need privileged permissions to use
992 // interfaces that do not have an associated Network.
993 break;
994 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +0900995 if (foundNetId == INetd.DUMMY_NET_ID) {
996 // Ignore services on the dummy0 interface: they are only seen when
997 // discovering locally advertised services, and are not reachable
998 // through that interface.
999 break;
1000 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001001 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001002 clientInfo.onServiceFound(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001003 break;
paulhu2b9ed952022-02-10 21:58:32 +08001004 }
1005 case IMDnsEventListener.SERVICE_LOST: {
1006 final DiscoveryInfo info = (DiscoveryInfo) obj;
1007 final String name = info.serviceName;
1008 final String type = info.registrationType;
1009 final int lostNetId = info.netId;
1010 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001011 // The network could be set to null (netId 0) if it was torn down when the
1012 // service is lost
1013 // TODO: avoid returning null in that case, possibly by remembering
1014 // found services on the same interface index and their network at the time
1015 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001016 clientInfo.onServiceLost(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001017 break;
paulhu2b9ed952022-02-10 21:58:32 +08001018 }
1019 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001020 clientInfo.onDiscoverServicesFailed(
1021 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001022 break;
paulhu2b9ed952022-02-10 21:58:32 +08001023 case IMDnsEventListener.SERVICE_REGISTERED: {
1024 final RegistrationInfo info = (RegistrationInfo) obj;
1025 final String name = info.serviceName;
1026 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001027 clientInfo.onRegisterServiceSucceeded(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001028 break;
paulhu2b9ed952022-02-10 21:58:32 +08001029 }
1030 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001031 clientInfo.onRegisterServiceFailed(
1032 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001033 break;
paulhu2b9ed952022-02-10 21:58:32 +08001034 case IMDnsEventListener.SERVICE_RESOLVED: {
1035 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001036 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +08001037 final String fullName = info.serviceFullName;
1038 while (index < fullName.length() && fullName.charAt(index) != '.') {
1039 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001040 ++index;
1041 }
1042 ++index;
1043 }
paulhu2b9ed952022-02-10 21:58:32 +08001044 if (index >= fullName.length()) {
1045 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001046 break;
1047 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001048
paulhube186602022-04-12 07:18:23 +00001049 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001050 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001051 String type = rest.replace(".local.", "");
1052
Paul Hu30bd70d2023-02-07 13:20:56 +00001053 final NsdServiceInfo serviceInfo = clientInfo.mResolvedService;
Paul Hu18aeccc2022-12-27 08:48:48 +00001054 serviceInfo.setServiceName(name);
1055 serviceInfo.setServiceType(type);
1056 serviceInfo.setPort(info.port);
1057 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001058 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001059
1060 stopResolveService(id);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001061 removeRequestMap(clientId, id, clientInfo);
1062
paulhu2b9ed952022-02-10 21:58:32 +08001063 final int id2 = getUniqueId();
1064 if (getAddrInfo(id2, info.hostname, info.interfaceIdx)) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001065 storeLegacyRequestMap(clientId, id2, clientInfo,
1066 NsdManager.RESOLVE_SERVICE);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001067 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001068 clientInfo.onResolveServiceFailed(
1069 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1070 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001071 }
1072 break;
paulhu2b9ed952022-02-10 21:58:32 +08001073 }
1074 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001075 /* NNN resolveId errorCode */
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001076 stopResolveService(id);
1077 removeRequestMap(clientId, id, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001078 clientInfo.onResolveServiceFailed(
1079 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1080 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001081 break;
paulhu2b9ed952022-02-10 21:58:32 +08001082 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001083 /* NNN resolveId errorCode */
1084 stopGetAddrInfo(id);
1085 removeRequestMap(clientId, id, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001086 clientInfo.onResolveServiceFailed(
1087 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1088 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001089 break;
paulhu2b9ed952022-02-10 21:58:32 +08001090 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001091 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001092 final GetAddressInfo info = (GetAddressInfo) obj;
1093 final String address = info.address;
1094 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001095 InetAddress serviceHost = null;
1096 try {
paulhu2b9ed952022-02-10 21:58:32 +08001097 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001098 } catch (UnknownHostException e) {
1099 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1100 }
1101
1102 // If the resolved service is on an interface without a network, consider it
1103 // as a failure: it would not be usable by apps as they would need
1104 // privileged permissions.
Paul Hu30bd70d2023-02-07 13:20:56 +00001105 if (netId != NETID_UNSET && serviceHost != null) {
1106 clientInfo.mResolvedService.setHost(serviceHost);
1107 setServiceNetworkForCallback(clientInfo.mResolvedService,
1108 netId, info.interfaceIdx);
1109 clientInfo.onResolveServiceSucceeded(
1110 clientId, clientInfo.mResolvedService);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001111 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001112 clientInfo.onResolveServiceFailed(
1113 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001114 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001115 stopGetAddrInfo(id);
1116 removeRequestMap(clientId, id, clientInfo);
1117 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001118 break;
paulhu2b9ed952022-02-10 21:58:32 +08001119 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001120 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001121 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001122 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001123 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001124 }
Paul Hu019621e2023-01-13 23:26:49 +08001125
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001126 @Nullable
1127 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(
1128 final MdnsEvent event, int code) {
Paul Hu019621e2023-01-13 23:26:49 +08001129 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001130 final String[] typeArray = serviceInfo.getServiceType();
1131 final String joinedType;
1132 if (typeArray.length == 0
1133 || !typeArray[typeArray.length - 1].equals(LOCAL_DOMAIN_NAME)) {
1134 Log.wtf(TAG, "MdnsServiceInfo type does not end in .local: "
1135 + Arrays.toString(typeArray));
1136 return null;
1137 } else {
1138 joinedType = TextUtils.join(".",
1139 Arrays.copyOfRange(typeArray, 0, typeArray.length - 1));
1140 }
1141 final String serviceType;
1142 switch (code) {
1143 case NsdManager.SERVICE_FOUND:
1144 case NsdManager.SERVICE_LOST:
1145 // For consistency with historical behavior, discovered service types have
1146 // a dot at the end.
1147 serviceType = joinedType + ".";
1148 break;
1149 case RESOLVE_SERVICE_SUCCEEDED:
1150 // For consistency with historical behavior, resolved service types have
1151 // a dot at the beginning.
1152 serviceType = "." + joinedType;
1153 break;
1154 default:
1155 serviceType = joinedType;
1156 break;
1157 }
Paul Hu019621e2023-01-13 23:26:49 +08001158 final String serviceName = serviceInfo.getServiceInstanceName();
1159 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1160 final Network network = serviceInfo.getNetwork();
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001161 // In MdnsDiscoveryManagerEvent, the Network can be null which means it is a
1162 // network for Tethering interface. In other words, the network == null means the
1163 // network has netId = INetd.LOCAL_NET_ID.
Paul Hu019621e2023-01-13 23:26:49 +08001164 setServiceNetworkForCallback(
1165 servInfo,
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001166 network == null ? INetd.LOCAL_NET_ID : network.netId,
Paul Hu019621e2023-01-13 23:26:49 +08001167 serviceInfo.getInterfaceIndex());
1168 return servInfo;
1169 }
1170
1171 private boolean handleMdnsDiscoveryManagerEvent(
1172 int transactionId, int code, Object obj) {
1173 final ClientInfo clientInfo = mIdToClientInfoMap.get(transactionId);
1174 if (clientInfo == null) {
1175 Log.e(TAG, String.format(
1176 "id %d for %d has no client mapping", transactionId, code));
1177 return false;
1178 }
1179
1180 final MdnsEvent event = (MdnsEvent) obj;
1181 final int clientId = event.mClientId;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001182 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event, code);
1183 // Errors are already logged if null
1184 if (info == null) return false;
Paul Hu019621e2023-01-13 23:26:49 +08001185 if (DBG) {
1186 Log.d(TAG, String.format("MdnsDiscoveryManager event code=%s transactionId=%d",
1187 NsdManager.nameOf(code), transactionId));
1188 }
1189 switch (code) {
1190 case NsdManager.SERVICE_FOUND:
Paul Hu319751a2023-01-13 23:56:34 +08001191 clientInfo.onServiceFound(clientId, info);
1192 break;
1193 case NsdManager.SERVICE_LOST:
1194 clientInfo.onServiceLost(clientId, info);
Paul Hu019621e2023-01-13 23:26:49 +08001195 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001196 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001197 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
1198 if (request == null) {
1199 Log.e(TAG, "Unknown client request in RESOLVE_SERVICE_SUCCEEDED");
1200 break;
1201 }
Paul Hu75069ed2023-01-14 00:31:09 +08001202 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Paul Hu75069ed2023-01-14 00:31:09 +08001203 info.setPort(serviceInfo.getPort());
1204
1205 Map<String, String> attrs = serviceInfo.getAttributes();
1206 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1207 final String key = kv.getKey();
1208 try {
1209 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1210 } catch (IllegalArgumentException e) {
1211 Log.e(TAG, "Invalid attribute", e);
1212 }
1213 }
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001214 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu2b865912023-03-06 14:27:53 +08001215 if (addresses.size() != 0) {
1216 info.setHostAddresses(addresses);
Paul Hu75069ed2023-01-14 00:31:09 +08001217 clientInfo.onResolveServiceSucceeded(clientId, info);
Paul Hu2b865912023-03-06 14:27:53 +08001218 } else {
1219 // No address. Notify resolution failure.
Paul Hu75069ed2023-01-14 00:31:09 +08001220 clientInfo.onResolveServiceFailed(
1221 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1222 }
1223
1224 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001225 if (!(request instanceof DiscoveryManagerRequest)) {
1226 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1227 break;
1228 }
Paul Hue4f5f252023-02-16 21:13:47 +08001229 stopDiscoveryManagerRequest(request, clientId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001230 break;
1231 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001232 case NsdManager.SERVICE_UPDATED: {
1233 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1234 info.setPort(serviceInfo.getPort());
1235
1236 Map<String, String> attrs = serviceInfo.getAttributes();
1237 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1238 final String key = kv.getKey();
1239 try {
1240 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1241 } catch (IllegalArgumentException e) {
1242 Log.e(TAG, "Invalid attribute", e);
1243 }
1244 }
1245
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001246 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001247 info.setHostAddresses(addresses);
1248 clientInfo.onServiceUpdated(clientId, info);
1249 break;
1250 }
1251 case NsdManager.SERVICE_UPDATED_LOST:
1252 clientInfo.onServiceUpdatedLost(clientId);
1253 break;
Paul Hu019621e2023-01-13 23:26:49 +08001254 default:
1255 return false;
1256 }
1257 return true;
1258 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001259 }
1260 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001261
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001262 @NonNull
1263 private static List<InetAddress> getInetAddresses(@NonNull MdnsServiceInfo serviceInfo) {
1264 final List<String> v4Addrs = serviceInfo.getIpv4Addresses();
1265 final List<String> v6Addrs = serviceInfo.getIpv6Addresses();
1266 final List<InetAddress> addresses = new ArrayList<>(v4Addrs.size() + v6Addrs.size());
1267 for (String ipv4Address : v4Addrs) {
1268 try {
1269 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1270 } catch (IllegalArgumentException e) {
1271 Log.wtf(TAG, "Invalid ipv4 address", e);
1272 }
1273 }
1274 for (String ipv6Address : v6Addrs) {
1275 try {
Yuyang Huanga6a6ff92023-04-24 13:33:34 +09001276 final Inet6Address addr = (Inet6Address) InetAddresses.parseNumericAddress(
1277 ipv6Address);
1278 addresses.add(InetAddressUtils.withScopeId(addr, serviceInfo.getInterfaceIndex()));
1279 } catch (IllegalArgumentException e) {
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001280 Log.wtf(TAG, "Invalid ipv6 address", e);
1281 }
1282 }
1283 return addresses;
1284 }
1285
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001286 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1287 switch (netId) {
1288 case NETID_UNSET:
1289 info.setNetwork(null);
1290 break;
1291 case INetd.LOCAL_NET_ID:
1292 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1293 // visible / usable for apps, so do not return it. Store the interface
1294 // index instead, so at least if the client tries to resolve the service
1295 // with that NsdServiceInfo, it will be done on the same interface.
1296 // If they recreate the NsdServiceInfo themselves, resolution would be
1297 // done on all interfaces as before T, which should also work.
1298 info.setNetwork(null);
1299 info.setInterfaceIndex(ifaceIdx);
1300 break;
1301 default:
1302 info.setNetwork(new Network(netId));
1303 }
1304 }
1305
paulhube186602022-04-12 07:18:23 +00001306 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1307 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1308 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1309 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1310 private String unescape(String s) {
1311 StringBuilder sb = new StringBuilder(s.length());
1312 for (int i = 0; i < s.length(); ++i) {
1313 char c = s.charAt(i);
1314 if (c == '\\') {
1315 if (++i >= s.length()) {
1316 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1317 break;
1318 }
1319 c = s.charAt(i);
1320 if (c != '.' && c != '\\') {
1321 if (i + 2 >= s.length()) {
1322 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1323 break;
1324 }
1325 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1326 + (s.charAt(i + 2) - '0'));
1327 i += 2;
1328 }
1329 }
1330 sb.append(c);
1331 }
1332 return sb.toString();
1333 }
1334
Paul Hu7445e3d2023-03-03 15:14:00 +08001335 /**
1336 * Check the given service type is valid and construct it to a service type
1337 * which can use for discovery / resolution service.
1338 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001339 * <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 +08001340 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1341 * underscore; they are alphanumerical characters or dashes or underscore, except the
1342 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1343 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001344 * <p>The subtype may also be specified with a comma after the service type, for example
1345 * _type._tcp,_subtype.
1346 *
Paul Hu7445e3d2023-03-03 15:14:00 +08001347 * @param serviceType the request service type for discovery / resolution service
1348 * @return constructed service type or null if the given service type is invalid.
1349 */
1350 @Nullable
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001351 public static Pair<String, String> parseTypeAndSubtype(String serviceType) {
Paul Hu7445e3d2023-03-03 15:14:00 +08001352 if (TextUtils.isEmpty(serviceType)) return null;
1353
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001354 final String typeOrSubtypePattern = "_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]";
Paul Hu7445e3d2023-03-03 15:14:00 +08001355 final Pattern serviceTypePattern = Pattern.compile(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001356 // Optional leading subtype (_subtype._type._tcp)
1357 // (?: xxx) is a non-capturing parenthesis, don't capture the dot
1358 "^(?:(" + typeOrSubtypePattern + ")\\.)?"
1359 // Actual type (_type._tcp.local)
1360 + "(" + typeOrSubtypePattern + "\\._(?:tcp|udp))"
Paul Hu7445e3d2023-03-03 15:14:00 +08001361 // Drop '.' at the end of service type that is compatible with old backend.
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001362 // e.g. allow "_type._tcp.local."
1363 + "\\.?"
1364 // Optional subtype after comma, for "_type._tcp,_subtype" format
1365 + "(?:,(" + typeOrSubtypePattern + "))?"
1366 + "$");
Paul Hu7445e3d2023-03-03 15:14:00 +08001367 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1368 if (!matcher.matches()) return null;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001369 // Use the subtype either at the beginning or after the comma
1370 final String subtype = matcher.group(1) != null ? matcher.group(1) : matcher.group(3);
1371 return new Pair<>(matcher.group(2), subtype);
Paul Hu7445e3d2023-03-03 15:14:00 +08001372 }
1373
Hugo Benichi803a2f02017-04-24 11:35:06 +09001374 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001375 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001376 this(ctx, handler, cleanupDelayMs, new Dependencies());
1377 }
1378
1379 @VisibleForTesting
1380 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001381 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001382 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001383 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001384 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001385 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1386 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001387 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001388
Paul Hu14667de2023-04-17 22:42:47 +08001389 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper(),
1390 LOGGER.forSubComponent("MdnsSocketProvider"));
Yuyang Huang700778b2023-03-08 16:17:05 +09001391 // Netlink monitor starts on boot, and intentionally never stopped, to ensure that all
1392 // address events are received.
1393 handler.post(mMdnsSocketProvider::startNetLinkMonitor);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001394 mMdnsSocketClient =
1395 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider);
Paul Hu14667de2023-04-17 22:42:47 +08001396 mMdnsDiscoveryManager = deps.makeMdnsDiscoveryManager(new ExecutorProvider(),
1397 mMdnsSocketClient, LOGGER.forSubComponent("MdnsDiscoveryManager"));
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001398 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1399 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
Paul Hu14667de2023-04-17 22:42:47 +08001400 new AdvertiserCallback(), LOGGER.forSubComponent("MdnsAdvertiser"));
Paul Hu4bd98ef2023-01-12 13:42:07 +08001401 }
1402
1403 /**
1404 * Dependencies of NsdService, for injection in tests.
1405 */
1406 @VisibleForTesting
1407 public static class Dependencies {
1408 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001409 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001410 *
1411 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001412 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001413 */
1414 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Motomu Utsumi278db582023-04-21 12:35:22 +09001415 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1416 MDNS_DISCOVERY_MANAGER_VERSION, DeviceConfigUtils.TETHERING_MODULE_NAME,
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +09001417 false /* defaultEnabled */);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001418 }
1419
1420 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001421 * Check whether the MdnsAdvertiser feature is enabled.
1422 *
1423 * @param context The global context information about an app environment.
1424 * @return true if the MdnsAdvertiser feature is enabled.
1425 */
1426 public boolean isMdnsAdvertiserEnabled(Context context) {
Motomu Utsumi278db582023-04-21 12:35:22 +09001427 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1428 MDNS_ADVERTISER_VERSION, DeviceConfigUtils.TETHERING_MODULE_NAME,
1429 false /* defaultEnabled */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001430 }
1431
1432 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001433 * Get the type allowlist flag value.
1434 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1435 */
1436 @Nullable
1437 public String getTypeAllowlistFlags() {
1438 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1439 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1440 }
1441
1442 /**
1443 * @see DeviceConfigUtils#isFeatureEnabled(Context, String, String, String, boolean)
1444 */
1445 public boolean isFeatureEnabled(Context context, String feature) {
1446 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1447 feature, DeviceConfigUtils.TETHERING_MODULE_NAME, false /* defaultEnabled */);
1448 }
1449
1450 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001451 * @see MdnsDiscoveryManager
1452 */
1453 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
Paul Hu14667de2023-04-17 22:42:47 +08001454 @NonNull ExecutorProvider executorProvider,
1455 @NonNull MdnsSocketClientBase socketClient, @NonNull SharedLog sharedLog) {
1456 return new MdnsDiscoveryManager(executorProvider, socketClient, sharedLog);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001457 }
1458
1459 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001460 * @see MdnsAdvertiser
1461 */
1462 public MdnsAdvertiser makeMdnsAdvertiser(
1463 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
Paul Hu14667de2023-04-17 22:42:47 +08001464 @NonNull MdnsAdvertiser.AdvertiserCallback cb, @NonNull SharedLog sharedLog) {
1465 return new MdnsAdvertiser(looper, socketProvider, cb, sharedLog);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001466 }
1467
1468 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001469 * @see MdnsSocketProvider
1470 */
Paul Hu14667de2023-04-17 22:42:47 +08001471 public MdnsSocketProvider makeMdnsSocketProvider(@NonNull Context context,
1472 @NonNull Looper looper, @NonNull SharedLog sharedLog) {
1473 return new MdnsSocketProvider(context, looper, sharedLog);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001474 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001475 }
1476
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001477 /**
1478 * Return whether a type is allowlisted to use the Java backend.
1479 * @param type The service type
1480 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1481 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1482 */
1483 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1484 @NonNull String flagPrefix) {
1485 if (type == null) return false;
1486 final String typesConfig = mDeps.getTypeAllowlistFlags();
1487 if (TextUtils.isEmpty(typesConfig)) return false;
1488
1489 final String mappingPrefix = type + ":";
1490 String mappedFlag = null;
1491 for (String mapping : TextUtils.split(typesConfig, ",")) {
1492 if (mapping.startsWith(mappingPrefix)) {
1493 mappedFlag = mapping.substring(mappingPrefix.length());
1494 break;
1495 }
1496 }
1497
1498 if (mappedFlag == null) return false;
1499
1500 return mDeps.isFeatureEnabled(mContext,
1501 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1502 }
1503
1504 private boolean useDiscoveryManagerForType(@Nullable String type) {
1505 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1506 }
1507
1508 private boolean useAdvertiserForType(@Nullable String type) {
1509 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1510 }
1511
paulhu1b35e822022-04-08 14:48:41 +08001512 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001513 HandlerThread thread = new HandlerThread(TAG);
1514 thread.start();
1515 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001516 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001517 return service;
1518 }
1519
paulhu2b9ed952022-02-10 21:58:32 +08001520 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1521 private final StateMachine mStateMachine;
1522
1523 MDnsEventCallback(StateMachine sm) {
1524 mStateMachine = sm;
1525 }
1526
1527 @Override
1528 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1529 mStateMachine.sendMessage(
1530 MDNS_SERVICE_EVENT, status.result, status.id, status);
1531 }
1532
1533 @Override
1534 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1535 mStateMachine.sendMessage(
1536 MDNS_SERVICE_EVENT, status.result, status.id, status);
1537 }
1538
1539 @Override
1540 public void onServiceResolutionStatus(final ResolutionInfo status) {
1541 mStateMachine.sendMessage(
1542 MDNS_SERVICE_EVENT, status.result, status.id, status);
1543 }
1544
1545 @Override
1546 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1547 mStateMachine.sendMessage(
1548 MDNS_SERVICE_EVENT, status.result, status.id, status);
1549 }
1550
1551 @Override
1552 public int getInterfaceVersion() throws RemoteException {
1553 return this.VERSION;
1554 }
1555
1556 @Override
1557 public String getInterfaceHash() throws RemoteException {
1558 return this.HASH;
1559 }
1560 }
1561
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001562 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
1563 @Override
1564 public void onRegisterServiceSucceeded(int serviceId, NsdServiceInfo registeredInfo) {
1565 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1566 if (clientInfo == null) return;
1567
1568 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1569 if (clientId < 0) return;
1570
1571 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1572 // historical behavior.
1573 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
1574 clientInfo.onRegisterServiceSucceeded(clientId, cbInfo);
1575 }
1576
1577 @Override
1578 public void onRegisterServiceFailed(int serviceId, int errorCode) {
1579 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1580 if (clientInfo == null) return;
1581
1582 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1583 if (clientId < 0) return;
1584
1585 clientInfo.onRegisterServiceFailed(clientId, errorCode);
1586 }
1587
1588 private ClientInfo getClientInfoOrLog(int serviceId) {
1589 final ClientInfo clientInfo = mIdToClientInfoMap.get(serviceId);
1590 if (clientInfo == null) {
1591 Log.e(TAG, String.format("Callback for service %d has no client", serviceId));
1592 }
1593 return clientInfo;
1594 }
1595
1596 private int getClientIdOrLog(@NonNull ClientInfo info, int serviceId) {
1597 final int clientId = info.getClientId(serviceId);
1598 if (clientId < 0) {
1599 Log.e(TAG, String.format("Client ID not found for service %d", serviceId));
1600 }
1601 return clientId;
1602 }
1603 }
1604
Paul Hu2e0a88c2023-03-09 16:05:01 +08001605 private static class ConnectorArgs {
1606 @NonNull public final NsdServiceConnector connector;
1607 @NonNull public final INsdManagerCallback callback;
1608 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001609 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001610
1611 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00001612 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08001613 this.connector = connector;
1614 this.callback = callback;
1615 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001616 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001617 }
1618 }
1619
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001620 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08001621 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001622 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu2e0a88c2023-03-09 16:05:01 +08001623 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001624 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00001625 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
1626 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend,
1627 Binder.getCallingUid())));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001628 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07001629 }
1630
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001631 private static class ListenerArgs {
1632 public final NsdServiceConnector connector;
1633 public final NsdServiceInfo serviceInfo;
1634 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
1635 this.connector = connector;
1636 this.serviceInfo = serviceInfo;
1637 }
1638 }
1639
1640 private class NsdServiceConnector extends INsdServiceConnector.Stub
1641 implements IBinder.DeathRecipient {
1642 @Override
1643 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
1644 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1645 NsdManager.REGISTER_SERVICE, 0, listenerKey,
1646 new ListenerArgs(this, serviceInfo)));
1647 }
1648
1649 @Override
1650 public void unregisterService(int listenerKey) {
1651 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1652 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
1653 new ListenerArgs(this, null)));
1654 }
1655
1656 @Override
1657 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
1658 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1659 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
1660 new ListenerArgs(this, serviceInfo)));
1661 }
1662
1663 @Override
1664 public void stopDiscovery(int listenerKey) {
1665 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1666 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
1667 }
1668
1669 @Override
1670 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
1671 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1672 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
1673 new ListenerArgs(this, serviceInfo)));
1674 }
1675
1676 @Override
Paul Hub58deb72022-12-26 09:24:42 +00001677 public void stopResolution(int listenerKey) {
1678 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1679 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
1680 }
1681
1682 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00001683 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
1684 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1685 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
1686 new ListenerArgs(this, serviceInfo)));
1687 }
1688
1689 @Override
1690 public void unregisterServiceInfoCallback(int listenerKey) {
1691 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1692 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
1693 new ListenerArgs(this, null)));
1694 }
1695
1696 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001697 public void startDaemon() {
1698 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1699 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
1700 }
1701
1702 @Override
1703 public void binderDied() {
1704 mNsdStateMachine.sendMessage(
1705 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
1706 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001707 }
1708
Hugo Benichi912db992017-04-24 16:41:03 +09001709 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07001710 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07001711 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09001712 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
1713 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07001714 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07001715 }
1716
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001717 private int getUniqueId() {
1718 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
1719 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001720 }
1721
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001722 private boolean registerService(int regId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09001723 if (DBG) {
paulhub2225702021-11-17 09:35:33 +08001724 Log.d(TAG, "registerService: " + regId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001725 }
Hugo Benichi6d706442017-04-24 16:19:58 +09001726 String name = service.getServiceName();
1727 String type = service.getServiceType();
1728 int port = service.getPort();
1729 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001730 final int registerInterface = getNetworkInterfaceIndex(service);
1731 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08001732 Log.e(TAG, "Interface to register service on not found");
1733 return false;
1734 }
1735 return mMDnsManager.registerService(regId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001736 }
1737
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001738 private boolean unregisterService(int regId) {
paulhu2b9ed952022-02-10 21:58:32 +08001739 return mMDnsManager.stopOperation(regId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001740 }
1741
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001742 private boolean discoverServices(int discoveryId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08001743 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001744 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
1745 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001746 Log.e(TAG, "Interface to discover service on not found");
1747 return false;
1748 }
paulhu2b9ed952022-02-10 21:58:32 +08001749 return mMDnsManager.discover(discoveryId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001750 }
1751
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001752 private boolean stopServiceDiscovery(int discoveryId) {
paulhu2b9ed952022-02-10 21:58:32 +08001753 return mMDnsManager.stopOperation(discoveryId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001754 }
1755
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001756 private boolean resolveService(int resolveId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001757 final String name = service.getServiceName();
1758 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001759 final int resolveInterface = getNetworkInterfaceIndex(service);
1760 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001761 Log.e(TAG, "Interface to resolve service on not found");
1762 return false;
1763 }
paulhu2b9ed952022-02-10 21:58:32 +08001764 return mMDnsManager.resolve(resolveId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001765 }
1766
1767 /**
1768 * Guess the interface to use to resolve or discover a service on a specific network.
1769 *
1770 * This is an imperfect guess, as for example the network may be gone or not yet fully
1771 * registered. This is fine as failing is correct if the network is gone, and a client
1772 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
1773 * this is to support the legacy mdnsresponder implementation, which historically resolved
1774 * services on an unspecified network.
1775 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001776 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
1777 final Network network = serviceInfo.getNetwork();
1778 if (network == null) {
1779 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
1780 // provided by NsdService from discovery results, and the service was found on an
1781 // interface that has no app-usable Network).
1782 if (serviceInfo.getInterfaceIndex() != 0) {
1783 return serviceInfo.getInterfaceIndex();
1784 }
1785 return IFACE_IDX_ANY;
1786 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001787
1788 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
1789 if (cm == null) {
1790 Log.wtf(TAG, "No ConnectivityManager for resolveService");
1791 return IFACE_IDX_ANY;
1792 }
1793 final LinkProperties lp = cm.getLinkProperties(network);
1794 if (lp == null) return IFACE_IDX_ANY;
1795
1796 // Only resolve on non-stacked interfaces
1797 final NetworkInterface iface;
1798 try {
1799 iface = NetworkInterface.getByName(lp.getInterfaceName());
1800 } catch (SocketException e) {
1801 Log.e(TAG, "Error querying interface", e);
1802 return IFACE_IDX_ANY;
1803 }
1804
1805 if (iface == null) {
1806 Log.e(TAG, "Interface not found: " + lp.getInterfaceName());
1807 return IFACE_IDX_ANY;
1808 }
1809
1810 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001811 }
1812
1813 private boolean stopResolveService(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001814 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001815 }
1816
paulhu2b9ed952022-02-10 21:58:32 +08001817 private boolean getAddrInfo(int resolveId, String hostname, int interfaceIdx) {
1818 return mMDnsManager.getServiceAddress(resolveId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001819 }
1820
1821 private boolean stopGetAddrInfo(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001822 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001823 }
1824
1825 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00001826 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1827 if (!PermissionUtils.checkDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001828
Paul Hub2e67d32023-04-18 05:50:14 +00001829 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
1830 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07001831 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00001832
1833 // Dump service and clients logs
1834 pw.println();
Paul Hu14667de2023-04-17 22:42:47 +08001835 pw.println("Logs:");
Paul Hub2e67d32023-04-18 05:50:14 +00001836 pw.increaseIndent();
1837 mServiceLogs.reverseDump(pw);
1838 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001839 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001840
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001841 private abstract static class ClientRequest {
1842 private final int mGlobalId;
1843
1844 private ClientRequest(int globalId) {
1845 mGlobalId = globalId;
1846 }
1847 }
1848
1849 private static class LegacyClientRequest extends ClientRequest {
1850 private final int mRequestCode;
1851
1852 private LegacyClientRequest(int globalId, int requestCode) {
1853 super(globalId);
1854 mRequestCode = requestCode;
1855 }
1856 }
1857
1858 private static class AdvertiserClientRequest extends ClientRequest {
1859 private AdvertiserClientRequest(int globalId) {
1860 super(globalId);
1861 }
1862 }
1863
1864 private static class DiscoveryManagerRequest extends ClientRequest {
1865 @NonNull
1866 private final MdnsListener mListener;
1867
1868 private DiscoveryManagerRequest(int globalId, @NonNull MdnsListener listener) {
1869 super(globalId);
1870 mListener = listener;
1871 }
1872 }
1873
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001874 /* Information tracked per client */
1875 private class ClientInfo {
1876
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001877 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001878 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001879 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001880 private NsdServiceInfo mResolvedService;
1881
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001882 /* A map from client-side ID (listenerKey) to the request */
1883 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08001884
Luke Huangf7277ed2021-07-12 21:15:10 +08001885 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001886 private boolean mIsPreSClient = false;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001887 // The flag of using java backend if the client's target SDK >= U
1888 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001889 // Store client logs
1890 private final SharedLog mClientLogs;
Luke Huangf7277ed2021-07-12 21:15:10 +08001891
Paul Hub2e67d32023-04-18 05:50:14 +00001892 private ClientInfo(INsdManagerCallback cb, boolean useJavaBackend, SharedLog sharedLog) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001893 mCb = cb;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001894 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001895 mClientLogs = sharedLog;
1896 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001897 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001898
1899 @Override
1900 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06001901 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07001902 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001903 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
1904 for (int i = 0; i < mClientRequests.size(); i++) {
1905 int clientID = mClientRequests.keyAt(i);
1906 sb.append("clientId ")
1907 .append(clientID)
1908 .append(" mDnsId ").append(mClientRequests.valueAt(i).mGlobalId)
1909 .append(" type ").append(
1910 mClientRequests.valueAt(i).getClass().getSimpleName())
1911 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07001912 }
1913 return sb.toString();
1914 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001915
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001916 private boolean isPreSClient() {
1917 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08001918 }
1919
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001920 private void setPreSClient() {
1921 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08001922 }
1923
Paul Hue4f5f252023-02-16 21:13:47 +08001924 private void unregisterMdnsListenerFromRequest(ClientRequest request) {
1925 final MdnsListener listener =
1926 ((DiscoveryManagerRequest) request).mListener;
1927 mMdnsDiscoveryManager.unregisterListener(
1928 listener.getListenedServiceType(), listener);
1929 }
1930
Dave Plattfeff2af2014-03-07 14:48:22 -08001931 // Remove any pending requests from the global map when we get rid of a client,
1932 // and send cancellations to the daemon.
1933 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00001934 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09001935 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001936 for (int i = 0; i < mClientRequests.size(); i++) {
1937 final int clientId = mClientRequests.keyAt(i);
1938 final ClientRequest request = mClientRequests.valueAt(i);
1939 final int globalId = request.mGlobalId;
Dave Plattfeff2af2014-03-07 14:48:22 -08001940 mIdToClientInfoMap.remove(globalId);
paulhub2225702021-11-17 09:35:33 +08001941 if (DBG) {
1942 Log.d(TAG, "Terminating client-ID " + clientId
1943 + " global-ID " + globalId + " type " + mClientRequests.get(clientId));
1944 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001945
1946 if (request instanceof DiscoveryManagerRequest) {
Paul Hue4f5f252023-02-16 21:13:47 +08001947 unregisterMdnsListenerFromRequest(request);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001948 continue;
1949 }
1950
1951 if (request instanceof AdvertiserClientRequest) {
1952 mAdvertiser.removeService(globalId);
1953 continue;
1954 }
1955
1956 if (!(request instanceof LegacyClientRequest)) {
1957 throw new IllegalStateException("Unknown request type: " + request.getClass());
1958 }
1959
1960 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08001961 case NsdManager.DISCOVER_SERVICES:
1962 stopServiceDiscovery(globalId);
1963 break;
1964 case NsdManager.RESOLVE_SERVICE:
1965 stopResolveService(globalId);
1966 break;
1967 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001968 unregisterService(globalId);
Dave Plattfeff2af2014-03-07 14:48:22 -08001969 break;
1970 default:
1971 break;
1972 }
1973 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001974 mClientRequests.clear();
1975 }
1976
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001977 // mClientRequests is a sparse array of listener id -> ClientRequest. For a given
1978 // mDnsClient id, return the corresponding listener id. mDnsClient id is also called a
1979 // global id.
Christopher Lane74411222014-04-25 18:39:07 -07001980 private int getClientId(final int globalId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001981 for (int i = 0; i < mClientRequests.size(); i++) {
1982 if (mClientRequests.valueAt(i).mGlobalId == globalId) {
1983 return mClientRequests.keyAt(i);
1984 }
Christopher Lane74411222014-04-25 18:39:07 -07001985 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001986 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07001987 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001988
Paul Hub2e67d32023-04-18 05:50:14 +00001989 private void log(String message) {
1990 mClientLogs.log(message);
1991 }
1992
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001993 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info) {
1994 try {
1995 mCb.onDiscoverServicesStarted(listenerKey, info);
1996 } catch (RemoteException e) {
1997 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
1998 }
1999 }
2000
2001 void onDiscoverServicesFailed(int listenerKey, int error) {
2002 try {
2003 mCb.onDiscoverServicesFailed(listenerKey, error);
2004 } catch (RemoteException e) {
2005 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
2006 }
2007 }
2008
2009 void onServiceFound(int listenerKey, NsdServiceInfo info) {
2010 try {
2011 mCb.onServiceFound(listenerKey, info);
2012 } catch (RemoteException e) {
2013 Log.e(TAG, "Error calling onServiceFound(", e);
2014 }
2015 }
2016
2017 void onServiceLost(int listenerKey, NsdServiceInfo info) {
2018 try {
2019 mCb.onServiceLost(listenerKey, info);
2020 } catch (RemoteException e) {
2021 Log.e(TAG, "Error calling onServiceLost(", e);
2022 }
2023 }
2024
2025 void onStopDiscoveryFailed(int listenerKey, int error) {
2026 try {
2027 mCb.onStopDiscoveryFailed(listenerKey, error);
2028 } catch (RemoteException e) {
2029 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
2030 }
2031 }
2032
2033 void onStopDiscoverySucceeded(int listenerKey) {
2034 try {
2035 mCb.onStopDiscoverySucceeded(listenerKey);
2036 } catch (RemoteException e) {
2037 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
2038 }
2039 }
2040
2041 void onRegisterServiceFailed(int listenerKey, int error) {
2042 try {
2043 mCb.onRegisterServiceFailed(listenerKey, error);
2044 } catch (RemoteException e) {
2045 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2046 }
2047 }
2048
2049 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info) {
2050 try {
2051 mCb.onRegisterServiceSucceeded(listenerKey, info);
2052 } catch (RemoteException e) {
2053 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2054 }
2055 }
2056
2057 void onUnregisterServiceFailed(int listenerKey, int error) {
2058 try {
2059 mCb.onUnregisterServiceFailed(listenerKey, error);
2060 } catch (RemoteException e) {
2061 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2062 }
2063 }
2064
2065 void onUnregisterServiceSucceeded(int listenerKey) {
2066 try {
2067 mCb.onUnregisterServiceSucceeded(listenerKey);
2068 } catch (RemoteException e) {
2069 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2070 }
2071 }
2072
2073 void onResolveServiceFailed(int listenerKey, int error) {
2074 try {
2075 mCb.onResolveServiceFailed(listenerKey, error);
2076 } catch (RemoteException e) {
2077 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2078 }
2079 }
2080
2081 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info) {
2082 try {
2083 mCb.onResolveServiceSucceeded(listenerKey, info);
2084 } catch (RemoteException e) {
2085 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2086 }
2087 }
Paul Hub58deb72022-12-26 09:24:42 +00002088
2089 void onStopResolutionFailed(int listenerKey, int error) {
2090 try {
2091 mCb.onStopResolutionFailed(listenerKey, error);
2092 } catch (RemoteException e) {
2093 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2094 }
2095 }
2096
2097 void onStopResolutionSucceeded(int listenerKey) {
2098 try {
2099 mCb.onStopResolutionSucceeded(listenerKey);
2100 } catch (RemoteException e) {
2101 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2102 }
2103 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002104
2105 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
2106 try {
2107 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2108 } catch (RemoteException e) {
2109 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2110 }
2111 }
2112
2113 void onServiceUpdated(int listenerKey, NsdServiceInfo info) {
2114 try {
2115 mCb.onServiceUpdated(listenerKey, info);
2116 } catch (RemoteException e) {
2117 Log.e(TAG, "Error calling onServiceUpdated", e);
2118 }
2119 }
2120
2121 void onServiceUpdatedLost(int listenerKey) {
2122 try {
2123 mCb.onServiceUpdatedLost(listenerKey);
2124 } catch (RemoteException e) {
2125 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2126 }
2127 }
2128
2129 void onServiceInfoCallbackUnregistered(int listenerKey) {
2130 try {
2131 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2132 } catch (RemoteException e) {
2133 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2134 }
2135 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002136 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002137}