blob: 3bc09db0c8495d95ae9494a5194334d1e4878142 [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;
Paul Hu4bd98ef2023-01-12 13:42:07 +080022import static android.provider.DeviceConfig.NAMESPACE_CONNECTIVITY;
paulhu2b9ed952022-02-10 21:58:32 +080023
Paul Hu23fa2022023-01-13 22:57:24 +080024import android.annotation.NonNull;
Paul Hu4bd98ef2023-01-12 13:42:07 +080025import android.annotation.Nullable;
paulhua262cc12019-08-12 16:25:11 +080026import android.content.Context;
Irfan Sheriff75006652012-04-17 23:15:29 -070027import android.content.Intent;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090028import android.net.ConnectivityManager;
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +090029import android.net.INetd;
Paul Hu75069ed2023-01-14 00:31:09 +080030import android.net.InetAddresses;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090031import android.net.LinkProperties;
32import android.net.Network;
paulhu2b9ed952022-02-10 21:58:32 +080033import android.net.mdns.aidl.DiscoveryInfo;
34import android.net.mdns.aidl.GetAddressInfo;
35import android.net.mdns.aidl.IMDnsEventListener;
36import android.net.mdns.aidl.RegistrationInfo;
37import android.net.mdns.aidl.ResolutionInfo;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070038import android.net.nsd.INsdManager;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090039import android.net.nsd.INsdManagerCallback;
40import android.net.nsd.INsdServiceConnector;
paulhu2b9ed952022-02-10 21:58:32 +080041import android.net.nsd.MDnsManager;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070042import android.net.nsd.NsdManager;
paulhua262cc12019-08-12 16:25:11 +080043import android.net.nsd.NsdServiceInfo;
Hugo Benichi803a2f02017-04-24 11:35:06 +090044import android.os.Handler;
paulhua262cc12019-08-12 16:25:11 +080045import android.os.HandlerThread;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090046import android.os.IBinder;
Paul Hu4bd98ef2023-01-12 13:42:07 +080047import android.os.Looper;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070048import android.os.Message;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090049import android.os.RemoteException;
Dianne Hackborn692107e2012-08-29 18:32:08 -070050import android.os.UserHandle;
Paul Hu23fa2022023-01-13 22:57:24 +080051import android.text.TextUtils;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090052import android.util.Log;
53import android.util.Pair;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070054import android.util.SparseArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070055
paulhua262cc12019-08-12 16:25:11 +080056import com.android.internal.annotations.VisibleForTesting;
paulhua262cc12019-08-12 16:25:11 +080057import com.android.internal.util.State;
58import com.android.internal.util.StateMachine;
Paul Hu4bd98ef2023-01-12 13:42:07 +080059import com.android.net.module.util.DeviceConfigUtils;
paulhu3ffffe72021-09-16 10:15:22 +080060import com.android.net.module.util.PermissionUtils;
Paul Hu4bd98ef2023-01-12 13:42:07 +080061import com.android.server.connectivity.mdns.ExecutorProvider;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090062import com.android.server.connectivity.mdns.MdnsAdvertiser;
Paul Hu4bd98ef2023-01-12 13:42:07 +080063import com.android.server.connectivity.mdns.MdnsDiscoveryManager;
64import com.android.server.connectivity.mdns.MdnsMultinetworkSocketClient;
Paul Hu23fa2022023-01-13 22:57:24 +080065import com.android.server.connectivity.mdns.MdnsSearchOptions;
66import com.android.server.connectivity.mdns.MdnsServiceBrowserListener;
67import com.android.server.connectivity.mdns.MdnsServiceInfo;
Paul Hu4bd98ef2023-01-12 13:42:07 +080068import com.android.server.connectivity.mdns.MdnsSocketClientBase;
69import com.android.server.connectivity.mdns.MdnsSocketProvider;
paulhua262cc12019-08-12 16:25:11 +080070
Irfan Sheriff77ec5582012-03-22 17:01:39 -070071import java.io.FileDescriptor;
72import java.io.PrintWriter;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070073import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090074import java.net.NetworkInterface;
75import java.net.SocketException;
76import java.net.UnknownHostException;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090077import java.nio.ByteBuffer;
78import java.nio.CharBuffer;
79import java.nio.charset.Charset;
80import java.nio.charset.CharsetEncoder;
81import java.nio.charset.StandardCharsets;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070082import java.util.HashMap;
Paul Hu23fa2022023-01-13 22:57:24 +080083import java.util.List;
Paul Hu75069ed2023-01-14 00:31:09 +080084import java.util.Map;
Paul Hu18aeccc2022-12-27 08:48:48 +000085import java.util.Objects;
Paul Hu23fa2022023-01-13 22:57:24 +080086import java.util.regex.Matcher;
87import java.util.regex.Pattern;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070088
Irfan Sheriff77ec5582012-03-22 17:01:39 -070089/**
90 * Network Service Discovery Service handles remote service discovery operation requests by
91 * implementing the INsdManager interface.
92 *
93 * @hide
94 */
95public class NsdService extends INsdManager.Stub {
96 private static final String TAG = "NsdService";
97 private static final String MDNS_TAG = "mDnsConnector";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090098 /**
99 * Enable discovery using the Java DiscoveryManager, instead of the legacy mdnsresponder
100 * implementation.
101 */
Paul Hu4bd98ef2023-01-12 13:42:07 +0800102 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Paul Hu23fa2022023-01-13 22:57:24 +0800103 private static final String LOCAL_DOMAIN_NAME = "local";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900104 // Max label length as per RFC 1034/1035
105 private static final int MAX_LABEL_LENGTH = 63;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700106
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900107 /**
108 * Enable advertising using the Java MdnsAdvertiser, instead of the legacy mdnsresponder
109 * implementation.
110 */
111 private static final String MDNS_ADVERTISER_VERSION = "mdns_advertiser_version";
112
113 public static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +0000114 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900115 private static final int IFACE_IDX_ANY = 0;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700116
Hugo Benichi32be63d2017-04-05 14:06:11 +0900117 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900118 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +0800119 private final MDnsManager mMDnsManager;
120 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900121 @NonNull
122 private final Dependencies mDeps;
123 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800124 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900125 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800126 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900127 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800128 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900129 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900130 private final MdnsAdvertiser mAdvertiser;
Paul Hu23fa2022023-01-13 22:57:24 +0800131 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800132 // state machine thread. If change this outside state machine, it will need to introduce
133 // synchronization.
134 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800135 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700136
137 /**
138 * Clients receiving asynchronous messages
139 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900140 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700141
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700142 /* A map from unique id to client info */
Hugo Benichi32be63d2017-04-05 14:06:11 +0900143 private final SparseArray<ClientInfo> mIdToClientInfoMap= new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700144
Luke Huang05298582021-06-13 16:52:05 +0000145 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700146
Hugo Benichi32be63d2017-04-05 14:06:11 +0900147 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700148 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800149 // The count of the connected legacy clients.
150 private int mLegacyClientCount = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700151
Paul Hu23fa2022023-01-13 22:57:24 +0800152 private static class MdnsListener implements MdnsServiceBrowserListener {
153 protected final int mClientId;
154 protected final int mTransactionId;
155 @NonNull
156 protected final NsdServiceInfo mReqServiceInfo;
157 @NonNull
158 protected final String mListenedServiceType;
159
160 MdnsListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
161 @NonNull String listenedServiceType) {
162 mClientId = clientId;
163 mTransactionId = transactionId;
164 mReqServiceInfo = reqServiceInfo;
165 mListenedServiceType = listenedServiceType;
166 }
167
168 @NonNull
169 public String getListenedServiceType() {
170 return mListenedServiceType;
171 }
172
173 @Override
174 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo) { }
175
176 @Override
177 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
178
179 @Override
180 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
181
182 @Override
183 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) { }
184
185 @Override
186 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
187
188 @Override
189 public void onSearchStoppedWithError(int error) { }
190
191 @Override
192 public void onSearchFailedToStart() { }
193
194 @Override
195 public void onDiscoveryQuerySent(@NonNull List<String> subtypes, int transactionId) { }
196
197 @Override
198 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
199 }
200
201 private class DiscoveryListener extends MdnsListener {
202
203 DiscoveryListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
204 @NonNull String listenServiceType) {
205 super(clientId, transactionId, reqServiceInfo, listenServiceType);
206 }
207
208 @Override
209 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu019621e2023-01-13 23:26:49 +0800210 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
211 NsdManager.SERVICE_FOUND,
212 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800213 }
214
215 @Override
216 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800217 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
218 NsdManager.SERVICE_LOST,
219 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800220 }
221 }
222
Paul Hu75069ed2023-01-14 00:31:09 +0800223 private class ResolutionListener extends MdnsListener {
224
225 ResolutionListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
226 @NonNull String listenServiceType) {
227 super(clientId, transactionId, reqServiceInfo, listenServiceType);
228 }
229
230 @Override
231 public void onServiceFound(MdnsServiceInfo serviceInfo) {
232 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
233 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
234 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
235 }
236 }
237
Paul Hu019621e2023-01-13 23:26:49 +0800238 /**
239 * Data class of mdns service callback information.
240 */
241 private static class MdnsEvent {
242 final int mClientId;
243 @NonNull
244 final String mRequestedServiceType;
245 @NonNull
246 final MdnsServiceInfo mMdnsServiceInfo;
247
248 MdnsEvent(int clientId, @NonNull String requestedServiceType,
249 @NonNull MdnsServiceInfo mdnsServiceInfo) {
250 mClientId = clientId;
251 mRequestedServiceType = requestedServiceType;
252 mMdnsServiceInfo = mdnsServiceInfo;
253 }
254 }
255
Irfan Sheriff75006652012-04-17 23:15:29 -0700256 private class NsdStateMachine extends StateMachine {
257
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700258 private final DefaultState mDefaultState = new DefaultState();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700259 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700260
261 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700262 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900263 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700264 }
265
Luke Huang92860f92021-06-23 06:29:30 +0000266 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800267 if (mIsDaemonStarted) {
268 if (DBG) Log.d(TAG, "Daemon is already started.");
269 return;
270 }
271 mMDnsManager.registerEventListener(mMDnsEventCallback);
272 mMDnsManager.startDaemon();
273 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000274 maybeScheduleStop();
275 }
276
paulhu2b9ed952022-02-10 21:58:32 +0800277 private void maybeStopDaemon() {
278 if (!mIsDaemonStarted) {
279 if (DBG) Log.d(TAG, "Daemon has not been started.");
280 return;
281 }
282 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
283 mMDnsManager.stopDaemon();
284 mIsDaemonStarted = false;
285 }
286
Luke Huang92860f92021-06-23 06:29:30 +0000287 private boolean isAnyRequestActive() {
288 return mIdToClientInfoMap.size() != 0;
289 }
290
291 private void scheduleStop() {
292 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
293 }
294 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800295 // The native daemon should stay alive and can't be cleanup
296 // if any legacy client connected.
297 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000298 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000299 }
300 }
301
Luke Huang92860f92021-06-23 06:29:30 +0000302 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000303 this.removeMessages(NsdManager.DAEMON_CLEANUP);
304 }
305
Paul Hu23fa2022023-01-13 22:57:24 +0800306 private void maybeStartMonitoringSockets() {
307 if (mIsMonitoringSocketsStarted) {
308 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
309 return;
310 }
311
312 mMdnsSocketProvider.startMonitoringSockets();
313 mIsMonitoringSocketsStarted = true;
314 }
315
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900316 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
317 if (!mIsMonitoringSocketsStarted) return;
318 if (isAnyRequestActive()) return;
319
Paul Hu58f20602023-02-18 11:41:07 +0800320 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800321 mIsMonitoringSocketsStarted = false;
322 }
323
Hugo Benichi803a2f02017-04-24 11:35:06 +0900324 NsdStateMachine(String name, Handler handler) {
325 super(name, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -0700326 addState(mDefaultState);
Irfan Sheriff75006652012-04-17 23:15:29 -0700327 addState(mEnabledState, mDefaultState);
paulhu5568f452021-11-30 13:31:29 +0800328 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900329 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700330 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700331 }
332
333 class DefaultState extends State {
334 @Override
335 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900336 final ClientInfo cInfo;
337 final int clientId = msg.arg2;
Irfan Sheriff75006652012-04-17 23:15:29 -0700338 switch (msg.what) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900339 case NsdManager.REGISTER_CLIENT:
340 final Pair<NsdServiceConnector, INsdManagerCallback> arg =
341 (Pair<NsdServiceConnector, INsdManagerCallback>) msg.obj;
342 final INsdManagerCallback cb = arg.second;
343 try {
344 cb.asBinder().linkToDeath(arg.first, 0);
345 cInfo = new ClientInfo(cb);
346 mClients.put(arg.first, cInfo);
347 } catch (RemoteException e) {
348 Log.w(TAG, "Client " + clientId + " has already died");
Irfan Sheriff75006652012-04-17 23:15:29 -0700349 }
350 break;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900351 case NsdManager.UNREGISTER_CLIENT:
352 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
353 cInfo = mClients.remove(connector);
Dave Plattfeff2af2014-03-07 14:48:22 -0800354 if (cInfo != null) {
355 cInfo.expungeAllRequests();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900356 if (cInfo.isPreSClient()) {
Luke Huangf7277ed2021-07-12 21:15:10 +0800357 mLegacyClientCount -= 1;
358 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800359 }
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900360 maybeStopMonitoringSocketsIfNoActiveRequest();
Luke Huangf7277ed2021-07-12 21:15:10 +0800361 maybeScheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700362 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700363 case NsdManager.DISCOVER_SERVICES:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900364 cInfo = getClientInfoForReply(msg);
365 if (cInfo != null) {
366 cInfo.onDiscoverServicesFailed(
367 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
368 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700369 break;
370 case NsdManager.STOP_DISCOVERY:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900371 cInfo = getClientInfoForReply(msg);
372 if (cInfo != null) {
373 cInfo.onStopDiscoveryFailed(
374 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
375 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700376 break;
377 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900378 cInfo = getClientInfoForReply(msg);
379 if (cInfo != null) {
380 cInfo.onRegisterServiceFailed(
381 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
382 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700383 break;
384 case NsdManager.UNREGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900385 cInfo = getClientInfoForReply(msg);
386 if (cInfo != null) {
387 cInfo.onUnregisterServiceFailed(
388 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
389 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700390 break;
391 case NsdManager.RESOLVE_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900392 cInfo = getClientInfoForReply(msg);
393 if (cInfo != null) {
394 cInfo.onResolveServiceFailed(
395 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
396 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700397 break;
Paul Hub58deb72022-12-26 09:24:42 +0000398 case NsdManager.STOP_RESOLUTION:
399 cInfo = getClientInfoForReply(msg);
400 if (cInfo != null) {
401 cInfo.onStopResolutionFailed(
402 clientId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
403 }
404 break;
Paul Hu18aeccc2022-12-27 08:48:48 +0000405 case NsdManager.REGISTER_SERVICE_CALLBACK:
406 cInfo = getClientInfoForReply(msg);
407 if (cInfo != null) {
408 cInfo.onServiceInfoCallbackRegistrationFailed(
409 clientId, NsdManager.FAILURE_BAD_PARAMETERS);
410 }
411 break;
Luke Huang05298582021-06-13 16:52:05 +0000412 case NsdManager.DAEMON_CLEANUP:
paulhu2b9ed952022-02-10 21:58:32 +0800413 maybeStopDaemon();
Luke Huang05298582021-06-13 16:52:05 +0000414 break;
Luke Huangf7277ed2021-07-12 21:15:10 +0800415 // This event should be only sent by the legacy (target SDK < S) clients.
416 // Mark the sending client as legacy.
417 case NsdManager.DAEMON_STARTUP:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900418 cInfo = getClientInfoForReply(msg);
Luke Huangf7277ed2021-07-12 21:15:10 +0800419 if (cInfo != null) {
420 cancelStop();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900421 cInfo.setPreSClient();
Luke Huangf7277ed2021-07-12 21:15:10 +0800422 mLegacyClientCount += 1;
423 maybeStartDaemon();
424 }
425 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700426 default:
paulhub2225702021-11-17 09:35:33 +0800427 Log.e(TAG, "Unhandled " + msg);
Irfan Sheriff75006652012-04-17 23:15:29 -0700428 return NOT_HANDLED;
429 }
430 return HANDLED;
431 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900432
433 private ClientInfo getClientInfoForReply(Message msg) {
434 final ListenerArgs args = (ListenerArgs) msg.obj;
435 return mClients.get(args.connector);
436 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700437 }
438
Irfan Sheriff75006652012-04-17 23:15:29 -0700439 class EnabledState extends State {
440 @Override
441 public void enter() {
442 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700443 }
444
445 @Override
446 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000447 // TODO: it is incorrect to stop the daemon without expunging all requests
448 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000449 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700450 }
451
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700452 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900453 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800454 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700455 return true;
456 }
457 return false;
458 }
459
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900460 private void storeLegacyRequestMap(int clientId, int globalId, ClientInfo clientInfo,
461 int what) {
462 clientInfo.mClientRequests.put(clientId, new LegacyClientRequest(globalId, what));
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700463 mIdToClientInfoMap.put(globalId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000464 // Remove the cleanup event because here comes a new request.
465 cancelStop();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700466 }
467
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900468 private void storeAdvertiserRequestMap(int clientId, int globalId,
Paul Hu23fa2022023-01-13 22:57:24 +0800469 ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900470 clientInfo.mClientRequests.put(clientId, new AdvertiserClientRequest(globalId));
471 mIdToClientInfoMap.put(globalId, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800472 }
473
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900474 private void removeRequestMap(int clientId, int globalId, ClientInfo clientInfo) {
475 final ClientRequest existing = clientInfo.mClientRequests.get(clientId);
476 if (existing == null) return;
477 clientInfo.mClientRequests.remove(clientId);
478 mIdToClientInfoMap.remove(globalId);
479
480 if (existing instanceof LegacyClientRequest) {
481 maybeScheduleStop();
482 } else {
483 maybeStopMonitoringSocketsIfNoActiveRequest();
484 }
485 }
486
487 private void storeDiscoveryManagerRequestMap(int clientId, int globalId,
488 MdnsListener listener, ClientInfo clientInfo) {
489 clientInfo.mClientRequests.put(clientId,
490 new DiscoveryManagerRequest(globalId, listener));
491 mIdToClientInfoMap.put(globalId, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800492 }
493
Paul Hu18aeccc2022-12-27 08:48:48 +0000494 private void clearRegisteredServiceInfo(ClientInfo clientInfo) {
495 clientInfo.mRegisteredService = null;
496 clientInfo.mClientIdForServiceUpdates = 0;
497 }
498
Paul Hu23fa2022023-01-13 22:57:24 +0800499 /**
500 * Check the given service type is valid and construct it to a service type
501 * which can use for discovery / resolution service.
502 *
503 * <p> The valid service type should be 2 labels, or 3 labels if the query is for a
504 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
505 * underscore; they are alphanumerical characters or dashes or underscore, except the
506 * last one that is just alphanumerical. The last label must be _tcp or _udp.
507 *
508 * @param serviceType the request service type for discovery / resolution service
509 * @return constructed service type or null if the given service type is invalid.
510 */
511 @Nullable
512 private String constructServiceType(String serviceType) {
513 if (TextUtils.isEmpty(serviceType)) return null;
514
515 final Pattern serviceTypePattern = Pattern.compile(
516 "^(_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]\\.)?"
517 + "(_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]\\._(?:tcp|udp))$");
518 final Matcher matcher = serviceTypePattern.matcher(serviceType);
519 if (!matcher.matches()) return null;
520 return matcher.group(1) == null
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900521 ? serviceType
522 : matcher.group(1) + "_sub." + matcher.group(2);
523 }
524
525 /**
526 * Truncate a service name to up to 63 UTF-8 bytes.
527 *
528 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
529 * names used in registerService follows historical behavior (see mdnsresponder
530 * handle_regservice_request).
531 */
532 @NonNull
533 private String truncateServiceName(@NonNull String originalName) {
534 // UTF-8 is at most 4 bytes per character; return early in the common case where
535 // the name can't possibly be over the limit given its string length.
536 if (originalName.length() <= MAX_LABEL_LENGTH / 4) return originalName;
537
538 final Charset utf8 = StandardCharsets.UTF_8;
539 final CharsetEncoder encoder = utf8.newEncoder();
540 final ByteBuffer out = ByteBuffer.allocate(MAX_LABEL_LENGTH);
541 // encode will write as many characters as possible to the out buffer, and just
542 // return an overflow code if there were too many characters (no need to check the
543 // return code here, this method truncates the name on purpose).
544 encoder.encode(CharBuffer.wrap(originalName), out, true /* endOfInput */);
545 return new String(out.array(), 0, out.position(), utf8);
Paul Hu23fa2022023-01-13 22:57:24 +0800546 }
547
Irfan Sheriff75006652012-04-17 23:15:29 -0700548 @Override
549 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900550 final ClientInfo clientInfo;
551 final int id;
552 final int clientId = msg.arg2;
553 final ListenerArgs args;
Irfan Sheriff75006652012-04-17 23:15:29 -0700554 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800555 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800556 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900557 args = (ListenerArgs) msg.obj;
558 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000559 // If the binder death notification for a INsdManagerCallback was received
560 // before any calls are received by NsdService, the clientInfo would be
561 // cleared and cause NPE. Add a null check here to prevent this corner case.
562 if (clientInfo == null) {
563 Log.e(TAG, "Unknown connector in discovery");
564 break;
565 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700566
567 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900568 clientInfo.onDiscoverServicesFailed(
569 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriff75006652012-04-17 23:15:29 -0700570 break;
571 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700572
Paul Hu23fa2022023-01-13 22:57:24 +0800573 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700574 id = getUniqueId();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900575 if (mDeps.isMdnsDiscoveryManagerEnabled(mContext)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800576 final String serviceType = constructServiceType(info.getServiceType());
577 if (serviceType == null) {
578 clientInfo.onDiscoverServicesFailed(clientId,
579 NsdManager.FAILURE_INTERNAL_ERROR);
580 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700581 }
Paul Hu23fa2022023-01-13 22:57:24 +0800582
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900583 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800584 maybeStartMonitoringSockets();
585 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900586 new DiscoveryListener(clientId, id, info, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800587 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
588 .setNetwork(info.getNetwork())
589 .setIsPassiveMode(true)
590 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900591 mMdnsDiscoveryManager.registerListener(
592 listenServiceType, listener, options);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900593 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800594 clientInfo.onDiscoverServicesStarted(clientId, info);
Irfan Sheriff75006652012-04-17 23:15:29 -0700595 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800596 maybeStartDaemon();
597 if (discoverServices(id, info)) {
598 if (DBG) {
599 Log.d(TAG, "Discover " + msg.arg2 + " " + id
600 + info.getServiceType());
601 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900602 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu23fa2022023-01-13 22:57:24 +0800603 clientInfo.onDiscoverServicesStarted(clientId, info);
604 } else {
605 stopServiceDiscovery(id);
606 clientInfo.onDiscoverServicesFailed(clientId,
607 NsdManager.FAILURE_INTERNAL_ERROR);
608 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700609 }
610 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800611 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900612 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800613 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900614 args = (ListenerArgs) msg.obj;
615 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000616 // If the binder death notification for a INsdManagerCallback was received
617 // before any calls are received by NsdService, the clientInfo would be
618 // cleared and cause NPE. Add a null check here to prevent this corner case.
619 if (clientInfo == null) {
620 Log.e(TAG, "Unknown connector in stop discovery");
621 break;
622 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700623
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900624 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
625 if (request == null) {
626 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700627 break;
628 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900629 id = request.mGlobalId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900630 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
631 // point, so this needs to check the type of the original request to
632 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900633 if (request instanceof DiscoveryManagerRequest) {
Ahmad Khalil4b8d45a2023-03-02 11:43:25 +0000634 final MdnsListener listener =
635 ((DiscoveryManagerRequest) request).mListener;
636 mMdnsDiscoveryManager.unregisterListener(
637 listener.getListenedServiceType(), listener);
638 removeRequestMap(clientId, id, clientInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900639 clientInfo.onStopDiscoverySucceeded(clientId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700640 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800641 removeRequestMap(clientId, id, clientInfo);
642 if (stopServiceDiscovery(id)) {
643 clientInfo.onStopDiscoverySucceeded(clientId);
644 } else {
645 clientInfo.onStopDiscoveryFailed(
646 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
647 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700648 }
649 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900650 }
651 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800652 if (DBG) Log.d(TAG, "Register service");
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 registration");
660 break;
661 }
662
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700663 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900664 clientInfo.onRegisterServiceFailed(
665 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700666 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700667 }
668
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700669 id = getUniqueId();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900670 if (mDeps.isMdnsAdvertiserEnabled(mContext)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900671 final NsdServiceInfo serviceInfo = args.serviceInfo;
672 final String serviceType = serviceInfo.getServiceType();
673 final String registerServiceType = constructServiceType(serviceType);
674 if (registerServiceType == null) {
675 Log.e(TAG, "Invalid service type: " + serviceType);
676 clientInfo.onRegisterServiceFailed(clientId,
677 NsdManager.FAILURE_INTERNAL_ERROR);
678 break;
679 }
680 serviceInfo.setServiceType(registerServiceType);
681 serviceInfo.setServiceName(truncateServiceName(
682 serviceInfo.getServiceName()));
683
684 maybeStartMonitoringSockets();
685 mAdvertiser.addService(id, serviceInfo);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900686 storeAdvertiserRequestMap(clientId, id, clientInfo);
Irfan Sheriff75006652012-04-17 23:15:29 -0700687 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900688 maybeStartDaemon();
689 if (registerService(id, args.serviceInfo)) {
690 if (DBG) Log.d(TAG, "Register " + clientId + " " + id);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900691 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900692 // Return success after mDns reports success
693 } else {
694 unregisterService(id);
695 clientInfo.onRegisterServiceFailed(
696 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
697 }
698
Irfan Sheriff75006652012-04-17 23:15:29 -0700699 }
700 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900701 }
702 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800703 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900704 args = (ListenerArgs) msg.obj;
705 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000706 // If the binder death notification for a INsdManagerCallback was received
707 // before any calls are received by NsdService, the clientInfo would be
708 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900709 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800710 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700711 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700712 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900713 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
714 if (request == null) {
715 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
716 break;
717 }
718 id = request.mGlobalId;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900719 removeRequestMap(clientId, id, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900720
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900721 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
722 // so this needs to check the type of the original request to unregister
723 // instead of looking at the flag value.
724 if (request instanceof AdvertiserClientRequest) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900725 mAdvertiser.removeService(id);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900726 clientInfo.onUnregisterServiceSucceeded(clientId);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700727 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900728 if (unregisterService(id)) {
729 clientInfo.onUnregisterServiceSucceeded(clientId);
730 } else {
731 clientInfo.onUnregisterServiceFailed(
732 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
733 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700734 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700735 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900736 }
Paul Hu75069ed2023-01-14 00:31:09 +0800737 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800738 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900739 args = (ListenerArgs) msg.obj;
740 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000741 // If the binder death notification for a INsdManagerCallback was received
742 // before any calls are received by NsdService, the clientInfo would be
743 // cleared and cause NPE. Add a null check here to prevent this corner case.
744 if (clientInfo == null) {
745 Log.e(TAG, "Unknown connector in resolution");
746 break;
747 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700748
Paul Hu75069ed2023-01-14 00:31:09 +0800749 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700750 id = getUniqueId();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900751 if (mDeps.isMdnsDiscoveryManagerEnabled(mContext)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800752 final String serviceType = constructServiceType(info.getServiceType());
753 if (serviceType == null) {
754 clientInfo.onResolveServiceFailed(clientId,
755 NsdManager.FAILURE_INTERNAL_ERROR);
756 break;
757 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900758 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +0800759
760 maybeStartMonitoringSockets();
761 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900762 new ResolutionListener(clientId, id, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800763 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
764 .setNetwork(info.getNetwork())
765 .setIsPassiveMode(true)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900766 .setResolveInstanceName(info.getServiceName())
Paul Hu75069ed2023-01-14 00:31:09 +0800767 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900768 mMdnsDiscoveryManager.registerListener(
769 resolveServiceType, listener, options);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900770 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Irfan Sheriff75006652012-04-17 23:15:29 -0700771 } else {
Paul Hu75069ed2023-01-14 00:31:09 +0800772 if (clientInfo.mResolvedService != null) {
773 clientInfo.onResolveServiceFailed(
774 clientId, NsdManager.FAILURE_ALREADY_ACTIVE);
775 break;
776 }
777
778 maybeStartDaemon();
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900779 if (resolveService(id, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800780 clientInfo.mResolvedService = new NsdServiceInfo();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900781 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu75069ed2023-01-14 00:31:09 +0800782 } else {
783 clientInfo.onResolveServiceFailed(
784 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
785 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700786 }
787 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800788 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900789 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +0000790 if (DBG) Log.d(TAG, "Stop service resolution");
791 args = (ListenerArgs) msg.obj;
792 clientInfo = mClients.get(args.connector);
793 // If the binder death notification for a INsdManagerCallback was received
794 // before any calls are received by NsdService, the clientInfo would be
795 // cleared and cause NPE. Add a null check here to prevent this corner case.
796 if (clientInfo == null) {
797 Log.e(TAG, "Unknown connector in stop resolution");
798 break;
799 }
800
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900801 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
802 if (request == null) {
803 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
804 break;
805 }
806 id = request.mGlobalId;
Ahmad Khalil4b8d45a2023-03-02 11:43:25 +0000807 removeRequestMap(clientId, id, clientInfo);
808 if (stopResolveService(id)) {
Paul Hub58deb72022-12-26 09:24:42 +0000809 clientInfo.onStopResolutionSucceeded(clientId);
810 } else {
Ahmad Khalil4b8d45a2023-03-02 11:43:25 +0000811 clientInfo.onStopResolutionFailed(
812 clientId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hub58deb72022-12-26 09:24:42 +0000813 }
Ahmad Khalil4b8d45a2023-03-02 11:43:25 +0000814 clientInfo.mResolvedService = null;
815 // TODO: Implement the stop resolution with MdnsDiscoveryManager.
Paul Hub58deb72022-12-26 09:24:42 +0000816 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900817 }
Paul Hu18aeccc2022-12-27 08:48:48 +0000818 case NsdManager.REGISTER_SERVICE_CALLBACK:
819 if (DBG) Log.d(TAG, "Register a service callback");
820 args = (ListenerArgs) msg.obj;
821 clientInfo = mClients.get(args.connector);
822 // If the binder death notification for a INsdManagerCallback was received
823 // before any calls are received by NsdService, the clientInfo would be
824 // cleared and cause NPE. Add a null check here to prevent this corner case.
825 if (clientInfo == null) {
826 Log.e(TAG, "Unknown connector in callback registration");
827 break;
828 }
829
830 if (clientInfo.mRegisteredService != null) {
831 clientInfo.onServiceInfoCallbackRegistrationFailed(
832 clientId, NsdManager.FAILURE_ALREADY_ACTIVE);
833 break;
834 }
835
836 maybeStartDaemon();
837 id = getUniqueId();
838 if (resolveService(id, args.serviceInfo)) {
839 clientInfo.mRegisteredService = new NsdServiceInfo();
840 clientInfo.mClientIdForServiceUpdates = clientId;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900841 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu18aeccc2022-12-27 08:48:48 +0000842 } else {
843 clientInfo.onServiceInfoCallbackRegistrationFailed(
844 clientId, NsdManager.FAILURE_BAD_PARAMETERS);
845 }
846 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900847 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +0000848 if (DBG) Log.d(TAG, "Unregister a service callback");
849 args = (ListenerArgs) msg.obj;
850 clientInfo = mClients.get(args.connector);
851 // If the binder death notification for a INsdManagerCallback was received
852 // before any calls are received by NsdService, the clientInfo would be
853 // cleared and cause NPE. Add a null check here to prevent this corner case.
854 if (clientInfo == null) {
855 Log.e(TAG, "Unknown connector in callback unregistration");
856 break;
857 }
858
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900859 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
860 if (request == null) {
861 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
862 break;
863 }
864 id = request.mGlobalId;
Paul Hu18aeccc2022-12-27 08:48:48 +0000865 removeRequestMap(clientId, id, clientInfo);
866 if (stopResolveService(id)) {
867 clientInfo.onServiceInfoCallbackUnregistered(clientId);
868 } else {
869 Log.e(TAG, "Failed to unregister service info callback");
870 }
871 clearRegisteredServiceInfo(clientInfo);
872 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900873 }
paulhu2b9ed952022-02-10 21:58:32 +0800874 case MDNS_SERVICE_EVENT:
875 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +0900876 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700877 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700878 break;
Paul Hu019621e2023-01-13 23:26:49 +0800879 case MDNS_DISCOVERY_MANAGER_EVENT:
880 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
881 return NOT_HANDLED;
882 }
883 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700884 default:
Hugo Benichif0c84092017-04-05 14:43:29 +0900885 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700886 }
Hugo Benichif0c84092017-04-05 14:43:29 +0900887 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700888 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700889
Paul Hu18aeccc2022-12-27 08:48:48 +0000890 private void notifyResolveFailedResult(boolean isListenedToUpdates, int clientId,
891 ClientInfo clientInfo, int error) {
892 if (isListenedToUpdates) {
893 clientInfo.onServiceInfoCallbackRegistrationFailed(clientId, error);
894 clearRegisteredServiceInfo(clientInfo);
895 } else {
896 // The resolve API always returned FAILURE_INTERNAL_ERROR on error; keep it
897 // for backwards compatibility.
898 clientInfo.onResolveServiceFailed(clientId, NsdManager.FAILURE_INTERNAL_ERROR);
899 clientInfo.mResolvedService = null;
900 }
901 }
902
paulhu2b9ed952022-02-10 21:58:32 +0800903 private boolean handleMDnsServiceEvent(int code, int id, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700904 NsdServiceInfo servInfo;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700905 ClientInfo clientInfo = mIdToClientInfoMap.get(id);
906 if (clientInfo == null) {
paulhu2b9ed952022-02-10 21:58:32 +0800907 Log.e(TAG, String.format("id %d for %d has no client mapping", id, code));
Hugo Benichif0c84092017-04-05 14:43:29 +0900908 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700909 }
910
911 /* This goes in response as msg.arg2 */
Christopher Lane74411222014-04-25 18:39:07 -0700912 int clientId = clientInfo.getClientId(id);
913 if (clientId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -0700914 // This can happen because of race conditions. For example,
915 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
916 // and we may get in this situation.
paulhu2b9ed952022-02-10 21:58:32 +0800917 Log.d(TAG, String.format("%d for listener id %d that is no longer active",
918 code, id));
Hugo Benichif0c84092017-04-05 14:43:29 +0900919 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700920 }
Hugo Benichi32be63d2017-04-05 14:06:11 +0900921 if (DBG) {
paulhu2b9ed952022-02-10 21:58:32 +0800922 Log.d(TAG, String.format("MDns service event code:%d id=%d", code, id));
Hugo Benichi32be63d2017-04-05 14:06:11 +0900923 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700924 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +0800925 case IMDnsEventListener.SERVICE_FOUND: {
926 final DiscoveryInfo info = (DiscoveryInfo) obj;
927 final String name = info.serviceName;
928 final String type = info.registrationType;
929 servInfo = new NsdServiceInfo(name, type);
930 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900931 if (foundNetId == 0L) {
932 // Ignore services that do not have a Network: they are not usable
933 // by apps, as they would need privileged permissions to use
934 // interfaces that do not have an associated Network.
935 break;
936 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +0900937 if (foundNetId == INetd.DUMMY_NET_ID) {
938 // Ignore services on the dummy0 interface: they are only seen when
939 // discovering locally advertised services, and are not reachable
940 // through that interface.
941 break;
942 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900943 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900944 clientInfo.onServiceFound(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700945 break;
paulhu2b9ed952022-02-10 21:58:32 +0800946 }
947 case IMDnsEventListener.SERVICE_LOST: {
948 final DiscoveryInfo info = (DiscoveryInfo) obj;
949 final String name = info.serviceName;
950 final String type = info.registrationType;
951 final int lostNetId = info.netId;
952 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900953 // The network could be set to null (netId 0) if it was torn down when the
954 // service is lost
955 // TODO: avoid returning null in that case, possibly by remembering
956 // found services on the same interface index and their network at the time
957 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900958 clientInfo.onServiceLost(clientId, servInfo);
Paul Hu18aeccc2022-12-27 08:48:48 +0000959 // TODO: also support registered service lost when not discovering
960 clientInfo.maybeNotifyRegisteredServiceLost(servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700961 break;
paulhu2b9ed952022-02-10 21:58:32 +0800962 }
963 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900964 clientInfo.onDiscoverServicesFailed(
965 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700966 break;
paulhu2b9ed952022-02-10 21:58:32 +0800967 case IMDnsEventListener.SERVICE_REGISTERED: {
968 final RegistrationInfo info = (RegistrationInfo) obj;
969 final String name = info.serviceName;
970 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900971 clientInfo.onRegisterServiceSucceeded(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700972 break;
paulhu2b9ed952022-02-10 21:58:32 +0800973 }
974 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900975 clientInfo.onRegisterServiceFailed(
976 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700977 break;
paulhu2b9ed952022-02-10 21:58:32 +0800978 case IMDnsEventListener.SERVICE_RESOLVED: {
979 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -0700980 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +0800981 final String fullName = info.serviceFullName;
982 while (index < fullName.length() && fullName.charAt(index) != '.') {
983 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -0700984 ++index;
985 }
986 ++index;
987 }
paulhu2b9ed952022-02-10 21:58:32 +0800988 if (index >= fullName.length()) {
989 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700990 break;
991 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900992
paulhube186602022-04-12 07:18:23 +0000993 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +0800994 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700995 String type = rest.replace(".local.", "");
996
Paul Hu18aeccc2022-12-27 08:48:48 +0000997 final boolean isListenedToUpdates =
998 clientId == clientInfo.mClientIdForServiceUpdates;
999 final NsdServiceInfo serviceInfo = isListenedToUpdates
1000 ? clientInfo.mRegisteredService : clientInfo.mResolvedService;
1001
1002 serviceInfo.setServiceName(name);
1003 serviceInfo.setServiceType(type);
1004 serviceInfo.setPort(info.port);
1005 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001006 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001007
1008 stopResolveService(id);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001009 removeRequestMap(clientId, id, clientInfo);
1010
paulhu2b9ed952022-02-10 21:58:32 +08001011 final int id2 = getUniqueId();
1012 if (getAddrInfo(id2, info.hostname, info.interfaceIdx)) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001013 storeLegacyRequestMap(clientId, id2, clientInfo,
1014 NsdManager.RESOLVE_SERVICE);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001015 } else {
Paul Hu18aeccc2022-12-27 08:48:48 +00001016 notifyResolveFailedResult(isListenedToUpdates, clientId, clientInfo,
1017 NsdManager.FAILURE_BAD_PARAMETERS);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001018 }
1019 break;
paulhu2b9ed952022-02-10 21:58:32 +08001020 }
1021 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001022 /* NNN resolveId errorCode */
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001023 stopResolveService(id);
1024 removeRequestMap(clientId, id, clientInfo);
Paul Hu18aeccc2022-12-27 08:48:48 +00001025 notifyResolveFailedResult(
1026 clientId == clientInfo.mClientIdForServiceUpdates,
1027 clientId, clientInfo, NsdManager.FAILURE_BAD_PARAMETERS);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001028 break;
paulhu2b9ed952022-02-10 21:58:32 +08001029 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001030 /* NNN resolveId errorCode */
1031 stopGetAddrInfo(id);
1032 removeRequestMap(clientId, id, clientInfo);
Paul Hu18aeccc2022-12-27 08:48:48 +00001033 notifyResolveFailedResult(
1034 clientId == clientInfo.mClientIdForServiceUpdates,
1035 clientId, clientInfo, NsdManager.FAILURE_BAD_PARAMETERS);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001036 break;
paulhu2b9ed952022-02-10 21:58:32 +08001037 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001038 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001039 final GetAddressInfo info = (GetAddressInfo) obj;
1040 final String address = info.address;
1041 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001042 InetAddress serviceHost = null;
1043 try {
paulhu2b9ed952022-02-10 21:58:32 +08001044 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001045 } catch (UnknownHostException e) {
1046 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1047 }
1048
1049 // If the resolved service is on an interface without a network, consider it
1050 // as a failure: it would not be usable by apps as they would need
1051 // privileged permissions.
Paul Hu18aeccc2022-12-27 08:48:48 +00001052 if (clientId == clientInfo.mClientIdForServiceUpdates) {
1053 if (netId != NETID_UNSET && serviceHost != null) {
1054 setServiceNetworkForCallback(clientInfo.mRegisteredService,
1055 netId, info.interfaceIdx);
1056 final List<InetAddress> addresses =
1057 clientInfo.mRegisteredService.getHostAddresses();
1058 addresses.add(serviceHost);
1059 clientInfo.mRegisteredService.setHostAddresses(addresses);
1060 clientInfo.onServiceUpdated(
1061 clientId, clientInfo.mRegisteredService);
1062 } else {
1063 stopGetAddrInfo(id);
1064 removeRequestMap(clientId, id, clientInfo);
1065 clearRegisteredServiceInfo(clientInfo);
1066 clientInfo.onServiceInfoCallbackRegistrationFailed(
1067 clientId, NsdManager.FAILURE_BAD_PARAMETERS);
1068 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001069 } else {
Paul Hu18aeccc2022-12-27 08:48:48 +00001070 if (netId != NETID_UNSET && serviceHost != null) {
1071 clientInfo.mResolvedService.setHost(serviceHost);
1072 setServiceNetworkForCallback(clientInfo.mResolvedService,
1073 netId, info.interfaceIdx);
1074 clientInfo.onResolveServiceSucceeded(
1075 clientId, clientInfo.mResolvedService);
1076 } else {
1077 clientInfo.onResolveServiceFailed(
1078 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1079 }
1080 stopGetAddrInfo(id);
1081 removeRequestMap(clientId, id, clientInfo);
1082 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001083 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001084 break;
paulhu2b9ed952022-02-10 21:58:32 +08001085 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001086 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001087 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001088 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001089 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001090 }
Paul Hu019621e2023-01-13 23:26:49 +08001091
1092 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(final MdnsEvent event) {
1093 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1094 final String serviceType = event.mRequestedServiceType;
1095 final String serviceName = serviceInfo.getServiceInstanceName();
1096 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1097 final Network network = serviceInfo.getNetwork();
1098 setServiceNetworkForCallback(
1099 servInfo,
1100 network == null ? NETID_UNSET : network.netId,
1101 serviceInfo.getInterfaceIndex());
1102 return servInfo;
1103 }
1104
1105 private boolean handleMdnsDiscoveryManagerEvent(
1106 int transactionId, int code, Object obj) {
1107 final ClientInfo clientInfo = mIdToClientInfoMap.get(transactionId);
1108 if (clientInfo == null) {
1109 Log.e(TAG, String.format(
1110 "id %d for %d has no client mapping", transactionId, code));
1111 return false;
1112 }
1113
1114 final MdnsEvent event = (MdnsEvent) obj;
1115 final int clientId = event.mClientId;
Paul Hu319751a2023-01-13 23:56:34 +08001116 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event);
Paul Hu019621e2023-01-13 23:26:49 +08001117 if (DBG) {
1118 Log.d(TAG, String.format("MdnsDiscoveryManager event code=%s transactionId=%d",
1119 NsdManager.nameOf(code), transactionId));
1120 }
1121 switch (code) {
1122 case NsdManager.SERVICE_FOUND:
Paul Hu319751a2023-01-13 23:56:34 +08001123 clientInfo.onServiceFound(clientId, info);
1124 break;
1125 case NsdManager.SERVICE_LOST:
1126 clientInfo.onServiceLost(clientId, info);
Paul Hu019621e2023-01-13 23:26:49 +08001127 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001128 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001129 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
1130 if (request == null) {
1131 Log.e(TAG, "Unknown client request in RESOLVE_SERVICE_SUCCEEDED");
1132 break;
1133 }
Paul Hu75069ed2023-01-14 00:31:09 +08001134 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1135 // Add '.' in front of the service type that aligns with historical behavior
1136 info.setServiceType("." + event.mRequestedServiceType);
1137 info.setPort(serviceInfo.getPort());
1138
1139 Map<String, String> attrs = serviceInfo.getAttributes();
1140 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1141 final String key = kv.getKey();
1142 try {
1143 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1144 } catch (IllegalArgumentException e) {
1145 Log.e(TAG, "Invalid attribute", e);
1146 }
1147 }
1148 try {
1149 if (serviceInfo.getIpv4Address() != null) {
1150 info.setHost(InetAddresses.parseNumericAddress(
1151 serviceInfo.getIpv4Address()));
1152 } else {
1153 info.setHost(InetAddresses.parseNumericAddress(
1154 serviceInfo.getIpv6Address()));
1155 }
1156 clientInfo.onResolveServiceSucceeded(clientId, info);
1157 } catch (IllegalArgumentException e) {
1158 Log.wtf(TAG, "Invalid address in RESOLVE_SERVICE_SUCCEEDED", e);
1159 clientInfo.onResolveServiceFailed(
1160 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1161 }
1162
1163 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001164 if (!(request instanceof DiscoveryManagerRequest)) {
1165 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1166 break;
1167 }
Ahmad Khalil4b8d45a2023-03-02 11:43:25 +00001168 final MdnsListener listener = ((DiscoveryManagerRequest) request).mListener;
1169 mMdnsDiscoveryManager.unregisterListener(
1170 listener.getListenedServiceType(), listener);
1171 removeRequestMap(clientId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001172 break;
1173 }
Paul Hu019621e2023-01-13 23:26:49 +08001174 default:
1175 return false;
1176 }
1177 return true;
1178 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001179 }
1180 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001181
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001182 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1183 switch (netId) {
1184 case NETID_UNSET:
1185 info.setNetwork(null);
1186 break;
1187 case INetd.LOCAL_NET_ID:
1188 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1189 // visible / usable for apps, so do not return it. Store the interface
1190 // index instead, so at least if the client tries to resolve the service
1191 // with that NsdServiceInfo, it will be done on the same interface.
1192 // If they recreate the NsdServiceInfo themselves, resolution would be
1193 // done on all interfaces as before T, which should also work.
1194 info.setNetwork(null);
1195 info.setInterfaceIndex(ifaceIdx);
1196 break;
1197 default:
1198 info.setNetwork(new Network(netId));
1199 }
1200 }
1201
paulhube186602022-04-12 07:18:23 +00001202 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1203 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1204 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1205 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1206 private String unescape(String s) {
1207 StringBuilder sb = new StringBuilder(s.length());
1208 for (int i = 0; i < s.length(); ++i) {
1209 char c = s.charAt(i);
1210 if (c == '\\') {
1211 if (++i >= s.length()) {
1212 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1213 break;
1214 }
1215 c = s.charAt(i);
1216 if (c != '.' && c != '\\') {
1217 if (i + 2 >= s.length()) {
1218 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1219 break;
1220 }
1221 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1222 + (s.charAt(i + 2) - '0'));
1223 i += 2;
1224 }
1225 }
1226 sb.append(c);
1227 }
1228 return sb.toString();
1229 }
1230
Hugo Benichi803a2f02017-04-24 11:35:06 +09001231 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001232 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001233 this(ctx, handler, cleanupDelayMs, new Dependencies());
1234 }
1235
1236 @VisibleForTesting
1237 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001238 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001239 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001240 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001241 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001242 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1243 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001244 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001245
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001246 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper());
1247 mMdnsSocketClient =
1248 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider);
1249 mMdnsDiscoveryManager =
1250 deps.makeMdnsDiscoveryManager(new ExecutorProvider(), mMdnsSocketClient);
1251 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1252 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
1253 new AdvertiserCallback());
Paul Hu4bd98ef2023-01-12 13:42:07 +08001254 }
1255
1256 /**
1257 * Dependencies of NsdService, for injection in tests.
1258 */
1259 @VisibleForTesting
1260 public static class Dependencies {
1261 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001262 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001263 *
1264 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001265 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001266 */
1267 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
1268 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY,
1269 MDNS_DISCOVERY_MANAGER_VERSION, false /* defaultEnabled */);
1270 }
1271
1272 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001273 * Check whether the MdnsAdvertiser feature is enabled.
1274 *
1275 * @param context The global context information about an app environment.
1276 * @return true if the MdnsAdvertiser feature is enabled.
1277 */
1278 public boolean isMdnsAdvertiserEnabled(Context context) {
1279 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY,
1280 MDNS_ADVERTISER_VERSION, false /* defaultEnabled */);
1281 }
1282
1283 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001284 * @see MdnsDiscoveryManager
1285 */
1286 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
1287 ExecutorProvider executorProvider, MdnsSocketClientBase socketClient) {
1288 return new MdnsDiscoveryManager(executorProvider, socketClient);
1289 }
1290
1291 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001292 * @see MdnsAdvertiser
1293 */
1294 public MdnsAdvertiser makeMdnsAdvertiser(
1295 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
1296 @NonNull MdnsAdvertiser.AdvertiserCallback cb) {
1297 return new MdnsAdvertiser(looper, socketProvider, cb);
1298 }
1299
1300 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001301 * @see MdnsSocketProvider
1302 */
1303 public MdnsSocketProvider makeMdnsSocketProvider(Context context, Looper looper) {
1304 return new MdnsSocketProvider(context, looper);
1305 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001306 }
1307
paulhu1b35e822022-04-08 14:48:41 +08001308 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001309 HandlerThread thread = new HandlerThread(TAG);
1310 thread.start();
1311 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001312 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001313 return service;
1314 }
1315
paulhu2b9ed952022-02-10 21:58:32 +08001316 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1317 private final StateMachine mStateMachine;
1318
1319 MDnsEventCallback(StateMachine sm) {
1320 mStateMachine = sm;
1321 }
1322
1323 @Override
1324 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1325 mStateMachine.sendMessage(
1326 MDNS_SERVICE_EVENT, status.result, status.id, status);
1327 }
1328
1329 @Override
1330 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1331 mStateMachine.sendMessage(
1332 MDNS_SERVICE_EVENT, status.result, status.id, status);
1333 }
1334
1335 @Override
1336 public void onServiceResolutionStatus(final ResolutionInfo status) {
1337 mStateMachine.sendMessage(
1338 MDNS_SERVICE_EVENT, status.result, status.id, status);
1339 }
1340
1341 @Override
1342 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1343 mStateMachine.sendMessage(
1344 MDNS_SERVICE_EVENT, status.result, status.id, status);
1345 }
1346
1347 @Override
1348 public int getInterfaceVersion() throws RemoteException {
1349 return this.VERSION;
1350 }
1351
1352 @Override
1353 public String getInterfaceHash() throws RemoteException {
1354 return this.HASH;
1355 }
1356 }
1357
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001358 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
1359 @Override
1360 public void onRegisterServiceSucceeded(int serviceId, NsdServiceInfo registeredInfo) {
1361 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1362 if (clientInfo == null) return;
1363
1364 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1365 if (clientId < 0) return;
1366
1367 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1368 // historical behavior.
1369 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
1370 clientInfo.onRegisterServiceSucceeded(clientId, cbInfo);
1371 }
1372
1373 @Override
1374 public void onRegisterServiceFailed(int serviceId, int errorCode) {
1375 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1376 if (clientInfo == null) return;
1377
1378 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1379 if (clientId < 0) return;
1380
1381 clientInfo.onRegisterServiceFailed(clientId, errorCode);
1382 }
1383
1384 private ClientInfo getClientInfoOrLog(int serviceId) {
1385 final ClientInfo clientInfo = mIdToClientInfoMap.get(serviceId);
1386 if (clientInfo == null) {
1387 Log.e(TAG, String.format("Callback for service %d has no client", serviceId));
1388 }
1389 return clientInfo;
1390 }
1391
1392 private int getClientIdOrLog(@NonNull ClientInfo info, int serviceId) {
1393 final int clientId = info.getClientId(serviceId);
1394 if (clientId < 0) {
1395 Log.e(TAG, String.format("Client ID not found for service %d", serviceId));
1396 }
1397 return clientId;
1398 }
1399 }
1400
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001401 @Override
1402 public INsdServiceConnector connect(INsdManagerCallback cb) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001403 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001404 final INsdServiceConnector connector = new NsdServiceConnector();
1405 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1406 NsdManager.REGISTER_CLIENT, new Pair<>(connector, cb)));
1407 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07001408 }
1409
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001410 private static class ListenerArgs {
1411 public final NsdServiceConnector connector;
1412 public final NsdServiceInfo serviceInfo;
1413 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
1414 this.connector = connector;
1415 this.serviceInfo = serviceInfo;
1416 }
1417 }
1418
1419 private class NsdServiceConnector extends INsdServiceConnector.Stub
1420 implements IBinder.DeathRecipient {
1421 @Override
1422 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
1423 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1424 NsdManager.REGISTER_SERVICE, 0, listenerKey,
1425 new ListenerArgs(this, serviceInfo)));
1426 }
1427
1428 @Override
1429 public void unregisterService(int listenerKey) {
1430 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1431 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
1432 new ListenerArgs(this, null)));
1433 }
1434
1435 @Override
1436 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
1437 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1438 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
1439 new ListenerArgs(this, serviceInfo)));
1440 }
1441
1442 @Override
1443 public void stopDiscovery(int listenerKey) {
1444 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1445 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
1446 }
1447
1448 @Override
1449 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
1450 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1451 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
1452 new ListenerArgs(this, serviceInfo)));
1453 }
1454
1455 @Override
Paul Hub58deb72022-12-26 09:24:42 +00001456 public void stopResolution(int listenerKey) {
1457 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1458 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
1459 }
1460
1461 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00001462 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
1463 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1464 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
1465 new ListenerArgs(this, serviceInfo)));
1466 }
1467
1468 @Override
1469 public void unregisterServiceInfoCallback(int listenerKey) {
1470 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1471 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
1472 new ListenerArgs(this, null)));
1473 }
1474
1475 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001476 public void startDaemon() {
1477 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1478 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
1479 }
1480
1481 @Override
1482 public void binderDied() {
1483 mNsdStateMachine.sendMessage(
1484 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
1485 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001486 }
1487
Hugo Benichi912db992017-04-24 16:41:03 +09001488 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07001489 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07001490 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09001491 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
1492 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07001493 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07001494 }
1495
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001496 private int getUniqueId() {
1497 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
1498 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001499 }
1500
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001501 private boolean registerService(int regId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09001502 if (DBG) {
paulhub2225702021-11-17 09:35:33 +08001503 Log.d(TAG, "registerService: " + regId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001504 }
Hugo Benichi6d706442017-04-24 16:19:58 +09001505 String name = service.getServiceName();
1506 String type = service.getServiceType();
1507 int port = service.getPort();
1508 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001509 final int registerInterface = getNetworkInterfaceIndex(service);
1510 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08001511 Log.e(TAG, "Interface to register service on not found");
1512 return false;
1513 }
1514 return mMDnsManager.registerService(regId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001515 }
1516
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001517 private boolean unregisterService(int regId) {
paulhu2b9ed952022-02-10 21:58:32 +08001518 return mMDnsManager.stopOperation(regId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001519 }
1520
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001521 private boolean discoverServices(int discoveryId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08001522 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001523 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
1524 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001525 Log.e(TAG, "Interface to discover service on not found");
1526 return false;
1527 }
paulhu2b9ed952022-02-10 21:58:32 +08001528 return mMDnsManager.discover(discoveryId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001529 }
1530
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001531 private boolean stopServiceDiscovery(int discoveryId) {
paulhu2b9ed952022-02-10 21:58:32 +08001532 return mMDnsManager.stopOperation(discoveryId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001533 }
1534
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001535 private boolean resolveService(int resolveId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001536 final String name = service.getServiceName();
1537 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001538 final int resolveInterface = getNetworkInterfaceIndex(service);
1539 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001540 Log.e(TAG, "Interface to resolve service on not found");
1541 return false;
1542 }
paulhu2b9ed952022-02-10 21:58:32 +08001543 return mMDnsManager.resolve(resolveId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001544 }
1545
1546 /**
1547 * Guess the interface to use to resolve or discover a service on a specific network.
1548 *
1549 * This is an imperfect guess, as for example the network may be gone or not yet fully
1550 * registered. This is fine as failing is correct if the network is gone, and a client
1551 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
1552 * this is to support the legacy mdnsresponder implementation, which historically resolved
1553 * services on an unspecified network.
1554 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001555 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
1556 final Network network = serviceInfo.getNetwork();
1557 if (network == null) {
1558 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
1559 // provided by NsdService from discovery results, and the service was found on an
1560 // interface that has no app-usable Network).
1561 if (serviceInfo.getInterfaceIndex() != 0) {
1562 return serviceInfo.getInterfaceIndex();
1563 }
1564 return IFACE_IDX_ANY;
1565 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001566
1567 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
1568 if (cm == null) {
1569 Log.wtf(TAG, "No ConnectivityManager for resolveService");
1570 return IFACE_IDX_ANY;
1571 }
1572 final LinkProperties lp = cm.getLinkProperties(network);
1573 if (lp == null) return IFACE_IDX_ANY;
1574
1575 // Only resolve on non-stacked interfaces
1576 final NetworkInterface iface;
1577 try {
1578 iface = NetworkInterface.getByName(lp.getInterfaceName());
1579 } catch (SocketException e) {
1580 Log.e(TAG, "Error querying interface", e);
1581 return IFACE_IDX_ANY;
1582 }
1583
1584 if (iface == null) {
1585 Log.e(TAG, "Interface not found: " + lp.getInterfaceName());
1586 return IFACE_IDX_ANY;
1587 }
1588
1589 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001590 }
1591
1592 private boolean stopResolveService(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001593 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001594 }
1595
paulhu2b9ed952022-02-10 21:58:32 +08001596 private boolean getAddrInfo(int resolveId, String hostname, int interfaceIdx) {
1597 return mMDnsManager.getServiceAddress(resolveId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001598 }
1599
1600 private boolean stopGetAddrInfo(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001601 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001602 }
1603
1604 @Override
Irfan Sheriff75006652012-04-17 23:15:29 -07001605 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
paulhu3ffffe72021-09-16 10:15:22 +08001606 if (!PermissionUtils.checkDumpPermission(mContext, TAG, pw)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001607
Irfan Sheriff75006652012-04-17 23:15:29 -07001608 for (ClientInfo client : mClients.values()) {
1609 pw.println("Client Info");
1610 pw.println(client);
1611 }
1612
1613 mNsdStateMachine.dump(fd, pw, args);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001614 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001615
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001616 private abstract static class ClientRequest {
1617 private final int mGlobalId;
1618
1619 private ClientRequest(int globalId) {
1620 mGlobalId = globalId;
1621 }
1622 }
1623
1624 private static class LegacyClientRequest extends ClientRequest {
1625 private final int mRequestCode;
1626
1627 private LegacyClientRequest(int globalId, int requestCode) {
1628 super(globalId);
1629 mRequestCode = requestCode;
1630 }
1631 }
1632
1633 private static class AdvertiserClientRequest extends ClientRequest {
1634 private AdvertiserClientRequest(int globalId) {
1635 super(globalId);
1636 }
1637 }
1638
1639 private static class DiscoveryManagerRequest extends ClientRequest {
1640 @NonNull
1641 private final MdnsListener mListener;
1642
1643 private DiscoveryManagerRequest(int globalId, @NonNull MdnsListener listener) {
1644 super(globalId);
1645 mListener = listener;
1646 }
1647 }
1648
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001649 /* Information tracked per client */
1650 private class ClientInfo {
1651
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001652 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001653 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001654 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001655 private NsdServiceInfo mResolvedService;
1656
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001657 /* A map from client-side ID (listenerKey) to the request */
1658 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08001659
Luke Huangf7277ed2021-07-12 21:15:10 +08001660 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001661 private boolean mIsPreSClient = false;
Luke Huangf7277ed2021-07-12 21:15:10 +08001662
Paul Hu18aeccc2022-12-27 08:48:48 +00001663 /*** The service that is registered to listen to its updates */
1664 private NsdServiceInfo mRegisteredService;
1665 /*** The client id that listen to updates */
1666 private int mClientIdForServiceUpdates;
1667
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001668 private ClientInfo(INsdManagerCallback cb) {
1669 mCb = cb;
paulhub2225702021-11-17 09:35:33 +08001670 if (DBG) Log.d(TAG, "New client");
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001671 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001672
1673 @Override
1674 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06001675 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07001676 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001677 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
1678 for (int i = 0; i < mClientRequests.size(); i++) {
1679 int clientID = mClientRequests.keyAt(i);
1680 sb.append("clientId ")
1681 .append(clientID)
1682 .append(" mDnsId ").append(mClientRequests.valueAt(i).mGlobalId)
1683 .append(" type ").append(
1684 mClientRequests.valueAt(i).getClass().getSimpleName())
1685 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07001686 }
1687 return sb.toString();
1688 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001689
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001690 private boolean isPreSClient() {
1691 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08001692 }
1693
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001694 private void setPreSClient() {
1695 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08001696 }
1697
Dave Plattfeff2af2014-03-07 14:48:22 -08001698 // Remove any pending requests from the global map when we get rid of a client,
1699 // and send cancellations to the daemon.
1700 private void expungeAllRequests() {
Hugo Benichid2552ae2017-04-11 14:42:47 +09001701 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001702 for (int i = 0; i < mClientRequests.size(); i++) {
1703 final int clientId = mClientRequests.keyAt(i);
1704 final ClientRequest request = mClientRequests.valueAt(i);
1705 final int globalId = request.mGlobalId;
Dave Plattfeff2af2014-03-07 14:48:22 -08001706 mIdToClientInfoMap.remove(globalId);
paulhub2225702021-11-17 09:35:33 +08001707 if (DBG) {
1708 Log.d(TAG, "Terminating client-ID " + clientId
1709 + " global-ID " + globalId + " type " + mClientRequests.get(clientId));
1710 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001711
1712 if (request instanceof DiscoveryManagerRequest) {
Ahmad Khalil4b8d45a2023-03-02 11:43:25 +00001713 final MdnsListener listener =
1714 ((DiscoveryManagerRequest) request).mListener;
1715 mMdnsDiscoveryManager.unregisterListener(
1716 listener.getListenedServiceType(), listener);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001717 continue;
1718 }
1719
1720 if (request instanceof AdvertiserClientRequest) {
1721 mAdvertiser.removeService(globalId);
1722 continue;
1723 }
1724
1725 if (!(request instanceof LegacyClientRequest)) {
1726 throw new IllegalStateException("Unknown request type: " + request.getClass());
1727 }
1728
1729 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08001730 case NsdManager.DISCOVER_SERVICES:
1731 stopServiceDiscovery(globalId);
1732 break;
1733 case NsdManager.RESOLVE_SERVICE:
1734 stopResolveService(globalId);
1735 break;
1736 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001737 unregisterService(globalId);
Dave Plattfeff2af2014-03-07 14:48:22 -08001738 break;
1739 default:
1740 break;
1741 }
1742 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001743 mClientRequests.clear();
1744 }
1745
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001746 // mClientRequests is a sparse array of listener id -> ClientRequest. For a given
1747 // mDnsClient id, return the corresponding listener id. mDnsClient id is also called a
1748 // global id.
Christopher Lane74411222014-04-25 18:39:07 -07001749 private int getClientId(final int globalId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001750 for (int i = 0; i < mClientRequests.size(); i++) {
1751 if (mClientRequests.valueAt(i).mGlobalId == globalId) {
1752 return mClientRequests.keyAt(i);
1753 }
Christopher Lane74411222014-04-25 18:39:07 -07001754 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001755 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07001756 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001757
Paul Hu18aeccc2022-12-27 08:48:48 +00001758 private void maybeNotifyRegisteredServiceLost(@NonNull NsdServiceInfo info) {
1759 if (mRegisteredService == null) return;
1760 if (!Objects.equals(mRegisteredService.getServiceName(), info.getServiceName())) return;
1761 // Resolved services have a leading dot appended at the beginning of their type, but in
1762 // discovered info it's at the end
1763 if (!Objects.equals(
1764 mRegisteredService.getServiceType() + ".", "." + info.getServiceType())) {
1765 return;
1766 }
1767 onServiceUpdatedLost(mClientIdForServiceUpdates);
1768 }
1769
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001770 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info) {
1771 try {
1772 mCb.onDiscoverServicesStarted(listenerKey, info);
1773 } catch (RemoteException e) {
1774 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
1775 }
1776 }
1777
1778 void onDiscoverServicesFailed(int listenerKey, int error) {
1779 try {
1780 mCb.onDiscoverServicesFailed(listenerKey, error);
1781 } catch (RemoteException e) {
1782 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
1783 }
1784 }
1785
1786 void onServiceFound(int listenerKey, NsdServiceInfo info) {
1787 try {
1788 mCb.onServiceFound(listenerKey, info);
1789 } catch (RemoteException e) {
1790 Log.e(TAG, "Error calling onServiceFound(", e);
1791 }
1792 }
1793
1794 void onServiceLost(int listenerKey, NsdServiceInfo info) {
1795 try {
1796 mCb.onServiceLost(listenerKey, info);
1797 } catch (RemoteException e) {
1798 Log.e(TAG, "Error calling onServiceLost(", e);
1799 }
1800 }
1801
1802 void onStopDiscoveryFailed(int listenerKey, int error) {
1803 try {
1804 mCb.onStopDiscoveryFailed(listenerKey, error);
1805 } catch (RemoteException e) {
1806 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
1807 }
1808 }
1809
1810 void onStopDiscoverySucceeded(int listenerKey) {
1811 try {
1812 mCb.onStopDiscoverySucceeded(listenerKey);
1813 } catch (RemoteException e) {
1814 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
1815 }
1816 }
1817
1818 void onRegisterServiceFailed(int listenerKey, int error) {
1819 try {
1820 mCb.onRegisterServiceFailed(listenerKey, error);
1821 } catch (RemoteException e) {
1822 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
1823 }
1824 }
1825
1826 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info) {
1827 try {
1828 mCb.onRegisterServiceSucceeded(listenerKey, info);
1829 } catch (RemoteException e) {
1830 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
1831 }
1832 }
1833
1834 void onUnregisterServiceFailed(int listenerKey, int error) {
1835 try {
1836 mCb.onUnregisterServiceFailed(listenerKey, error);
1837 } catch (RemoteException e) {
1838 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
1839 }
1840 }
1841
1842 void onUnregisterServiceSucceeded(int listenerKey) {
1843 try {
1844 mCb.onUnregisterServiceSucceeded(listenerKey);
1845 } catch (RemoteException e) {
1846 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
1847 }
1848 }
1849
1850 void onResolveServiceFailed(int listenerKey, int error) {
1851 try {
1852 mCb.onResolveServiceFailed(listenerKey, error);
1853 } catch (RemoteException e) {
1854 Log.e(TAG, "Error calling onResolveServiceFailed", e);
1855 }
1856 }
1857
1858 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info) {
1859 try {
1860 mCb.onResolveServiceSucceeded(listenerKey, info);
1861 } catch (RemoteException e) {
1862 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
1863 }
1864 }
Paul Hub58deb72022-12-26 09:24:42 +00001865
1866 void onStopResolutionFailed(int listenerKey, int error) {
1867 try {
1868 mCb.onStopResolutionFailed(listenerKey, error);
1869 } catch (RemoteException e) {
1870 Log.e(TAG, "Error calling onStopResolutionFailed", e);
1871 }
1872 }
1873
1874 void onStopResolutionSucceeded(int listenerKey) {
1875 try {
1876 mCb.onStopResolutionSucceeded(listenerKey);
1877 } catch (RemoteException e) {
1878 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
1879 }
1880 }
Paul Hu18aeccc2022-12-27 08:48:48 +00001881
1882 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
1883 try {
1884 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
1885 } catch (RemoteException e) {
1886 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
1887 }
1888 }
1889
1890 void onServiceUpdated(int listenerKey, NsdServiceInfo info) {
1891 try {
1892 mCb.onServiceUpdated(listenerKey, info);
1893 } catch (RemoteException e) {
1894 Log.e(TAG, "Error calling onServiceUpdated", e);
1895 }
1896 }
1897
1898 void onServiceUpdatedLost(int listenerKey) {
1899 try {
1900 mCb.onServiceUpdatedLost(listenerKey);
1901 } catch (RemoteException e) {
1902 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
1903 }
1904 }
1905
1906 void onServiceInfoCallbackUnregistered(int listenerKey) {
1907 try {
1908 mCb.onServiceInfoCallbackUnregistered(listenerKey);
1909 } catch (RemoteException e) {
1910 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
1911 }
1912 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001913 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001914}