blob: c47c572c246dd7cf6aff6f9b1b871831d8b7f81a [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.MdnsSocketProvider;
Yuyang Huangde802c82023-05-02 17:14:22 +090077import com.android.server.connectivity.mdns.util.MdnsUtils;
paulhua262cc12019-08-12 16:25:11 +080078
Irfan Sheriff77ec5582012-03-22 17:01:39 -070079import java.io.FileDescriptor;
80import java.io.PrintWriter;
Yuyang Huangaa0e9602023-03-17 12:43:09 +090081import java.net.Inet6Address;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070082import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090083import java.net.NetworkInterface;
84import java.net.SocketException;
85import java.net.UnknownHostException;
Paul Hu2b865912023-03-06 14:27:53 +080086import java.util.ArrayList;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +090087import java.util.Arrays;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070088import java.util.HashMap;
Paul Hu23fa2022023-01-13 22:57:24 +080089import java.util.List;
Paul Hu75069ed2023-01-14 00:31:09 +080090import java.util.Map;
Paul Hu23fa2022023-01-13 22:57:24 +080091import java.util.regex.Matcher;
92import java.util.regex.Pattern;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070093
Irfan Sheriff77ec5582012-03-22 17:01:39 -070094/**
95 * Network Service Discovery Service handles remote service discovery operation requests by
96 * implementing the INsdManager interface.
97 *
98 * @hide
99 */
100public class NsdService extends INsdManager.Stub {
101 private static final String TAG = "NsdService";
102 private static final String MDNS_TAG = "mDnsConnector";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900103 /**
104 * Enable discovery using the Java DiscoveryManager, instead of the legacy mdnsresponder
105 * implementation.
106 */
Paul Hu4bd98ef2023-01-12 13:42:07 +0800107 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Paul Hu23fa2022023-01-13 22:57:24 +0800108 private static final String LOCAL_DOMAIN_NAME = "local";
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700109
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900110 /**
111 * Enable advertising using the Java MdnsAdvertiser, instead of the legacy mdnsresponder
112 * implementation.
113 */
114 private static final String MDNS_ADVERTISER_VERSION = "mdns_advertiser_version";
115
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900116 /**
117 * Comma-separated list of type:flag mappings indicating the flags to use to allowlist
118 * discovery/advertising using MdnsDiscoveryManager / MdnsAdvertiser for a given type.
119 *
120 * For example _mytype._tcp.local and _othertype._tcp.local would be configured with:
121 * _mytype._tcp:mytype,_othertype._tcp.local:othertype
122 *
123 * In which case the flags:
124 * "mdns_discovery_manager_allowlist_mytype_version",
125 * "mdns_advertiser_allowlist_mytype_version",
126 * "mdns_discovery_manager_allowlist_othertype_version",
127 * "mdns_advertiser_allowlist_othertype_version"
128 * would be used to toggle MdnsDiscoveryManager / MdnsAdvertiser for each type. The flags will
129 * be read with
130 * {@link DeviceConfigUtils#isFeatureEnabled(Context, String, String, String, boolean)}.
131 *
132 * @see #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX
133 * @see #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX
134 * @see #MDNS_ALLOWLIST_FLAG_SUFFIX
135 */
136 private static final String MDNS_TYPE_ALLOWLIST_FLAGS = "mdns_type_allowlist_flags";
137
138 private static final String MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX =
139 "mdns_discovery_manager_allowlist_";
140 private static final String MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX =
141 "mdns_advertiser_allowlist_";
142 private static final String MDNS_ALLOWLIST_FLAG_SUFFIX = "_version";
143
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900144 public static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +0000145 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900146 private static final int IFACE_IDX_ANY = 0;
Paul Hu14667de2023-04-17 22:42:47 +0800147 private static final SharedLog LOGGER = new SharedLog("serviceDiscovery");
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700148
Hugo Benichi32be63d2017-04-05 14:06:11 +0900149 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900150 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +0800151 private final MDnsManager mMDnsManager;
152 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900153 @NonNull
154 private final Dependencies mDeps;
155 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800156 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900157 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800158 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900159 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800160 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900161 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900162 private final MdnsAdvertiser mAdvertiser;
Paul Hu14667de2023-04-17 22:42:47 +0800163 private final SharedLog mServiceLogs = LOGGER.forSubComponent(TAG);
Paul Hu23fa2022023-01-13 22:57:24 +0800164 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800165 // state machine thread. If change this outside state machine, it will need to introduce
166 // synchronization.
167 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800168 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700169
170 /**
171 * Clients receiving asynchronous messages
172 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900173 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700174
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700175 /* A map from unique id to client info */
Hugo Benichi32be63d2017-04-05 14:06:11 +0900176 private final SparseArray<ClientInfo> mIdToClientInfoMap= new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700177
Luke Huang05298582021-06-13 16:52:05 +0000178 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700179
Hugo Benichi32be63d2017-04-05 14:06:11 +0900180 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700181 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800182 // The count of the connected legacy clients.
183 private int mLegacyClientCount = 0;
Paul Hub2e67d32023-04-18 05:50:14 +0000184 // The number of client that ever connected.
185 private int mClientNumberId = 1;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700186
Paul Hu23fa2022023-01-13 22:57:24 +0800187 private static class MdnsListener implements MdnsServiceBrowserListener {
188 protected final int mClientId;
189 protected final int mTransactionId;
190 @NonNull
191 protected final NsdServiceInfo mReqServiceInfo;
192 @NonNull
193 protected final String mListenedServiceType;
194
195 MdnsListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
196 @NonNull String listenedServiceType) {
197 mClientId = clientId;
198 mTransactionId = transactionId;
199 mReqServiceInfo = reqServiceInfo;
200 mListenedServiceType = listenedServiceType;
201 }
202
203 @NonNull
204 public String getListenedServiceType() {
205 return mListenedServiceType;
206 }
207
208 @Override
209 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo) { }
210
211 @Override
212 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
213
214 @Override
215 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
216
217 @Override
218 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) { }
219
220 @Override
221 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
222
223 @Override
224 public void onSearchStoppedWithError(int error) { }
225
226 @Override
227 public void onSearchFailedToStart() { }
228
229 @Override
230 public void onDiscoveryQuerySent(@NonNull List<String> subtypes, int transactionId) { }
231
232 @Override
233 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
234 }
235
236 private class DiscoveryListener extends MdnsListener {
237
238 DiscoveryListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
239 @NonNull String listenServiceType) {
240 super(clientId, transactionId, reqServiceInfo, listenServiceType);
241 }
242
243 @Override
244 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu019621e2023-01-13 23:26:49 +0800245 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
246 NsdManager.SERVICE_FOUND,
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900247 new MdnsEvent(mClientId, serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800248 }
249
250 @Override
251 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800252 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
253 NsdManager.SERVICE_LOST,
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900254 new MdnsEvent(mClientId, serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800255 }
256 }
257
Paul Hu75069ed2023-01-14 00:31:09 +0800258 private class ResolutionListener extends MdnsListener {
259
260 ResolutionListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
261 @NonNull String listenServiceType) {
262 super(clientId, transactionId, reqServiceInfo, listenServiceType);
263 }
264
265 @Override
266 public void onServiceFound(MdnsServiceInfo serviceInfo) {
267 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
268 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900269 new MdnsEvent(mClientId, serviceInfo));
Paul Hu75069ed2023-01-14 00:31:09 +0800270 }
271 }
272
Paul Hu30bd70d2023-02-07 13:20:56 +0000273 private class ServiceInfoListener extends MdnsListener {
274
275 ServiceInfoListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
276 @NonNull String listenServiceType) {
277 super(clientId, transactionId, reqServiceInfo, listenServiceType);
278 }
279
280 @Override
281 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo) {
282 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
283 NsdManager.SERVICE_UPDATED,
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900284 new MdnsEvent(mClientId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000285 }
286
287 @Override
288 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) {
289 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
290 NsdManager.SERVICE_UPDATED,
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900291 new MdnsEvent(mClientId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000292 }
293
294 @Override
295 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) {
296 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
297 NsdManager.SERVICE_UPDATED_LOST,
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900298 new MdnsEvent(mClientId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000299 }
300 }
301
Paul Hu019621e2023-01-13 23:26:49 +0800302 /**
303 * Data class of mdns service callback information.
304 */
305 private static class MdnsEvent {
306 final int mClientId;
307 @NonNull
Paul Hu019621e2023-01-13 23:26:49 +0800308 final MdnsServiceInfo mMdnsServiceInfo;
309
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900310 MdnsEvent(int clientId, @NonNull MdnsServiceInfo mdnsServiceInfo) {
Paul Hu019621e2023-01-13 23:26:49 +0800311 mClientId = clientId;
Paul Hu019621e2023-01-13 23:26:49 +0800312 mMdnsServiceInfo = mdnsServiceInfo;
313 }
314 }
315
Irfan Sheriff75006652012-04-17 23:15:29 -0700316 private class NsdStateMachine extends StateMachine {
317
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700318 private final DefaultState mDefaultState = new DefaultState();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700319 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700320
321 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700322 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900323 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700324 }
325
Luke Huang92860f92021-06-23 06:29:30 +0000326 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800327 if (mIsDaemonStarted) {
328 if (DBG) Log.d(TAG, "Daemon is already started.");
329 return;
330 }
331 mMDnsManager.registerEventListener(mMDnsEventCallback);
332 mMDnsManager.startDaemon();
333 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000334 maybeScheduleStop();
Paul Hub2e67d32023-04-18 05:50:14 +0000335 mServiceLogs.log("Start mdns_responder daemon");
Luke Huang05298582021-06-13 16:52:05 +0000336 }
337
paulhu2b9ed952022-02-10 21:58:32 +0800338 private void maybeStopDaemon() {
339 if (!mIsDaemonStarted) {
340 if (DBG) Log.d(TAG, "Daemon has not been started.");
341 return;
342 }
343 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
344 mMDnsManager.stopDaemon();
345 mIsDaemonStarted = false;
Paul Hub2e67d32023-04-18 05:50:14 +0000346 mServiceLogs.log("Stop mdns_responder daemon");
paulhu2b9ed952022-02-10 21:58:32 +0800347 }
348
Luke Huang92860f92021-06-23 06:29:30 +0000349 private boolean isAnyRequestActive() {
350 return mIdToClientInfoMap.size() != 0;
351 }
352
353 private void scheduleStop() {
354 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
355 }
356 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800357 // The native daemon should stay alive and can't be cleanup
358 // if any legacy client connected.
359 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000360 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000361 }
362 }
363
Luke Huang92860f92021-06-23 06:29:30 +0000364 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000365 this.removeMessages(NsdManager.DAEMON_CLEANUP);
366 }
367
Paul Hu23fa2022023-01-13 22:57:24 +0800368 private void maybeStartMonitoringSockets() {
369 if (mIsMonitoringSocketsStarted) {
370 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
371 return;
372 }
373
374 mMdnsSocketProvider.startMonitoringSockets();
375 mIsMonitoringSocketsStarted = true;
376 }
377
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900378 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
379 if (!mIsMonitoringSocketsStarted) return;
380 if (isAnyRequestActive()) return;
381
Paul Hu58f20602023-02-18 11:41:07 +0800382 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800383 mIsMonitoringSocketsStarted = false;
384 }
385
Hugo Benichi803a2f02017-04-24 11:35:06 +0900386 NsdStateMachine(String name, Handler handler) {
387 super(name, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -0700388 addState(mDefaultState);
Irfan Sheriff75006652012-04-17 23:15:29 -0700389 addState(mEnabledState, mDefaultState);
paulhu5568f452021-11-30 13:31:29 +0800390 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900391 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700392 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700393 }
394
395 class DefaultState extends State {
396 @Override
397 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900398 final ClientInfo cInfo;
399 final int clientId = msg.arg2;
Irfan Sheriff75006652012-04-17 23:15:29 -0700400 switch (msg.what) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900401 case NsdManager.REGISTER_CLIENT:
Paul Hu2e0a88c2023-03-09 16:05:01 +0800402 final ConnectorArgs arg = (ConnectorArgs) msg.obj;
403 final INsdManagerCallback cb = arg.callback;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900404 try {
Paul Hu2e0a88c2023-03-09 16:05:01 +0800405 cb.asBinder().linkToDeath(arg.connector, 0);
Paul Hub2e67d32023-04-18 05:50:14 +0000406 final String tag = "Client" + arg.uid + "-" + mClientNumberId++;
407 cInfo = new ClientInfo(cb, arg.useJavaBackend,
408 mServiceLogs.forSubComponent(tag));
Paul Hu2e0a88c2023-03-09 16:05:01 +0800409 mClients.put(arg.connector, cInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900410 } catch (RemoteException e) {
411 Log.w(TAG, "Client " + clientId + " has already died");
Irfan Sheriff75006652012-04-17 23:15:29 -0700412 }
413 break;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900414 case NsdManager.UNREGISTER_CLIENT:
415 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
416 cInfo = mClients.remove(connector);
Dave Plattfeff2af2014-03-07 14:48:22 -0800417 if (cInfo != null) {
418 cInfo.expungeAllRequests();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900419 if (cInfo.isPreSClient()) {
Luke Huangf7277ed2021-07-12 21:15:10 +0800420 mLegacyClientCount -= 1;
421 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800422 }
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900423 maybeStopMonitoringSocketsIfNoActiveRequest();
Luke Huangf7277ed2021-07-12 21:15:10 +0800424 maybeScheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700425 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700426 case NsdManager.DISCOVER_SERVICES:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900427 cInfo = getClientInfoForReply(msg);
428 if (cInfo != null) {
429 cInfo.onDiscoverServicesFailed(
430 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
431 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700432 break;
433 case NsdManager.STOP_DISCOVERY:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900434 cInfo = getClientInfoForReply(msg);
435 if (cInfo != null) {
436 cInfo.onStopDiscoveryFailed(
437 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
438 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700439 break;
440 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900441 cInfo = getClientInfoForReply(msg);
442 if (cInfo != null) {
443 cInfo.onRegisterServiceFailed(
444 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
445 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700446 break;
447 case NsdManager.UNREGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900448 cInfo = getClientInfoForReply(msg);
449 if (cInfo != null) {
450 cInfo.onUnregisterServiceFailed(
451 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
452 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700453 break;
454 case NsdManager.RESOLVE_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900455 cInfo = getClientInfoForReply(msg);
456 if (cInfo != null) {
457 cInfo.onResolveServiceFailed(
458 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
459 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700460 break;
Paul Hub58deb72022-12-26 09:24:42 +0000461 case NsdManager.STOP_RESOLUTION:
462 cInfo = getClientInfoForReply(msg);
463 if (cInfo != null) {
464 cInfo.onStopResolutionFailed(
465 clientId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
466 }
467 break;
Paul Hu18aeccc2022-12-27 08:48:48 +0000468 case NsdManager.REGISTER_SERVICE_CALLBACK:
469 cInfo = getClientInfoForReply(msg);
470 if (cInfo != null) {
471 cInfo.onServiceInfoCallbackRegistrationFailed(
472 clientId, NsdManager.FAILURE_BAD_PARAMETERS);
473 }
474 break;
Luke Huang05298582021-06-13 16:52:05 +0000475 case NsdManager.DAEMON_CLEANUP:
paulhu2b9ed952022-02-10 21:58:32 +0800476 maybeStopDaemon();
Luke Huang05298582021-06-13 16:52:05 +0000477 break;
Luke Huangf7277ed2021-07-12 21:15:10 +0800478 // This event should be only sent by the legacy (target SDK < S) clients.
479 // Mark the sending client as legacy.
480 case NsdManager.DAEMON_STARTUP:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900481 cInfo = getClientInfoForReply(msg);
Luke Huangf7277ed2021-07-12 21:15:10 +0800482 if (cInfo != null) {
483 cancelStop();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900484 cInfo.setPreSClient();
Luke Huangf7277ed2021-07-12 21:15:10 +0800485 mLegacyClientCount += 1;
486 maybeStartDaemon();
487 }
488 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700489 default:
paulhub2225702021-11-17 09:35:33 +0800490 Log.e(TAG, "Unhandled " + msg);
Irfan Sheriff75006652012-04-17 23:15:29 -0700491 return NOT_HANDLED;
492 }
493 return HANDLED;
494 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900495
496 private ClientInfo getClientInfoForReply(Message msg) {
497 final ListenerArgs args = (ListenerArgs) msg.obj;
498 return mClients.get(args.connector);
499 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700500 }
501
Irfan Sheriff75006652012-04-17 23:15:29 -0700502 class EnabledState extends State {
503 @Override
504 public void enter() {
505 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700506 }
507
508 @Override
509 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000510 // TODO: it is incorrect to stop the daemon without expunging all requests
511 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000512 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700513 }
514
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700515 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900516 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800517 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700518 return true;
519 }
520 return false;
521 }
522
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900523 private void storeLegacyRequestMap(int clientId, int globalId, ClientInfo clientInfo,
524 int what) {
525 clientInfo.mClientRequests.put(clientId, new LegacyClientRequest(globalId, what));
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700526 mIdToClientInfoMap.put(globalId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000527 // Remove the cleanup event because here comes a new request.
528 cancelStop();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700529 }
530
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900531 private void storeAdvertiserRequestMap(int clientId, int globalId,
Paul Hu23fa2022023-01-13 22:57:24 +0800532 ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900533 clientInfo.mClientRequests.put(clientId, new AdvertiserClientRequest(globalId));
534 mIdToClientInfoMap.put(globalId, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800535 }
536
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900537 private void removeRequestMap(int clientId, int globalId, ClientInfo clientInfo) {
538 final ClientRequest existing = clientInfo.mClientRequests.get(clientId);
539 if (existing == null) return;
540 clientInfo.mClientRequests.remove(clientId);
541 mIdToClientInfoMap.remove(globalId);
542
543 if (existing instanceof LegacyClientRequest) {
544 maybeScheduleStop();
545 } else {
546 maybeStopMonitoringSocketsIfNoActiveRequest();
547 }
548 }
549
550 private void storeDiscoveryManagerRequestMap(int clientId, int globalId,
551 MdnsListener listener, ClientInfo clientInfo) {
552 clientInfo.mClientRequests.put(clientId,
553 new DiscoveryManagerRequest(globalId, listener));
554 mIdToClientInfoMap.put(globalId, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800555 }
556
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900557 /**
558 * Truncate a service name to up to 63 UTF-8 bytes.
559 *
560 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
561 * names used in registerService follows historical behavior (see mdnsresponder
562 * handle_regservice_request).
563 */
564 @NonNull
565 private String truncateServiceName(@NonNull String originalName) {
Yuyang Huangde802c82023-05-02 17:14:22 +0900566 return MdnsUtils.truncateServiceName(originalName, MAX_LABEL_LENGTH);
Paul Hu23fa2022023-01-13 22:57:24 +0800567 }
568
Paul Hue4f5f252023-02-16 21:13:47 +0800569 private void stopDiscoveryManagerRequest(ClientRequest request, int clientId, int id,
570 ClientInfo clientInfo) {
571 clientInfo.unregisterMdnsListenerFromRequest(request);
572 removeRequestMap(clientId, id, clientInfo);
573 }
574
Irfan Sheriff75006652012-04-17 23:15:29 -0700575 @Override
576 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900577 final ClientInfo clientInfo;
578 final int id;
579 final int clientId = msg.arg2;
580 final ListenerArgs args;
Irfan Sheriff75006652012-04-17 23:15:29 -0700581 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800582 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800583 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900584 args = (ListenerArgs) msg.obj;
585 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000586 // If the binder death notification for a INsdManagerCallback was received
587 // before any calls are received by NsdService, the clientInfo would be
588 // cleared and cause NPE. Add a null check here to prevent this corner case.
589 if (clientInfo == null) {
590 Log.e(TAG, "Unknown connector in discovery");
591 break;
592 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700593
594 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900595 clientInfo.onDiscoverServicesFailed(
596 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriff75006652012-04-17 23:15:29 -0700597 break;
598 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700599
Paul Hu23fa2022023-01-13 22:57:24 +0800600 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700601 id = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900602 final Pair<String, String> typeAndSubtype =
603 parseTypeAndSubtype(info.getServiceType());
604 final String serviceType = typeAndSubtype == null
605 ? null : typeAndSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800606 if (clientInfo.mUseJavaBackend
607 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900608 || useDiscoveryManagerForType(serviceType)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800609 if (serviceType == null) {
610 clientInfo.onDiscoverServicesFailed(clientId,
611 NsdManager.FAILURE_INTERNAL_ERROR);
612 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700613 }
Paul Hu23fa2022023-01-13 22:57:24 +0800614
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900615 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800616 maybeStartMonitoringSockets();
617 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900618 new DiscoveryListener(clientId, id, info, listenServiceType);
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900619 final MdnsSearchOptions.Builder optionsBuilder =
620 MdnsSearchOptions.newBuilder()
621 .setNetwork(info.getNetwork())
622 .setIsPassiveMode(true);
623 if (typeAndSubtype.second != null) {
624 // The parsing ensures subtype starts with an underscore.
625 // MdnsSearchOptions expects the underscore to not be present.
626 optionsBuilder.addSubtype(typeAndSubtype.second.substring(1));
627 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900628 mMdnsDiscoveryManager.registerListener(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900629 listenServiceType, listener, optionsBuilder.build());
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900630 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800631 clientInfo.onDiscoverServicesStarted(clientId, info);
Paul Hub2e67d32023-04-18 05:50:14 +0000632 clientInfo.log("Register a DiscoveryListener " + id
633 + " for service type:" + listenServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700634 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800635 maybeStartDaemon();
636 if (discoverServices(id, info)) {
637 if (DBG) {
638 Log.d(TAG, "Discover " + msg.arg2 + " " + id
639 + info.getServiceType());
640 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900641 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu23fa2022023-01-13 22:57:24 +0800642 clientInfo.onDiscoverServicesStarted(clientId, info);
643 } else {
644 stopServiceDiscovery(id);
645 clientInfo.onDiscoverServicesFailed(clientId,
646 NsdManager.FAILURE_INTERNAL_ERROR);
647 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700648 }
649 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800650 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900651 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800652 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900653 args = (ListenerArgs) msg.obj;
654 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000655 // If the binder death notification for a INsdManagerCallback was received
656 // before any calls are received by NsdService, the clientInfo would be
657 // cleared and cause NPE. Add a null check here to prevent this corner case.
658 if (clientInfo == null) {
659 Log.e(TAG, "Unknown connector in stop discovery");
660 break;
661 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700662
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900663 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
664 if (request == null) {
665 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700666 break;
667 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900668 id = request.mGlobalId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900669 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
670 // point, so this needs to check the type of the original request to
671 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900672 if (request instanceof DiscoveryManagerRequest) {
Paul Hue4f5f252023-02-16 21:13:47 +0800673 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900674 clientInfo.onStopDiscoverySucceeded(clientId);
Paul Hub2e67d32023-04-18 05:50:14 +0000675 clientInfo.log("Unregister the DiscoveryListener " + id);
Irfan Sheriff75006652012-04-17 23:15:29 -0700676 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800677 removeRequestMap(clientId, id, clientInfo);
678 if (stopServiceDiscovery(id)) {
679 clientInfo.onStopDiscoverySucceeded(clientId);
680 } else {
681 clientInfo.onStopDiscoveryFailed(
682 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
683 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700684 }
685 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900686 }
687 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800688 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900689 args = (ListenerArgs) msg.obj;
690 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000691 // If the binder death notification for a INsdManagerCallback was received
692 // before any calls are received by NsdService, the clientInfo would be
693 // cleared and cause NPE. Add a null check here to prevent this corner case.
694 if (clientInfo == null) {
695 Log.e(TAG, "Unknown connector in registration");
696 break;
697 }
698
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700699 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900700 clientInfo.onRegisterServiceFailed(
701 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700702 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700703 }
704
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700705 id = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900706 final NsdServiceInfo serviceInfo = args.serviceInfo;
707 final String serviceType = serviceInfo.getServiceType();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900708 final Pair<String, String> typeSubtype = parseTypeAndSubtype(serviceType);
709 final String registerServiceType = typeSubtype == null
710 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800711 if (clientInfo.mUseJavaBackend
712 || mDeps.isMdnsAdvertiserEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900713 || useAdvertiserForType(registerServiceType)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900714 if (registerServiceType == null) {
715 Log.e(TAG, "Invalid service type: " + serviceType);
716 clientInfo.onRegisterServiceFailed(clientId,
717 NsdManager.FAILURE_INTERNAL_ERROR);
718 break;
719 }
720 serviceInfo.setServiceType(registerServiceType);
721 serviceInfo.setServiceName(truncateServiceName(
722 serviceInfo.getServiceName()));
723
724 maybeStartMonitoringSockets();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900725 // TODO: pass in the subtype as well. Including the subtype in the
726 // service type would generate service instance names like
727 // Name._subtype._sub._type._tcp, which is incorrect
728 // (it should be Name._type._tcp).
Remi NGUYEN VANce44beb2023-05-11 20:42:26 +0900729 mAdvertiser.addService(id, serviceInfo, typeSubtype.second);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900730 storeAdvertiserRequestMap(clientId, id, clientInfo);
Irfan Sheriff75006652012-04-17 23:15:29 -0700731 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900732 maybeStartDaemon();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900733 if (registerService(id, serviceInfo)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900734 if (DBG) Log.d(TAG, "Register " + clientId + " " + id);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900735 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900736 // Return success after mDns reports success
737 } else {
738 unregisterService(id);
739 clientInfo.onRegisterServiceFailed(
740 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
741 }
742
Irfan Sheriff75006652012-04-17 23:15:29 -0700743 }
744 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900745 }
746 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800747 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900748 args = (ListenerArgs) msg.obj;
749 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000750 // If the binder death notification for a INsdManagerCallback was received
751 // before any calls are received by NsdService, the clientInfo would be
752 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900753 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800754 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700755 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700756 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900757 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
758 if (request == null) {
759 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
760 break;
761 }
762 id = request.mGlobalId;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900763 removeRequestMap(clientId, id, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900764
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900765 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
766 // so this needs to check the type of the original request to unregister
767 // instead of looking at the flag value.
768 if (request instanceof AdvertiserClientRequest) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900769 mAdvertiser.removeService(id);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900770 clientInfo.onUnregisterServiceSucceeded(clientId);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700771 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900772 if (unregisterService(id)) {
773 clientInfo.onUnregisterServiceSucceeded(clientId);
774 } else {
775 clientInfo.onUnregisterServiceFailed(
776 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
777 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700778 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700779 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900780 }
Paul Hu75069ed2023-01-14 00:31:09 +0800781 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800782 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900783 args = (ListenerArgs) msg.obj;
784 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000785 // If the binder death notification for a INsdManagerCallback was received
786 // before any calls are received by NsdService, the clientInfo would be
787 // cleared and cause NPE. Add a null check here to prevent this corner case.
788 if (clientInfo == null) {
789 Log.e(TAG, "Unknown connector in resolution");
790 break;
791 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700792
Paul Hu75069ed2023-01-14 00:31:09 +0800793 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700794 id = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900795 final Pair<String, String> typeSubtype =
796 parseTypeAndSubtype(info.getServiceType());
797 final String serviceType = typeSubtype == null
798 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800799 if (clientInfo.mUseJavaBackend
800 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900801 || useDiscoveryManagerForType(serviceType)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800802 if (serviceType == null) {
803 clientInfo.onResolveServiceFailed(clientId,
804 NsdManager.FAILURE_INTERNAL_ERROR);
805 break;
806 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900807 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +0800808
809 maybeStartMonitoringSockets();
810 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900811 new ResolutionListener(clientId, id, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800812 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
813 .setNetwork(info.getNetwork())
814 .setIsPassiveMode(true)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900815 .setResolveInstanceName(info.getServiceName())
Paul Hu75069ed2023-01-14 00:31:09 +0800816 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900817 mMdnsDiscoveryManager.registerListener(
818 resolveServiceType, listener, options);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900819 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Paul Hub2e67d32023-04-18 05:50:14 +0000820 clientInfo.log("Register a ResolutionListener " + id
821 + " for service type:" + resolveServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700822 } else {
Paul Hu75069ed2023-01-14 00:31:09 +0800823 if (clientInfo.mResolvedService != null) {
824 clientInfo.onResolveServiceFailed(
825 clientId, NsdManager.FAILURE_ALREADY_ACTIVE);
826 break;
827 }
828
829 maybeStartDaemon();
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900830 if (resolveService(id, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800831 clientInfo.mResolvedService = new NsdServiceInfo();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900832 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu75069ed2023-01-14 00:31:09 +0800833 } else {
834 clientInfo.onResolveServiceFailed(
835 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
836 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700837 }
838 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800839 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900840 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +0000841 if (DBG) Log.d(TAG, "Stop service resolution");
842 args = (ListenerArgs) msg.obj;
843 clientInfo = mClients.get(args.connector);
844 // If the binder death notification for a INsdManagerCallback was received
845 // before any calls are received by NsdService, the clientInfo would be
846 // cleared and cause NPE. Add a null check here to prevent this corner case.
847 if (clientInfo == null) {
848 Log.e(TAG, "Unknown connector in stop resolution");
849 break;
850 }
851
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900852 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
853 if (request == null) {
854 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
855 break;
856 }
857 id = request.mGlobalId;
Paul Hue4f5f252023-02-16 21:13:47 +0800858 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
859 // point, so this needs to check the type of the original request to
860 // unregister instead of looking at the flag value.
861 if (request instanceof DiscoveryManagerRequest) {
862 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Paul Hub58deb72022-12-26 09:24:42 +0000863 clientInfo.onStopResolutionSucceeded(clientId);
Paul Hub2e67d32023-04-18 05:50:14 +0000864 clientInfo.log("Unregister the ResolutionListener " + id);
Paul Hub58deb72022-12-26 09:24:42 +0000865 } else {
Paul Hue4f5f252023-02-16 21:13:47 +0800866 removeRequestMap(clientId, id, clientInfo);
867 if (stopResolveService(id)) {
868 clientInfo.onStopResolutionSucceeded(clientId);
869 } else {
870 clientInfo.onStopResolutionFailed(
871 clientId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
872 }
873 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +0000874 }
Paul Hub58deb72022-12-26 09:24:42 +0000875 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900876 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000877 case NsdManager.REGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +0000878 if (DBG) Log.d(TAG, "Register a service callback");
879 args = (ListenerArgs) msg.obj;
880 clientInfo = mClients.get(args.connector);
881 // If the binder death notification for a INsdManagerCallback was received
882 // before any calls are received by NsdService, the clientInfo would be
883 // cleared and cause NPE. Add a null check here to prevent this corner case.
884 if (clientInfo == null) {
885 Log.e(TAG, "Unknown connector in callback registration");
886 break;
887 }
888
Paul Hu30bd70d2023-02-07 13:20:56 +0000889 final NsdServiceInfo info = args.serviceInfo;
890 id = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900891 final Pair<String, String> typeAndSubtype =
892 parseTypeAndSubtype(info.getServiceType());
893 final String serviceType = typeAndSubtype == null
894 ? null : typeAndSubtype.first;
Paul Hu30bd70d2023-02-07 13:20:56 +0000895 if (serviceType == null) {
896 clientInfo.onServiceInfoCallbackRegistrationFailed(clientId,
897 NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +0000898 break;
899 }
Paul Hu30bd70d2023-02-07 13:20:56 +0000900 final String resolveServiceType = serviceType + ".local";
Paul Hu18aeccc2022-12-27 08:48:48 +0000901
Paul Hu30bd70d2023-02-07 13:20:56 +0000902 maybeStartMonitoringSockets();
903 final MdnsListener listener =
904 new ServiceInfoListener(clientId, id, info, resolveServiceType);
905 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
906 .setNetwork(info.getNetwork())
907 .setIsPassiveMode(true)
908 .setResolveInstanceName(info.getServiceName())
909 .build();
910 mMdnsDiscoveryManager.registerListener(
911 resolveServiceType, listener, options);
912 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Paul Hub2e67d32023-04-18 05:50:14 +0000913 clientInfo.log("Register a ServiceInfoListener " + id
914 + " for service type:" + resolveServiceType);
Paul Hu18aeccc2022-12-27 08:48:48 +0000915 break;
Paul Hu30bd70d2023-02-07 13:20:56 +0000916 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900917 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +0000918 if (DBG) Log.d(TAG, "Unregister a service callback");
919 args = (ListenerArgs) msg.obj;
920 clientInfo = mClients.get(args.connector);
921 // If the binder death notification for a INsdManagerCallback was received
922 // before any calls are received by NsdService, the clientInfo would be
923 // cleared and cause NPE. Add a null check here to prevent this corner case.
924 if (clientInfo == null) {
925 Log.e(TAG, "Unknown connector in callback unregistration");
926 break;
927 }
928
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900929 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
930 if (request == null) {
Paul Hu30bd70d2023-02-07 13:20:56 +0000931 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE_CALLBACK");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900932 break;
933 }
934 id = request.mGlobalId;
Paul Hu30bd70d2023-02-07 13:20:56 +0000935 if (request instanceof DiscoveryManagerRequest) {
936 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Paul Hu18aeccc2022-12-27 08:48:48 +0000937 clientInfo.onServiceInfoCallbackUnregistered(clientId);
Paul Hub2e67d32023-04-18 05:50:14 +0000938 clientInfo.log("Unregister the ServiceInfoListener " + id);
Paul Hu18aeccc2022-12-27 08:48:48 +0000939 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +0000940 loge("Unregister failed with non-DiscoveryManagerRequest.");
Paul Hu18aeccc2022-12-27 08:48:48 +0000941 }
Paul Hu18aeccc2022-12-27 08:48:48 +0000942 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900943 }
paulhu2b9ed952022-02-10 21:58:32 +0800944 case MDNS_SERVICE_EVENT:
945 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +0900946 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700947 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700948 break;
Paul Hu019621e2023-01-13 23:26:49 +0800949 case MDNS_DISCOVERY_MANAGER_EVENT:
950 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
951 return NOT_HANDLED;
952 }
953 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700954 default:
Hugo Benichif0c84092017-04-05 14:43:29 +0900955 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700956 }
Hugo Benichif0c84092017-04-05 14:43:29 +0900957 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700958 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700959
paulhu2b9ed952022-02-10 21:58:32 +0800960 private boolean handleMDnsServiceEvent(int code, int id, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700961 NsdServiceInfo servInfo;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700962 ClientInfo clientInfo = mIdToClientInfoMap.get(id);
963 if (clientInfo == null) {
paulhu2b9ed952022-02-10 21:58:32 +0800964 Log.e(TAG, String.format("id %d for %d has no client mapping", id, code));
Hugo Benichif0c84092017-04-05 14:43:29 +0900965 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700966 }
967
968 /* This goes in response as msg.arg2 */
Christopher Lane74411222014-04-25 18:39:07 -0700969 int clientId = clientInfo.getClientId(id);
970 if (clientId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -0700971 // This can happen because of race conditions. For example,
972 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
973 // and we may get in this situation.
paulhu2b9ed952022-02-10 21:58:32 +0800974 Log.d(TAG, String.format("%d for listener id %d that is no longer active",
975 code, id));
Hugo Benichif0c84092017-04-05 14:43:29 +0900976 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700977 }
Hugo Benichi32be63d2017-04-05 14:06:11 +0900978 if (DBG) {
paulhu2b9ed952022-02-10 21:58:32 +0800979 Log.d(TAG, String.format("MDns service event code:%d id=%d", code, id));
Hugo Benichi32be63d2017-04-05 14:06:11 +0900980 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700981 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +0800982 case IMDnsEventListener.SERVICE_FOUND: {
983 final DiscoveryInfo info = (DiscoveryInfo) obj;
984 final String name = info.serviceName;
985 final String type = info.registrationType;
986 servInfo = new NsdServiceInfo(name, type);
987 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900988 if (foundNetId == 0L) {
989 // Ignore services that do not have a Network: they are not usable
990 // by apps, as they would need privileged permissions to use
991 // interfaces that do not have an associated Network.
992 break;
993 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +0900994 if (foundNetId == INetd.DUMMY_NET_ID) {
995 // Ignore services on the dummy0 interface: they are only seen when
996 // discovering locally advertised services, and are not reachable
997 // through that interface.
998 break;
999 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001000 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001001 clientInfo.onServiceFound(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001002 break;
paulhu2b9ed952022-02-10 21:58:32 +08001003 }
1004 case IMDnsEventListener.SERVICE_LOST: {
1005 final DiscoveryInfo info = (DiscoveryInfo) obj;
1006 final String name = info.serviceName;
1007 final String type = info.registrationType;
1008 final int lostNetId = info.netId;
1009 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001010 // The network could be set to null (netId 0) if it was torn down when the
1011 // service is lost
1012 // TODO: avoid returning null in that case, possibly by remembering
1013 // found services on the same interface index and their network at the time
1014 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001015 clientInfo.onServiceLost(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001016 break;
paulhu2b9ed952022-02-10 21:58:32 +08001017 }
1018 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001019 clientInfo.onDiscoverServicesFailed(
1020 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001021 break;
paulhu2b9ed952022-02-10 21:58:32 +08001022 case IMDnsEventListener.SERVICE_REGISTERED: {
1023 final RegistrationInfo info = (RegistrationInfo) obj;
1024 final String name = info.serviceName;
1025 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001026 clientInfo.onRegisterServiceSucceeded(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001027 break;
paulhu2b9ed952022-02-10 21:58:32 +08001028 }
1029 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001030 clientInfo.onRegisterServiceFailed(
1031 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001032 break;
paulhu2b9ed952022-02-10 21:58:32 +08001033 case IMDnsEventListener.SERVICE_RESOLVED: {
1034 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001035 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +08001036 final String fullName = info.serviceFullName;
1037 while (index < fullName.length() && fullName.charAt(index) != '.') {
1038 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001039 ++index;
1040 }
1041 ++index;
1042 }
paulhu2b9ed952022-02-10 21:58:32 +08001043 if (index >= fullName.length()) {
1044 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001045 break;
1046 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001047
paulhube186602022-04-12 07:18:23 +00001048 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001049 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001050 String type = rest.replace(".local.", "");
1051
Paul Hu30bd70d2023-02-07 13:20:56 +00001052 final NsdServiceInfo serviceInfo = clientInfo.mResolvedService;
Paul Hu18aeccc2022-12-27 08:48:48 +00001053 serviceInfo.setServiceName(name);
1054 serviceInfo.setServiceType(type);
1055 serviceInfo.setPort(info.port);
1056 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001057 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001058
1059 stopResolveService(id);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001060 removeRequestMap(clientId, id, clientInfo);
1061
paulhu2b9ed952022-02-10 21:58:32 +08001062 final int id2 = getUniqueId();
1063 if (getAddrInfo(id2, info.hostname, info.interfaceIdx)) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001064 storeLegacyRequestMap(clientId, id2, clientInfo,
1065 NsdManager.RESOLVE_SERVICE);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001066 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001067 clientInfo.onResolveServiceFailed(
1068 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1069 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001070 }
1071 break;
paulhu2b9ed952022-02-10 21:58:32 +08001072 }
1073 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001074 /* NNN resolveId errorCode */
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001075 stopResolveService(id);
1076 removeRequestMap(clientId, id, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001077 clientInfo.onResolveServiceFailed(
1078 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1079 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001080 break;
paulhu2b9ed952022-02-10 21:58:32 +08001081 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001082 /* NNN resolveId errorCode */
1083 stopGetAddrInfo(id);
1084 removeRequestMap(clientId, id, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001085 clientInfo.onResolveServiceFailed(
1086 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1087 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001088 break;
paulhu2b9ed952022-02-10 21:58:32 +08001089 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001090 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001091 final GetAddressInfo info = (GetAddressInfo) obj;
1092 final String address = info.address;
1093 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001094 InetAddress serviceHost = null;
1095 try {
paulhu2b9ed952022-02-10 21:58:32 +08001096 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001097 } catch (UnknownHostException e) {
1098 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1099 }
1100
1101 // If the resolved service is on an interface without a network, consider it
1102 // as a failure: it would not be usable by apps as they would need
1103 // privileged permissions.
Paul Hu30bd70d2023-02-07 13:20:56 +00001104 if (netId != NETID_UNSET && serviceHost != null) {
1105 clientInfo.mResolvedService.setHost(serviceHost);
1106 setServiceNetworkForCallback(clientInfo.mResolvedService,
1107 netId, info.interfaceIdx);
1108 clientInfo.onResolveServiceSucceeded(
1109 clientId, clientInfo.mResolvedService);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001110 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001111 clientInfo.onResolveServiceFailed(
1112 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001113 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001114 stopGetAddrInfo(id);
1115 removeRequestMap(clientId, id, clientInfo);
1116 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001117 break;
paulhu2b9ed952022-02-10 21:58:32 +08001118 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001119 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001120 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001121 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001122 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001123 }
Paul Hu019621e2023-01-13 23:26:49 +08001124
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001125 @Nullable
1126 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(
1127 final MdnsEvent event, int code) {
Paul Hu019621e2023-01-13 23:26:49 +08001128 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001129 final String[] typeArray = serviceInfo.getServiceType();
1130 final String joinedType;
1131 if (typeArray.length == 0
1132 || !typeArray[typeArray.length - 1].equals(LOCAL_DOMAIN_NAME)) {
1133 Log.wtf(TAG, "MdnsServiceInfo type does not end in .local: "
1134 + Arrays.toString(typeArray));
1135 return null;
1136 } else {
1137 joinedType = TextUtils.join(".",
1138 Arrays.copyOfRange(typeArray, 0, typeArray.length - 1));
1139 }
1140 final String serviceType;
1141 switch (code) {
1142 case NsdManager.SERVICE_FOUND:
1143 case NsdManager.SERVICE_LOST:
1144 // For consistency with historical behavior, discovered service types have
1145 // a dot at the end.
1146 serviceType = joinedType + ".";
1147 break;
1148 case RESOLVE_SERVICE_SUCCEEDED:
1149 // For consistency with historical behavior, resolved service types have
1150 // a dot at the beginning.
1151 serviceType = "." + joinedType;
1152 break;
1153 default:
1154 serviceType = joinedType;
1155 break;
1156 }
Paul Hu019621e2023-01-13 23:26:49 +08001157 final String serviceName = serviceInfo.getServiceInstanceName();
1158 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1159 final Network network = serviceInfo.getNetwork();
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001160 // In MdnsDiscoveryManagerEvent, the Network can be null which means it is a
1161 // network for Tethering interface. In other words, the network == null means the
1162 // network has netId = INetd.LOCAL_NET_ID.
Paul Hu019621e2023-01-13 23:26:49 +08001163 setServiceNetworkForCallback(
1164 servInfo,
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001165 network == null ? INetd.LOCAL_NET_ID : network.netId,
Paul Hu019621e2023-01-13 23:26:49 +08001166 serviceInfo.getInterfaceIndex());
1167 return servInfo;
1168 }
1169
1170 private boolean handleMdnsDiscoveryManagerEvent(
1171 int transactionId, int code, Object obj) {
1172 final ClientInfo clientInfo = mIdToClientInfoMap.get(transactionId);
1173 if (clientInfo == null) {
1174 Log.e(TAG, String.format(
1175 "id %d for %d has no client mapping", transactionId, code));
1176 return false;
1177 }
1178
1179 final MdnsEvent event = (MdnsEvent) obj;
1180 final int clientId = event.mClientId;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001181 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event, code);
1182 // Errors are already logged if null
1183 if (info == null) return false;
Paul Hu019621e2023-01-13 23:26:49 +08001184 if (DBG) {
1185 Log.d(TAG, String.format("MdnsDiscoveryManager event code=%s transactionId=%d",
1186 NsdManager.nameOf(code), transactionId));
1187 }
1188 switch (code) {
1189 case NsdManager.SERVICE_FOUND:
Paul Hu319751a2023-01-13 23:56:34 +08001190 clientInfo.onServiceFound(clientId, info);
1191 break;
1192 case NsdManager.SERVICE_LOST:
1193 clientInfo.onServiceLost(clientId, info);
Paul Hu019621e2023-01-13 23:26:49 +08001194 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001195 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001196 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
1197 if (request == null) {
1198 Log.e(TAG, "Unknown client request in RESOLVE_SERVICE_SUCCEEDED");
1199 break;
1200 }
Paul Hu75069ed2023-01-14 00:31:09 +08001201 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Paul Hu75069ed2023-01-14 00:31:09 +08001202 info.setPort(serviceInfo.getPort());
1203
1204 Map<String, String> attrs = serviceInfo.getAttributes();
1205 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1206 final String key = kv.getKey();
1207 try {
1208 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1209 } catch (IllegalArgumentException e) {
1210 Log.e(TAG, "Invalid attribute", e);
1211 }
1212 }
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001213 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu2b865912023-03-06 14:27:53 +08001214 if (addresses.size() != 0) {
1215 info.setHostAddresses(addresses);
Paul Hu75069ed2023-01-14 00:31:09 +08001216 clientInfo.onResolveServiceSucceeded(clientId, info);
Paul Hu2b865912023-03-06 14:27:53 +08001217 } else {
1218 // No address. Notify resolution failure.
Paul Hu75069ed2023-01-14 00:31:09 +08001219 clientInfo.onResolveServiceFailed(
1220 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1221 }
1222
1223 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001224 if (!(request instanceof DiscoveryManagerRequest)) {
1225 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1226 break;
1227 }
Paul Hue4f5f252023-02-16 21:13:47 +08001228 stopDiscoveryManagerRequest(request, clientId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001229 break;
1230 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001231 case NsdManager.SERVICE_UPDATED: {
1232 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1233 info.setPort(serviceInfo.getPort());
1234
1235 Map<String, String> attrs = serviceInfo.getAttributes();
1236 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1237 final String key = kv.getKey();
1238 try {
1239 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1240 } catch (IllegalArgumentException e) {
1241 Log.e(TAG, "Invalid attribute", e);
1242 }
1243 }
1244
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001245 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001246 info.setHostAddresses(addresses);
1247 clientInfo.onServiceUpdated(clientId, info);
1248 break;
1249 }
1250 case NsdManager.SERVICE_UPDATED_LOST:
1251 clientInfo.onServiceUpdatedLost(clientId);
1252 break;
Paul Hu019621e2023-01-13 23:26:49 +08001253 default:
1254 return false;
1255 }
1256 return true;
1257 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001258 }
1259 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001260
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001261 @NonNull
1262 private static List<InetAddress> getInetAddresses(@NonNull MdnsServiceInfo serviceInfo) {
1263 final List<String> v4Addrs = serviceInfo.getIpv4Addresses();
1264 final List<String> v6Addrs = serviceInfo.getIpv6Addresses();
1265 final List<InetAddress> addresses = new ArrayList<>(v4Addrs.size() + v6Addrs.size());
1266 for (String ipv4Address : v4Addrs) {
1267 try {
1268 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1269 } catch (IllegalArgumentException e) {
1270 Log.wtf(TAG, "Invalid ipv4 address", e);
1271 }
1272 }
1273 for (String ipv6Address : v6Addrs) {
1274 try {
Yuyang Huanga6a6ff92023-04-24 13:33:34 +09001275 final Inet6Address addr = (Inet6Address) InetAddresses.parseNumericAddress(
1276 ipv6Address);
1277 addresses.add(InetAddressUtils.withScopeId(addr, serviceInfo.getInterfaceIndex()));
1278 } catch (IllegalArgumentException e) {
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001279 Log.wtf(TAG, "Invalid ipv6 address", e);
1280 }
1281 }
1282 return addresses;
1283 }
1284
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001285 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1286 switch (netId) {
1287 case NETID_UNSET:
1288 info.setNetwork(null);
1289 break;
1290 case INetd.LOCAL_NET_ID:
1291 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1292 // visible / usable for apps, so do not return it. Store the interface
1293 // index instead, so at least if the client tries to resolve the service
1294 // with that NsdServiceInfo, it will be done on the same interface.
1295 // If they recreate the NsdServiceInfo themselves, resolution would be
1296 // done on all interfaces as before T, which should also work.
1297 info.setNetwork(null);
1298 info.setInterfaceIndex(ifaceIdx);
1299 break;
1300 default:
1301 info.setNetwork(new Network(netId));
1302 }
1303 }
1304
paulhube186602022-04-12 07:18:23 +00001305 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1306 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1307 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1308 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1309 private String unescape(String s) {
1310 StringBuilder sb = new StringBuilder(s.length());
1311 for (int i = 0; i < s.length(); ++i) {
1312 char c = s.charAt(i);
1313 if (c == '\\') {
1314 if (++i >= s.length()) {
1315 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1316 break;
1317 }
1318 c = s.charAt(i);
1319 if (c != '.' && c != '\\') {
1320 if (i + 2 >= s.length()) {
1321 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1322 break;
1323 }
1324 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1325 + (s.charAt(i + 2) - '0'));
1326 i += 2;
1327 }
1328 }
1329 sb.append(c);
1330 }
1331 return sb.toString();
1332 }
1333
Paul Hu7445e3d2023-03-03 15:14:00 +08001334 /**
1335 * Check the given service type is valid and construct it to a service type
1336 * which can use for discovery / resolution service.
1337 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001338 * <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 +08001339 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1340 * underscore; they are alphanumerical characters or dashes or underscore, except the
1341 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1342 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001343 * <p>The subtype may also be specified with a comma after the service type, for example
1344 * _type._tcp,_subtype.
1345 *
Paul Hu7445e3d2023-03-03 15:14:00 +08001346 * @param serviceType the request service type for discovery / resolution service
1347 * @return constructed service type or null if the given service type is invalid.
1348 */
1349 @Nullable
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001350 public static Pair<String, String> parseTypeAndSubtype(String serviceType) {
Paul Hu7445e3d2023-03-03 15:14:00 +08001351 if (TextUtils.isEmpty(serviceType)) return null;
1352
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001353 final String typeOrSubtypePattern = "_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]";
Paul Hu7445e3d2023-03-03 15:14:00 +08001354 final Pattern serviceTypePattern = Pattern.compile(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001355 // Optional leading subtype (_subtype._type._tcp)
1356 // (?: xxx) is a non-capturing parenthesis, don't capture the dot
1357 "^(?:(" + typeOrSubtypePattern + ")\\.)?"
1358 // Actual type (_type._tcp.local)
1359 + "(" + typeOrSubtypePattern + "\\._(?:tcp|udp))"
Paul Hu7445e3d2023-03-03 15:14:00 +08001360 // Drop '.' at the end of service type that is compatible with old backend.
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001361 // e.g. allow "_type._tcp.local."
1362 + "\\.?"
1363 // Optional subtype after comma, for "_type._tcp,_subtype" format
1364 + "(?:,(" + typeOrSubtypePattern + "))?"
1365 + "$");
Paul Hu7445e3d2023-03-03 15:14:00 +08001366 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1367 if (!matcher.matches()) return null;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001368 // Use the subtype either at the beginning or after the comma
1369 final String subtype = matcher.group(1) != null ? matcher.group(1) : matcher.group(3);
1370 return new Pair<>(matcher.group(2), subtype);
Paul Hu7445e3d2023-03-03 15:14:00 +08001371 }
1372
Hugo Benichi803a2f02017-04-24 11:35:06 +09001373 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001374 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001375 this(ctx, handler, cleanupDelayMs, new Dependencies());
1376 }
1377
1378 @VisibleForTesting
1379 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001380 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001381 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001382 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001383 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001384 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1385 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001386 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001387
Paul Hu14667de2023-04-17 22:42:47 +08001388 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper(),
1389 LOGGER.forSubComponent("MdnsSocketProvider"));
Yuyang Huang700778b2023-03-08 16:17:05 +09001390 // Netlink monitor starts on boot, and intentionally never stopped, to ensure that all
1391 // address events are received.
1392 handler.post(mMdnsSocketProvider::startNetLinkMonitor);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001393 mMdnsSocketClient =
1394 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider);
Paul Hu14667de2023-04-17 22:42:47 +08001395 mMdnsDiscoveryManager = deps.makeMdnsDiscoveryManager(new ExecutorProvider(),
Yuyang Huang243d1a52023-05-23 17:26:52 +09001396 mMdnsSocketClient, LOGGER.forSubComponent("MdnsDiscoveryManager"));
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001397 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1398 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
Paul Hu14667de2023-04-17 22:42:47 +08001399 new AdvertiserCallback(), LOGGER.forSubComponent("MdnsAdvertiser"));
Paul Hu4bd98ef2023-01-12 13:42:07 +08001400 }
1401
1402 /**
1403 * Dependencies of NsdService, for injection in tests.
1404 */
1405 @VisibleForTesting
1406 public static class Dependencies {
1407 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001408 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001409 *
1410 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001411 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001412 */
1413 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Motomu Utsumi278db582023-04-21 12:35:22 +09001414 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1415 MDNS_DISCOVERY_MANAGER_VERSION, DeviceConfigUtils.TETHERING_MODULE_NAME,
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +09001416 false /* defaultEnabled */);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001417 }
1418
1419 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001420 * Check whether the MdnsAdvertiser feature is enabled.
1421 *
1422 * @param context The global context information about an app environment.
1423 * @return true if the MdnsAdvertiser feature is enabled.
1424 */
1425 public boolean isMdnsAdvertiserEnabled(Context context) {
Motomu Utsumi278db582023-04-21 12:35:22 +09001426 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1427 MDNS_ADVERTISER_VERSION, DeviceConfigUtils.TETHERING_MODULE_NAME,
1428 false /* defaultEnabled */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001429 }
1430
1431 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001432 * Get the type allowlist flag value.
1433 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1434 */
1435 @Nullable
1436 public String getTypeAllowlistFlags() {
1437 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1438 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1439 }
1440
1441 /**
1442 * @see DeviceConfigUtils#isFeatureEnabled(Context, String, String, String, boolean)
1443 */
1444 public boolean isFeatureEnabled(Context context, String feature) {
1445 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1446 feature, DeviceConfigUtils.TETHERING_MODULE_NAME, false /* defaultEnabled */);
1447 }
1448
1449 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001450 * @see MdnsDiscoveryManager
1451 */
1452 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
Paul Hu14667de2023-04-17 22:42:47 +08001453 @NonNull ExecutorProvider executorProvider,
Yuyang Huang243d1a52023-05-23 17:26:52 +09001454 @NonNull MdnsMultinetworkSocketClient socketClient, @NonNull SharedLog sharedLog) {
1455 return new MdnsDiscoveryManager(executorProvider, socketClient, sharedLog);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001456 }
1457
1458 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001459 * @see MdnsAdvertiser
1460 */
1461 public MdnsAdvertiser makeMdnsAdvertiser(
1462 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
Paul Hu14667de2023-04-17 22:42:47 +08001463 @NonNull MdnsAdvertiser.AdvertiserCallback cb, @NonNull SharedLog sharedLog) {
1464 return new MdnsAdvertiser(looper, socketProvider, cb, sharedLog);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001465 }
1466
1467 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001468 * @see MdnsSocketProvider
1469 */
Paul Hu14667de2023-04-17 22:42:47 +08001470 public MdnsSocketProvider makeMdnsSocketProvider(@NonNull Context context,
1471 @NonNull Looper looper, @NonNull SharedLog sharedLog) {
1472 return new MdnsSocketProvider(context, looper, sharedLog);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001473 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001474 }
1475
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001476 /**
1477 * Return whether a type is allowlisted to use the Java backend.
1478 * @param type The service type
1479 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1480 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1481 */
1482 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1483 @NonNull String flagPrefix) {
1484 if (type == null) return false;
1485 final String typesConfig = mDeps.getTypeAllowlistFlags();
1486 if (TextUtils.isEmpty(typesConfig)) return false;
1487
1488 final String mappingPrefix = type + ":";
1489 String mappedFlag = null;
1490 for (String mapping : TextUtils.split(typesConfig, ",")) {
1491 if (mapping.startsWith(mappingPrefix)) {
1492 mappedFlag = mapping.substring(mappingPrefix.length());
1493 break;
1494 }
1495 }
1496
1497 if (mappedFlag == null) return false;
1498
1499 return mDeps.isFeatureEnabled(mContext,
1500 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1501 }
1502
1503 private boolean useDiscoveryManagerForType(@Nullable String type) {
1504 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1505 }
1506
1507 private boolean useAdvertiserForType(@Nullable String type) {
1508 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1509 }
1510
paulhu1b35e822022-04-08 14:48:41 +08001511 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001512 HandlerThread thread = new HandlerThread(TAG);
1513 thread.start();
1514 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001515 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001516 return service;
1517 }
1518
paulhu2b9ed952022-02-10 21:58:32 +08001519 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1520 private final StateMachine mStateMachine;
1521
1522 MDnsEventCallback(StateMachine sm) {
1523 mStateMachine = sm;
1524 }
1525
1526 @Override
1527 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1528 mStateMachine.sendMessage(
1529 MDNS_SERVICE_EVENT, status.result, status.id, status);
1530 }
1531
1532 @Override
1533 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1534 mStateMachine.sendMessage(
1535 MDNS_SERVICE_EVENT, status.result, status.id, status);
1536 }
1537
1538 @Override
1539 public void onServiceResolutionStatus(final ResolutionInfo status) {
1540 mStateMachine.sendMessage(
1541 MDNS_SERVICE_EVENT, status.result, status.id, status);
1542 }
1543
1544 @Override
1545 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1546 mStateMachine.sendMessage(
1547 MDNS_SERVICE_EVENT, status.result, status.id, status);
1548 }
1549
1550 @Override
1551 public int getInterfaceVersion() throws RemoteException {
1552 return this.VERSION;
1553 }
1554
1555 @Override
1556 public String getInterfaceHash() throws RemoteException {
1557 return this.HASH;
1558 }
1559 }
1560
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001561 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
1562 @Override
1563 public void onRegisterServiceSucceeded(int serviceId, NsdServiceInfo registeredInfo) {
1564 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1565 if (clientInfo == null) return;
1566
1567 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1568 if (clientId < 0) return;
1569
1570 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1571 // historical behavior.
1572 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
1573 clientInfo.onRegisterServiceSucceeded(clientId, cbInfo);
1574 }
1575
1576 @Override
1577 public void onRegisterServiceFailed(int serviceId, int errorCode) {
1578 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1579 if (clientInfo == null) return;
1580
1581 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1582 if (clientId < 0) return;
1583
1584 clientInfo.onRegisterServiceFailed(clientId, errorCode);
1585 }
1586
1587 private ClientInfo getClientInfoOrLog(int serviceId) {
1588 final ClientInfo clientInfo = mIdToClientInfoMap.get(serviceId);
1589 if (clientInfo == null) {
1590 Log.e(TAG, String.format("Callback for service %d has no client", serviceId));
1591 }
1592 return clientInfo;
1593 }
1594
1595 private int getClientIdOrLog(@NonNull ClientInfo info, int serviceId) {
1596 final int clientId = info.getClientId(serviceId);
1597 if (clientId < 0) {
1598 Log.e(TAG, String.format("Client ID not found for service %d", serviceId));
1599 }
1600 return clientId;
1601 }
1602 }
1603
Paul Hu2e0a88c2023-03-09 16:05:01 +08001604 private static class ConnectorArgs {
1605 @NonNull public final NsdServiceConnector connector;
1606 @NonNull public final INsdManagerCallback callback;
1607 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001608 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001609
1610 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00001611 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08001612 this.connector = connector;
1613 this.callback = callback;
1614 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001615 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001616 }
1617 }
1618
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001619 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08001620 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001621 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu2e0a88c2023-03-09 16:05:01 +08001622 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001623 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00001624 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
1625 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend,
1626 Binder.getCallingUid())));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001627 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07001628 }
1629
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001630 private static class ListenerArgs {
1631 public final NsdServiceConnector connector;
1632 public final NsdServiceInfo serviceInfo;
1633 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
1634 this.connector = connector;
1635 this.serviceInfo = serviceInfo;
1636 }
1637 }
1638
1639 private class NsdServiceConnector extends INsdServiceConnector.Stub
1640 implements IBinder.DeathRecipient {
1641 @Override
1642 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
1643 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1644 NsdManager.REGISTER_SERVICE, 0, listenerKey,
1645 new ListenerArgs(this, serviceInfo)));
1646 }
1647
1648 @Override
1649 public void unregisterService(int listenerKey) {
1650 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1651 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
1652 new ListenerArgs(this, null)));
1653 }
1654
1655 @Override
1656 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
1657 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1658 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
1659 new ListenerArgs(this, serviceInfo)));
1660 }
1661
1662 @Override
1663 public void stopDiscovery(int listenerKey) {
1664 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1665 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
1666 }
1667
1668 @Override
1669 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
1670 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1671 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
1672 new ListenerArgs(this, serviceInfo)));
1673 }
1674
1675 @Override
Paul Hub58deb72022-12-26 09:24:42 +00001676 public void stopResolution(int listenerKey) {
1677 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1678 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
1679 }
1680
1681 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00001682 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
1683 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1684 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
1685 new ListenerArgs(this, serviceInfo)));
1686 }
1687
1688 @Override
1689 public void unregisterServiceInfoCallback(int listenerKey) {
1690 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1691 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
1692 new ListenerArgs(this, null)));
1693 }
1694
1695 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001696 public void startDaemon() {
1697 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1698 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
1699 }
1700
1701 @Override
1702 public void binderDied() {
1703 mNsdStateMachine.sendMessage(
1704 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
1705 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001706 }
1707
Hugo Benichi912db992017-04-24 16:41:03 +09001708 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07001709 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07001710 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09001711 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
1712 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07001713 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07001714 }
1715
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001716 private int getUniqueId() {
1717 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
1718 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001719 }
1720
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001721 private boolean registerService(int regId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09001722 if (DBG) {
paulhub2225702021-11-17 09:35:33 +08001723 Log.d(TAG, "registerService: " + regId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001724 }
Hugo Benichi6d706442017-04-24 16:19:58 +09001725 String name = service.getServiceName();
1726 String type = service.getServiceType();
1727 int port = service.getPort();
1728 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001729 final int registerInterface = getNetworkInterfaceIndex(service);
1730 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08001731 Log.e(TAG, "Interface to register service on not found");
1732 return false;
1733 }
1734 return mMDnsManager.registerService(regId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001735 }
1736
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001737 private boolean unregisterService(int regId) {
paulhu2b9ed952022-02-10 21:58:32 +08001738 return mMDnsManager.stopOperation(regId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001739 }
1740
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001741 private boolean discoverServices(int discoveryId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08001742 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001743 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
1744 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001745 Log.e(TAG, "Interface to discover service on not found");
1746 return false;
1747 }
paulhu2b9ed952022-02-10 21:58:32 +08001748 return mMDnsManager.discover(discoveryId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001749 }
1750
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001751 private boolean stopServiceDiscovery(int discoveryId) {
paulhu2b9ed952022-02-10 21:58:32 +08001752 return mMDnsManager.stopOperation(discoveryId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001753 }
1754
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001755 private boolean resolveService(int resolveId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001756 final String name = service.getServiceName();
1757 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001758 final int resolveInterface = getNetworkInterfaceIndex(service);
1759 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001760 Log.e(TAG, "Interface to resolve service on not found");
1761 return false;
1762 }
paulhu2b9ed952022-02-10 21:58:32 +08001763 return mMDnsManager.resolve(resolveId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001764 }
1765
1766 /**
1767 * Guess the interface to use to resolve or discover a service on a specific network.
1768 *
1769 * This is an imperfect guess, as for example the network may be gone or not yet fully
1770 * registered. This is fine as failing is correct if the network is gone, and a client
1771 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
1772 * this is to support the legacy mdnsresponder implementation, which historically resolved
1773 * services on an unspecified network.
1774 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001775 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
1776 final Network network = serviceInfo.getNetwork();
1777 if (network == null) {
1778 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
1779 // provided by NsdService from discovery results, and the service was found on an
1780 // interface that has no app-usable Network).
1781 if (serviceInfo.getInterfaceIndex() != 0) {
1782 return serviceInfo.getInterfaceIndex();
1783 }
1784 return IFACE_IDX_ANY;
1785 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001786
1787 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
1788 if (cm == null) {
1789 Log.wtf(TAG, "No ConnectivityManager for resolveService");
1790 return IFACE_IDX_ANY;
1791 }
1792 final LinkProperties lp = cm.getLinkProperties(network);
1793 if (lp == null) return IFACE_IDX_ANY;
1794
1795 // Only resolve on non-stacked interfaces
1796 final NetworkInterface iface;
1797 try {
1798 iface = NetworkInterface.getByName(lp.getInterfaceName());
1799 } catch (SocketException e) {
1800 Log.e(TAG, "Error querying interface", e);
1801 return IFACE_IDX_ANY;
1802 }
1803
1804 if (iface == null) {
1805 Log.e(TAG, "Interface not found: " + lp.getInterfaceName());
1806 return IFACE_IDX_ANY;
1807 }
1808
1809 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001810 }
1811
1812 private boolean stopResolveService(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001813 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001814 }
1815
paulhu2b9ed952022-02-10 21:58:32 +08001816 private boolean getAddrInfo(int resolveId, String hostname, int interfaceIdx) {
1817 return mMDnsManager.getServiceAddress(resolveId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001818 }
1819
1820 private boolean stopGetAddrInfo(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001821 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001822 }
1823
1824 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00001825 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1826 if (!PermissionUtils.checkDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001827
Paul Hub2e67d32023-04-18 05:50:14 +00001828 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
1829 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07001830 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00001831
1832 // Dump service and clients logs
1833 pw.println();
Paul Hu14667de2023-04-17 22:42:47 +08001834 pw.println("Logs:");
Paul Hub2e67d32023-04-18 05:50:14 +00001835 pw.increaseIndent();
1836 mServiceLogs.reverseDump(pw);
1837 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001838 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001839
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001840 private abstract static class ClientRequest {
1841 private final int mGlobalId;
1842
1843 private ClientRequest(int globalId) {
1844 mGlobalId = globalId;
1845 }
1846 }
1847
1848 private static class LegacyClientRequest extends ClientRequest {
1849 private final int mRequestCode;
1850
1851 private LegacyClientRequest(int globalId, int requestCode) {
1852 super(globalId);
1853 mRequestCode = requestCode;
1854 }
1855 }
1856
1857 private static class AdvertiserClientRequest extends ClientRequest {
1858 private AdvertiserClientRequest(int globalId) {
1859 super(globalId);
1860 }
1861 }
1862
1863 private static class DiscoveryManagerRequest extends ClientRequest {
1864 @NonNull
1865 private final MdnsListener mListener;
1866
1867 private DiscoveryManagerRequest(int globalId, @NonNull MdnsListener listener) {
1868 super(globalId);
1869 mListener = listener;
1870 }
1871 }
1872
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001873 /* Information tracked per client */
1874 private class ClientInfo {
1875
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001876 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001877 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001878 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001879 private NsdServiceInfo mResolvedService;
1880
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001881 /* A map from client-side ID (listenerKey) to the request */
1882 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08001883
Luke Huangf7277ed2021-07-12 21:15:10 +08001884 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001885 private boolean mIsPreSClient = false;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001886 // The flag of using java backend if the client's target SDK >= U
1887 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001888 // Store client logs
1889 private final SharedLog mClientLogs;
Luke Huangf7277ed2021-07-12 21:15:10 +08001890
Paul Hub2e67d32023-04-18 05:50:14 +00001891 private ClientInfo(INsdManagerCallback cb, boolean useJavaBackend, SharedLog sharedLog) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001892 mCb = cb;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001893 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001894 mClientLogs = sharedLog;
1895 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001896 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001897
1898 @Override
1899 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06001900 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07001901 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001902 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
1903 for (int i = 0; i < mClientRequests.size(); i++) {
1904 int clientID = mClientRequests.keyAt(i);
1905 sb.append("clientId ")
1906 .append(clientID)
1907 .append(" mDnsId ").append(mClientRequests.valueAt(i).mGlobalId)
1908 .append(" type ").append(
1909 mClientRequests.valueAt(i).getClass().getSimpleName())
1910 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07001911 }
1912 return sb.toString();
1913 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001914
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001915 private boolean isPreSClient() {
1916 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08001917 }
1918
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001919 private void setPreSClient() {
1920 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08001921 }
1922
Paul Hue4f5f252023-02-16 21:13:47 +08001923 private void unregisterMdnsListenerFromRequest(ClientRequest request) {
1924 final MdnsListener listener =
1925 ((DiscoveryManagerRequest) request).mListener;
1926 mMdnsDiscoveryManager.unregisterListener(
1927 listener.getListenedServiceType(), listener);
1928 }
1929
Dave Plattfeff2af2014-03-07 14:48:22 -08001930 // Remove any pending requests from the global map when we get rid of a client,
1931 // and send cancellations to the daemon.
1932 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00001933 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09001934 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001935 for (int i = 0; i < mClientRequests.size(); i++) {
1936 final int clientId = mClientRequests.keyAt(i);
1937 final ClientRequest request = mClientRequests.valueAt(i);
1938 final int globalId = request.mGlobalId;
Dave Plattfeff2af2014-03-07 14:48:22 -08001939 mIdToClientInfoMap.remove(globalId);
paulhub2225702021-11-17 09:35:33 +08001940 if (DBG) {
1941 Log.d(TAG, "Terminating client-ID " + clientId
1942 + " global-ID " + globalId + " type " + mClientRequests.get(clientId));
1943 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001944
1945 if (request instanceof DiscoveryManagerRequest) {
Paul Hue4f5f252023-02-16 21:13:47 +08001946 unregisterMdnsListenerFromRequest(request);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001947 continue;
1948 }
1949
1950 if (request instanceof AdvertiserClientRequest) {
1951 mAdvertiser.removeService(globalId);
1952 continue;
1953 }
1954
1955 if (!(request instanceof LegacyClientRequest)) {
1956 throw new IllegalStateException("Unknown request type: " + request.getClass());
1957 }
1958
1959 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08001960 case NsdManager.DISCOVER_SERVICES:
1961 stopServiceDiscovery(globalId);
1962 break;
1963 case NsdManager.RESOLVE_SERVICE:
1964 stopResolveService(globalId);
1965 break;
1966 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001967 unregisterService(globalId);
Dave Plattfeff2af2014-03-07 14:48:22 -08001968 break;
1969 default:
1970 break;
1971 }
1972 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001973 mClientRequests.clear();
1974 }
1975
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001976 // mClientRequests is a sparse array of listener id -> ClientRequest. For a given
1977 // mDnsClient id, return the corresponding listener id. mDnsClient id is also called a
1978 // global id.
Christopher Lane74411222014-04-25 18:39:07 -07001979 private int getClientId(final int globalId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001980 for (int i = 0; i < mClientRequests.size(); i++) {
1981 if (mClientRequests.valueAt(i).mGlobalId == globalId) {
1982 return mClientRequests.keyAt(i);
1983 }
Christopher Lane74411222014-04-25 18:39:07 -07001984 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001985 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07001986 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001987
Paul Hub2e67d32023-04-18 05:50:14 +00001988 private void log(String message) {
1989 mClientLogs.log(message);
1990 }
1991
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001992 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info) {
1993 try {
1994 mCb.onDiscoverServicesStarted(listenerKey, info);
1995 } catch (RemoteException e) {
1996 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
1997 }
1998 }
1999
2000 void onDiscoverServicesFailed(int listenerKey, int error) {
2001 try {
2002 mCb.onDiscoverServicesFailed(listenerKey, error);
2003 } catch (RemoteException e) {
2004 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
2005 }
2006 }
2007
2008 void onServiceFound(int listenerKey, NsdServiceInfo info) {
2009 try {
2010 mCb.onServiceFound(listenerKey, info);
2011 } catch (RemoteException e) {
2012 Log.e(TAG, "Error calling onServiceFound(", e);
2013 }
2014 }
2015
2016 void onServiceLost(int listenerKey, NsdServiceInfo info) {
2017 try {
2018 mCb.onServiceLost(listenerKey, info);
2019 } catch (RemoteException e) {
2020 Log.e(TAG, "Error calling onServiceLost(", e);
2021 }
2022 }
2023
2024 void onStopDiscoveryFailed(int listenerKey, int error) {
2025 try {
2026 mCb.onStopDiscoveryFailed(listenerKey, error);
2027 } catch (RemoteException e) {
2028 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
2029 }
2030 }
2031
2032 void onStopDiscoverySucceeded(int listenerKey) {
2033 try {
2034 mCb.onStopDiscoverySucceeded(listenerKey);
2035 } catch (RemoteException e) {
2036 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
2037 }
2038 }
2039
2040 void onRegisterServiceFailed(int listenerKey, int error) {
2041 try {
2042 mCb.onRegisterServiceFailed(listenerKey, error);
2043 } catch (RemoteException e) {
2044 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2045 }
2046 }
2047
2048 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info) {
2049 try {
2050 mCb.onRegisterServiceSucceeded(listenerKey, info);
2051 } catch (RemoteException e) {
2052 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2053 }
2054 }
2055
2056 void onUnregisterServiceFailed(int listenerKey, int error) {
2057 try {
2058 mCb.onUnregisterServiceFailed(listenerKey, error);
2059 } catch (RemoteException e) {
2060 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2061 }
2062 }
2063
2064 void onUnregisterServiceSucceeded(int listenerKey) {
2065 try {
2066 mCb.onUnregisterServiceSucceeded(listenerKey);
2067 } catch (RemoteException e) {
2068 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2069 }
2070 }
2071
2072 void onResolveServiceFailed(int listenerKey, int error) {
2073 try {
2074 mCb.onResolveServiceFailed(listenerKey, error);
2075 } catch (RemoteException e) {
2076 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2077 }
2078 }
2079
2080 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info) {
2081 try {
2082 mCb.onResolveServiceSucceeded(listenerKey, info);
2083 } catch (RemoteException e) {
2084 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2085 }
2086 }
Paul Hub58deb72022-12-26 09:24:42 +00002087
2088 void onStopResolutionFailed(int listenerKey, int error) {
2089 try {
2090 mCb.onStopResolutionFailed(listenerKey, error);
2091 } catch (RemoteException e) {
2092 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2093 }
2094 }
2095
2096 void onStopResolutionSucceeded(int listenerKey) {
2097 try {
2098 mCb.onStopResolutionSucceeded(listenerKey);
2099 } catch (RemoteException e) {
2100 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2101 }
2102 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002103
2104 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
2105 try {
2106 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2107 } catch (RemoteException e) {
2108 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2109 }
2110 }
2111
2112 void onServiceUpdated(int listenerKey, NsdServiceInfo info) {
2113 try {
2114 mCb.onServiceUpdated(listenerKey, info);
2115 } catch (RemoteException e) {
2116 Log.e(TAG, "Error calling onServiceUpdated", e);
2117 }
2118 }
2119
2120 void onServiceUpdatedLost(int listenerKey) {
2121 try {
2122 mCb.onServiceUpdatedLost(listenerKey);
2123 } catch (RemoteException e) {
2124 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2125 }
2126 }
2127
2128 void onServiceInfoCallbackUnregistered(int listenerKey) {
2129 try {
2130 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2131 } catch (RemoteException e) {
2132 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2133 }
2134 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002135 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002136}