blob: 8e06fde045b6312c5b89f518c3d81cbfe48db981 [file] [log] [blame]
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001/*
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002 * Copyright (C) 2021 The Android Open Source Project
Irfan Sheriff77ec5582012-03-22 17:01:39 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
paulhu2b9ed952022-02-10 21:58:32 +080019import static android.net.ConnectivityManager.NETID_UNSET;
Paul Hu019621e2023-01-13 23:26:49 +080020import static android.net.nsd.NsdManager.MDNS_DISCOVERY_MANAGER_EVENT;
paulhu2b9ed952022-02-10 21:58:32 +080021import static android.net.nsd.NsdManager.MDNS_SERVICE_EVENT;
Paul Hu4bd98ef2023-01-12 13:42:07 +080022import static android.provider.DeviceConfig.NAMESPACE_CONNECTIVITY;
paulhu2b9ed952022-02-10 21:58:32 +080023
Paul Hu23fa2022023-01-13 22:57:24 +080024import android.annotation.NonNull;
Paul Hu4bd98ef2023-01-12 13:42:07 +080025import android.annotation.Nullable;
paulhua262cc12019-08-12 16:25:11 +080026import android.content.Context;
Irfan Sheriff75006652012-04-17 23:15:29 -070027import android.content.Intent;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090028import android.net.ConnectivityManager;
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +090029import android.net.INetd;
Paul Hu75069ed2023-01-14 00:31:09 +080030import android.net.InetAddresses;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090031import android.net.LinkProperties;
32import android.net.Network;
paulhu2b9ed952022-02-10 21:58:32 +080033import android.net.mdns.aidl.DiscoveryInfo;
34import android.net.mdns.aidl.GetAddressInfo;
35import android.net.mdns.aidl.IMDnsEventListener;
36import android.net.mdns.aidl.RegistrationInfo;
37import android.net.mdns.aidl.ResolutionInfo;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070038import android.net.nsd.INsdManager;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090039import android.net.nsd.INsdManagerCallback;
40import android.net.nsd.INsdServiceConnector;
paulhu2b9ed952022-02-10 21:58:32 +080041import android.net.nsd.MDnsManager;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070042import android.net.nsd.NsdManager;
paulhua262cc12019-08-12 16:25:11 +080043import android.net.nsd.NsdServiceInfo;
Hugo Benichi803a2f02017-04-24 11:35:06 +090044import android.os.Handler;
paulhua262cc12019-08-12 16:25:11 +080045import android.os.HandlerThread;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090046import android.os.IBinder;
Paul Hu4bd98ef2023-01-12 13:42:07 +080047import android.os.Looper;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070048import android.os.Message;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090049import android.os.RemoteException;
Dianne Hackborn692107e2012-08-29 18:32:08 -070050import android.os.UserHandle;
Paul Hu23fa2022023-01-13 22:57:24 +080051import android.text.TextUtils;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090052import android.util.Log;
53import android.util.Pair;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070054import android.util.SparseArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070055
paulhua262cc12019-08-12 16:25:11 +080056import com.android.internal.annotations.VisibleForTesting;
paulhua262cc12019-08-12 16:25:11 +080057import com.android.internal.util.State;
58import com.android.internal.util.StateMachine;
Paul Hu4bd98ef2023-01-12 13:42:07 +080059import com.android.net.module.util.DeviceConfigUtils;
paulhu3ffffe72021-09-16 10:15:22 +080060import com.android.net.module.util.PermissionUtils;
Paul Hu4bd98ef2023-01-12 13:42:07 +080061import com.android.server.connectivity.mdns.ExecutorProvider;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090062import com.android.server.connectivity.mdns.MdnsAdvertiser;
Paul Hu4bd98ef2023-01-12 13:42:07 +080063import com.android.server.connectivity.mdns.MdnsDiscoveryManager;
64import com.android.server.connectivity.mdns.MdnsMultinetworkSocketClient;
Paul Hu23fa2022023-01-13 22:57:24 +080065import com.android.server.connectivity.mdns.MdnsSearchOptions;
66import com.android.server.connectivity.mdns.MdnsServiceBrowserListener;
67import com.android.server.connectivity.mdns.MdnsServiceInfo;
Paul Hu4bd98ef2023-01-12 13:42:07 +080068import com.android.server.connectivity.mdns.MdnsSocketClientBase;
69import com.android.server.connectivity.mdns.MdnsSocketProvider;
paulhua262cc12019-08-12 16:25:11 +080070
Irfan Sheriff77ec5582012-03-22 17:01:39 -070071import java.io.FileDescriptor;
72import java.io.PrintWriter;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070073import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090074import java.net.NetworkInterface;
75import java.net.SocketException;
76import java.net.UnknownHostException;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090077import java.nio.ByteBuffer;
78import java.nio.CharBuffer;
79import java.nio.charset.Charset;
80import java.nio.charset.CharsetEncoder;
81import java.nio.charset.StandardCharsets;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070082import java.util.HashMap;
Paul Hu23fa2022023-01-13 22:57:24 +080083import java.util.List;
Paul Hu75069ed2023-01-14 00:31:09 +080084import java.util.Map;
Paul Hu18aeccc2022-12-27 08:48:48 +000085import java.util.Objects;
Paul Hu23fa2022023-01-13 22:57:24 +080086import java.util.regex.Matcher;
87import java.util.regex.Pattern;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070088
Irfan Sheriff77ec5582012-03-22 17:01:39 -070089/**
90 * Network Service Discovery Service handles remote service discovery operation requests by
91 * implementing the INsdManager interface.
92 *
93 * @hide
94 */
95public class NsdService extends INsdManager.Stub {
96 private static final String TAG = "NsdService";
97 private static final String MDNS_TAG = "mDnsConnector";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090098 /**
99 * Enable discovery using the Java DiscoveryManager, instead of the legacy mdnsresponder
100 * implementation.
101 */
Paul Hu4bd98ef2023-01-12 13:42:07 +0800102 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Paul Hu23fa2022023-01-13 22:57:24 +0800103 private static final String LOCAL_DOMAIN_NAME = "local";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900104 // Max label length as per RFC 1034/1035
105 private static final int MAX_LABEL_LENGTH = 63;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700106
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900107 /**
108 * Enable advertising using the Java MdnsAdvertiser, instead of the legacy mdnsresponder
109 * implementation.
110 */
111 private static final String MDNS_ADVERTISER_VERSION = "mdns_advertiser_version";
112
113 public static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +0000114 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900115 private static final int IFACE_IDX_ANY = 0;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700116
Hugo Benichi32be63d2017-04-05 14:06:11 +0900117 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900118 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +0800119 private final MDnsManager mMDnsManager;
120 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900121 @NonNull
122 private final Dependencies mDeps;
123 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800124 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900125 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800126 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900127 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800128 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900129 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900130 private final MdnsAdvertiser mAdvertiser;
Paul Hu23fa2022023-01-13 22:57:24 +0800131 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800132 // state machine thread. If change this outside state machine, it will need to introduce
133 // synchronization.
134 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800135 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700136
137 /**
138 * Clients receiving asynchronous messages
139 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900140 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700141
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700142 /* A map from unique id to client info */
Hugo Benichi32be63d2017-04-05 14:06:11 +0900143 private final SparseArray<ClientInfo> mIdToClientInfoMap= new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700144
Luke Huang05298582021-06-13 16:52:05 +0000145 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700146
Hugo Benichi32be63d2017-04-05 14:06:11 +0900147 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700148 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800149 // The count of the connected legacy clients.
150 private int mLegacyClientCount = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700151
Paul Hu23fa2022023-01-13 22:57:24 +0800152 private static class MdnsListener implements MdnsServiceBrowserListener {
153 protected final int mClientId;
154 protected final int mTransactionId;
155 @NonNull
156 protected final NsdServiceInfo mReqServiceInfo;
157 @NonNull
158 protected final String mListenedServiceType;
159
160 MdnsListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
161 @NonNull String listenedServiceType) {
162 mClientId = clientId;
163 mTransactionId = transactionId;
164 mReqServiceInfo = reqServiceInfo;
165 mListenedServiceType = listenedServiceType;
166 }
167
168 @NonNull
169 public String getListenedServiceType() {
170 return mListenedServiceType;
171 }
172
173 @Override
174 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo) { }
175
176 @Override
177 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
178
179 @Override
180 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
181
182 @Override
183 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) { }
184
185 @Override
186 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
187
188 @Override
189 public void onSearchStoppedWithError(int error) { }
190
191 @Override
192 public void onSearchFailedToStart() { }
193
194 @Override
195 public void onDiscoveryQuerySent(@NonNull List<String> subtypes, int transactionId) { }
196
197 @Override
198 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
199 }
200
201 private class DiscoveryListener extends MdnsListener {
202
203 DiscoveryListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
204 @NonNull String listenServiceType) {
205 super(clientId, transactionId, reqServiceInfo, listenServiceType);
206 }
207
208 @Override
209 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu019621e2023-01-13 23:26:49 +0800210 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
211 NsdManager.SERVICE_FOUND,
212 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800213 }
214
215 @Override
216 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800217 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
218 NsdManager.SERVICE_LOST,
219 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800220 }
221 }
222
Paul Hu75069ed2023-01-14 00:31:09 +0800223 private class ResolutionListener extends MdnsListener {
224
225 ResolutionListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
226 @NonNull String listenServiceType) {
227 super(clientId, transactionId, reqServiceInfo, listenServiceType);
228 }
229
230 @Override
231 public void onServiceFound(MdnsServiceInfo serviceInfo) {
232 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
233 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
234 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
235 }
236 }
237
Paul Hu019621e2023-01-13 23:26:49 +0800238 /**
239 * Data class of mdns service callback information.
240 */
241 private static class MdnsEvent {
242 final int mClientId;
243 @NonNull
244 final String mRequestedServiceType;
245 @NonNull
246 final MdnsServiceInfo mMdnsServiceInfo;
247
248 MdnsEvent(int clientId, @NonNull String requestedServiceType,
249 @NonNull MdnsServiceInfo mdnsServiceInfo) {
250 mClientId = clientId;
251 mRequestedServiceType = requestedServiceType;
252 mMdnsServiceInfo = mdnsServiceInfo;
253 }
254 }
255
Irfan Sheriff75006652012-04-17 23:15:29 -0700256 private class NsdStateMachine extends StateMachine {
257
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700258 private final DefaultState mDefaultState = new DefaultState();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700259 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700260
261 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700262 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900263 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700264 }
265
Luke Huang92860f92021-06-23 06:29:30 +0000266 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800267 if (mIsDaemonStarted) {
268 if (DBG) Log.d(TAG, "Daemon is already started.");
269 return;
270 }
271 mMDnsManager.registerEventListener(mMDnsEventCallback);
272 mMDnsManager.startDaemon();
273 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000274 maybeScheduleStop();
275 }
276
paulhu2b9ed952022-02-10 21:58:32 +0800277 private void maybeStopDaemon() {
278 if (!mIsDaemonStarted) {
279 if (DBG) Log.d(TAG, "Daemon has not been started.");
280 return;
281 }
282 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
283 mMDnsManager.stopDaemon();
284 mIsDaemonStarted = false;
285 }
286
Luke Huang92860f92021-06-23 06:29:30 +0000287 private boolean isAnyRequestActive() {
288 return mIdToClientInfoMap.size() != 0;
289 }
290
291 private void scheduleStop() {
292 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
293 }
294 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800295 // The native daemon should stay alive and can't be cleanup
296 // if any legacy client connected.
297 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000298 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000299 }
300 }
301
Luke Huang92860f92021-06-23 06:29:30 +0000302 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000303 this.removeMessages(NsdManager.DAEMON_CLEANUP);
304 }
305
Paul Hu23fa2022023-01-13 22:57:24 +0800306 private void maybeStartMonitoringSockets() {
307 if (mIsMonitoringSocketsStarted) {
308 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
309 return;
310 }
311
312 mMdnsSocketProvider.startMonitoringSockets();
313 mIsMonitoringSocketsStarted = true;
314 }
315
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900316 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
317 if (!mIsMonitoringSocketsStarted) return;
318 if (isAnyRequestActive()) return;
319
Paul Hu58f20602023-02-18 11:41:07 +0800320 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800321 mIsMonitoringSocketsStarted = false;
322 }
323
Hugo Benichi803a2f02017-04-24 11:35:06 +0900324 NsdStateMachine(String name, Handler handler) {
325 super(name, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -0700326 addState(mDefaultState);
Irfan Sheriff75006652012-04-17 23:15:29 -0700327 addState(mEnabledState, mDefaultState);
paulhu5568f452021-11-30 13:31:29 +0800328 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900329 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700330 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700331 }
332
333 class DefaultState extends State {
334 @Override
335 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900336 final ClientInfo cInfo;
337 final int clientId = msg.arg2;
Irfan Sheriff75006652012-04-17 23:15:29 -0700338 switch (msg.what) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900339 case NsdManager.REGISTER_CLIENT:
340 final Pair<NsdServiceConnector, INsdManagerCallback> arg =
341 (Pair<NsdServiceConnector, INsdManagerCallback>) msg.obj;
342 final INsdManagerCallback cb = arg.second;
343 try {
344 cb.asBinder().linkToDeath(arg.first, 0);
345 cInfo = new ClientInfo(cb);
346 mClients.put(arg.first, cInfo);
347 } catch (RemoteException e) {
348 Log.w(TAG, "Client " + clientId + " has already died");
Irfan Sheriff75006652012-04-17 23:15:29 -0700349 }
350 break;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900351 case NsdManager.UNREGISTER_CLIENT:
352 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
353 cInfo = mClients.remove(connector);
Dave Plattfeff2af2014-03-07 14:48:22 -0800354 if (cInfo != null) {
355 cInfo.expungeAllRequests();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900356 if (cInfo.isPreSClient()) {
Luke Huangf7277ed2021-07-12 21:15:10 +0800357 mLegacyClientCount -= 1;
358 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800359 }
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900360 maybeStopMonitoringSocketsIfNoActiveRequest();
Luke Huangf7277ed2021-07-12 21:15:10 +0800361 maybeScheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700362 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700363 case NsdManager.DISCOVER_SERVICES:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900364 cInfo = getClientInfoForReply(msg);
365 if (cInfo != null) {
366 cInfo.onDiscoverServicesFailed(
367 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
368 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700369 break;
370 case NsdManager.STOP_DISCOVERY:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900371 cInfo = getClientInfoForReply(msg);
372 if (cInfo != null) {
373 cInfo.onStopDiscoveryFailed(
374 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
375 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700376 break;
377 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900378 cInfo = getClientInfoForReply(msg);
379 if (cInfo != null) {
380 cInfo.onRegisterServiceFailed(
381 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
382 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700383 break;
384 case NsdManager.UNREGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900385 cInfo = getClientInfoForReply(msg);
386 if (cInfo != null) {
387 cInfo.onUnregisterServiceFailed(
388 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
389 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700390 break;
391 case NsdManager.RESOLVE_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900392 cInfo = getClientInfoForReply(msg);
393 if (cInfo != null) {
394 cInfo.onResolveServiceFailed(
395 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
396 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700397 break;
Paul Hub58deb72022-12-26 09:24:42 +0000398 case NsdManager.STOP_RESOLUTION:
399 cInfo = getClientInfoForReply(msg);
400 if (cInfo != null) {
401 cInfo.onStopResolutionFailed(
402 clientId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
403 }
404 break;
Paul Hu18aeccc2022-12-27 08:48:48 +0000405 case NsdManager.REGISTER_SERVICE_CALLBACK:
406 cInfo = getClientInfoForReply(msg);
407 if (cInfo != null) {
408 cInfo.onServiceInfoCallbackRegistrationFailed(
409 clientId, NsdManager.FAILURE_BAD_PARAMETERS);
410 }
411 break;
Luke Huang05298582021-06-13 16:52:05 +0000412 case NsdManager.DAEMON_CLEANUP:
paulhu2b9ed952022-02-10 21:58:32 +0800413 maybeStopDaemon();
Luke Huang05298582021-06-13 16:52:05 +0000414 break;
Luke Huangf7277ed2021-07-12 21:15:10 +0800415 // This event should be only sent by the legacy (target SDK < S) clients.
416 // Mark the sending client as legacy.
417 case NsdManager.DAEMON_STARTUP:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900418 cInfo = getClientInfoForReply(msg);
Luke Huangf7277ed2021-07-12 21:15:10 +0800419 if (cInfo != null) {
420 cancelStop();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900421 cInfo.setPreSClient();
Luke Huangf7277ed2021-07-12 21:15:10 +0800422 mLegacyClientCount += 1;
423 maybeStartDaemon();
424 }
425 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700426 default:
paulhub2225702021-11-17 09:35:33 +0800427 Log.e(TAG, "Unhandled " + msg);
Irfan Sheriff75006652012-04-17 23:15:29 -0700428 return NOT_HANDLED;
429 }
430 return HANDLED;
431 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900432
433 private ClientInfo getClientInfoForReply(Message msg) {
434 final ListenerArgs args = (ListenerArgs) msg.obj;
435 return mClients.get(args.connector);
436 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700437 }
438
Irfan Sheriff75006652012-04-17 23:15:29 -0700439 class EnabledState extends State {
440 @Override
441 public void enter() {
442 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700443 }
444
445 @Override
446 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000447 // TODO: it is incorrect to stop the daemon without expunging all requests
448 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000449 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700450 }
451
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700452 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900453 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800454 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700455 return true;
456 }
457 return false;
458 }
459
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900460 private void storeLegacyRequestMap(int clientId, int globalId, ClientInfo clientInfo,
461 int what) {
462 clientInfo.mClientRequests.put(clientId, new LegacyClientRequest(globalId, what));
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700463 mIdToClientInfoMap.put(globalId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000464 // Remove the cleanup event because here comes a new request.
465 cancelStop();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700466 }
467
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900468 private void storeAdvertiserRequestMap(int clientId, int globalId,
Paul Hu23fa2022023-01-13 22:57:24 +0800469 ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900470 clientInfo.mClientRequests.put(clientId, new AdvertiserClientRequest(globalId));
471 mIdToClientInfoMap.put(globalId, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800472 }
473
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900474 private void removeRequestMap(int clientId, int globalId, ClientInfo clientInfo) {
475 final ClientRequest existing = clientInfo.mClientRequests.get(clientId);
476 if (existing == null) return;
477 clientInfo.mClientRequests.remove(clientId);
478 mIdToClientInfoMap.remove(globalId);
479
480 if (existing instanceof LegacyClientRequest) {
481 maybeScheduleStop();
482 } else {
483 maybeStopMonitoringSocketsIfNoActiveRequest();
484 }
485 }
486
487 private void storeDiscoveryManagerRequestMap(int clientId, int globalId,
488 MdnsListener listener, ClientInfo clientInfo) {
489 clientInfo.mClientRequests.put(clientId,
490 new DiscoveryManagerRequest(globalId, listener));
491 mIdToClientInfoMap.put(globalId, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800492 }
493
Paul Hu18aeccc2022-12-27 08:48:48 +0000494 private void clearRegisteredServiceInfo(ClientInfo clientInfo) {
495 clientInfo.mRegisteredService = null;
496 clientInfo.mClientIdForServiceUpdates = 0;
497 }
498
Paul Hu23fa2022023-01-13 22:57:24 +0800499 /**
500 * Check the given service type is valid and construct it to a service type
501 * which can use for discovery / resolution service.
502 *
503 * <p> The valid service type should be 2 labels, or 3 labels if the query is for a
504 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
505 * underscore; they are alphanumerical characters or dashes or underscore, except the
506 * last one that is just alphanumerical. The last label must be _tcp or _udp.
507 *
508 * @param serviceType the request service type for discovery / resolution service
509 * @return constructed service type or null if the given service type is invalid.
510 */
511 @Nullable
512 private String constructServiceType(String serviceType) {
513 if (TextUtils.isEmpty(serviceType)) return null;
514
515 final Pattern serviceTypePattern = Pattern.compile(
516 "^(_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]\\.)?"
517 + "(_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]\\._(?:tcp|udp))$");
518 final Matcher matcher = serviceTypePattern.matcher(serviceType);
519 if (!matcher.matches()) return null;
520 return matcher.group(1) == null
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900521 ? serviceType
522 : matcher.group(1) + "_sub." + matcher.group(2);
523 }
524
525 /**
526 * Truncate a service name to up to 63 UTF-8 bytes.
527 *
528 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
529 * names used in registerService follows historical behavior (see mdnsresponder
530 * handle_regservice_request).
531 */
532 @NonNull
533 private String truncateServiceName(@NonNull String originalName) {
534 // UTF-8 is at most 4 bytes per character; return early in the common case where
535 // the name can't possibly be over the limit given its string length.
536 if (originalName.length() <= MAX_LABEL_LENGTH / 4) return originalName;
537
538 final Charset utf8 = StandardCharsets.UTF_8;
539 final CharsetEncoder encoder = utf8.newEncoder();
540 final ByteBuffer out = ByteBuffer.allocate(MAX_LABEL_LENGTH);
541 // encode will write as many characters as possible to the out buffer, and just
542 // return an overflow code if there were too many characters (no need to check the
543 // return code here, this method truncates the name on purpose).
544 encoder.encode(CharBuffer.wrap(originalName), out, true /* endOfInput */);
545 return new String(out.array(), 0, out.position(), utf8);
Paul Hu23fa2022023-01-13 22:57:24 +0800546 }
547
Irfan Sheriff75006652012-04-17 23:15:29 -0700548 @Override
549 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900550 final ClientInfo clientInfo;
551 final int id;
552 final int clientId = msg.arg2;
553 final ListenerArgs args;
Irfan Sheriff75006652012-04-17 23:15:29 -0700554 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800555 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800556 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900557 args = (ListenerArgs) msg.obj;
558 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000559 // If the binder death notification for a INsdManagerCallback was received
560 // before any calls are received by NsdService, the clientInfo would be
561 // cleared and cause NPE. Add a null check here to prevent this corner case.
562 if (clientInfo == null) {
563 Log.e(TAG, "Unknown connector in discovery");
564 break;
565 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700566
567 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900568 clientInfo.onDiscoverServicesFailed(
569 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriff75006652012-04-17 23:15:29 -0700570 break;
571 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700572
Paul Hu23fa2022023-01-13 22:57:24 +0800573 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700574 id = getUniqueId();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900575 if (mDeps.isMdnsDiscoveryManagerEnabled(mContext)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800576 final String serviceType = constructServiceType(info.getServiceType());
577 if (serviceType == null) {
578 clientInfo.onDiscoverServicesFailed(clientId,
579 NsdManager.FAILURE_INTERNAL_ERROR);
580 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700581 }
Paul Hu23fa2022023-01-13 22:57:24 +0800582
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900583 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800584 maybeStartMonitoringSockets();
585 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900586 new DiscoveryListener(clientId, id, info, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800587 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
588 .setNetwork(info.getNetwork())
589 .setIsPassiveMode(true)
590 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900591 mMdnsDiscoveryManager.registerListener(
592 listenServiceType, listener, options);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900593 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800594 clientInfo.onDiscoverServicesStarted(clientId, info);
Irfan Sheriff75006652012-04-17 23:15:29 -0700595 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800596 maybeStartDaemon();
597 if (discoverServices(id, info)) {
598 if (DBG) {
599 Log.d(TAG, "Discover " + msg.arg2 + " " + id
600 + info.getServiceType());
601 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900602 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu23fa2022023-01-13 22:57:24 +0800603 clientInfo.onDiscoverServicesStarted(clientId, info);
604 } else {
605 stopServiceDiscovery(id);
606 clientInfo.onDiscoverServicesFailed(clientId,
607 NsdManager.FAILURE_INTERNAL_ERROR);
608 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700609 }
610 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800611 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900612 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800613 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900614 args = (ListenerArgs) msg.obj;
615 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000616 // If the binder death notification for a INsdManagerCallback was received
617 // before any calls are received by NsdService, the clientInfo would be
618 // cleared and cause NPE. Add a null check here to prevent this corner case.
619 if (clientInfo == null) {
620 Log.e(TAG, "Unknown connector in stop discovery");
621 break;
622 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700623
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900624 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
625 if (request == null) {
626 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700627 break;
628 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900629 id = request.mGlobalId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900630 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
631 // point, so this needs to check the type of the original request to
632 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900633 if (request instanceof DiscoveryManagerRequest) {
Ahmad Khalil4b8d45a2023-03-02 11:43:25 +0000634 final MdnsListener listener =
635 ((DiscoveryManagerRequest) request).mListener;
636 mMdnsDiscoveryManager.unregisterListener(
637 listener.getListenedServiceType(), listener);
638 removeRequestMap(clientId, id, clientInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900639 clientInfo.onStopDiscoverySucceeded(clientId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700640 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800641 removeRequestMap(clientId, id, clientInfo);
642 if (stopServiceDiscovery(id)) {
643 clientInfo.onStopDiscoverySucceeded(clientId);
644 } else {
645 clientInfo.onStopDiscoveryFailed(
646 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
647 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700648 }
649 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900650 }
651 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800652 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900653 args = (ListenerArgs) msg.obj;
654 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000655 // If the binder death notification for a INsdManagerCallback was received
656 // before any calls are received by NsdService, the clientInfo would be
657 // cleared and cause NPE. Add a null check here to prevent this corner case.
658 if (clientInfo == null) {
659 Log.e(TAG, "Unknown connector in registration");
660 break;
661 }
662
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700663 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900664 clientInfo.onRegisterServiceFailed(
665 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700666 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700667 }
668
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700669 id = getUniqueId();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900670 if (mDeps.isMdnsAdvertiserEnabled(mContext)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900671 final NsdServiceInfo serviceInfo = args.serviceInfo;
672 final String serviceType = serviceInfo.getServiceType();
673 final String registerServiceType = constructServiceType(serviceType);
674 if (registerServiceType == null) {
675 Log.e(TAG, "Invalid service type: " + serviceType);
676 clientInfo.onRegisterServiceFailed(clientId,
677 NsdManager.FAILURE_INTERNAL_ERROR);
678 break;
679 }
680 serviceInfo.setServiceType(registerServiceType);
681 serviceInfo.setServiceName(truncateServiceName(
682 serviceInfo.getServiceName()));
683
684 maybeStartMonitoringSockets();
685 mAdvertiser.addService(id, serviceInfo);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900686 storeAdvertiserRequestMap(clientId, id, clientInfo);
Irfan Sheriff75006652012-04-17 23:15:29 -0700687 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900688 maybeStartDaemon();
689 if (registerService(id, args.serviceInfo)) {
690 if (DBG) Log.d(TAG, "Register " + clientId + " " + id);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900691 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900692 // Return success after mDns reports success
693 } else {
694 unregisterService(id);
695 clientInfo.onRegisterServiceFailed(
696 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
697 }
698
Irfan Sheriff75006652012-04-17 23:15:29 -0700699 }
700 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900701 }
702 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800703 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900704 args = (ListenerArgs) msg.obj;
705 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000706 // If the binder death notification for a INsdManagerCallback was received
707 // before any calls are received by NsdService, the clientInfo would be
708 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900709 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800710 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700711 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700712 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900713 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
714 if (request == null) {
715 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
716 break;
717 }
718 id = request.mGlobalId;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900719 removeRequestMap(clientId, id, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900720
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900721 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
722 // so this needs to check the type of the original request to unregister
723 // instead of looking at the flag value.
724 if (request instanceof AdvertiserClientRequest) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900725 mAdvertiser.removeService(id);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900726 clientInfo.onUnregisterServiceSucceeded(clientId);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700727 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900728 if (unregisterService(id)) {
729 clientInfo.onUnregisterServiceSucceeded(clientId);
730 } else {
731 clientInfo.onUnregisterServiceFailed(
732 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
733 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700734 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700735 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900736 }
Paul Hu75069ed2023-01-14 00:31:09 +0800737 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800738 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900739 args = (ListenerArgs) msg.obj;
740 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000741 // If the binder death notification for a INsdManagerCallback was received
742 // before any calls are received by NsdService, the clientInfo would be
743 // cleared and cause NPE. Add a null check here to prevent this corner case.
744 if (clientInfo == null) {
745 Log.e(TAG, "Unknown connector in resolution");
746 break;
747 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700748
Paul Hu75069ed2023-01-14 00:31:09 +0800749 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700750 id = getUniqueId();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900751 if (mDeps.isMdnsDiscoveryManagerEnabled(mContext)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800752 final String serviceType = constructServiceType(info.getServiceType());
753 if (serviceType == null) {
754 clientInfo.onResolveServiceFailed(clientId,
755 NsdManager.FAILURE_INTERNAL_ERROR);
756 break;
757 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900758 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +0800759
760 maybeStartMonitoringSockets();
761 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900762 new ResolutionListener(clientId, id, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800763 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
764 .setNetwork(info.getNetwork())
765 .setIsPassiveMode(true)
766 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900767 mMdnsDiscoveryManager.registerListener(
768 resolveServiceType, listener, options);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900769 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Irfan Sheriff75006652012-04-17 23:15:29 -0700770 } else {
Paul Hu75069ed2023-01-14 00:31:09 +0800771 if (clientInfo.mResolvedService != null) {
772 clientInfo.onResolveServiceFailed(
773 clientId, NsdManager.FAILURE_ALREADY_ACTIVE);
774 break;
775 }
776
777 maybeStartDaemon();
778 if (resolveService(id, args.serviceInfo)) {
779 clientInfo.mResolvedService = new NsdServiceInfo();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900780 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu75069ed2023-01-14 00:31:09 +0800781 } else {
782 clientInfo.onResolveServiceFailed(
783 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
784 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700785 }
786 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800787 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900788 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +0000789 if (DBG) Log.d(TAG, "Stop service resolution");
790 args = (ListenerArgs) msg.obj;
791 clientInfo = mClients.get(args.connector);
792 // If the binder death notification for a INsdManagerCallback was received
793 // before any calls are received by NsdService, the clientInfo would be
794 // cleared and cause NPE. Add a null check here to prevent this corner case.
795 if (clientInfo == null) {
796 Log.e(TAG, "Unknown connector in stop resolution");
797 break;
798 }
799
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900800 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
801 if (request == null) {
802 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
803 break;
804 }
805 id = request.mGlobalId;
Ahmad Khalil4b8d45a2023-03-02 11:43:25 +0000806 removeRequestMap(clientId, id, clientInfo);
807 if (stopResolveService(id)) {
Paul Hub58deb72022-12-26 09:24:42 +0000808 clientInfo.onStopResolutionSucceeded(clientId);
809 } else {
Ahmad Khalil4b8d45a2023-03-02 11:43:25 +0000810 clientInfo.onStopResolutionFailed(
811 clientId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hub58deb72022-12-26 09:24:42 +0000812 }
Ahmad Khalil4b8d45a2023-03-02 11:43:25 +0000813 clientInfo.mResolvedService = null;
814 // TODO: Implement the stop resolution with MdnsDiscoveryManager.
Paul Hub58deb72022-12-26 09:24:42 +0000815 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900816 }
Paul Hu18aeccc2022-12-27 08:48:48 +0000817 case NsdManager.REGISTER_SERVICE_CALLBACK:
818 if (DBG) Log.d(TAG, "Register a service callback");
819 args = (ListenerArgs) msg.obj;
820 clientInfo = mClients.get(args.connector);
821 // If the binder death notification for a INsdManagerCallback was received
822 // before any calls are received by NsdService, the clientInfo would be
823 // cleared and cause NPE. Add a null check here to prevent this corner case.
824 if (clientInfo == null) {
825 Log.e(TAG, "Unknown connector in callback registration");
826 break;
827 }
828
829 if (clientInfo.mRegisteredService != null) {
830 clientInfo.onServiceInfoCallbackRegistrationFailed(
831 clientId, NsdManager.FAILURE_ALREADY_ACTIVE);
832 break;
833 }
834
835 maybeStartDaemon();
836 id = getUniqueId();
837 if (resolveService(id, args.serviceInfo)) {
838 clientInfo.mRegisteredService = new NsdServiceInfo();
839 clientInfo.mClientIdForServiceUpdates = clientId;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900840 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu18aeccc2022-12-27 08:48:48 +0000841 } else {
842 clientInfo.onServiceInfoCallbackRegistrationFailed(
843 clientId, NsdManager.FAILURE_BAD_PARAMETERS);
844 }
845 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900846 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +0000847 if (DBG) Log.d(TAG, "Unregister a service callback");
848 args = (ListenerArgs) msg.obj;
849 clientInfo = mClients.get(args.connector);
850 // If the binder death notification for a INsdManagerCallback was received
851 // before any calls are received by NsdService, the clientInfo would be
852 // cleared and cause NPE. Add a null check here to prevent this corner case.
853 if (clientInfo == null) {
854 Log.e(TAG, "Unknown connector in callback unregistration");
855 break;
856 }
857
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900858 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
859 if (request == null) {
860 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
861 break;
862 }
863 id = request.mGlobalId;
Paul Hu18aeccc2022-12-27 08:48:48 +0000864 removeRequestMap(clientId, id, clientInfo);
865 if (stopResolveService(id)) {
866 clientInfo.onServiceInfoCallbackUnregistered(clientId);
867 } else {
868 Log.e(TAG, "Failed to unregister service info callback");
869 }
870 clearRegisteredServiceInfo(clientInfo);
871 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900872 }
paulhu2b9ed952022-02-10 21:58:32 +0800873 case MDNS_SERVICE_EVENT:
874 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +0900875 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700876 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700877 break;
Paul Hu019621e2023-01-13 23:26:49 +0800878 case MDNS_DISCOVERY_MANAGER_EVENT:
879 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
880 return NOT_HANDLED;
881 }
882 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700883 default:
Hugo Benichif0c84092017-04-05 14:43:29 +0900884 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700885 }
Hugo Benichif0c84092017-04-05 14:43:29 +0900886 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700887 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700888
Paul Hu18aeccc2022-12-27 08:48:48 +0000889 private void notifyResolveFailedResult(boolean isListenedToUpdates, int clientId,
890 ClientInfo clientInfo, int error) {
891 if (isListenedToUpdates) {
892 clientInfo.onServiceInfoCallbackRegistrationFailed(clientId, error);
893 clearRegisteredServiceInfo(clientInfo);
894 } else {
895 // The resolve API always returned FAILURE_INTERNAL_ERROR on error; keep it
896 // for backwards compatibility.
897 clientInfo.onResolveServiceFailed(clientId, NsdManager.FAILURE_INTERNAL_ERROR);
898 clientInfo.mResolvedService = null;
899 }
900 }
901
paulhu2b9ed952022-02-10 21:58:32 +0800902 private boolean handleMDnsServiceEvent(int code, int id, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700903 NsdServiceInfo servInfo;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700904 ClientInfo clientInfo = mIdToClientInfoMap.get(id);
905 if (clientInfo == null) {
paulhu2b9ed952022-02-10 21:58:32 +0800906 Log.e(TAG, String.format("id %d for %d has no client mapping", id, code));
Hugo Benichif0c84092017-04-05 14:43:29 +0900907 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700908 }
909
910 /* This goes in response as msg.arg2 */
Christopher Lane74411222014-04-25 18:39:07 -0700911 int clientId = clientInfo.getClientId(id);
912 if (clientId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -0700913 // This can happen because of race conditions. For example,
914 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
915 // and we may get in this situation.
paulhu2b9ed952022-02-10 21:58:32 +0800916 Log.d(TAG, String.format("%d for listener id %d that is no longer active",
917 code, id));
Hugo Benichif0c84092017-04-05 14:43:29 +0900918 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700919 }
Hugo Benichi32be63d2017-04-05 14:06:11 +0900920 if (DBG) {
paulhu2b9ed952022-02-10 21:58:32 +0800921 Log.d(TAG, String.format("MDns service event code:%d id=%d", code, id));
Hugo Benichi32be63d2017-04-05 14:06:11 +0900922 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700923 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +0800924 case IMDnsEventListener.SERVICE_FOUND: {
925 final DiscoveryInfo info = (DiscoveryInfo) obj;
926 final String name = info.serviceName;
927 final String type = info.registrationType;
928 servInfo = new NsdServiceInfo(name, type);
929 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900930 if (foundNetId == 0L) {
931 // Ignore services that do not have a Network: they are not usable
932 // by apps, as they would need privileged permissions to use
933 // interfaces that do not have an associated Network.
934 break;
935 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +0900936 if (foundNetId == INetd.DUMMY_NET_ID) {
937 // Ignore services on the dummy0 interface: they are only seen when
938 // discovering locally advertised services, and are not reachable
939 // through that interface.
940 break;
941 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900942 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900943 clientInfo.onServiceFound(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700944 break;
paulhu2b9ed952022-02-10 21:58:32 +0800945 }
946 case IMDnsEventListener.SERVICE_LOST: {
947 final DiscoveryInfo info = (DiscoveryInfo) obj;
948 final String name = info.serviceName;
949 final String type = info.registrationType;
950 final int lostNetId = info.netId;
951 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900952 // The network could be set to null (netId 0) if it was torn down when the
953 // service is lost
954 // TODO: avoid returning null in that case, possibly by remembering
955 // found services on the same interface index and their network at the time
956 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900957 clientInfo.onServiceLost(clientId, servInfo);
Paul Hu18aeccc2022-12-27 08:48:48 +0000958 // TODO: also support registered service lost when not discovering
959 clientInfo.maybeNotifyRegisteredServiceLost(servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700960 break;
paulhu2b9ed952022-02-10 21:58:32 +0800961 }
962 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900963 clientInfo.onDiscoverServicesFailed(
964 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700965 break;
paulhu2b9ed952022-02-10 21:58:32 +0800966 case IMDnsEventListener.SERVICE_REGISTERED: {
967 final RegistrationInfo info = (RegistrationInfo) obj;
968 final String name = info.serviceName;
969 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900970 clientInfo.onRegisterServiceSucceeded(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700971 break;
paulhu2b9ed952022-02-10 21:58:32 +0800972 }
973 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900974 clientInfo.onRegisterServiceFailed(
975 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700976 break;
paulhu2b9ed952022-02-10 21:58:32 +0800977 case IMDnsEventListener.SERVICE_RESOLVED: {
978 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -0700979 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +0800980 final String fullName = info.serviceFullName;
981 while (index < fullName.length() && fullName.charAt(index) != '.') {
982 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -0700983 ++index;
984 }
985 ++index;
986 }
paulhu2b9ed952022-02-10 21:58:32 +0800987 if (index >= fullName.length()) {
988 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700989 break;
990 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900991
paulhube186602022-04-12 07:18:23 +0000992 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +0800993 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700994 String type = rest.replace(".local.", "");
995
Paul Hu18aeccc2022-12-27 08:48:48 +0000996 final boolean isListenedToUpdates =
997 clientId == clientInfo.mClientIdForServiceUpdates;
998 final NsdServiceInfo serviceInfo = isListenedToUpdates
999 ? clientInfo.mRegisteredService : clientInfo.mResolvedService;
1000
1001 serviceInfo.setServiceName(name);
1002 serviceInfo.setServiceType(type);
1003 serviceInfo.setPort(info.port);
1004 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001005 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001006
1007 stopResolveService(id);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001008 removeRequestMap(clientId, id, clientInfo);
1009
paulhu2b9ed952022-02-10 21:58:32 +08001010 final int id2 = getUniqueId();
1011 if (getAddrInfo(id2, info.hostname, info.interfaceIdx)) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001012 storeLegacyRequestMap(clientId, id2, clientInfo,
1013 NsdManager.RESOLVE_SERVICE);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001014 } else {
Paul Hu18aeccc2022-12-27 08:48:48 +00001015 notifyResolveFailedResult(isListenedToUpdates, clientId, clientInfo,
1016 NsdManager.FAILURE_BAD_PARAMETERS);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001017 }
1018 break;
paulhu2b9ed952022-02-10 21:58:32 +08001019 }
1020 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001021 /* NNN resolveId errorCode */
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001022 stopResolveService(id);
1023 removeRequestMap(clientId, id, clientInfo);
Paul Hu18aeccc2022-12-27 08:48:48 +00001024 notifyResolveFailedResult(
1025 clientId == clientInfo.mClientIdForServiceUpdates,
1026 clientId, clientInfo, NsdManager.FAILURE_BAD_PARAMETERS);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001027 break;
paulhu2b9ed952022-02-10 21:58:32 +08001028 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001029 /* NNN resolveId errorCode */
1030 stopGetAddrInfo(id);
1031 removeRequestMap(clientId, id, clientInfo);
Paul Hu18aeccc2022-12-27 08:48:48 +00001032 notifyResolveFailedResult(
1033 clientId == clientInfo.mClientIdForServiceUpdates,
1034 clientId, clientInfo, NsdManager.FAILURE_BAD_PARAMETERS);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001035 break;
paulhu2b9ed952022-02-10 21:58:32 +08001036 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001037 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001038 final GetAddressInfo info = (GetAddressInfo) obj;
1039 final String address = info.address;
1040 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001041 InetAddress serviceHost = null;
1042 try {
paulhu2b9ed952022-02-10 21:58:32 +08001043 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001044 } catch (UnknownHostException e) {
1045 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1046 }
1047
1048 // If the resolved service is on an interface without a network, consider it
1049 // as a failure: it would not be usable by apps as they would need
1050 // privileged permissions.
Paul Hu18aeccc2022-12-27 08:48:48 +00001051 if (clientId == clientInfo.mClientIdForServiceUpdates) {
1052 if (netId != NETID_UNSET && serviceHost != null) {
1053 setServiceNetworkForCallback(clientInfo.mRegisteredService,
1054 netId, info.interfaceIdx);
1055 final List<InetAddress> addresses =
1056 clientInfo.mRegisteredService.getHostAddresses();
1057 addresses.add(serviceHost);
1058 clientInfo.mRegisteredService.setHostAddresses(addresses);
1059 clientInfo.onServiceUpdated(
1060 clientId, clientInfo.mRegisteredService);
1061 } else {
1062 stopGetAddrInfo(id);
1063 removeRequestMap(clientId, id, clientInfo);
1064 clearRegisteredServiceInfo(clientInfo);
1065 clientInfo.onServiceInfoCallbackRegistrationFailed(
1066 clientId, NsdManager.FAILURE_BAD_PARAMETERS);
1067 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001068 } else {
Paul Hu18aeccc2022-12-27 08:48:48 +00001069 if (netId != NETID_UNSET && serviceHost != null) {
1070 clientInfo.mResolvedService.setHost(serviceHost);
1071 setServiceNetworkForCallback(clientInfo.mResolvedService,
1072 netId, info.interfaceIdx);
1073 clientInfo.onResolveServiceSucceeded(
1074 clientId, clientInfo.mResolvedService);
1075 } else {
1076 clientInfo.onResolveServiceFailed(
1077 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1078 }
1079 stopGetAddrInfo(id);
1080 removeRequestMap(clientId, id, clientInfo);
1081 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001082 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001083 break;
paulhu2b9ed952022-02-10 21:58:32 +08001084 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001085 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001086 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001087 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001088 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001089 }
Paul Hu019621e2023-01-13 23:26:49 +08001090
1091 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(final MdnsEvent event) {
1092 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1093 final String serviceType = event.mRequestedServiceType;
1094 final String serviceName = serviceInfo.getServiceInstanceName();
1095 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1096 final Network network = serviceInfo.getNetwork();
1097 setServiceNetworkForCallback(
1098 servInfo,
1099 network == null ? NETID_UNSET : network.netId,
1100 serviceInfo.getInterfaceIndex());
1101 return servInfo;
1102 }
1103
1104 private boolean handleMdnsDiscoveryManagerEvent(
1105 int transactionId, int code, Object obj) {
1106 final ClientInfo clientInfo = mIdToClientInfoMap.get(transactionId);
1107 if (clientInfo == null) {
1108 Log.e(TAG, String.format(
1109 "id %d for %d has no client mapping", transactionId, code));
1110 return false;
1111 }
1112
1113 final MdnsEvent event = (MdnsEvent) obj;
1114 final int clientId = event.mClientId;
Paul Hu319751a2023-01-13 23:56:34 +08001115 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event);
Paul Hu019621e2023-01-13 23:26:49 +08001116 if (DBG) {
1117 Log.d(TAG, String.format("MdnsDiscoveryManager event code=%s transactionId=%d",
1118 NsdManager.nameOf(code), transactionId));
1119 }
1120 switch (code) {
1121 case NsdManager.SERVICE_FOUND:
Paul Hu319751a2023-01-13 23:56:34 +08001122 clientInfo.onServiceFound(clientId, info);
1123 break;
1124 case NsdManager.SERVICE_LOST:
1125 clientInfo.onServiceLost(clientId, info);
Paul Hu019621e2023-01-13 23:26:49 +08001126 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001127 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001128 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
1129 if (request == null) {
1130 Log.e(TAG, "Unknown client request in RESOLVE_SERVICE_SUCCEEDED");
1131 break;
1132 }
Paul Hu75069ed2023-01-14 00:31:09 +08001133 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1134 // Add '.' in front of the service type that aligns with historical behavior
1135 info.setServiceType("." + event.mRequestedServiceType);
1136 info.setPort(serviceInfo.getPort());
1137
1138 Map<String, String> attrs = serviceInfo.getAttributes();
1139 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1140 final String key = kv.getKey();
1141 try {
1142 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1143 } catch (IllegalArgumentException e) {
1144 Log.e(TAG, "Invalid attribute", e);
1145 }
1146 }
1147 try {
1148 if (serviceInfo.getIpv4Address() != null) {
1149 info.setHost(InetAddresses.parseNumericAddress(
1150 serviceInfo.getIpv4Address()));
1151 } else {
1152 info.setHost(InetAddresses.parseNumericAddress(
1153 serviceInfo.getIpv6Address()));
1154 }
1155 clientInfo.onResolveServiceSucceeded(clientId, info);
1156 } catch (IllegalArgumentException e) {
1157 Log.wtf(TAG, "Invalid address in RESOLVE_SERVICE_SUCCEEDED", e);
1158 clientInfo.onResolveServiceFailed(
1159 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1160 }
1161
1162 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001163 if (!(request instanceof DiscoveryManagerRequest)) {
1164 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1165 break;
1166 }
Ahmad Khalil4b8d45a2023-03-02 11:43:25 +00001167 final MdnsListener listener = ((DiscoveryManagerRequest) request).mListener;
1168 mMdnsDiscoveryManager.unregisterListener(
1169 listener.getListenedServiceType(), listener);
1170 removeRequestMap(clientId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001171 break;
1172 }
Paul Hu019621e2023-01-13 23:26:49 +08001173 default:
1174 return false;
1175 }
1176 return true;
1177 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001178 }
1179 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001180
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001181 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1182 switch (netId) {
1183 case NETID_UNSET:
1184 info.setNetwork(null);
1185 break;
1186 case INetd.LOCAL_NET_ID:
1187 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1188 // visible / usable for apps, so do not return it. Store the interface
1189 // index instead, so at least if the client tries to resolve the service
1190 // with that NsdServiceInfo, it will be done on the same interface.
1191 // If they recreate the NsdServiceInfo themselves, resolution would be
1192 // done on all interfaces as before T, which should also work.
1193 info.setNetwork(null);
1194 info.setInterfaceIndex(ifaceIdx);
1195 break;
1196 default:
1197 info.setNetwork(new Network(netId));
1198 }
1199 }
1200
paulhube186602022-04-12 07:18:23 +00001201 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1202 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1203 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1204 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1205 private String unescape(String s) {
1206 StringBuilder sb = new StringBuilder(s.length());
1207 for (int i = 0; i < s.length(); ++i) {
1208 char c = s.charAt(i);
1209 if (c == '\\') {
1210 if (++i >= s.length()) {
1211 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1212 break;
1213 }
1214 c = s.charAt(i);
1215 if (c != '.' && c != '\\') {
1216 if (i + 2 >= s.length()) {
1217 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1218 break;
1219 }
1220 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1221 + (s.charAt(i + 2) - '0'));
1222 i += 2;
1223 }
1224 }
1225 sb.append(c);
1226 }
1227 return sb.toString();
1228 }
1229
Hugo Benichi803a2f02017-04-24 11:35:06 +09001230 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001231 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001232 this(ctx, handler, cleanupDelayMs, new Dependencies());
1233 }
1234
1235 @VisibleForTesting
1236 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001237 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001238 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001239 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001240 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001241 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1242 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001243 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001244
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001245 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper());
1246 mMdnsSocketClient =
1247 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider);
1248 mMdnsDiscoveryManager =
1249 deps.makeMdnsDiscoveryManager(new ExecutorProvider(), mMdnsSocketClient);
1250 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1251 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
1252 new AdvertiserCallback());
Paul Hu4bd98ef2023-01-12 13:42:07 +08001253 }
1254
1255 /**
1256 * Dependencies of NsdService, for injection in tests.
1257 */
1258 @VisibleForTesting
1259 public static class Dependencies {
1260 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001261 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001262 *
1263 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001264 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001265 */
1266 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
1267 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY,
1268 MDNS_DISCOVERY_MANAGER_VERSION, false /* defaultEnabled */);
1269 }
1270
1271 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001272 * Check whether the MdnsAdvertiser feature is enabled.
1273 *
1274 * @param context The global context information about an app environment.
1275 * @return true if the MdnsAdvertiser feature is enabled.
1276 */
1277 public boolean isMdnsAdvertiserEnabled(Context context) {
1278 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY,
1279 MDNS_ADVERTISER_VERSION, false /* defaultEnabled */);
1280 }
1281
1282 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001283 * @see MdnsDiscoveryManager
1284 */
1285 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
1286 ExecutorProvider executorProvider, MdnsSocketClientBase socketClient) {
1287 return new MdnsDiscoveryManager(executorProvider, socketClient);
1288 }
1289
1290 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001291 * @see MdnsAdvertiser
1292 */
1293 public MdnsAdvertiser makeMdnsAdvertiser(
1294 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
1295 @NonNull MdnsAdvertiser.AdvertiserCallback cb) {
1296 return new MdnsAdvertiser(looper, socketProvider, cb);
1297 }
1298
1299 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001300 * @see MdnsSocketProvider
1301 */
1302 public MdnsSocketProvider makeMdnsSocketProvider(Context context, Looper looper) {
1303 return new MdnsSocketProvider(context, looper);
1304 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001305 }
1306
paulhu1b35e822022-04-08 14:48:41 +08001307 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001308 HandlerThread thread = new HandlerThread(TAG);
1309 thread.start();
1310 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001311 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001312 return service;
1313 }
1314
paulhu2b9ed952022-02-10 21:58:32 +08001315 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1316 private final StateMachine mStateMachine;
1317
1318 MDnsEventCallback(StateMachine sm) {
1319 mStateMachine = sm;
1320 }
1321
1322 @Override
1323 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1324 mStateMachine.sendMessage(
1325 MDNS_SERVICE_EVENT, status.result, status.id, status);
1326 }
1327
1328 @Override
1329 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1330 mStateMachine.sendMessage(
1331 MDNS_SERVICE_EVENT, status.result, status.id, status);
1332 }
1333
1334 @Override
1335 public void onServiceResolutionStatus(final ResolutionInfo status) {
1336 mStateMachine.sendMessage(
1337 MDNS_SERVICE_EVENT, status.result, status.id, status);
1338 }
1339
1340 @Override
1341 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1342 mStateMachine.sendMessage(
1343 MDNS_SERVICE_EVENT, status.result, status.id, status);
1344 }
1345
1346 @Override
1347 public int getInterfaceVersion() throws RemoteException {
1348 return this.VERSION;
1349 }
1350
1351 @Override
1352 public String getInterfaceHash() throws RemoteException {
1353 return this.HASH;
1354 }
1355 }
1356
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001357 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
1358 @Override
1359 public void onRegisterServiceSucceeded(int serviceId, NsdServiceInfo registeredInfo) {
1360 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1361 if (clientInfo == null) return;
1362
1363 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1364 if (clientId < 0) return;
1365
1366 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1367 // historical behavior.
1368 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
1369 clientInfo.onRegisterServiceSucceeded(clientId, cbInfo);
1370 }
1371
1372 @Override
1373 public void onRegisterServiceFailed(int serviceId, int errorCode) {
1374 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1375 if (clientInfo == null) return;
1376
1377 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1378 if (clientId < 0) return;
1379
1380 clientInfo.onRegisterServiceFailed(clientId, errorCode);
1381 }
1382
1383 private ClientInfo getClientInfoOrLog(int serviceId) {
1384 final ClientInfo clientInfo = mIdToClientInfoMap.get(serviceId);
1385 if (clientInfo == null) {
1386 Log.e(TAG, String.format("Callback for service %d has no client", serviceId));
1387 }
1388 return clientInfo;
1389 }
1390
1391 private int getClientIdOrLog(@NonNull ClientInfo info, int serviceId) {
1392 final int clientId = info.getClientId(serviceId);
1393 if (clientId < 0) {
1394 Log.e(TAG, String.format("Client ID not found for service %d", serviceId));
1395 }
1396 return clientId;
1397 }
1398 }
1399
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001400 @Override
1401 public INsdServiceConnector connect(INsdManagerCallback cb) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001402 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001403 final INsdServiceConnector connector = new NsdServiceConnector();
1404 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1405 NsdManager.REGISTER_CLIENT, new Pair<>(connector, cb)));
1406 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07001407 }
1408
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001409 private static class ListenerArgs {
1410 public final NsdServiceConnector connector;
1411 public final NsdServiceInfo serviceInfo;
1412 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
1413 this.connector = connector;
1414 this.serviceInfo = serviceInfo;
1415 }
1416 }
1417
1418 private class NsdServiceConnector extends INsdServiceConnector.Stub
1419 implements IBinder.DeathRecipient {
1420 @Override
1421 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
1422 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1423 NsdManager.REGISTER_SERVICE, 0, listenerKey,
1424 new ListenerArgs(this, serviceInfo)));
1425 }
1426
1427 @Override
1428 public void unregisterService(int listenerKey) {
1429 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1430 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
1431 new ListenerArgs(this, null)));
1432 }
1433
1434 @Override
1435 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
1436 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1437 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
1438 new ListenerArgs(this, serviceInfo)));
1439 }
1440
1441 @Override
1442 public void stopDiscovery(int listenerKey) {
1443 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1444 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
1445 }
1446
1447 @Override
1448 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
1449 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1450 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
1451 new ListenerArgs(this, serviceInfo)));
1452 }
1453
1454 @Override
Paul Hub58deb72022-12-26 09:24:42 +00001455 public void stopResolution(int listenerKey) {
1456 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1457 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
1458 }
1459
1460 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00001461 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
1462 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1463 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
1464 new ListenerArgs(this, serviceInfo)));
1465 }
1466
1467 @Override
1468 public void unregisterServiceInfoCallback(int listenerKey) {
1469 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1470 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
1471 new ListenerArgs(this, null)));
1472 }
1473
1474 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001475 public void startDaemon() {
1476 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1477 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
1478 }
1479
1480 @Override
1481 public void binderDied() {
1482 mNsdStateMachine.sendMessage(
1483 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
1484 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001485 }
1486
Hugo Benichi912db992017-04-24 16:41:03 +09001487 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07001488 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07001489 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09001490 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
1491 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07001492 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07001493 }
1494
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001495 private int getUniqueId() {
1496 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
1497 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001498 }
1499
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001500 private boolean registerService(int regId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09001501 if (DBG) {
paulhub2225702021-11-17 09:35:33 +08001502 Log.d(TAG, "registerService: " + regId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001503 }
Hugo Benichi6d706442017-04-24 16:19:58 +09001504 String name = service.getServiceName();
1505 String type = service.getServiceType();
1506 int port = service.getPort();
1507 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001508 final int registerInterface = getNetworkInterfaceIndex(service);
1509 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08001510 Log.e(TAG, "Interface to register service on not found");
1511 return false;
1512 }
1513 return mMDnsManager.registerService(regId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001514 }
1515
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001516 private boolean unregisterService(int regId) {
paulhu2b9ed952022-02-10 21:58:32 +08001517 return mMDnsManager.stopOperation(regId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001518 }
1519
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001520 private boolean discoverServices(int discoveryId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08001521 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001522 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
1523 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001524 Log.e(TAG, "Interface to discover service on not found");
1525 return false;
1526 }
paulhu2b9ed952022-02-10 21:58:32 +08001527 return mMDnsManager.discover(discoveryId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001528 }
1529
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001530 private boolean stopServiceDiscovery(int discoveryId) {
paulhu2b9ed952022-02-10 21:58:32 +08001531 return mMDnsManager.stopOperation(discoveryId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001532 }
1533
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001534 private boolean resolveService(int resolveId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001535 final String name = service.getServiceName();
1536 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001537 final int resolveInterface = getNetworkInterfaceIndex(service);
1538 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001539 Log.e(TAG, "Interface to resolve service on not found");
1540 return false;
1541 }
paulhu2b9ed952022-02-10 21:58:32 +08001542 return mMDnsManager.resolve(resolveId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001543 }
1544
1545 /**
1546 * Guess the interface to use to resolve or discover a service on a specific network.
1547 *
1548 * This is an imperfect guess, as for example the network may be gone or not yet fully
1549 * registered. This is fine as failing is correct if the network is gone, and a client
1550 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
1551 * this is to support the legacy mdnsresponder implementation, which historically resolved
1552 * services on an unspecified network.
1553 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001554 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
1555 final Network network = serviceInfo.getNetwork();
1556 if (network == null) {
1557 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
1558 // provided by NsdService from discovery results, and the service was found on an
1559 // interface that has no app-usable Network).
1560 if (serviceInfo.getInterfaceIndex() != 0) {
1561 return serviceInfo.getInterfaceIndex();
1562 }
1563 return IFACE_IDX_ANY;
1564 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001565
1566 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
1567 if (cm == null) {
1568 Log.wtf(TAG, "No ConnectivityManager for resolveService");
1569 return IFACE_IDX_ANY;
1570 }
1571 final LinkProperties lp = cm.getLinkProperties(network);
1572 if (lp == null) return IFACE_IDX_ANY;
1573
1574 // Only resolve on non-stacked interfaces
1575 final NetworkInterface iface;
1576 try {
1577 iface = NetworkInterface.getByName(lp.getInterfaceName());
1578 } catch (SocketException e) {
1579 Log.e(TAG, "Error querying interface", e);
1580 return IFACE_IDX_ANY;
1581 }
1582
1583 if (iface == null) {
1584 Log.e(TAG, "Interface not found: " + lp.getInterfaceName());
1585 return IFACE_IDX_ANY;
1586 }
1587
1588 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001589 }
1590
1591 private boolean stopResolveService(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001592 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001593 }
1594
paulhu2b9ed952022-02-10 21:58:32 +08001595 private boolean getAddrInfo(int resolveId, String hostname, int interfaceIdx) {
1596 return mMDnsManager.getServiceAddress(resolveId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001597 }
1598
1599 private boolean stopGetAddrInfo(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001600 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001601 }
1602
1603 @Override
Irfan Sheriff75006652012-04-17 23:15:29 -07001604 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
paulhu3ffffe72021-09-16 10:15:22 +08001605 if (!PermissionUtils.checkDumpPermission(mContext, TAG, pw)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001606
Irfan Sheriff75006652012-04-17 23:15:29 -07001607 for (ClientInfo client : mClients.values()) {
1608 pw.println("Client Info");
1609 pw.println(client);
1610 }
1611
1612 mNsdStateMachine.dump(fd, pw, args);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001613 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001614
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001615 private abstract static class ClientRequest {
1616 private final int mGlobalId;
1617
1618 private ClientRequest(int globalId) {
1619 mGlobalId = globalId;
1620 }
1621 }
1622
1623 private static class LegacyClientRequest extends ClientRequest {
1624 private final int mRequestCode;
1625
1626 private LegacyClientRequest(int globalId, int requestCode) {
1627 super(globalId);
1628 mRequestCode = requestCode;
1629 }
1630 }
1631
1632 private static class AdvertiserClientRequest extends ClientRequest {
1633 private AdvertiserClientRequest(int globalId) {
1634 super(globalId);
1635 }
1636 }
1637
1638 private static class DiscoveryManagerRequest extends ClientRequest {
1639 @NonNull
1640 private final MdnsListener mListener;
1641
1642 private DiscoveryManagerRequest(int globalId, @NonNull MdnsListener listener) {
1643 super(globalId);
1644 mListener = listener;
1645 }
1646 }
1647
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001648 /* Information tracked per client */
1649 private class ClientInfo {
1650
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001651 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001652 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001653 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001654 private NsdServiceInfo mResolvedService;
1655
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001656 /* A map from client-side ID (listenerKey) to the request */
1657 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08001658
Luke Huangf7277ed2021-07-12 21:15:10 +08001659 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001660 private boolean mIsPreSClient = false;
Luke Huangf7277ed2021-07-12 21:15:10 +08001661
Paul Hu18aeccc2022-12-27 08:48:48 +00001662 /*** The service that is registered to listen to its updates */
1663 private NsdServiceInfo mRegisteredService;
1664 /*** The client id that listen to updates */
1665 private int mClientIdForServiceUpdates;
1666
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001667 private ClientInfo(INsdManagerCallback cb) {
1668 mCb = cb;
paulhub2225702021-11-17 09:35:33 +08001669 if (DBG) Log.d(TAG, "New client");
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001670 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001671
1672 @Override
1673 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06001674 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07001675 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001676 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
1677 for (int i = 0; i < mClientRequests.size(); i++) {
1678 int clientID = mClientRequests.keyAt(i);
1679 sb.append("clientId ")
1680 .append(clientID)
1681 .append(" mDnsId ").append(mClientRequests.valueAt(i).mGlobalId)
1682 .append(" type ").append(
1683 mClientRequests.valueAt(i).getClass().getSimpleName())
1684 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07001685 }
1686 return sb.toString();
1687 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001688
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001689 private boolean isPreSClient() {
1690 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08001691 }
1692
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001693 private void setPreSClient() {
1694 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08001695 }
1696
Dave Plattfeff2af2014-03-07 14:48:22 -08001697 // Remove any pending requests from the global map when we get rid of a client,
1698 // and send cancellations to the daemon.
1699 private void expungeAllRequests() {
Hugo Benichid2552ae2017-04-11 14:42:47 +09001700 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001701 for (int i = 0; i < mClientRequests.size(); i++) {
1702 final int clientId = mClientRequests.keyAt(i);
1703 final ClientRequest request = mClientRequests.valueAt(i);
1704 final int globalId = request.mGlobalId;
Dave Plattfeff2af2014-03-07 14:48:22 -08001705 mIdToClientInfoMap.remove(globalId);
paulhub2225702021-11-17 09:35:33 +08001706 if (DBG) {
1707 Log.d(TAG, "Terminating client-ID " + clientId
1708 + " global-ID " + globalId + " type " + mClientRequests.get(clientId));
1709 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001710
1711 if (request instanceof DiscoveryManagerRequest) {
Ahmad Khalil4b8d45a2023-03-02 11:43:25 +00001712 final MdnsListener listener =
1713 ((DiscoveryManagerRequest) request).mListener;
1714 mMdnsDiscoveryManager.unregisterListener(
1715 listener.getListenedServiceType(), listener);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001716 continue;
1717 }
1718
1719 if (request instanceof AdvertiserClientRequest) {
1720 mAdvertiser.removeService(globalId);
1721 continue;
1722 }
1723
1724 if (!(request instanceof LegacyClientRequest)) {
1725 throw new IllegalStateException("Unknown request type: " + request.getClass());
1726 }
1727
1728 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08001729 case NsdManager.DISCOVER_SERVICES:
1730 stopServiceDiscovery(globalId);
1731 break;
1732 case NsdManager.RESOLVE_SERVICE:
1733 stopResolveService(globalId);
1734 break;
1735 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001736 unregisterService(globalId);
Dave Plattfeff2af2014-03-07 14:48:22 -08001737 break;
1738 default:
1739 break;
1740 }
1741 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001742 mClientRequests.clear();
1743 }
1744
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001745 // mClientRequests is a sparse array of listener id -> ClientRequest. For a given
1746 // mDnsClient id, return the corresponding listener id. mDnsClient id is also called a
1747 // global id.
Christopher Lane74411222014-04-25 18:39:07 -07001748 private int getClientId(final int globalId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001749 for (int i = 0; i < mClientRequests.size(); i++) {
1750 if (mClientRequests.valueAt(i).mGlobalId == globalId) {
1751 return mClientRequests.keyAt(i);
1752 }
Christopher Lane74411222014-04-25 18:39:07 -07001753 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001754 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07001755 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001756
Paul Hu18aeccc2022-12-27 08:48:48 +00001757 private void maybeNotifyRegisteredServiceLost(@NonNull NsdServiceInfo info) {
1758 if (mRegisteredService == null) return;
1759 if (!Objects.equals(mRegisteredService.getServiceName(), info.getServiceName())) return;
1760 // Resolved services have a leading dot appended at the beginning of their type, but in
1761 // discovered info it's at the end
1762 if (!Objects.equals(
1763 mRegisteredService.getServiceType() + ".", "." + info.getServiceType())) {
1764 return;
1765 }
1766 onServiceUpdatedLost(mClientIdForServiceUpdates);
1767 }
1768
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001769 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info) {
1770 try {
1771 mCb.onDiscoverServicesStarted(listenerKey, info);
1772 } catch (RemoteException e) {
1773 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
1774 }
1775 }
1776
1777 void onDiscoverServicesFailed(int listenerKey, int error) {
1778 try {
1779 mCb.onDiscoverServicesFailed(listenerKey, error);
1780 } catch (RemoteException e) {
1781 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
1782 }
1783 }
1784
1785 void onServiceFound(int listenerKey, NsdServiceInfo info) {
1786 try {
1787 mCb.onServiceFound(listenerKey, info);
1788 } catch (RemoteException e) {
1789 Log.e(TAG, "Error calling onServiceFound(", e);
1790 }
1791 }
1792
1793 void onServiceLost(int listenerKey, NsdServiceInfo info) {
1794 try {
1795 mCb.onServiceLost(listenerKey, info);
1796 } catch (RemoteException e) {
1797 Log.e(TAG, "Error calling onServiceLost(", e);
1798 }
1799 }
1800
1801 void onStopDiscoveryFailed(int listenerKey, int error) {
1802 try {
1803 mCb.onStopDiscoveryFailed(listenerKey, error);
1804 } catch (RemoteException e) {
1805 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
1806 }
1807 }
1808
1809 void onStopDiscoverySucceeded(int listenerKey) {
1810 try {
1811 mCb.onStopDiscoverySucceeded(listenerKey);
1812 } catch (RemoteException e) {
1813 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
1814 }
1815 }
1816
1817 void onRegisterServiceFailed(int listenerKey, int error) {
1818 try {
1819 mCb.onRegisterServiceFailed(listenerKey, error);
1820 } catch (RemoteException e) {
1821 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
1822 }
1823 }
1824
1825 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info) {
1826 try {
1827 mCb.onRegisterServiceSucceeded(listenerKey, info);
1828 } catch (RemoteException e) {
1829 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
1830 }
1831 }
1832
1833 void onUnregisterServiceFailed(int listenerKey, int error) {
1834 try {
1835 mCb.onUnregisterServiceFailed(listenerKey, error);
1836 } catch (RemoteException e) {
1837 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
1838 }
1839 }
1840
1841 void onUnregisterServiceSucceeded(int listenerKey) {
1842 try {
1843 mCb.onUnregisterServiceSucceeded(listenerKey);
1844 } catch (RemoteException e) {
1845 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
1846 }
1847 }
1848
1849 void onResolveServiceFailed(int listenerKey, int error) {
1850 try {
1851 mCb.onResolveServiceFailed(listenerKey, error);
1852 } catch (RemoteException e) {
1853 Log.e(TAG, "Error calling onResolveServiceFailed", e);
1854 }
1855 }
1856
1857 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info) {
1858 try {
1859 mCb.onResolveServiceSucceeded(listenerKey, info);
1860 } catch (RemoteException e) {
1861 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
1862 }
1863 }
Paul Hub58deb72022-12-26 09:24:42 +00001864
1865 void onStopResolutionFailed(int listenerKey, int error) {
1866 try {
1867 mCb.onStopResolutionFailed(listenerKey, error);
1868 } catch (RemoteException e) {
1869 Log.e(TAG, "Error calling onStopResolutionFailed", e);
1870 }
1871 }
1872
1873 void onStopResolutionSucceeded(int listenerKey) {
1874 try {
1875 mCb.onStopResolutionSucceeded(listenerKey);
1876 } catch (RemoteException e) {
1877 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
1878 }
1879 }
Paul Hu18aeccc2022-12-27 08:48:48 +00001880
1881 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
1882 try {
1883 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
1884 } catch (RemoteException e) {
1885 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
1886 }
1887 }
1888
1889 void onServiceUpdated(int listenerKey, NsdServiceInfo info) {
1890 try {
1891 mCb.onServiceUpdated(listenerKey, info);
1892 } catch (RemoteException e) {
1893 Log.e(TAG, "Error calling onServiceUpdated", e);
1894 }
1895 }
1896
1897 void onServiceUpdatedLost(int listenerKey) {
1898 try {
1899 mCb.onServiceUpdatedLost(listenerKey);
1900 } catch (RemoteException e) {
1901 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
1902 }
1903 }
1904
1905 void onServiceInfoCallbackUnregistered(int listenerKey) {
1906 try {
1907 mCb.onServiceInfoCallbackUnregistered(listenerKey);
1908 } catch (RemoteException e) {
1909 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
1910 }
1911 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001912 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001913}