blob: 49c6ef0d08109e3cbcff7531a4e6c239f17f1ba7 [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;
Paul Hu4bd98ef2023-01-12 13:42:07 +0800121 @Nullable
122 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
123 @Nullable
124 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
125 @Nullable
126 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900127 @Nullable
128 private final MdnsAdvertiser mAdvertiser;
Paul Hu23fa2022023-01-13 22:57:24 +0800129 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800130 // state machine thread. If change this outside state machine, it will need to introduce
131 // synchronization.
132 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800133 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700134
135 /**
136 * Clients receiving asynchronous messages
137 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900138 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700139
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700140 /* A map from unique id to client info */
Hugo Benichi32be63d2017-04-05 14:06:11 +0900141 private final SparseArray<ClientInfo> mIdToClientInfoMap= new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700142
Luke Huang05298582021-06-13 16:52:05 +0000143 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700144
Hugo Benichi32be63d2017-04-05 14:06:11 +0900145 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700146 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800147 // The count of the connected legacy clients.
148 private int mLegacyClientCount = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700149
Paul Hu23fa2022023-01-13 22:57:24 +0800150 private static class MdnsListener implements MdnsServiceBrowserListener {
151 protected final int mClientId;
152 protected final int mTransactionId;
153 @NonNull
154 protected final NsdServiceInfo mReqServiceInfo;
155 @NonNull
156 protected final String mListenedServiceType;
157
158 MdnsListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
159 @NonNull String listenedServiceType) {
160 mClientId = clientId;
161 mTransactionId = transactionId;
162 mReqServiceInfo = reqServiceInfo;
163 mListenedServiceType = listenedServiceType;
164 }
165
166 @NonNull
167 public String getListenedServiceType() {
168 return mListenedServiceType;
169 }
170
171 @Override
172 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo) { }
173
174 @Override
175 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
176
177 @Override
178 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
179
180 @Override
181 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) { }
182
183 @Override
184 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
185
186 @Override
187 public void onSearchStoppedWithError(int error) { }
188
189 @Override
190 public void onSearchFailedToStart() { }
191
192 @Override
193 public void onDiscoveryQuerySent(@NonNull List<String> subtypes, int transactionId) { }
194
195 @Override
196 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
197 }
198
199 private class DiscoveryListener extends MdnsListener {
200
201 DiscoveryListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
202 @NonNull String listenServiceType) {
203 super(clientId, transactionId, reqServiceInfo, listenServiceType);
204 }
205
206 @Override
207 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu019621e2023-01-13 23:26:49 +0800208 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
209 NsdManager.SERVICE_FOUND,
210 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800211 }
212
213 @Override
214 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800215 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
216 NsdManager.SERVICE_LOST,
217 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800218 }
219 }
220
Paul Hu75069ed2023-01-14 00:31:09 +0800221 private class ResolutionListener extends MdnsListener {
222
223 ResolutionListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
224 @NonNull String listenServiceType) {
225 super(clientId, transactionId, reqServiceInfo, listenServiceType);
226 }
227
228 @Override
229 public void onServiceFound(MdnsServiceInfo serviceInfo) {
230 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
231 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
232 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
233 }
234 }
235
Paul Hu019621e2023-01-13 23:26:49 +0800236 /**
237 * Data class of mdns service callback information.
238 */
239 private static class MdnsEvent {
240 final int mClientId;
241 @NonNull
242 final String mRequestedServiceType;
243 @NonNull
244 final MdnsServiceInfo mMdnsServiceInfo;
245
246 MdnsEvent(int clientId, @NonNull String requestedServiceType,
247 @NonNull MdnsServiceInfo mdnsServiceInfo) {
248 mClientId = clientId;
249 mRequestedServiceType = requestedServiceType;
250 mMdnsServiceInfo = mdnsServiceInfo;
251 }
252 }
253
Irfan Sheriff75006652012-04-17 23:15:29 -0700254 private class NsdStateMachine extends StateMachine {
255
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700256 private final DefaultState mDefaultState = new DefaultState();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700257 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700258
259 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700260 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900261 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700262 }
263
Luke Huang92860f92021-06-23 06:29:30 +0000264 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800265 if (mIsDaemonStarted) {
266 if (DBG) Log.d(TAG, "Daemon is already started.");
267 return;
268 }
269 mMDnsManager.registerEventListener(mMDnsEventCallback);
270 mMDnsManager.startDaemon();
271 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000272 maybeScheduleStop();
273 }
274
paulhu2b9ed952022-02-10 21:58:32 +0800275 private void maybeStopDaemon() {
276 if (!mIsDaemonStarted) {
277 if (DBG) Log.d(TAG, "Daemon has not been started.");
278 return;
279 }
280 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
281 mMDnsManager.stopDaemon();
282 mIsDaemonStarted = false;
283 }
284
Luke Huang92860f92021-06-23 06:29:30 +0000285 private boolean isAnyRequestActive() {
286 return mIdToClientInfoMap.size() != 0;
287 }
288
289 private void scheduleStop() {
290 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
291 }
292 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800293 // The native daemon should stay alive and can't be cleanup
294 // if any legacy client connected.
295 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000296 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000297 }
298 }
299
Luke Huang92860f92021-06-23 06:29:30 +0000300 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000301 this.removeMessages(NsdManager.DAEMON_CLEANUP);
302 }
303
Paul Hu23fa2022023-01-13 22:57:24 +0800304 private void maybeStartMonitoringSockets() {
305 if (mIsMonitoringSocketsStarted) {
306 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
307 return;
308 }
309
310 mMdnsSocketProvider.startMonitoringSockets();
311 mIsMonitoringSocketsStarted = true;
312 }
313
314 private void maybeStopMonitoringSockets() {
315 if (!mIsMonitoringSocketsStarted) {
316 if (DBG) Log.d(TAG, "Socket monitoring has not been started.");
317 return;
318 }
319 mMdnsSocketProvider.stopMonitoringSockets();
320 mIsMonitoringSocketsStarted = false;
321 }
322
323 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
324 if (!isAnyRequestActive()) {
325 maybeStopMonitoringSockets();
326 }
327 }
328
Hugo Benichi803a2f02017-04-24 11:35:06 +0900329 NsdStateMachine(String name, Handler handler) {
330 super(name, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -0700331 addState(mDefaultState);
Irfan Sheriff75006652012-04-17 23:15:29 -0700332 addState(mEnabledState, mDefaultState);
paulhu5568f452021-11-30 13:31:29 +0800333 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900334 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700335 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700336 }
337
338 class DefaultState extends State {
339 @Override
340 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900341 final ClientInfo cInfo;
342 final int clientId = msg.arg2;
Irfan Sheriff75006652012-04-17 23:15:29 -0700343 switch (msg.what) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900344 case NsdManager.REGISTER_CLIENT:
345 final Pair<NsdServiceConnector, INsdManagerCallback> arg =
346 (Pair<NsdServiceConnector, INsdManagerCallback>) msg.obj;
347 final INsdManagerCallback cb = arg.second;
348 try {
349 cb.asBinder().linkToDeath(arg.first, 0);
350 cInfo = new ClientInfo(cb);
351 mClients.put(arg.first, cInfo);
352 } catch (RemoteException e) {
353 Log.w(TAG, "Client " + clientId + " has already died");
Irfan Sheriff75006652012-04-17 23:15:29 -0700354 }
355 break;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900356 case NsdManager.UNREGISTER_CLIENT:
357 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
358 cInfo = mClients.remove(connector);
Dave Plattfeff2af2014-03-07 14:48:22 -0800359 if (cInfo != null) {
360 cInfo.expungeAllRequests();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900361 if (cInfo.isPreSClient()) {
Luke Huangf7277ed2021-07-12 21:15:10 +0800362 mLegacyClientCount -= 1;
363 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800364 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900365 if (mMdnsDiscoveryManager != null || mAdvertiser != null) {
Paul Hu23fa2022023-01-13 22:57:24 +0800366 maybeStopMonitoringSocketsIfNoActiveRequest();
367 }
Luke Huangf7277ed2021-07-12 21:15:10 +0800368 maybeScheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700369 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700370 case NsdManager.DISCOVER_SERVICES:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900371 cInfo = getClientInfoForReply(msg);
372 if (cInfo != null) {
373 cInfo.onDiscoverServicesFailed(
374 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
375 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700376 break;
377 case NsdManager.STOP_DISCOVERY:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900378 cInfo = getClientInfoForReply(msg);
379 if (cInfo != null) {
380 cInfo.onStopDiscoveryFailed(
381 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
382 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700383 break;
384 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900385 cInfo = getClientInfoForReply(msg);
386 if (cInfo != null) {
387 cInfo.onRegisterServiceFailed(
388 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
389 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700390 break;
391 case NsdManager.UNREGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900392 cInfo = getClientInfoForReply(msg);
393 if (cInfo != null) {
394 cInfo.onUnregisterServiceFailed(
395 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
396 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700397 break;
398 case NsdManager.RESOLVE_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900399 cInfo = getClientInfoForReply(msg);
400 if (cInfo != null) {
401 cInfo.onResolveServiceFailed(
402 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
403 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700404 break;
Paul Hub58deb72022-12-26 09:24:42 +0000405 case NsdManager.STOP_RESOLUTION:
406 cInfo = getClientInfoForReply(msg);
407 if (cInfo != null) {
408 cInfo.onStopResolutionFailed(
409 clientId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
410 }
411 break;
Paul Hu18aeccc2022-12-27 08:48:48 +0000412 case NsdManager.REGISTER_SERVICE_CALLBACK:
413 cInfo = getClientInfoForReply(msg);
414 if (cInfo != null) {
415 cInfo.onServiceInfoCallbackRegistrationFailed(
416 clientId, NsdManager.FAILURE_BAD_PARAMETERS);
417 }
418 break;
Luke Huang05298582021-06-13 16:52:05 +0000419 case NsdManager.DAEMON_CLEANUP:
paulhu2b9ed952022-02-10 21:58:32 +0800420 maybeStopDaemon();
Luke Huang05298582021-06-13 16:52:05 +0000421 break;
Luke Huangf7277ed2021-07-12 21:15:10 +0800422 // This event should be only sent by the legacy (target SDK < S) clients.
423 // Mark the sending client as legacy.
424 case NsdManager.DAEMON_STARTUP:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900425 cInfo = getClientInfoForReply(msg);
Luke Huangf7277ed2021-07-12 21:15:10 +0800426 if (cInfo != null) {
427 cancelStop();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900428 cInfo.setPreSClient();
Luke Huangf7277ed2021-07-12 21:15:10 +0800429 mLegacyClientCount += 1;
430 maybeStartDaemon();
431 }
432 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700433 default:
paulhub2225702021-11-17 09:35:33 +0800434 Log.e(TAG, "Unhandled " + msg);
Irfan Sheriff75006652012-04-17 23:15:29 -0700435 return NOT_HANDLED;
436 }
437 return HANDLED;
438 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900439
440 private ClientInfo getClientInfoForReply(Message msg) {
441 final ListenerArgs args = (ListenerArgs) msg.obj;
442 return mClients.get(args.connector);
443 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700444 }
445
Irfan Sheriff75006652012-04-17 23:15:29 -0700446 class EnabledState extends State {
447 @Override
448 public void enter() {
449 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700450 }
451
452 @Override
453 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000454 // TODO: it is incorrect to stop the daemon without expunging all requests
455 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000456 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700457 }
458
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700459 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900460 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800461 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700462 return true;
463 }
464 return false;
465 }
466
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900467 private void storeLegacyRequestMap(int clientId, int globalId, ClientInfo clientInfo,
468 int what) {
469 clientInfo.mClientRequests.put(clientId, new LegacyClientRequest(globalId, what));
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700470 mIdToClientInfoMap.put(globalId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000471 // Remove the cleanup event because here comes a new request.
472 cancelStop();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700473 }
474
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900475 private void storeAdvertiserRequestMap(int clientId, int globalId,
Paul Hu23fa2022023-01-13 22:57:24 +0800476 ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900477 clientInfo.mClientRequests.put(clientId, new AdvertiserClientRequest(globalId));
478 mIdToClientInfoMap.put(globalId, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800479 }
480
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900481 private void removeRequestMap(int clientId, int globalId, ClientInfo clientInfo) {
482 final ClientRequest existing = clientInfo.mClientRequests.get(clientId);
483 if (existing == null) return;
484 clientInfo.mClientRequests.remove(clientId);
485 mIdToClientInfoMap.remove(globalId);
486
487 if (existing instanceof LegacyClientRequest) {
488 maybeScheduleStop();
489 } else {
490 maybeStopMonitoringSocketsIfNoActiveRequest();
491 }
492 }
493
494 private void storeDiscoveryManagerRequestMap(int clientId, int globalId,
495 MdnsListener listener, ClientInfo clientInfo) {
496 clientInfo.mClientRequests.put(clientId,
497 new DiscoveryManagerRequest(globalId, listener));
498 mIdToClientInfoMap.put(globalId, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800499 }
500
Paul Hu18aeccc2022-12-27 08:48:48 +0000501 private void clearRegisteredServiceInfo(ClientInfo clientInfo) {
502 clientInfo.mRegisteredService = null;
503 clientInfo.mClientIdForServiceUpdates = 0;
504 }
505
Paul Hu23fa2022023-01-13 22:57:24 +0800506 /**
507 * Check the given service type is valid and construct it to a service type
508 * which can use for discovery / resolution service.
509 *
510 * <p> The valid service type should be 2 labels, or 3 labels if the query is for a
511 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
512 * underscore; they are alphanumerical characters or dashes or underscore, except the
513 * last one that is just alphanumerical. The last label must be _tcp or _udp.
514 *
515 * @param serviceType the request service type for discovery / resolution service
516 * @return constructed service type or null if the given service type is invalid.
517 */
518 @Nullable
519 private String constructServiceType(String serviceType) {
520 if (TextUtils.isEmpty(serviceType)) return null;
521
522 final Pattern serviceTypePattern = Pattern.compile(
523 "^(_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]\\.)?"
524 + "(_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]\\._(?:tcp|udp))$");
525 final Matcher matcher = serviceTypePattern.matcher(serviceType);
526 if (!matcher.matches()) return null;
527 return matcher.group(1) == null
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900528 ? serviceType
529 : matcher.group(1) + "_sub." + matcher.group(2);
530 }
531
532 /**
533 * Truncate a service name to up to 63 UTF-8 bytes.
534 *
535 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
536 * names used in registerService follows historical behavior (see mdnsresponder
537 * handle_regservice_request).
538 */
539 @NonNull
540 private String truncateServiceName(@NonNull String originalName) {
541 // UTF-8 is at most 4 bytes per character; return early in the common case where
542 // the name can't possibly be over the limit given its string length.
543 if (originalName.length() <= MAX_LABEL_LENGTH / 4) return originalName;
544
545 final Charset utf8 = StandardCharsets.UTF_8;
546 final CharsetEncoder encoder = utf8.newEncoder();
547 final ByteBuffer out = ByteBuffer.allocate(MAX_LABEL_LENGTH);
548 // encode will write as many characters as possible to the out buffer, and just
549 // return an overflow code if there were too many characters (no need to check the
550 // return code here, this method truncates the name on purpose).
551 encoder.encode(CharBuffer.wrap(originalName), out, true /* endOfInput */);
552 return new String(out.array(), 0, out.position(), utf8);
Paul Hu23fa2022023-01-13 22:57:24 +0800553 }
554
Irfan Sheriff75006652012-04-17 23:15:29 -0700555 @Override
556 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900557 final ClientInfo clientInfo;
558 final int id;
559 final int clientId = msg.arg2;
560 final ListenerArgs args;
Irfan Sheriff75006652012-04-17 23:15:29 -0700561 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800562 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800563 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900564 args = (ListenerArgs) msg.obj;
565 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000566 // If the binder death notification for a INsdManagerCallback was received
567 // before any calls are received by NsdService, the clientInfo would be
568 // cleared and cause NPE. Add a null check here to prevent this corner case.
569 if (clientInfo == null) {
570 Log.e(TAG, "Unknown connector in discovery");
571 break;
572 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700573
574 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900575 clientInfo.onDiscoverServicesFailed(
576 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriff75006652012-04-17 23:15:29 -0700577 break;
578 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700579
Paul Hu23fa2022023-01-13 22:57:24 +0800580 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700581 id = getUniqueId();
Paul Hu23fa2022023-01-13 22:57:24 +0800582 if (mMdnsDiscoveryManager != null) {
583 final String serviceType = constructServiceType(info.getServiceType());
584 if (serviceType == null) {
585 clientInfo.onDiscoverServicesFailed(clientId,
586 NsdManager.FAILURE_INTERNAL_ERROR);
587 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700588 }
Paul Hu23fa2022023-01-13 22:57:24 +0800589
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900590 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800591 maybeStartMonitoringSockets();
592 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900593 new DiscoveryListener(clientId, id, info, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800594 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
595 .setNetwork(info.getNetwork())
596 .setIsPassiveMode(true)
597 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900598 mMdnsDiscoveryManager.registerListener(
599 listenServiceType, listener, options);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900600 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800601 clientInfo.onDiscoverServicesStarted(clientId, info);
Irfan Sheriff75006652012-04-17 23:15:29 -0700602 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800603 maybeStartDaemon();
604 if (discoverServices(id, info)) {
605 if (DBG) {
606 Log.d(TAG, "Discover " + msg.arg2 + " " + id
607 + info.getServiceType());
608 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900609 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu23fa2022023-01-13 22:57:24 +0800610 clientInfo.onDiscoverServicesStarted(clientId, info);
611 } else {
612 stopServiceDiscovery(id);
613 clientInfo.onDiscoverServicesFailed(clientId,
614 NsdManager.FAILURE_INTERNAL_ERROR);
615 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700616 }
617 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800618 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900619 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800620 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900621 args = (ListenerArgs) msg.obj;
622 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000623 // If the binder death notification for a INsdManagerCallback was received
624 // before any calls are received by NsdService, the clientInfo would be
625 // cleared and cause NPE. Add a null check here to prevent this corner case.
626 if (clientInfo == null) {
627 Log.e(TAG, "Unknown connector in stop discovery");
628 break;
629 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700630
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900631 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
632 if (request == null) {
633 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700634 break;
635 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900636 id = request.mGlobalId;
637 if (request instanceof DiscoveryManagerRequest) {
638 final MdnsListener listener =
639 ((DiscoveryManagerRequest) request).mListener;
Paul Hu23fa2022023-01-13 22:57:24 +0800640 mMdnsDiscoveryManager.unregisterListener(
641 listener.getListenedServiceType(), listener);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900642 removeRequestMap(clientId, id, clientInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900643 clientInfo.onStopDiscoverySucceeded(clientId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700644 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800645 removeRequestMap(clientId, id, clientInfo);
646 if (stopServiceDiscovery(id)) {
647 clientInfo.onStopDiscoverySucceeded(clientId);
648 } else {
649 clientInfo.onStopDiscoveryFailed(
650 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
651 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700652 }
653 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900654 }
655 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800656 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900657 args = (ListenerArgs) msg.obj;
658 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000659 // If the binder death notification for a INsdManagerCallback was received
660 // before any calls are received by NsdService, the clientInfo would be
661 // cleared and cause NPE. Add a null check here to prevent this corner case.
662 if (clientInfo == null) {
663 Log.e(TAG, "Unknown connector in registration");
664 break;
665 }
666
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700667 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900668 clientInfo.onRegisterServiceFailed(
669 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700670 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700671 }
672
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700673 id = getUniqueId();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900674 if (mAdvertiser != null) {
675 final NsdServiceInfo serviceInfo = args.serviceInfo;
676 final String serviceType = serviceInfo.getServiceType();
677 final String registerServiceType = constructServiceType(serviceType);
678 if (registerServiceType == null) {
679 Log.e(TAG, "Invalid service type: " + serviceType);
680 clientInfo.onRegisterServiceFailed(clientId,
681 NsdManager.FAILURE_INTERNAL_ERROR);
682 break;
683 }
684 serviceInfo.setServiceType(registerServiceType);
685 serviceInfo.setServiceName(truncateServiceName(
686 serviceInfo.getServiceName()));
687
688 maybeStartMonitoringSockets();
689 mAdvertiser.addService(id, serviceInfo);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900690 storeAdvertiserRequestMap(clientId, id, clientInfo);
Irfan Sheriff75006652012-04-17 23:15:29 -0700691 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900692 maybeStartDaemon();
693 if (registerService(id, args.serviceInfo)) {
694 if (DBG) Log.d(TAG, "Register " + clientId + " " + id);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900695 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900696 // Return success after mDns reports success
697 } else {
698 unregisterService(id);
699 clientInfo.onRegisterServiceFailed(
700 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
701 }
702
Irfan Sheriff75006652012-04-17 23:15:29 -0700703 }
704 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900705 }
706 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800707 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900708 args = (ListenerArgs) msg.obj;
709 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000710 // If the binder death notification for a INsdManagerCallback was received
711 // before any calls are received by NsdService, the clientInfo would be
712 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900713 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800714 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700715 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700716 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900717 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
718 if (request == null) {
719 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
720 break;
721 }
722 id = request.mGlobalId;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900723 removeRequestMap(clientId, id, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900724
725 if (mAdvertiser != null) {
726 mAdvertiser.removeService(id);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900727 clientInfo.onUnregisterServiceSucceeded(clientId);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700728 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900729 if (unregisterService(id)) {
730 clientInfo.onUnregisterServiceSucceeded(clientId);
731 } else {
732 clientInfo.onUnregisterServiceFailed(
733 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
734 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700735 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700736 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900737 }
Paul Hu75069ed2023-01-14 00:31:09 +0800738 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800739 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900740 args = (ListenerArgs) msg.obj;
741 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000742 // If the binder death notification for a INsdManagerCallback was received
743 // before any calls are received by NsdService, the clientInfo would be
744 // cleared and cause NPE. Add a null check here to prevent this corner case.
745 if (clientInfo == null) {
746 Log.e(TAG, "Unknown connector in resolution");
747 break;
748 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700749
Paul Hu75069ed2023-01-14 00:31:09 +0800750 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700751 id = getUniqueId();
Paul Hu75069ed2023-01-14 00:31:09 +0800752 if (mMdnsDiscoveryManager != null) {
753 final String serviceType = constructServiceType(info.getServiceType());
754 if (serviceType == null) {
755 clientInfo.onResolveServiceFailed(clientId,
756 NsdManager.FAILURE_INTERNAL_ERROR);
757 break;
758 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900759 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +0800760
761 maybeStartMonitoringSockets();
762 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900763 new ResolutionListener(clientId, id, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800764 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
765 .setNetwork(info.getNetwork())
766 .setIsPassiveMode(true)
767 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900768 mMdnsDiscoveryManager.registerListener(
769 resolveServiceType, listener, options);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900770 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Irfan Sheriff75006652012-04-17 23:15:29 -0700771 } else {
Paul Hu75069ed2023-01-14 00:31:09 +0800772 if (clientInfo.mResolvedService != null) {
773 clientInfo.onResolveServiceFailed(
774 clientId, NsdManager.FAILURE_ALREADY_ACTIVE);
775 break;
776 }
777
778 maybeStartDaemon();
779 if (resolveService(id, args.serviceInfo)) {
780 clientInfo.mResolvedService = new NsdServiceInfo();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900781 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu75069ed2023-01-14 00:31:09 +0800782 } else {
783 clientInfo.onResolveServiceFailed(
784 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
785 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700786 }
787 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800788 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900789 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +0000790 if (DBG) Log.d(TAG, "Stop service resolution");
791 args = (ListenerArgs) msg.obj;
792 clientInfo = mClients.get(args.connector);
793 // If the binder death notification for a INsdManagerCallback was received
794 // before any calls are received by NsdService, the clientInfo would be
795 // cleared and cause NPE. Add a null check here to prevent this corner case.
796 if (clientInfo == null) {
797 Log.e(TAG, "Unknown connector in stop resolution");
798 break;
799 }
800
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900801 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
802 if (request == null) {
803 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
804 break;
805 }
806 id = request.mGlobalId;
Paul Hub58deb72022-12-26 09:24:42 +0000807 removeRequestMap(clientId, id, clientInfo);
808 if (stopResolveService(id)) {
809 clientInfo.onStopResolutionSucceeded(clientId);
810 } else {
811 clientInfo.onStopResolutionFailed(
812 clientId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
813 }
814 clientInfo.mResolvedService = null;
815 // TODO: Implement the stop resolution with MdnsDiscoveryManager.
816 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900817 }
Paul Hu18aeccc2022-12-27 08:48:48 +0000818 case NsdManager.REGISTER_SERVICE_CALLBACK:
819 if (DBG) Log.d(TAG, "Register a service callback");
820 args = (ListenerArgs) msg.obj;
821 clientInfo = mClients.get(args.connector);
822 // If the binder death notification for a INsdManagerCallback was received
823 // before any calls are received by NsdService, the clientInfo would be
824 // cleared and cause NPE. Add a null check here to prevent this corner case.
825 if (clientInfo == null) {
826 Log.e(TAG, "Unknown connector in callback registration");
827 break;
828 }
829
830 if (clientInfo.mRegisteredService != null) {
831 clientInfo.onServiceInfoCallbackRegistrationFailed(
832 clientId, NsdManager.FAILURE_ALREADY_ACTIVE);
833 break;
834 }
835
836 maybeStartDaemon();
837 id = getUniqueId();
838 if (resolveService(id, args.serviceInfo)) {
839 clientInfo.mRegisteredService = new NsdServiceInfo();
840 clientInfo.mClientIdForServiceUpdates = clientId;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900841 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu18aeccc2022-12-27 08:48:48 +0000842 } else {
843 clientInfo.onServiceInfoCallbackRegistrationFailed(
844 clientId, NsdManager.FAILURE_BAD_PARAMETERS);
845 }
846 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900847 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +0000848 if (DBG) Log.d(TAG, "Unregister a service callback");
849 args = (ListenerArgs) msg.obj;
850 clientInfo = mClients.get(args.connector);
851 // If the binder death notification for a INsdManagerCallback was received
852 // before any calls are received by NsdService, the clientInfo would be
853 // cleared and cause NPE. Add a null check here to prevent this corner case.
854 if (clientInfo == null) {
855 Log.e(TAG, "Unknown connector in callback unregistration");
856 break;
857 }
858
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900859 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
860 if (request == null) {
861 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
862 break;
863 }
864 id = request.mGlobalId;
Paul Hu18aeccc2022-12-27 08:48:48 +0000865 removeRequestMap(clientId, id, clientInfo);
866 if (stopResolveService(id)) {
867 clientInfo.onServiceInfoCallbackUnregistered(clientId);
868 } else {
869 Log.e(TAG, "Failed to unregister service info callback");
870 }
871 clearRegisteredServiceInfo(clientInfo);
872 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900873 }
paulhu2b9ed952022-02-10 21:58:32 +0800874 case MDNS_SERVICE_EVENT:
875 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +0900876 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700877 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700878 break;
Paul Hu019621e2023-01-13 23:26:49 +0800879 case MDNS_DISCOVERY_MANAGER_EVENT:
880 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
881 return NOT_HANDLED;
882 }
883 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700884 default:
Hugo Benichif0c84092017-04-05 14:43:29 +0900885 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700886 }
Hugo Benichif0c84092017-04-05 14:43:29 +0900887 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700888 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700889
Paul Hu18aeccc2022-12-27 08:48:48 +0000890 private void notifyResolveFailedResult(boolean isListenedToUpdates, int clientId,
891 ClientInfo clientInfo, int error) {
892 if (isListenedToUpdates) {
893 clientInfo.onServiceInfoCallbackRegistrationFailed(clientId, error);
894 clearRegisteredServiceInfo(clientInfo);
895 } else {
896 // The resolve API always returned FAILURE_INTERNAL_ERROR on error; keep it
897 // for backwards compatibility.
898 clientInfo.onResolveServiceFailed(clientId, NsdManager.FAILURE_INTERNAL_ERROR);
899 clientInfo.mResolvedService = null;
900 }
901 }
902
paulhu2b9ed952022-02-10 21:58:32 +0800903 private boolean handleMDnsServiceEvent(int code, int id, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700904 NsdServiceInfo servInfo;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700905 ClientInfo clientInfo = mIdToClientInfoMap.get(id);
906 if (clientInfo == null) {
paulhu2b9ed952022-02-10 21:58:32 +0800907 Log.e(TAG, String.format("id %d for %d has no client mapping", id, code));
Hugo Benichif0c84092017-04-05 14:43:29 +0900908 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700909 }
910
911 /* This goes in response as msg.arg2 */
Christopher Lane74411222014-04-25 18:39:07 -0700912 int clientId = clientInfo.getClientId(id);
913 if (clientId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -0700914 // This can happen because of race conditions. For example,
915 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
916 // and we may get in this situation.
paulhu2b9ed952022-02-10 21:58:32 +0800917 Log.d(TAG, String.format("%d for listener id %d that is no longer active",
918 code, id));
Hugo Benichif0c84092017-04-05 14:43:29 +0900919 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700920 }
Hugo Benichi32be63d2017-04-05 14:06:11 +0900921 if (DBG) {
paulhu2b9ed952022-02-10 21:58:32 +0800922 Log.d(TAG, String.format("MDns service event code:%d id=%d", code, id));
Hugo Benichi32be63d2017-04-05 14:06:11 +0900923 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700924 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +0800925 case IMDnsEventListener.SERVICE_FOUND: {
926 final DiscoveryInfo info = (DiscoveryInfo) obj;
927 final String name = info.serviceName;
928 final String type = info.registrationType;
929 servInfo = new NsdServiceInfo(name, type);
930 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900931 if (foundNetId == 0L) {
932 // Ignore services that do not have a Network: they are not usable
933 // by apps, as they would need privileged permissions to use
934 // interfaces that do not have an associated Network.
935 break;
936 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +0900937 if (foundNetId == INetd.DUMMY_NET_ID) {
938 // Ignore services on the dummy0 interface: they are only seen when
939 // discovering locally advertised services, and are not reachable
940 // through that interface.
941 break;
942 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900943 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900944 clientInfo.onServiceFound(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700945 break;
paulhu2b9ed952022-02-10 21:58:32 +0800946 }
947 case IMDnsEventListener.SERVICE_LOST: {
948 final DiscoveryInfo info = (DiscoveryInfo) obj;
949 final String name = info.serviceName;
950 final String type = info.registrationType;
951 final int lostNetId = info.netId;
952 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900953 // The network could be set to null (netId 0) if it was torn down when the
954 // service is lost
955 // TODO: avoid returning null in that case, possibly by remembering
956 // found services on the same interface index and their network at the time
957 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900958 clientInfo.onServiceLost(clientId, servInfo);
Paul Hu18aeccc2022-12-27 08:48:48 +0000959 // TODO: also support registered service lost when not discovering
960 clientInfo.maybeNotifyRegisteredServiceLost(servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700961 break;
paulhu2b9ed952022-02-10 21:58:32 +0800962 }
963 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900964 clientInfo.onDiscoverServicesFailed(
965 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700966 break;
paulhu2b9ed952022-02-10 21:58:32 +0800967 case IMDnsEventListener.SERVICE_REGISTERED: {
968 final RegistrationInfo info = (RegistrationInfo) obj;
969 final String name = info.serviceName;
970 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900971 clientInfo.onRegisterServiceSucceeded(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700972 break;
paulhu2b9ed952022-02-10 21:58:32 +0800973 }
974 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900975 clientInfo.onRegisterServiceFailed(
976 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700977 break;
paulhu2b9ed952022-02-10 21:58:32 +0800978 case IMDnsEventListener.SERVICE_RESOLVED: {
979 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -0700980 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +0800981 final String fullName = info.serviceFullName;
982 while (index < fullName.length() && fullName.charAt(index) != '.') {
983 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -0700984 ++index;
985 }
986 ++index;
987 }
paulhu2b9ed952022-02-10 21:58:32 +0800988 if (index >= fullName.length()) {
989 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700990 break;
991 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900992
paulhube186602022-04-12 07:18:23 +0000993 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +0800994 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700995 String type = rest.replace(".local.", "");
996
Paul Hu18aeccc2022-12-27 08:48:48 +0000997 final boolean isListenedToUpdates =
998 clientId == clientInfo.mClientIdForServiceUpdates;
999 final NsdServiceInfo serviceInfo = isListenedToUpdates
1000 ? clientInfo.mRegisteredService : clientInfo.mResolvedService;
1001
1002 serviceInfo.setServiceName(name);
1003 serviceInfo.setServiceType(type);
1004 serviceInfo.setPort(info.port);
1005 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001006 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001007
1008 stopResolveService(id);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001009 removeRequestMap(clientId, id, clientInfo);
1010
paulhu2b9ed952022-02-10 21:58:32 +08001011 final int id2 = getUniqueId();
1012 if (getAddrInfo(id2, info.hostname, info.interfaceIdx)) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001013 storeLegacyRequestMap(clientId, id2, clientInfo,
1014 NsdManager.RESOLVE_SERVICE);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001015 } else {
Paul Hu18aeccc2022-12-27 08:48:48 +00001016 notifyResolveFailedResult(isListenedToUpdates, clientId, clientInfo,
1017 NsdManager.FAILURE_BAD_PARAMETERS);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001018 }
1019 break;
paulhu2b9ed952022-02-10 21:58:32 +08001020 }
1021 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001022 /* NNN resolveId errorCode */
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001023 stopResolveService(id);
1024 removeRequestMap(clientId, id, clientInfo);
Paul Hu18aeccc2022-12-27 08:48:48 +00001025 notifyResolveFailedResult(
1026 clientId == clientInfo.mClientIdForServiceUpdates,
1027 clientId, clientInfo, NsdManager.FAILURE_BAD_PARAMETERS);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001028 break;
paulhu2b9ed952022-02-10 21:58:32 +08001029 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001030 /* NNN resolveId errorCode */
1031 stopGetAddrInfo(id);
1032 removeRequestMap(clientId, id, clientInfo);
Paul Hu18aeccc2022-12-27 08:48:48 +00001033 notifyResolveFailedResult(
1034 clientId == clientInfo.mClientIdForServiceUpdates,
1035 clientId, clientInfo, NsdManager.FAILURE_BAD_PARAMETERS);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001036 break;
paulhu2b9ed952022-02-10 21:58:32 +08001037 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001038 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001039 final GetAddressInfo info = (GetAddressInfo) obj;
1040 final String address = info.address;
1041 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001042 InetAddress serviceHost = null;
1043 try {
paulhu2b9ed952022-02-10 21:58:32 +08001044 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001045 } catch (UnknownHostException e) {
1046 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1047 }
1048
1049 // If the resolved service is on an interface without a network, consider it
1050 // as a failure: it would not be usable by apps as they would need
1051 // privileged permissions.
Paul Hu18aeccc2022-12-27 08:48:48 +00001052 if (clientId == clientInfo.mClientIdForServiceUpdates) {
1053 if (netId != NETID_UNSET && serviceHost != null) {
1054 setServiceNetworkForCallback(clientInfo.mRegisteredService,
1055 netId, info.interfaceIdx);
1056 final List<InetAddress> addresses =
1057 clientInfo.mRegisteredService.getHostAddresses();
1058 addresses.add(serviceHost);
1059 clientInfo.mRegisteredService.setHostAddresses(addresses);
1060 clientInfo.onServiceUpdated(
1061 clientId, clientInfo.mRegisteredService);
1062 } else {
1063 stopGetAddrInfo(id);
1064 removeRequestMap(clientId, id, clientInfo);
1065 clearRegisteredServiceInfo(clientInfo);
1066 clientInfo.onServiceInfoCallbackRegistrationFailed(
1067 clientId, NsdManager.FAILURE_BAD_PARAMETERS);
1068 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001069 } else {
Paul Hu18aeccc2022-12-27 08:48:48 +00001070 if (netId != NETID_UNSET && serviceHost != null) {
1071 clientInfo.mResolvedService.setHost(serviceHost);
1072 setServiceNetworkForCallback(clientInfo.mResolvedService,
1073 netId, info.interfaceIdx);
1074 clientInfo.onResolveServiceSucceeded(
1075 clientId, clientInfo.mResolvedService);
1076 } else {
1077 clientInfo.onResolveServiceFailed(
1078 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1079 }
1080 stopGetAddrInfo(id);
1081 removeRequestMap(clientId, id, clientInfo);
1082 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001083 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001084 break;
paulhu2b9ed952022-02-10 21:58:32 +08001085 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001086 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001087 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001088 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001089 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001090 }
Paul Hu019621e2023-01-13 23:26:49 +08001091
1092 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(final MdnsEvent event) {
1093 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1094 final String serviceType = event.mRequestedServiceType;
1095 final String serviceName = serviceInfo.getServiceInstanceName();
1096 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1097 final Network network = serviceInfo.getNetwork();
1098 setServiceNetworkForCallback(
1099 servInfo,
1100 network == null ? NETID_UNSET : network.netId,
1101 serviceInfo.getInterfaceIndex());
1102 return servInfo;
1103 }
1104
1105 private boolean handleMdnsDiscoveryManagerEvent(
1106 int transactionId, int code, Object obj) {
1107 final ClientInfo clientInfo = mIdToClientInfoMap.get(transactionId);
1108 if (clientInfo == null) {
1109 Log.e(TAG, String.format(
1110 "id %d for %d has no client mapping", transactionId, code));
1111 return false;
1112 }
1113
1114 final MdnsEvent event = (MdnsEvent) obj;
1115 final int clientId = event.mClientId;
Paul Hu319751a2023-01-13 23:56:34 +08001116 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event);
Paul Hu019621e2023-01-13 23:26:49 +08001117 if (DBG) {
1118 Log.d(TAG, String.format("MdnsDiscoveryManager event code=%s transactionId=%d",
1119 NsdManager.nameOf(code), transactionId));
1120 }
1121 switch (code) {
1122 case NsdManager.SERVICE_FOUND:
Paul Hu319751a2023-01-13 23:56:34 +08001123 clientInfo.onServiceFound(clientId, info);
1124 break;
1125 case NsdManager.SERVICE_LOST:
1126 clientInfo.onServiceLost(clientId, info);
Paul Hu019621e2023-01-13 23:26:49 +08001127 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001128 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001129 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
1130 if (request == null) {
1131 Log.e(TAG, "Unknown client request in RESOLVE_SERVICE_SUCCEEDED");
1132 break;
1133 }
Paul Hu75069ed2023-01-14 00:31:09 +08001134 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1135 // Add '.' in front of the service type that aligns with historical behavior
1136 info.setServiceType("." + event.mRequestedServiceType);
1137 info.setPort(serviceInfo.getPort());
1138
1139 Map<String, String> attrs = serviceInfo.getAttributes();
1140 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1141 final String key = kv.getKey();
1142 try {
1143 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1144 } catch (IllegalArgumentException e) {
1145 Log.e(TAG, "Invalid attribute", e);
1146 }
1147 }
1148 try {
1149 if (serviceInfo.getIpv4Address() != null) {
1150 info.setHost(InetAddresses.parseNumericAddress(
1151 serviceInfo.getIpv4Address()));
1152 } else {
1153 info.setHost(InetAddresses.parseNumericAddress(
1154 serviceInfo.getIpv6Address()));
1155 }
1156 clientInfo.onResolveServiceSucceeded(clientId, info);
1157 } catch (IllegalArgumentException e) {
1158 Log.wtf(TAG, "Invalid address in RESOLVE_SERVICE_SUCCEEDED", e);
1159 clientInfo.onResolveServiceFailed(
1160 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1161 }
1162
1163 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001164 if (!(request instanceof DiscoveryManagerRequest)) {
1165 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1166 break;
1167 }
1168 final MdnsListener listener = ((DiscoveryManagerRequest) request).mListener;
Paul Hu75069ed2023-01-14 00:31:09 +08001169 mMdnsDiscoveryManager.unregisterListener(
1170 listener.getListenedServiceType(), listener);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001171 removeRequestMap(clientId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001172 break;
1173 }
Paul Hu019621e2023-01-13 23:26:49 +08001174 default:
1175 return false;
1176 }
1177 return true;
1178 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001179 }
1180 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001181
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001182 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1183 switch (netId) {
1184 case NETID_UNSET:
1185 info.setNetwork(null);
1186 break;
1187 case INetd.LOCAL_NET_ID:
1188 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1189 // visible / usable for apps, so do not return it. Store the interface
1190 // index instead, so at least if the client tries to resolve the service
1191 // with that NsdServiceInfo, it will be done on the same interface.
1192 // If they recreate the NsdServiceInfo themselves, resolution would be
1193 // done on all interfaces as before T, which should also work.
1194 info.setNetwork(null);
1195 info.setInterfaceIndex(ifaceIdx);
1196 break;
1197 default:
1198 info.setNetwork(new Network(netId));
1199 }
1200 }
1201
paulhube186602022-04-12 07:18:23 +00001202 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1203 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1204 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1205 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1206 private String unescape(String s) {
1207 StringBuilder sb = new StringBuilder(s.length());
1208 for (int i = 0; i < s.length(); ++i) {
1209 char c = s.charAt(i);
1210 if (c == '\\') {
1211 if (++i >= s.length()) {
1212 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1213 break;
1214 }
1215 c = s.charAt(i);
1216 if (c != '.' && c != '\\') {
1217 if (i + 2 >= s.length()) {
1218 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1219 break;
1220 }
1221 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1222 + (s.charAt(i + 2) - '0'));
1223 i += 2;
1224 }
1225 }
1226 sb.append(c);
1227 }
1228 return sb.toString();
1229 }
1230
Hugo Benichi803a2f02017-04-24 11:35:06 +09001231 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001232 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001233 this(ctx, handler, cleanupDelayMs, new Dependencies());
1234 }
1235
1236 @VisibleForTesting
1237 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001238 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001239 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001240 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001241 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001242 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1243 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001244
1245 final boolean discoveryManagerEnabled = deps.isMdnsDiscoveryManagerEnabled(ctx);
1246 final boolean advertiserEnabled = deps.isMdnsAdvertiserEnabled(ctx);
1247 if (discoveryManagerEnabled || advertiserEnabled) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001248 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper());
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001249 } else {
1250 mMdnsSocketProvider = null;
1251 }
1252
1253 if (discoveryManagerEnabled) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001254 mMdnsSocketClient =
1255 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider);
1256 mMdnsDiscoveryManager =
1257 deps.makeMdnsDiscoveryManager(new ExecutorProvider(), mMdnsSocketClient);
1258 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1259 } else {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001260 mMdnsSocketClient = null;
1261 mMdnsDiscoveryManager = null;
1262 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001263
1264 if (advertiserEnabled) {
1265 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
1266 new AdvertiserCallback());
1267 } else {
1268 mAdvertiser = null;
1269 }
Paul Hu4bd98ef2023-01-12 13:42:07 +08001270 }
1271
1272 /**
1273 * Dependencies of NsdService, for injection in tests.
1274 */
1275 @VisibleForTesting
1276 public static class Dependencies {
1277 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001278 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001279 *
1280 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001281 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001282 */
1283 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
1284 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY,
1285 MDNS_DISCOVERY_MANAGER_VERSION, false /* defaultEnabled */);
1286 }
1287
1288 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001289 * Check whether the MdnsAdvertiser feature is enabled.
1290 *
1291 * @param context The global context information about an app environment.
1292 * @return true if the MdnsAdvertiser feature is enabled.
1293 */
1294 public boolean isMdnsAdvertiserEnabled(Context context) {
1295 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY,
1296 MDNS_ADVERTISER_VERSION, false /* defaultEnabled */);
1297 }
1298
1299 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001300 * @see MdnsDiscoveryManager
1301 */
1302 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
1303 ExecutorProvider executorProvider, MdnsSocketClientBase socketClient) {
1304 return new MdnsDiscoveryManager(executorProvider, socketClient);
1305 }
1306
1307 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001308 * @see MdnsAdvertiser
1309 */
1310 public MdnsAdvertiser makeMdnsAdvertiser(
1311 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
1312 @NonNull MdnsAdvertiser.AdvertiserCallback cb) {
1313 return new MdnsAdvertiser(looper, socketProvider, cb);
1314 }
1315
1316 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001317 * @see MdnsSocketProvider
1318 */
1319 public MdnsSocketProvider makeMdnsSocketProvider(Context context, Looper looper) {
1320 return new MdnsSocketProvider(context, looper);
1321 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001322 }
1323
paulhu1b35e822022-04-08 14:48:41 +08001324 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001325 HandlerThread thread = new HandlerThread(TAG);
1326 thread.start();
1327 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001328 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001329 return service;
1330 }
1331
paulhu2b9ed952022-02-10 21:58:32 +08001332 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1333 private final StateMachine mStateMachine;
1334
1335 MDnsEventCallback(StateMachine sm) {
1336 mStateMachine = sm;
1337 }
1338
1339 @Override
1340 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1341 mStateMachine.sendMessage(
1342 MDNS_SERVICE_EVENT, status.result, status.id, status);
1343 }
1344
1345 @Override
1346 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1347 mStateMachine.sendMessage(
1348 MDNS_SERVICE_EVENT, status.result, status.id, status);
1349 }
1350
1351 @Override
1352 public void onServiceResolutionStatus(final ResolutionInfo status) {
1353 mStateMachine.sendMessage(
1354 MDNS_SERVICE_EVENT, status.result, status.id, status);
1355 }
1356
1357 @Override
1358 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1359 mStateMachine.sendMessage(
1360 MDNS_SERVICE_EVENT, status.result, status.id, status);
1361 }
1362
1363 @Override
1364 public int getInterfaceVersion() throws RemoteException {
1365 return this.VERSION;
1366 }
1367
1368 @Override
1369 public String getInterfaceHash() throws RemoteException {
1370 return this.HASH;
1371 }
1372 }
1373
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001374 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
1375 @Override
1376 public void onRegisterServiceSucceeded(int serviceId, NsdServiceInfo registeredInfo) {
1377 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1378 if (clientInfo == null) return;
1379
1380 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1381 if (clientId < 0) return;
1382
1383 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1384 // historical behavior.
1385 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
1386 clientInfo.onRegisterServiceSucceeded(clientId, cbInfo);
1387 }
1388
1389 @Override
1390 public void onRegisterServiceFailed(int serviceId, int errorCode) {
1391 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1392 if (clientInfo == null) return;
1393
1394 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1395 if (clientId < 0) return;
1396
1397 clientInfo.onRegisterServiceFailed(clientId, errorCode);
1398 }
1399
1400 private ClientInfo getClientInfoOrLog(int serviceId) {
1401 final ClientInfo clientInfo = mIdToClientInfoMap.get(serviceId);
1402 if (clientInfo == null) {
1403 Log.e(TAG, String.format("Callback for service %d has no client", serviceId));
1404 }
1405 return clientInfo;
1406 }
1407
1408 private int getClientIdOrLog(@NonNull ClientInfo info, int serviceId) {
1409 final int clientId = info.getClientId(serviceId);
1410 if (clientId < 0) {
1411 Log.e(TAG, String.format("Client ID not found for service %d", serviceId));
1412 }
1413 return clientId;
1414 }
1415 }
1416
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001417 @Override
1418 public INsdServiceConnector connect(INsdManagerCallback cb) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001419 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001420 final INsdServiceConnector connector = new NsdServiceConnector();
1421 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1422 NsdManager.REGISTER_CLIENT, new Pair<>(connector, cb)));
1423 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07001424 }
1425
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001426 private static class ListenerArgs {
1427 public final NsdServiceConnector connector;
1428 public final NsdServiceInfo serviceInfo;
1429 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
1430 this.connector = connector;
1431 this.serviceInfo = serviceInfo;
1432 }
1433 }
1434
1435 private class NsdServiceConnector extends INsdServiceConnector.Stub
1436 implements IBinder.DeathRecipient {
1437 @Override
1438 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
1439 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1440 NsdManager.REGISTER_SERVICE, 0, listenerKey,
1441 new ListenerArgs(this, serviceInfo)));
1442 }
1443
1444 @Override
1445 public void unregisterService(int listenerKey) {
1446 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1447 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
1448 new ListenerArgs(this, null)));
1449 }
1450
1451 @Override
1452 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
1453 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1454 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
1455 new ListenerArgs(this, serviceInfo)));
1456 }
1457
1458 @Override
1459 public void stopDiscovery(int listenerKey) {
1460 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1461 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
1462 }
1463
1464 @Override
1465 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
1466 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1467 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
1468 new ListenerArgs(this, serviceInfo)));
1469 }
1470
1471 @Override
Paul Hub58deb72022-12-26 09:24:42 +00001472 public void stopResolution(int listenerKey) {
1473 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1474 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
1475 }
1476
1477 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00001478 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
1479 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1480 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
1481 new ListenerArgs(this, serviceInfo)));
1482 }
1483
1484 @Override
1485 public void unregisterServiceInfoCallback(int listenerKey) {
1486 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1487 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
1488 new ListenerArgs(this, null)));
1489 }
1490
1491 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001492 public void startDaemon() {
1493 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1494 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
1495 }
1496
1497 @Override
1498 public void binderDied() {
1499 mNsdStateMachine.sendMessage(
1500 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
1501 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001502 }
1503
Hugo Benichi912db992017-04-24 16:41:03 +09001504 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07001505 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07001506 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09001507 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
1508 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07001509 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07001510 }
1511
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001512 private int getUniqueId() {
1513 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
1514 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001515 }
1516
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001517 private boolean registerService(int regId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09001518 if (DBG) {
paulhub2225702021-11-17 09:35:33 +08001519 Log.d(TAG, "registerService: " + regId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001520 }
Hugo Benichi6d706442017-04-24 16:19:58 +09001521 String name = service.getServiceName();
1522 String type = service.getServiceType();
1523 int port = service.getPort();
1524 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001525 final int registerInterface = getNetworkInterfaceIndex(service);
1526 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08001527 Log.e(TAG, "Interface to register service on not found");
1528 return false;
1529 }
1530 return mMDnsManager.registerService(regId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001531 }
1532
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001533 private boolean unregisterService(int regId) {
paulhu2b9ed952022-02-10 21:58:32 +08001534 return mMDnsManager.stopOperation(regId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001535 }
1536
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001537 private boolean discoverServices(int discoveryId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08001538 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001539 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
1540 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001541 Log.e(TAG, "Interface to discover service on not found");
1542 return false;
1543 }
paulhu2b9ed952022-02-10 21:58:32 +08001544 return mMDnsManager.discover(discoveryId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001545 }
1546
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001547 private boolean stopServiceDiscovery(int discoveryId) {
paulhu2b9ed952022-02-10 21:58:32 +08001548 return mMDnsManager.stopOperation(discoveryId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001549 }
1550
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001551 private boolean resolveService(int resolveId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001552 final String name = service.getServiceName();
1553 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001554 final int resolveInterface = getNetworkInterfaceIndex(service);
1555 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001556 Log.e(TAG, "Interface to resolve service on not found");
1557 return false;
1558 }
paulhu2b9ed952022-02-10 21:58:32 +08001559 return mMDnsManager.resolve(resolveId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001560 }
1561
1562 /**
1563 * Guess the interface to use to resolve or discover a service on a specific network.
1564 *
1565 * This is an imperfect guess, as for example the network may be gone or not yet fully
1566 * registered. This is fine as failing is correct if the network is gone, and a client
1567 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
1568 * this is to support the legacy mdnsresponder implementation, which historically resolved
1569 * services on an unspecified network.
1570 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001571 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
1572 final Network network = serviceInfo.getNetwork();
1573 if (network == null) {
1574 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
1575 // provided by NsdService from discovery results, and the service was found on an
1576 // interface that has no app-usable Network).
1577 if (serviceInfo.getInterfaceIndex() != 0) {
1578 return serviceInfo.getInterfaceIndex();
1579 }
1580 return IFACE_IDX_ANY;
1581 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001582
1583 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
1584 if (cm == null) {
1585 Log.wtf(TAG, "No ConnectivityManager for resolveService");
1586 return IFACE_IDX_ANY;
1587 }
1588 final LinkProperties lp = cm.getLinkProperties(network);
1589 if (lp == null) return IFACE_IDX_ANY;
1590
1591 // Only resolve on non-stacked interfaces
1592 final NetworkInterface iface;
1593 try {
1594 iface = NetworkInterface.getByName(lp.getInterfaceName());
1595 } catch (SocketException e) {
1596 Log.e(TAG, "Error querying interface", e);
1597 return IFACE_IDX_ANY;
1598 }
1599
1600 if (iface == null) {
1601 Log.e(TAG, "Interface not found: " + lp.getInterfaceName());
1602 return IFACE_IDX_ANY;
1603 }
1604
1605 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001606 }
1607
1608 private boolean stopResolveService(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001609 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001610 }
1611
paulhu2b9ed952022-02-10 21:58:32 +08001612 private boolean getAddrInfo(int resolveId, String hostname, int interfaceIdx) {
1613 return mMDnsManager.getServiceAddress(resolveId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001614 }
1615
1616 private boolean stopGetAddrInfo(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001617 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001618 }
1619
1620 @Override
Irfan Sheriff75006652012-04-17 23:15:29 -07001621 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
paulhu3ffffe72021-09-16 10:15:22 +08001622 if (!PermissionUtils.checkDumpPermission(mContext, TAG, pw)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001623
Irfan Sheriff75006652012-04-17 23:15:29 -07001624 for (ClientInfo client : mClients.values()) {
1625 pw.println("Client Info");
1626 pw.println(client);
1627 }
1628
1629 mNsdStateMachine.dump(fd, pw, args);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001630 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001631
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001632 private abstract static class ClientRequest {
1633 private final int mGlobalId;
1634
1635 private ClientRequest(int globalId) {
1636 mGlobalId = globalId;
1637 }
1638 }
1639
1640 private static class LegacyClientRequest extends ClientRequest {
1641 private final int mRequestCode;
1642
1643 private LegacyClientRequest(int globalId, int requestCode) {
1644 super(globalId);
1645 mRequestCode = requestCode;
1646 }
1647 }
1648
1649 private static class AdvertiserClientRequest extends ClientRequest {
1650 private AdvertiserClientRequest(int globalId) {
1651 super(globalId);
1652 }
1653 }
1654
1655 private static class DiscoveryManagerRequest extends ClientRequest {
1656 @NonNull
1657 private final MdnsListener mListener;
1658
1659 private DiscoveryManagerRequest(int globalId, @NonNull MdnsListener listener) {
1660 super(globalId);
1661 mListener = listener;
1662 }
1663 }
1664
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001665 /* Information tracked per client */
1666 private class ClientInfo {
1667
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001668 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001669 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001670 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001671 private NsdServiceInfo mResolvedService;
1672
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001673 /* A map from client-side ID (listenerKey) to the request */
1674 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08001675
Luke Huangf7277ed2021-07-12 21:15:10 +08001676 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001677 private boolean mIsPreSClient = false;
Luke Huangf7277ed2021-07-12 21:15:10 +08001678
Paul Hu18aeccc2022-12-27 08:48:48 +00001679 /*** The service that is registered to listen to its updates */
1680 private NsdServiceInfo mRegisteredService;
1681 /*** The client id that listen to updates */
1682 private int mClientIdForServiceUpdates;
1683
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001684 private ClientInfo(INsdManagerCallback cb) {
1685 mCb = cb;
paulhub2225702021-11-17 09:35:33 +08001686 if (DBG) Log.d(TAG, "New client");
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001687 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001688
1689 @Override
1690 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06001691 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07001692 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001693 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
1694 for (int i = 0; i < mClientRequests.size(); i++) {
1695 int clientID = mClientRequests.keyAt(i);
1696 sb.append("clientId ")
1697 .append(clientID)
1698 .append(" mDnsId ").append(mClientRequests.valueAt(i).mGlobalId)
1699 .append(" type ").append(
1700 mClientRequests.valueAt(i).getClass().getSimpleName())
1701 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07001702 }
1703 return sb.toString();
1704 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001705
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001706 private boolean isPreSClient() {
1707 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08001708 }
1709
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001710 private void setPreSClient() {
1711 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08001712 }
1713
Dave Plattfeff2af2014-03-07 14:48:22 -08001714 // Remove any pending requests from the global map when we get rid of a client,
1715 // and send cancellations to the daemon.
1716 private void expungeAllRequests() {
Hugo Benichid2552ae2017-04-11 14:42:47 +09001717 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001718 for (int i = 0; i < mClientRequests.size(); i++) {
1719 final int clientId = mClientRequests.keyAt(i);
1720 final ClientRequest request = mClientRequests.valueAt(i);
1721 final int globalId = request.mGlobalId;
Dave Plattfeff2af2014-03-07 14:48:22 -08001722 mIdToClientInfoMap.remove(globalId);
paulhub2225702021-11-17 09:35:33 +08001723 if (DBG) {
1724 Log.d(TAG, "Terminating client-ID " + clientId
1725 + " global-ID " + globalId + " type " + mClientRequests.get(clientId));
1726 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001727
1728 if (request instanceof DiscoveryManagerRequest) {
1729 final MdnsListener listener =
1730 ((DiscoveryManagerRequest) request).mListener;
1731 mMdnsDiscoveryManager.unregisterListener(
1732 listener.getListenedServiceType(), listener);
1733 continue;
1734 }
1735
1736 if (request instanceof AdvertiserClientRequest) {
1737 mAdvertiser.removeService(globalId);
1738 continue;
1739 }
1740
1741 if (!(request instanceof LegacyClientRequest)) {
1742 throw new IllegalStateException("Unknown request type: " + request.getClass());
1743 }
1744
1745 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08001746 case NsdManager.DISCOVER_SERVICES:
1747 stopServiceDiscovery(globalId);
1748 break;
1749 case NsdManager.RESOLVE_SERVICE:
1750 stopResolveService(globalId);
1751 break;
1752 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001753 unregisterService(globalId);
Dave Plattfeff2af2014-03-07 14:48:22 -08001754 break;
1755 default:
1756 break;
1757 }
1758 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001759 mClientRequests.clear();
1760 }
1761
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001762 // mClientRequests is a sparse array of listener id -> ClientRequest. For a given
1763 // mDnsClient id, return the corresponding listener id. mDnsClient id is also called a
1764 // global id.
Christopher Lane74411222014-04-25 18:39:07 -07001765 private int getClientId(final int globalId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001766 for (int i = 0; i < mClientRequests.size(); i++) {
1767 if (mClientRequests.valueAt(i).mGlobalId == globalId) {
1768 return mClientRequests.keyAt(i);
1769 }
Christopher Lane74411222014-04-25 18:39:07 -07001770 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001771 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07001772 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001773
Paul Hu18aeccc2022-12-27 08:48:48 +00001774 private void maybeNotifyRegisteredServiceLost(@NonNull NsdServiceInfo info) {
1775 if (mRegisteredService == null) return;
1776 if (!Objects.equals(mRegisteredService.getServiceName(), info.getServiceName())) return;
1777 // Resolved services have a leading dot appended at the beginning of their type, but in
1778 // discovered info it's at the end
1779 if (!Objects.equals(
1780 mRegisteredService.getServiceType() + ".", "." + info.getServiceType())) {
1781 return;
1782 }
1783 onServiceUpdatedLost(mClientIdForServiceUpdates);
1784 }
1785
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001786 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info) {
1787 try {
1788 mCb.onDiscoverServicesStarted(listenerKey, info);
1789 } catch (RemoteException e) {
1790 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
1791 }
1792 }
1793
1794 void onDiscoverServicesFailed(int listenerKey, int error) {
1795 try {
1796 mCb.onDiscoverServicesFailed(listenerKey, error);
1797 } catch (RemoteException e) {
1798 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
1799 }
1800 }
1801
1802 void onServiceFound(int listenerKey, NsdServiceInfo info) {
1803 try {
1804 mCb.onServiceFound(listenerKey, info);
1805 } catch (RemoteException e) {
1806 Log.e(TAG, "Error calling onServiceFound(", e);
1807 }
1808 }
1809
1810 void onServiceLost(int listenerKey, NsdServiceInfo info) {
1811 try {
1812 mCb.onServiceLost(listenerKey, info);
1813 } catch (RemoteException e) {
1814 Log.e(TAG, "Error calling onServiceLost(", e);
1815 }
1816 }
1817
1818 void onStopDiscoveryFailed(int listenerKey, int error) {
1819 try {
1820 mCb.onStopDiscoveryFailed(listenerKey, error);
1821 } catch (RemoteException e) {
1822 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
1823 }
1824 }
1825
1826 void onStopDiscoverySucceeded(int listenerKey) {
1827 try {
1828 mCb.onStopDiscoverySucceeded(listenerKey);
1829 } catch (RemoteException e) {
1830 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
1831 }
1832 }
1833
1834 void onRegisterServiceFailed(int listenerKey, int error) {
1835 try {
1836 mCb.onRegisterServiceFailed(listenerKey, error);
1837 } catch (RemoteException e) {
1838 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
1839 }
1840 }
1841
1842 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info) {
1843 try {
1844 mCb.onRegisterServiceSucceeded(listenerKey, info);
1845 } catch (RemoteException e) {
1846 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
1847 }
1848 }
1849
1850 void onUnregisterServiceFailed(int listenerKey, int error) {
1851 try {
1852 mCb.onUnregisterServiceFailed(listenerKey, error);
1853 } catch (RemoteException e) {
1854 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
1855 }
1856 }
1857
1858 void onUnregisterServiceSucceeded(int listenerKey) {
1859 try {
1860 mCb.onUnregisterServiceSucceeded(listenerKey);
1861 } catch (RemoteException e) {
1862 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
1863 }
1864 }
1865
1866 void onResolveServiceFailed(int listenerKey, int error) {
1867 try {
1868 mCb.onResolveServiceFailed(listenerKey, error);
1869 } catch (RemoteException e) {
1870 Log.e(TAG, "Error calling onResolveServiceFailed", e);
1871 }
1872 }
1873
1874 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info) {
1875 try {
1876 mCb.onResolveServiceSucceeded(listenerKey, info);
1877 } catch (RemoteException e) {
1878 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
1879 }
1880 }
Paul Hub58deb72022-12-26 09:24:42 +00001881
1882 void onStopResolutionFailed(int listenerKey, int error) {
1883 try {
1884 mCb.onStopResolutionFailed(listenerKey, error);
1885 } catch (RemoteException e) {
1886 Log.e(TAG, "Error calling onStopResolutionFailed", e);
1887 }
1888 }
1889
1890 void onStopResolutionSucceeded(int listenerKey) {
1891 try {
1892 mCb.onStopResolutionSucceeded(listenerKey);
1893 } catch (RemoteException e) {
1894 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
1895 }
1896 }
Paul Hu18aeccc2022-12-27 08:48:48 +00001897
1898 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
1899 try {
1900 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
1901 } catch (RemoteException e) {
1902 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
1903 }
1904 }
1905
1906 void onServiceUpdated(int listenerKey, NsdServiceInfo info) {
1907 try {
1908 mCb.onServiceUpdated(listenerKey, info);
1909 } catch (RemoteException e) {
1910 Log.e(TAG, "Error calling onServiceUpdated", e);
1911 }
1912 }
1913
1914 void onServiceUpdatedLost(int listenerKey) {
1915 try {
1916 mCb.onServiceUpdatedLost(listenerKey);
1917 } catch (RemoteException e) {
1918 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
1919 }
1920 }
1921
1922 void onServiceInfoCallbackUnregistered(int listenerKey) {
1923 try {
1924 mCb.onServiceInfoCallbackUnregistered(listenerKey);
1925 } catch (RemoteException e) {
1926 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
1927 }
1928 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001929 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001930}