blob: 54ec093ac10568698a4593f80e9578a7cb6ed3d7 [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
Paul Hue4f5f252023-02-16 21:13:47 +0800548 private void stopDiscoveryManagerRequest(ClientRequest request, int clientId, int id,
549 ClientInfo clientInfo) {
550 clientInfo.unregisterMdnsListenerFromRequest(request);
551 removeRequestMap(clientId, id, clientInfo);
552 }
553
Irfan Sheriff75006652012-04-17 23:15:29 -0700554 @Override
555 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900556 final ClientInfo clientInfo;
557 final int id;
558 final int clientId = msg.arg2;
559 final ListenerArgs args;
Irfan Sheriff75006652012-04-17 23:15:29 -0700560 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800561 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800562 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900563 args = (ListenerArgs) msg.obj;
564 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000565 // If the binder death notification for a INsdManagerCallback was received
566 // before any calls are received by NsdService, the clientInfo would be
567 // cleared and cause NPE. Add a null check here to prevent this corner case.
568 if (clientInfo == null) {
569 Log.e(TAG, "Unknown connector in discovery");
570 break;
571 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700572
573 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900574 clientInfo.onDiscoverServicesFailed(
575 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriff75006652012-04-17 23:15:29 -0700576 break;
577 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700578
Paul Hu23fa2022023-01-13 22:57:24 +0800579 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700580 id = getUniqueId();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900581 if (mDeps.isMdnsDiscoveryManagerEnabled(mContext)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800582 final String serviceType = constructServiceType(info.getServiceType());
583 if (serviceType == null) {
584 clientInfo.onDiscoverServicesFailed(clientId,
585 NsdManager.FAILURE_INTERNAL_ERROR);
586 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700587 }
Paul Hu23fa2022023-01-13 22:57:24 +0800588
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900589 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800590 maybeStartMonitoringSockets();
591 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900592 new DiscoveryListener(clientId, id, info, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800593 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
594 .setNetwork(info.getNetwork())
595 .setIsPassiveMode(true)
596 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900597 mMdnsDiscoveryManager.registerListener(
598 listenServiceType, listener, options);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900599 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800600 clientInfo.onDiscoverServicesStarted(clientId, info);
Irfan Sheriff75006652012-04-17 23:15:29 -0700601 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800602 maybeStartDaemon();
603 if (discoverServices(id, info)) {
604 if (DBG) {
605 Log.d(TAG, "Discover " + msg.arg2 + " " + id
606 + info.getServiceType());
607 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900608 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu23fa2022023-01-13 22:57:24 +0800609 clientInfo.onDiscoverServicesStarted(clientId, info);
610 } else {
611 stopServiceDiscovery(id);
612 clientInfo.onDiscoverServicesFailed(clientId,
613 NsdManager.FAILURE_INTERNAL_ERROR);
614 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700615 }
616 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800617 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900618 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800619 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900620 args = (ListenerArgs) msg.obj;
621 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000622 // If the binder death notification for a INsdManagerCallback was received
623 // before any calls are received by NsdService, the clientInfo would be
624 // cleared and cause NPE. Add a null check here to prevent this corner case.
625 if (clientInfo == null) {
626 Log.e(TAG, "Unknown connector in stop discovery");
627 break;
628 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700629
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900630 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
631 if (request == null) {
632 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700633 break;
634 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900635 id = request.mGlobalId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900636 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
637 // point, so this needs to check the type of the original request to
638 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900639 if (request instanceof DiscoveryManagerRequest) {
Paul Hue4f5f252023-02-16 21:13:47 +0800640 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900641 clientInfo.onStopDiscoverySucceeded(clientId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700642 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800643 removeRequestMap(clientId, id, clientInfo);
644 if (stopServiceDiscovery(id)) {
645 clientInfo.onStopDiscoverySucceeded(clientId);
646 } else {
647 clientInfo.onStopDiscoveryFailed(
648 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
649 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700650 }
651 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900652 }
653 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800654 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900655 args = (ListenerArgs) msg.obj;
656 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000657 // If the binder death notification for a INsdManagerCallback was received
658 // before any calls are received by NsdService, the clientInfo would be
659 // cleared and cause NPE. Add a null check here to prevent this corner case.
660 if (clientInfo == null) {
661 Log.e(TAG, "Unknown connector in registration");
662 break;
663 }
664
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700665 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900666 clientInfo.onRegisterServiceFailed(
667 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700668 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700669 }
670
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700671 id = getUniqueId();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900672 if (mDeps.isMdnsAdvertiserEnabled(mContext)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900673 final NsdServiceInfo serviceInfo = args.serviceInfo;
674 final String serviceType = serviceInfo.getServiceType();
675 final String registerServiceType = constructServiceType(serviceType);
676 if (registerServiceType == null) {
677 Log.e(TAG, "Invalid service type: " + serviceType);
678 clientInfo.onRegisterServiceFailed(clientId,
679 NsdManager.FAILURE_INTERNAL_ERROR);
680 break;
681 }
682 serviceInfo.setServiceType(registerServiceType);
683 serviceInfo.setServiceName(truncateServiceName(
684 serviceInfo.getServiceName()));
685
686 maybeStartMonitoringSockets();
687 mAdvertiser.addService(id, serviceInfo);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900688 storeAdvertiserRequestMap(clientId, id, clientInfo);
Irfan Sheriff75006652012-04-17 23:15:29 -0700689 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900690 maybeStartDaemon();
691 if (registerService(id, args.serviceInfo)) {
692 if (DBG) Log.d(TAG, "Register " + clientId + " " + id);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900693 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900694 // Return success after mDns reports success
695 } else {
696 unregisterService(id);
697 clientInfo.onRegisterServiceFailed(
698 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
699 }
700
Irfan Sheriff75006652012-04-17 23:15:29 -0700701 }
702 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900703 }
704 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800705 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900706 args = (ListenerArgs) msg.obj;
707 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000708 // If the binder death notification for a INsdManagerCallback was received
709 // before any calls are received by NsdService, the clientInfo would be
710 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900711 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800712 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700713 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700714 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900715 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
716 if (request == null) {
717 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
718 break;
719 }
720 id = request.mGlobalId;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900721 removeRequestMap(clientId, id, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900722
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900723 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
724 // so this needs to check the type of the original request to unregister
725 // instead of looking at the flag value.
726 if (request instanceof AdvertiserClientRequest) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900727 mAdvertiser.removeService(id);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900728 clientInfo.onUnregisterServiceSucceeded(clientId);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700729 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900730 if (unregisterService(id)) {
731 clientInfo.onUnregisterServiceSucceeded(clientId);
732 } else {
733 clientInfo.onUnregisterServiceFailed(
734 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
735 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700736 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700737 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900738 }
Paul Hu75069ed2023-01-14 00:31:09 +0800739 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800740 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900741 args = (ListenerArgs) msg.obj;
742 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000743 // If the binder death notification for a INsdManagerCallback was received
744 // before any calls are received by NsdService, the clientInfo would be
745 // cleared and cause NPE. Add a null check here to prevent this corner case.
746 if (clientInfo == null) {
747 Log.e(TAG, "Unknown connector in resolution");
748 break;
749 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700750
Paul Hu75069ed2023-01-14 00:31:09 +0800751 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700752 id = getUniqueId();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900753 if (mDeps.isMdnsDiscoveryManagerEnabled(mContext)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800754 final String serviceType = constructServiceType(info.getServiceType());
755 if (serviceType == null) {
756 clientInfo.onResolveServiceFailed(clientId,
757 NsdManager.FAILURE_INTERNAL_ERROR);
758 break;
759 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900760 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +0800761
762 maybeStartMonitoringSockets();
763 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900764 new ResolutionListener(clientId, id, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800765 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
766 .setNetwork(info.getNetwork())
767 .setIsPassiveMode(true)
768 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900769 mMdnsDiscoveryManager.registerListener(
770 resolveServiceType, listener, options);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900771 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Irfan Sheriff75006652012-04-17 23:15:29 -0700772 } else {
Paul Hu75069ed2023-01-14 00:31:09 +0800773 if (clientInfo.mResolvedService != null) {
774 clientInfo.onResolveServiceFailed(
775 clientId, NsdManager.FAILURE_ALREADY_ACTIVE);
776 break;
777 }
778
779 maybeStartDaemon();
780 if (resolveService(id, args.serviceInfo)) {
781 clientInfo.mResolvedService = new NsdServiceInfo();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900782 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu75069ed2023-01-14 00:31:09 +0800783 } else {
784 clientInfo.onResolveServiceFailed(
785 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
786 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700787 }
788 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800789 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900790 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +0000791 if (DBG) Log.d(TAG, "Stop service resolution");
792 args = (ListenerArgs) msg.obj;
793 clientInfo = mClients.get(args.connector);
794 // If the binder death notification for a INsdManagerCallback was received
795 // before any calls are received by NsdService, the clientInfo would be
796 // cleared and cause NPE. Add a null check here to prevent this corner case.
797 if (clientInfo == null) {
798 Log.e(TAG, "Unknown connector in stop resolution");
799 break;
800 }
801
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900802 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
803 if (request == null) {
804 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
805 break;
806 }
807 id = request.mGlobalId;
Paul Hue4f5f252023-02-16 21:13:47 +0800808 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
809 // point, so this needs to check the type of the original request to
810 // unregister instead of looking at the flag value.
811 if (request instanceof DiscoveryManagerRequest) {
812 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Paul Hub58deb72022-12-26 09:24:42 +0000813 clientInfo.onStopResolutionSucceeded(clientId);
814 } else {
Paul Hue4f5f252023-02-16 21:13:47 +0800815 removeRequestMap(clientId, id, clientInfo);
816 if (stopResolveService(id)) {
817 clientInfo.onStopResolutionSucceeded(clientId);
818 } else {
819 clientInfo.onStopResolutionFailed(
820 clientId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
821 }
822 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +0000823 }
Paul Hub58deb72022-12-26 09:24:42 +0000824 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900825 }
Paul Hu18aeccc2022-12-27 08:48:48 +0000826 case NsdManager.REGISTER_SERVICE_CALLBACK:
827 if (DBG) Log.d(TAG, "Register a service callback");
828 args = (ListenerArgs) msg.obj;
829 clientInfo = mClients.get(args.connector);
830 // If the binder death notification for a INsdManagerCallback was received
831 // before any calls are received by NsdService, the clientInfo would be
832 // cleared and cause NPE. Add a null check here to prevent this corner case.
833 if (clientInfo == null) {
834 Log.e(TAG, "Unknown connector in callback registration");
835 break;
836 }
837
838 if (clientInfo.mRegisteredService != null) {
839 clientInfo.onServiceInfoCallbackRegistrationFailed(
840 clientId, NsdManager.FAILURE_ALREADY_ACTIVE);
841 break;
842 }
843
844 maybeStartDaemon();
845 id = getUniqueId();
846 if (resolveService(id, args.serviceInfo)) {
847 clientInfo.mRegisteredService = new NsdServiceInfo();
848 clientInfo.mClientIdForServiceUpdates = clientId;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900849 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu18aeccc2022-12-27 08:48:48 +0000850 } else {
851 clientInfo.onServiceInfoCallbackRegistrationFailed(
852 clientId, NsdManager.FAILURE_BAD_PARAMETERS);
853 }
854 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900855 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +0000856 if (DBG) Log.d(TAG, "Unregister a service callback");
857 args = (ListenerArgs) msg.obj;
858 clientInfo = mClients.get(args.connector);
859 // If the binder death notification for a INsdManagerCallback was received
860 // before any calls are received by NsdService, the clientInfo would be
861 // cleared and cause NPE. Add a null check here to prevent this corner case.
862 if (clientInfo == null) {
863 Log.e(TAG, "Unknown connector in callback unregistration");
864 break;
865 }
866
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900867 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
868 if (request == null) {
869 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
870 break;
871 }
872 id = request.mGlobalId;
Paul Hu18aeccc2022-12-27 08:48:48 +0000873 removeRequestMap(clientId, id, clientInfo);
874 if (stopResolveService(id)) {
875 clientInfo.onServiceInfoCallbackUnregistered(clientId);
876 } else {
877 Log.e(TAG, "Failed to unregister service info callback");
878 }
879 clearRegisteredServiceInfo(clientInfo);
880 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900881 }
paulhu2b9ed952022-02-10 21:58:32 +0800882 case MDNS_SERVICE_EVENT:
883 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +0900884 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700885 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700886 break;
Paul Hu019621e2023-01-13 23:26:49 +0800887 case MDNS_DISCOVERY_MANAGER_EVENT:
888 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
889 return NOT_HANDLED;
890 }
891 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700892 default:
Hugo Benichif0c84092017-04-05 14:43:29 +0900893 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700894 }
Hugo Benichif0c84092017-04-05 14:43:29 +0900895 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700896 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700897
Paul Hu18aeccc2022-12-27 08:48:48 +0000898 private void notifyResolveFailedResult(boolean isListenedToUpdates, int clientId,
899 ClientInfo clientInfo, int error) {
900 if (isListenedToUpdates) {
901 clientInfo.onServiceInfoCallbackRegistrationFailed(clientId, error);
902 clearRegisteredServiceInfo(clientInfo);
903 } else {
904 // The resolve API always returned FAILURE_INTERNAL_ERROR on error; keep it
905 // for backwards compatibility.
906 clientInfo.onResolveServiceFailed(clientId, NsdManager.FAILURE_INTERNAL_ERROR);
907 clientInfo.mResolvedService = null;
908 }
909 }
910
paulhu2b9ed952022-02-10 21:58:32 +0800911 private boolean handleMDnsServiceEvent(int code, int id, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700912 NsdServiceInfo servInfo;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700913 ClientInfo clientInfo = mIdToClientInfoMap.get(id);
914 if (clientInfo == null) {
paulhu2b9ed952022-02-10 21:58:32 +0800915 Log.e(TAG, String.format("id %d for %d has no client mapping", id, code));
Hugo Benichif0c84092017-04-05 14:43:29 +0900916 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700917 }
918
919 /* This goes in response as msg.arg2 */
Christopher Lane74411222014-04-25 18:39:07 -0700920 int clientId = clientInfo.getClientId(id);
921 if (clientId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -0700922 // This can happen because of race conditions. For example,
923 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
924 // and we may get in this situation.
paulhu2b9ed952022-02-10 21:58:32 +0800925 Log.d(TAG, String.format("%d for listener id %d that is no longer active",
926 code, id));
Hugo Benichif0c84092017-04-05 14:43:29 +0900927 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700928 }
Hugo Benichi32be63d2017-04-05 14:06:11 +0900929 if (DBG) {
paulhu2b9ed952022-02-10 21:58:32 +0800930 Log.d(TAG, String.format("MDns service event code:%d id=%d", code, id));
Hugo Benichi32be63d2017-04-05 14:06:11 +0900931 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700932 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +0800933 case IMDnsEventListener.SERVICE_FOUND: {
934 final DiscoveryInfo info = (DiscoveryInfo) obj;
935 final String name = info.serviceName;
936 final String type = info.registrationType;
937 servInfo = new NsdServiceInfo(name, type);
938 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900939 if (foundNetId == 0L) {
940 // Ignore services that do not have a Network: they are not usable
941 // by apps, as they would need privileged permissions to use
942 // interfaces that do not have an associated Network.
943 break;
944 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +0900945 if (foundNetId == INetd.DUMMY_NET_ID) {
946 // Ignore services on the dummy0 interface: they are only seen when
947 // discovering locally advertised services, and are not reachable
948 // through that interface.
949 break;
950 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900951 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900952 clientInfo.onServiceFound(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700953 break;
paulhu2b9ed952022-02-10 21:58:32 +0800954 }
955 case IMDnsEventListener.SERVICE_LOST: {
956 final DiscoveryInfo info = (DiscoveryInfo) obj;
957 final String name = info.serviceName;
958 final String type = info.registrationType;
959 final int lostNetId = info.netId;
960 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900961 // The network could be set to null (netId 0) if it was torn down when the
962 // service is lost
963 // TODO: avoid returning null in that case, possibly by remembering
964 // found services on the same interface index and their network at the time
965 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900966 clientInfo.onServiceLost(clientId, servInfo);
Paul Hu18aeccc2022-12-27 08:48:48 +0000967 // TODO: also support registered service lost when not discovering
968 clientInfo.maybeNotifyRegisteredServiceLost(servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700969 break;
paulhu2b9ed952022-02-10 21:58:32 +0800970 }
971 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900972 clientInfo.onDiscoverServicesFailed(
973 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700974 break;
paulhu2b9ed952022-02-10 21:58:32 +0800975 case IMDnsEventListener.SERVICE_REGISTERED: {
976 final RegistrationInfo info = (RegistrationInfo) obj;
977 final String name = info.serviceName;
978 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900979 clientInfo.onRegisterServiceSucceeded(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700980 break;
paulhu2b9ed952022-02-10 21:58:32 +0800981 }
982 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900983 clientInfo.onRegisterServiceFailed(
984 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700985 break;
paulhu2b9ed952022-02-10 21:58:32 +0800986 case IMDnsEventListener.SERVICE_RESOLVED: {
987 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -0700988 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +0800989 final String fullName = info.serviceFullName;
990 while (index < fullName.length() && fullName.charAt(index) != '.') {
991 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -0700992 ++index;
993 }
994 ++index;
995 }
paulhu2b9ed952022-02-10 21:58:32 +0800996 if (index >= fullName.length()) {
997 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700998 break;
999 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001000
paulhube186602022-04-12 07:18:23 +00001001 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001002 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001003 String type = rest.replace(".local.", "");
1004
Paul Hu18aeccc2022-12-27 08:48:48 +00001005 final boolean isListenedToUpdates =
1006 clientId == clientInfo.mClientIdForServiceUpdates;
1007 final NsdServiceInfo serviceInfo = isListenedToUpdates
1008 ? clientInfo.mRegisteredService : clientInfo.mResolvedService;
1009
1010 serviceInfo.setServiceName(name);
1011 serviceInfo.setServiceType(type);
1012 serviceInfo.setPort(info.port);
1013 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001014 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001015
1016 stopResolveService(id);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001017 removeRequestMap(clientId, id, clientInfo);
1018
paulhu2b9ed952022-02-10 21:58:32 +08001019 final int id2 = getUniqueId();
1020 if (getAddrInfo(id2, info.hostname, info.interfaceIdx)) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001021 storeLegacyRequestMap(clientId, id2, clientInfo,
1022 NsdManager.RESOLVE_SERVICE);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001023 } else {
Paul Hu18aeccc2022-12-27 08:48:48 +00001024 notifyResolveFailedResult(isListenedToUpdates, clientId, clientInfo,
1025 NsdManager.FAILURE_BAD_PARAMETERS);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001026 }
1027 break;
paulhu2b9ed952022-02-10 21:58:32 +08001028 }
1029 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001030 /* NNN resolveId errorCode */
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001031 stopResolveService(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_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001038 /* NNN resolveId errorCode */
1039 stopGetAddrInfo(id);
1040 removeRequestMap(clientId, id, clientInfo);
Paul Hu18aeccc2022-12-27 08:48:48 +00001041 notifyResolveFailedResult(
1042 clientId == clientInfo.mClientIdForServiceUpdates,
1043 clientId, clientInfo, NsdManager.FAILURE_BAD_PARAMETERS);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001044 break;
paulhu2b9ed952022-02-10 21:58:32 +08001045 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001046 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001047 final GetAddressInfo info = (GetAddressInfo) obj;
1048 final String address = info.address;
1049 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001050 InetAddress serviceHost = null;
1051 try {
paulhu2b9ed952022-02-10 21:58:32 +08001052 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001053 } catch (UnknownHostException e) {
1054 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1055 }
1056
1057 // If the resolved service is on an interface without a network, consider it
1058 // as a failure: it would not be usable by apps as they would need
1059 // privileged permissions.
Paul Hu18aeccc2022-12-27 08:48:48 +00001060 if (clientId == clientInfo.mClientIdForServiceUpdates) {
1061 if (netId != NETID_UNSET && serviceHost != null) {
1062 setServiceNetworkForCallback(clientInfo.mRegisteredService,
1063 netId, info.interfaceIdx);
1064 final List<InetAddress> addresses =
1065 clientInfo.mRegisteredService.getHostAddresses();
1066 addresses.add(serviceHost);
1067 clientInfo.mRegisteredService.setHostAddresses(addresses);
1068 clientInfo.onServiceUpdated(
1069 clientId, clientInfo.mRegisteredService);
1070 } else {
1071 stopGetAddrInfo(id);
1072 removeRequestMap(clientId, id, clientInfo);
1073 clearRegisteredServiceInfo(clientInfo);
1074 clientInfo.onServiceInfoCallbackRegistrationFailed(
1075 clientId, NsdManager.FAILURE_BAD_PARAMETERS);
1076 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001077 } else {
Paul Hu18aeccc2022-12-27 08:48:48 +00001078 if (netId != NETID_UNSET && serviceHost != null) {
1079 clientInfo.mResolvedService.setHost(serviceHost);
1080 setServiceNetworkForCallback(clientInfo.mResolvedService,
1081 netId, info.interfaceIdx);
1082 clientInfo.onResolveServiceSucceeded(
1083 clientId, clientInfo.mResolvedService);
1084 } else {
1085 clientInfo.onResolveServiceFailed(
1086 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1087 }
1088 stopGetAddrInfo(id);
1089 removeRequestMap(clientId, id, clientInfo);
1090 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001091 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001092 break;
paulhu2b9ed952022-02-10 21:58:32 +08001093 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001094 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001095 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001096 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001097 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001098 }
Paul Hu019621e2023-01-13 23:26:49 +08001099
1100 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(final MdnsEvent event) {
1101 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1102 final String serviceType = event.mRequestedServiceType;
1103 final String serviceName = serviceInfo.getServiceInstanceName();
1104 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1105 final Network network = serviceInfo.getNetwork();
1106 setServiceNetworkForCallback(
1107 servInfo,
1108 network == null ? NETID_UNSET : network.netId,
1109 serviceInfo.getInterfaceIndex());
1110 return servInfo;
1111 }
1112
1113 private boolean handleMdnsDiscoveryManagerEvent(
1114 int transactionId, int code, Object obj) {
1115 final ClientInfo clientInfo = mIdToClientInfoMap.get(transactionId);
1116 if (clientInfo == null) {
1117 Log.e(TAG, String.format(
1118 "id %d for %d has no client mapping", transactionId, code));
1119 return false;
1120 }
1121
1122 final MdnsEvent event = (MdnsEvent) obj;
1123 final int clientId = event.mClientId;
Paul Hu319751a2023-01-13 23:56:34 +08001124 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event);
Paul Hu019621e2023-01-13 23:26:49 +08001125 if (DBG) {
1126 Log.d(TAG, String.format("MdnsDiscoveryManager event code=%s transactionId=%d",
1127 NsdManager.nameOf(code), transactionId));
1128 }
1129 switch (code) {
1130 case NsdManager.SERVICE_FOUND:
Paul Hu319751a2023-01-13 23:56:34 +08001131 clientInfo.onServiceFound(clientId, info);
1132 break;
1133 case NsdManager.SERVICE_LOST:
1134 clientInfo.onServiceLost(clientId, info);
Paul Hu019621e2023-01-13 23:26:49 +08001135 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001136 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001137 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
1138 if (request == null) {
1139 Log.e(TAG, "Unknown client request in RESOLVE_SERVICE_SUCCEEDED");
1140 break;
1141 }
Paul Hu75069ed2023-01-14 00:31:09 +08001142 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1143 // Add '.' in front of the service type that aligns with historical behavior
1144 info.setServiceType("." + event.mRequestedServiceType);
1145 info.setPort(serviceInfo.getPort());
1146
1147 Map<String, String> attrs = serviceInfo.getAttributes();
1148 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1149 final String key = kv.getKey();
1150 try {
1151 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1152 } catch (IllegalArgumentException e) {
1153 Log.e(TAG, "Invalid attribute", e);
1154 }
1155 }
1156 try {
1157 if (serviceInfo.getIpv4Address() != null) {
1158 info.setHost(InetAddresses.parseNumericAddress(
1159 serviceInfo.getIpv4Address()));
1160 } else {
1161 info.setHost(InetAddresses.parseNumericAddress(
1162 serviceInfo.getIpv6Address()));
1163 }
1164 clientInfo.onResolveServiceSucceeded(clientId, info);
1165 } catch (IllegalArgumentException e) {
1166 Log.wtf(TAG, "Invalid address in RESOLVE_SERVICE_SUCCEEDED", e);
1167 clientInfo.onResolveServiceFailed(
1168 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1169 }
1170
1171 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001172 if (!(request instanceof DiscoveryManagerRequest)) {
1173 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1174 break;
1175 }
Paul Hue4f5f252023-02-16 21:13:47 +08001176 stopDiscoveryManagerRequest(request, clientId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001177 break;
1178 }
Paul Hu019621e2023-01-13 23:26:49 +08001179 default:
1180 return false;
1181 }
1182 return true;
1183 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001184 }
1185 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001186
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001187 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1188 switch (netId) {
1189 case NETID_UNSET:
1190 info.setNetwork(null);
1191 break;
1192 case INetd.LOCAL_NET_ID:
1193 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1194 // visible / usable for apps, so do not return it. Store the interface
1195 // index instead, so at least if the client tries to resolve the service
1196 // with that NsdServiceInfo, it will be done on the same interface.
1197 // If they recreate the NsdServiceInfo themselves, resolution would be
1198 // done on all interfaces as before T, which should also work.
1199 info.setNetwork(null);
1200 info.setInterfaceIndex(ifaceIdx);
1201 break;
1202 default:
1203 info.setNetwork(new Network(netId));
1204 }
1205 }
1206
paulhube186602022-04-12 07:18:23 +00001207 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1208 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1209 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1210 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1211 private String unescape(String s) {
1212 StringBuilder sb = new StringBuilder(s.length());
1213 for (int i = 0; i < s.length(); ++i) {
1214 char c = s.charAt(i);
1215 if (c == '\\') {
1216 if (++i >= s.length()) {
1217 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1218 break;
1219 }
1220 c = s.charAt(i);
1221 if (c != '.' && c != '\\') {
1222 if (i + 2 >= s.length()) {
1223 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1224 break;
1225 }
1226 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1227 + (s.charAt(i + 2) - '0'));
1228 i += 2;
1229 }
1230 }
1231 sb.append(c);
1232 }
1233 return sb.toString();
1234 }
1235
Hugo Benichi803a2f02017-04-24 11:35:06 +09001236 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001237 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001238 this(ctx, handler, cleanupDelayMs, new Dependencies());
1239 }
1240
1241 @VisibleForTesting
1242 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001243 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001244 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001245 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001246 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001247 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1248 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001249 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001250
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001251 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper());
1252 mMdnsSocketClient =
1253 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider);
1254 mMdnsDiscoveryManager =
1255 deps.makeMdnsDiscoveryManager(new ExecutorProvider(), mMdnsSocketClient);
1256 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1257 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
1258 new AdvertiserCallback());
Paul Hu4bd98ef2023-01-12 13:42:07 +08001259 }
1260
1261 /**
1262 * Dependencies of NsdService, for injection in tests.
1263 */
1264 @VisibleForTesting
1265 public static class Dependencies {
1266 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001267 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001268 *
1269 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001270 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001271 */
1272 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
1273 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY,
1274 MDNS_DISCOVERY_MANAGER_VERSION, false /* defaultEnabled */);
1275 }
1276
1277 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001278 * Check whether the MdnsAdvertiser feature is enabled.
1279 *
1280 * @param context The global context information about an app environment.
1281 * @return true if the MdnsAdvertiser feature is enabled.
1282 */
1283 public boolean isMdnsAdvertiserEnabled(Context context) {
1284 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY,
1285 MDNS_ADVERTISER_VERSION, false /* defaultEnabled */);
1286 }
1287
1288 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001289 * @see MdnsDiscoveryManager
1290 */
1291 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
1292 ExecutorProvider executorProvider, MdnsSocketClientBase socketClient) {
1293 return new MdnsDiscoveryManager(executorProvider, socketClient);
1294 }
1295
1296 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001297 * @see MdnsAdvertiser
1298 */
1299 public MdnsAdvertiser makeMdnsAdvertiser(
1300 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
1301 @NonNull MdnsAdvertiser.AdvertiserCallback cb) {
1302 return new MdnsAdvertiser(looper, socketProvider, cb);
1303 }
1304
1305 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001306 * @see MdnsSocketProvider
1307 */
1308 public MdnsSocketProvider makeMdnsSocketProvider(Context context, Looper looper) {
1309 return new MdnsSocketProvider(context, looper);
1310 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001311 }
1312
paulhu1b35e822022-04-08 14:48:41 +08001313 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001314 HandlerThread thread = new HandlerThread(TAG);
1315 thread.start();
1316 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001317 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001318 return service;
1319 }
1320
paulhu2b9ed952022-02-10 21:58:32 +08001321 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1322 private final StateMachine mStateMachine;
1323
1324 MDnsEventCallback(StateMachine sm) {
1325 mStateMachine = sm;
1326 }
1327
1328 @Override
1329 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1330 mStateMachine.sendMessage(
1331 MDNS_SERVICE_EVENT, status.result, status.id, status);
1332 }
1333
1334 @Override
1335 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1336 mStateMachine.sendMessage(
1337 MDNS_SERVICE_EVENT, status.result, status.id, status);
1338 }
1339
1340 @Override
1341 public void onServiceResolutionStatus(final ResolutionInfo status) {
1342 mStateMachine.sendMessage(
1343 MDNS_SERVICE_EVENT, status.result, status.id, status);
1344 }
1345
1346 @Override
1347 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1348 mStateMachine.sendMessage(
1349 MDNS_SERVICE_EVENT, status.result, status.id, status);
1350 }
1351
1352 @Override
1353 public int getInterfaceVersion() throws RemoteException {
1354 return this.VERSION;
1355 }
1356
1357 @Override
1358 public String getInterfaceHash() throws RemoteException {
1359 return this.HASH;
1360 }
1361 }
1362
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001363 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
1364 @Override
1365 public void onRegisterServiceSucceeded(int serviceId, NsdServiceInfo registeredInfo) {
1366 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1367 if (clientInfo == null) return;
1368
1369 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1370 if (clientId < 0) return;
1371
1372 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1373 // historical behavior.
1374 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
1375 clientInfo.onRegisterServiceSucceeded(clientId, cbInfo);
1376 }
1377
1378 @Override
1379 public void onRegisterServiceFailed(int serviceId, int errorCode) {
1380 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1381 if (clientInfo == null) return;
1382
1383 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1384 if (clientId < 0) return;
1385
1386 clientInfo.onRegisterServiceFailed(clientId, errorCode);
1387 }
1388
1389 private ClientInfo getClientInfoOrLog(int serviceId) {
1390 final ClientInfo clientInfo = mIdToClientInfoMap.get(serviceId);
1391 if (clientInfo == null) {
1392 Log.e(TAG, String.format("Callback for service %d has no client", serviceId));
1393 }
1394 return clientInfo;
1395 }
1396
1397 private int getClientIdOrLog(@NonNull ClientInfo info, int serviceId) {
1398 final int clientId = info.getClientId(serviceId);
1399 if (clientId < 0) {
1400 Log.e(TAG, String.format("Client ID not found for service %d", serviceId));
1401 }
1402 return clientId;
1403 }
1404 }
1405
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001406 @Override
1407 public INsdServiceConnector connect(INsdManagerCallback cb) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001408 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001409 final INsdServiceConnector connector = new NsdServiceConnector();
1410 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1411 NsdManager.REGISTER_CLIENT, new Pair<>(connector, cb)));
1412 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07001413 }
1414
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001415 private static class ListenerArgs {
1416 public final NsdServiceConnector connector;
1417 public final NsdServiceInfo serviceInfo;
1418 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
1419 this.connector = connector;
1420 this.serviceInfo = serviceInfo;
1421 }
1422 }
1423
1424 private class NsdServiceConnector extends INsdServiceConnector.Stub
1425 implements IBinder.DeathRecipient {
1426 @Override
1427 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
1428 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1429 NsdManager.REGISTER_SERVICE, 0, listenerKey,
1430 new ListenerArgs(this, serviceInfo)));
1431 }
1432
1433 @Override
1434 public void unregisterService(int listenerKey) {
1435 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1436 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
1437 new ListenerArgs(this, null)));
1438 }
1439
1440 @Override
1441 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
1442 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1443 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
1444 new ListenerArgs(this, serviceInfo)));
1445 }
1446
1447 @Override
1448 public void stopDiscovery(int listenerKey) {
1449 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1450 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
1451 }
1452
1453 @Override
1454 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
1455 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1456 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
1457 new ListenerArgs(this, serviceInfo)));
1458 }
1459
1460 @Override
Paul Hub58deb72022-12-26 09:24:42 +00001461 public void stopResolution(int listenerKey) {
1462 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1463 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
1464 }
1465
1466 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00001467 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
1468 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1469 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
1470 new ListenerArgs(this, serviceInfo)));
1471 }
1472
1473 @Override
1474 public void unregisterServiceInfoCallback(int listenerKey) {
1475 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1476 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
1477 new ListenerArgs(this, null)));
1478 }
1479
1480 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001481 public void startDaemon() {
1482 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1483 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
1484 }
1485
1486 @Override
1487 public void binderDied() {
1488 mNsdStateMachine.sendMessage(
1489 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
1490 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001491 }
1492
Hugo Benichi912db992017-04-24 16:41:03 +09001493 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07001494 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07001495 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09001496 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
1497 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07001498 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07001499 }
1500
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001501 private int getUniqueId() {
1502 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
1503 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001504 }
1505
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001506 private boolean registerService(int regId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09001507 if (DBG) {
paulhub2225702021-11-17 09:35:33 +08001508 Log.d(TAG, "registerService: " + regId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001509 }
Hugo Benichi6d706442017-04-24 16:19:58 +09001510 String name = service.getServiceName();
1511 String type = service.getServiceType();
1512 int port = service.getPort();
1513 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001514 final int registerInterface = getNetworkInterfaceIndex(service);
1515 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08001516 Log.e(TAG, "Interface to register service on not found");
1517 return false;
1518 }
1519 return mMDnsManager.registerService(regId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001520 }
1521
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001522 private boolean unregisterService(int regId) {
paulhu2b9ed952022-02-10 21:58:32 +08001523 return mMDnsManager.stopOperation(regId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001524 }
1525
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001526 private boolean discoverServices(int discoveryId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08001527 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001528 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
1529 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001530 Log.e(TAG, "Interface to discover service on not found");
1531 return false;
1532 }
paulhu2b9ed952022-02-10 21:58:32 +08001533 return mMDnsManager.discover(discoveryId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001534 }
1535
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001536 private boolean stopServiceDiscovery(int discoveryId) {
paulhu2b9ed952022-02-10 21:58:32 +08001537 return mMDnsManager.stopOperation(discoveryId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001538 }
1539
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001540 private boolean resolveService(int resolveId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001541 final String name = service.getServiceName();
1542 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001543 final int resolveInterface = getNetworkInterfaceIndex(service);
1544 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001545 Log.e(TAG, "Interface to resolve service on not found");
1546 return false;
1547 }
paulhu2b9ed952022-02-10 21:58:32 +08001548 return mMDnsManager.resolve(resolveId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001549 }
1550
1551 /**
1552 * Guess the interface to use to resolve or discover a service on a specific network.
1553 *
1554 * This is an imperfect guess, as for example the network may be gone or not yet fully
1555 * registered. This is fine as failing is correct if the network is gone, and a client
1556 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
1557 * this is to support the legacy mdnsresponder implementation, which historically resolved
1558 * services on an unspecified network.
1559 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001560 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
1561 final Network network = serviceInfo.getNetwork();
1562 if (network == null) {
1563 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
1564 // provided by NsdService from discovery results, and the service was found on an
1565 // interface that has no app-usable Network).
1566 if (serviceInfo.getInterfaceIndex() != 0) {
1567 return serviceInfo.getInterfaceIndex();
1568 }
1569 return IFACE_IDX_ANY;
1570 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001571
1572 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
1573 if (cm == null) {
1574 Log.wtf(TAG, "No ConnectivityManager for resolveService");
1575 return IFACE_IDX_ANY;
1576 }
1577 final LinkProperties lp = cm.getLinkProperties(network);
1578 if (lp == null) return IFACE_IDX_ANY;
1579
1580 // Only resolve on non-stacked interfaces
1581 final NetworkInterface iface;
1582 try {
1583 iface = NetworkInterface.getByName(lp.getInterfaceName());
1584 } catch (SocketException e) {
1585 Log.e(TAG, "Error querying interface", e);
1586 return IFACE_IDX_ANY;
1587 }
1588
1589 if (iface == null) {
1590 Log.e(TAG, "Interface not found: " + lp.getInterfaceName());
1591 return IFACE_IDX_ANY;
1592 }
1593
1594 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001595 }
1596
1597 private boolean stopResolveService(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001598 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001599 }
1600
paulhu2b9ed952022-02-10 21:58:32 +08001601 private boolean getAddrInfo(int resolveId, String hostname, int interfaceIdx) {
1602 return mMDnsManager.getServiceAddress(resolveId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001603 }
1604
1605 private boolean stopGetAddrInfo(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001606 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001607 }
1608
1609 @Override
Irfan Sheriff75006652012-04-17 23:15:29 -07001610 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
paulhu3ffffe72021-09-16 10:15:22 +08001611 if (!PermissionUtils.checkDumpPermission(mContext, TAG, pw)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001612
Irfan Sheriff75006652012-04-17 23:15:29 -07001613 for (ClientInfo client : mClients.values()) {
1614 pw.println("Client Info");
1615 pw.println(client);
1616 }
1617
1618 mNsdStateMachine.dump(fd, pw, args);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001619 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001620
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001621 private abstract static class ClientRequest {
1622 private final int mGlobalId;
1623
1624 private ClientRequest(int globalId) {
1625 mGlobalId = globalId;
1626 }
1627 }
1628
1629 private static class LegacyClientRequest extends ClientRequest {
1630 private final int mRequestCode;
1631
1632 private LegacyClientRequest(int globalId, int requestCode) {
1633 super(globalId);
1634 mRequestCode = requestCode;
1635 }
1636 }
1637
1638 private static class AdvertiserClientRequest extends ClientRequest {
1639 private AdvertiserClientRequest(int globalId) {
1640 super(globalId);
1641 }
1642 }
1643
1644 private static class DiscoveryManagerRequest extends ClientRequest {
1645 @NonNull
1646 private final MdnsListener mListener;
1647
1648 private DiscoveryManagerRequest(int globalId, @NonNull MdnsListener listener) {
1649 super(globalId);
1650 mListener = listener;
1651 }
1652 }
1653
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001654 /* Information tracked per client */
1655 private class ClientInfo {
1656
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001657 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001658 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001659 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001660 private NsdServiceInfo mResolvedService;
1661
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001662 /* A map from client-side ID (listenerKey) to the request */
1663 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08001664
Luke Huangf7277ed2021-07-12 21:15:10 +08001665 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001666 private boolean mIsPreSClient = false;
Luke Huangf7277ed2021-07-12 21:15:10 +08001667
Paul Hu18aeccc2022-12-27 08:48:48 +00001668 /*** The service that is registered to listen to its updates */
1669 private NsdServiceInfo mRegisteredService;
1670 /*** The client id that listen to updates */
1671 private int mClientIdForServiceUpdates;
1672
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001673 private ClientInfo(INsdManagerCallback cb) {
1674 mCb = cb;
paulhub2225702021-11-17 09:35:33 +08001675 if (DBG) Log.d(TAG, "New client");
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001676 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001677
1678 @Override
1679 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06001680 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07001681 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001682 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
1683 for (int i = 0; i < mClientRequests.size(); i++) {
1684 int clientID = mClientRequests.keyAt(i);
1685 sb.append("clientId ")
1686 .append(clientID)
1687 .append(" mDnsId ").append(mClientRequests.valueAt(i).mGlobalId)
1688 .append(" type ").append(
1689 mClientRequests.valueAt(i).getClass().getSimpleName())
1690 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07001691 }
1692 return sb.toString();
1693 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001694
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001695 private boolean isPreSClient() {
1696 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08001697 }
1698
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001699 private void setPreSClient() {
1700 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08001701 }
1702
Paul Hue4f5f252023-02-16 21:13:47 +08001703 private void unregisterMdnsListenerFromRequest(ClientRequest request) {
1704 final MdnsListener listener =
1705 ((DiscoveryManagerRequest) request).mListener;
1706 mMdnsDiscoveryManager.unregisterListener(
1707 listener.getListenedServiceType(), listener);
1708 }
1709
Dave Plattfeff2af2014-03-07 14:48:22 -08001710 // Remove any pending requests from the global map when we get rid of a client,
1711 // and send cancellations to the daemon.
1712 private void expungeAllRequests() {
Hugo Benichid2552ae2017-04-11 14:42:47 +09001713 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001714 for (int i = 0; i < mClientRequests.size(); i++) {
1715 final int clientId = mClientRequests.keyAt(i);
1716 final ClientRequest request = mClientRequests.valueAt(i);
1717 final int globalId = request.mGlobalId;
Dave Plattfeff2af2014-03-07 14:48:22 -08001718 mIdToClientInfoMap.remove(globalId);
paulhub2225702021-11-17 09:35:33 +08001719 if (DBG) {
1720 Log.d(TAG, "Terminating client-ID " + clientId
1721 + " global-ID " + globalId + " type " + mClientRequests.get(clientId));
1722 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001723
1724 if (request instanceof DiscoveryManagerRequest) {
Paul Hue4f5f252023-02-16 21:13:47 +08001725 unregisterMdnsListenerFromRequest(request);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001726 continue;
1727 }
1728
1729 if (request instanceof AdvertiserClientRequest) {
1730 mAdvertiser.removeService(globalId);
1731 continue;
1732 }
1733
1734 if (!(request instanceof LegacyClientRequest)) {
1735 throw new IllegalStateException("Unknown request type: " + request.getClass());
1736 }
1737
1738 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08001739 case NsdManager.DISCOVER_SERVICES:
1740 stopServiceDiscovery(globalId);
1741 break;
1742 case NsdManager.RESOLVE_SERVICE:
1743 stopResolveService(globalId);
1744 break;
1745 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001746 unregisterService(globalId);
Dave Plattfeff2af2014-03-07 14:48:22 -08001747 break;
1748 default:
1749 break;
1750 }
1751 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001752 mClientRequests.clear();
1753 }
1754
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001755 // mClientRequests is a sparse array of listener id -> ClientRequest. For a given
1756 // mDnsClient id, return the corresponding listener id. mDnsClient id is also called a
1757 // global id.
Christopher Lane74411222014-04-25 18:39:07 -07001758 private int getClientId(final int globalId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001759 for (int i = 0; i < mClientRequests.size(); i++) {
1760 if (mClientRequests.valueAt(i).mGlobalId == globalId) {
1761 return mClientRequests.keyAt(i);
1762 }
Christopher Lane74411222014-04-25 18:39:07 -07001763 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001764 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07001765 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001766
Paul Hu18aeccc2022-12-27 08:48:48 +00001767 private void maybeNotifyRegisteredServiceLost(@NonNull NsdServiceInfo info) {
1768 if (mRegisteredService == null) return;
1769 if (!Objects.equals(mRegisteredService.getServiceName(), info.getServiceName())) return;
1770 // Resolved services have a leading dot appended at the beginning of their type, but in
1771 // discovered info it's at the end
1772 if (!Objects.equals(
1773 mRegisteredService.getServiceType() + ".", "." + info.getServiceType())) {
1774 return;
1775 }
1776 onServiceUpdatedLost(mClientIdForServiceUpdates);
1777 }
1778
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001779 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info) {
1780 try {
1781 mCb.onDiscoverServicesStarted(listenerKey, info);
1782 } catch (RemoteException e) {
1783 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
1784 }
1785 }
1786
1787 void onDiscoverServicesFailed(int listenerKey, int error) {
1788 try {
1789 mCb.onDiscoverServicesFailed(listenerKey, error);
1790 } catch (RemoteException e) {
1791 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
1792 }
1793 }
1794
1795 void onServiceFound(int listenerKey, NsdServiceInfo info) {
1796 try {
1797 mCb.onServiceFound(listenerKey, info);
1798 } catch (RemoteException e) {
1799 Log.e(TAG, "Error calling onServiceFound(", e);
1800 }
1801 }
1802
1803 void onServiceLost(int listenerKey, NsdServiceInfo info) {
1804 try {
1805 mCb.onServiceLost(listenerKey, info);
1806 } catch (RemoteException e) {
1807 Log.e(TAG, "Error calling onServiceLost(", e);
1808 }
1809 }
1810
1811 void onStopDiscoveryFailed(int listenerKey, int error) {
1812 try {
1813 mCb.onStopDiscoveryFailed(listenerKey, error);
1814 } catch (RemoteException e) {
1815 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
1816 }
1817 }
1818
1819 void onStopDiscoverySucceeded(int listenerKey) {
1820 try {
1821 mCb.onStopDiscoverySucceeded(listenerKey);
1822 } catch (RemoteException e) {
1823 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
1824 }
1825 }
1826
1827 void onRegisterServiceFailed(int listenerKey, int error) {
1828 try {
1829 mCb.onRegisterServiceFailed(listenerKey, error);
1830 } catch (RemoteException e) {
1831 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
1832 }
1833 }
1834
1835 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info) {
1836 try {
1837 mCb.onRegisterServiceSucceeded(listenerKey, info);
1838 } catch (RemoteException e) {
1839 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
1840 }
1841 }
1842
1843 void onUnregisterServiceFailed(int listenerKey, int error) {
1844 try {
1845 mCb.onUnregisterServiceFailed(listenerKey, error);
1846 } catch (RemoteException e) {
1847 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
1848 }
1849 }
1850
1851 void onUnregisterServiceSucceeded(int listenerKey) {
1852 try {
1853 mCb.onUnregisterServiceSucceeded(listenerKey);
1854 } catch (RemoteException e) {
1855 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
1856 }
1857 }
1858
1859 void onResolveServiceFailed(int listenerKey, int error) {
1860 try {
1861 mCb.onResolveServiceFailed(listenerKey, error);
1862 } catch (RemoteException e) {
1863 Log.e(TAG, "Error calling onResolveServiceFailed", e);
1864 }
1865 }
1866
1867 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info) {
1868 try {
1869 mCb.onResolveServiceSucceeded(listenerKey, info);
1870 } catch (RemoteException e) {
1871 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
1872 }
1873 }
Paul Hub58deb72022-12-26 09:24:42 +00001874
1875 void onStopResolutionFailed(int listenerKey, int error) {
1876 try {
1877 mCb.onStopResolutionFailed(listenerKey, error);
1878 } catch (RemoteException e) {
1879 Log.e(TAG, "Error calling onStopResolutionFailed", e);
1880 }
1881 }
1882
1883 void onStopResolutionSucceeded(int listenerKey) {
1884 try {
1885 mCb.onStopResolutionSucceeded(listenerKey);
1886 } catch (RemoteException e) {
1887 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
1888 }
1889 }
Paul Hu18aeccc2022-12-27 08:48:48 +00001890
1891 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
1892 try {
1893 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
1894 } catch (RemoteException e) {
1895 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
1896 }
1897 }
1898
1899 void onServiceUpdated(int listenerKey, NsdServiceInfo info) {
1900 try {
1901 mCb.onServiceUpdated(listenerKey, info);
1902 } catch (RemoteException e) {
1903 Log.e(TAG, "Error calling onServiceUpdated", e);
1904 }
1905 }
1906
1907 void onServiceUpdatedLost(int listenerKey) {
1908 try {
1909 mCb.onServiceUpdatedLost(listenerKey);
1910 } catch (RemoteException e) {
1911 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
1912 }
1913 }
1914
1915 void onServiceInfoCallbackUnregistered(int listenerKey) {
1916 try {
1917 mCb.onServiceInfoCallbackUnregistered(listenerKey);
1918 } catch (RemoteException e) {
1919 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
1920 }
1921 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001922 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001923}