blob: 90214849bb64e2f7498f583eb3d5b07d6c039b7a [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
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900499
500 /**
501 * Truncate a service name to up to 63 UTF-8 bytes.
502 *
503 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
504 * names used in registerService follows historical behavior (see mdnsresponder
505 * handle_regservice_request).
506 */
507 @NonNull
508 private String truncateServiceName(@NonNull String originalName) {
509 // UTF-8 is at most 4 bytes per character; return early in the common case where
510 // the name can't possibly be over the limit given its string length.
511 if (originalName.length() <= MAX_LABEL_LENGTH / 4) return originalName;
512
513 final Charset utf8 = StandardCharsets.UTF_8;
514 final CharsetEncoder encoder = utf8.newEncoder();
515 final ByteBuffer out = ByteBuffer.allocate(MAX_LABEL_LENGTH);
516 // encode will write as many characters as possible to the out buffer, and just
517 // return an overflow code if there were too many characters (no need to check the
518 // return code here, this method truncates the name on purpose).
519 encoder.encode(CharBuffer.wrap(originalName), out, true /* endOfInput */);
520 return new String(out.array(), 0, out.position(), utf8);
Paul Hu23fa2022023-01-13 22:57:24 +0800521 }
522
Paul Hue4f5f252023-02-16 21:13:47 +0800523 private void stopDiscoveryManagerRequest(ClientRequest request, int clientId, int id,
524 ClientInfo clientInfo) {
525 clientInfo.unregisterMdnsListenerFromRequest(request);
526 removeRequestMap(clientId, id, clientInfo);
527 }
528
Irfan Sheriff75006652012-04-17 23:15:29 -0700529 @Override
530 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900531 final ClientInfo clientInfo;
532 final int id;
533 final int clientId = msg.arg2;
534 final ListenerArgs args;
Irfan Sheriff75006652012-04-17 23:15:29 -0700535 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800536 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800537 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900538 args = (ListenerArgs) msg.obj;
539 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000540 // If the binder death notification for a INsdManagerCallback was received
541 // before any calls are received by NsdService, the clientInfo would be
542 // cleared and cause NPE. Add a null check here to prevent this corner case.
543 if (clientInfo == null) {
544 Log.e(TAG, "Unknown connector in discovery");
545 break;
546 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700547
548 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900549 clientInfo.onDiscoverServicesFailed(
550 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriff75006652012-04-17 23:15:29 -0700551 break;
552 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700553
Paul Hu23fa2022023-01-13 22:57:24 +0800554 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700555 id = getUniqueId();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900556 if (mDeps.isMdnsDiscoveryManagerEnabled(mContext)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800557 final String serviceType = constructServiceType(info.getServiceType());
558 if (serviceType == null) {
559 clientInfo.onDiscoverServicesFailed(clientId,
560 NsdManager.FAILURE_INTERNAL_ERROR);
561 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700562 }
Paul Hu23fa2022023-01-13 22:57:24 +0800563
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900564 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800565 maybeStartMonitoringSockets();
566 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900567 new DiscoveryListener(clientId, id, info, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800568 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
569 .setNetwork(info.getNetwork())
570 .setIsPassiveMode(true)
571 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900572 mMdnsDiscoveryManager.registerListener(
573 listenServiceType, listener, options);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900574 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800575 clientInfo.onDiscoverServicesStarted(clientId, info);
Irfan Sheriff75006652012-04-17 23:15:29 -0700576 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800577 maybeStartDaemon();
578 if (discoverServices(id, info)) {
579 if (DBG) {
580 Log.d(TAG, "Discover " + msg.arg2 + " " + id
581 + info.getServiceType());
582 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900583 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu23fa2022023-01-13 22:57:24 +0800584 clientInfo.onDiscoverServicesStarted(clientId, info);
585 } else {
586 stopServiceDiscovery(id);
587 clientInfo.onDiscoverServicesFailed(clientId,
588 NsdManager.FAILURE_INTERNAL_ERROR);
589 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700590 }
591 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800592 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900593 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800594 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900595 args = (ListenerArgs) msg.obj;
596 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000597 // If the binder death notification for a INsdManagerCallback was received
598 // before any calls are received by NsdService, the clientInfo would be
599 // cleared and cause NPE. Add a null check here to prevent this corner case.
600 if (clientInfo == null) {
601 Log.e(TAG, "Unknown connector in stop discovery");
602 break;
603 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700604
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900605 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
606 if (request == null) {
607 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700608 break;
609 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900610 id = request.mGlobalId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900611 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
612 // point, so this needs to check the type of the original request to
613 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900614 if (request instanceof DiscoveryManagerRequest) {
Paul Hue4f5f252023-02-16 21:13:47 +0800615 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900616 clientInfo.onStopDiscoverySucceeded(clientId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700617 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800618 removeRequestMap(clientId, id, clientInfo);
619 if (stopServiceDiscovery(id)) {
620 clientInfo.onStopDiscoverySucceeded(clientId);
621 } else {
622 clientInfo.onStopDiscoveryFailed(
623 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
624 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700625 }
626 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900627 }
628 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800629 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900630 args = (ListenerArgs) msg.obj;
631 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000632 // If the binder death notification for a INsdManagerCallback was received
633 // before any calls are received by NsdService, the clientInfo would be
634 // cleared and cause NPE. Add a null check here to prevent this corner case.
635 if (clientInfo == null) {
636 Log.e(TAG, "Unknown connector in registration");
637 break;
638 }
639
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700640 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900641 clientInfo.onRegisterServiceFailed(
642 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700643 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700644 }
645
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700646 id = getUniqueId();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900647 if (mDeps.isMdnsAdvertiserEnabled(mContext)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900648 final NsdServiceInfo serviceInfo = args.serviceInfo;
649 final String serviceType = serviceInfo.getServiceType();
650 final String registerServiceType = constructServiceType(serviceType);
651 if (registerServiceType == null) {
652 Log.e(TAG, "Invalid service type: " + serviceType);
653 clientInfo.onRegisterServiceFailed(clientId,
654 NsdManager.FAILURE_INTERNAL_ERROR);
655 break;
656 }
657 serviceInfo.setServiceType(registerServiceType);
658 serviceInfo.setServiceName(truncateServiceName(
659 serviceInfo.getServiceName()));
660
661 maybeStartMonitoringSockets();
662 mAdvertiser.addService(id, serviceInfo);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900663 storeAdvertiserRequestMap(clientId, id, clientInfo);
Irfan Sheriff75006652012-04-17 23:15:29 -0700664 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900665 maybeStartDaemon();
666 if (registerService(id, args.serviceInfo)) {
667 if (DBG) Log.d(TAG, "Register " + clientId + " " + id);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900668 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900669 // Return success after mDns reports success
670 } else {
671 unregisterService(id);
672 clientInfo.onRegisterServiceFailed(
673 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
674 }
675
Irfan Sheriff75006652012-04-17 23:15:29 -0700676 }
677 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900678 }
679 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800680 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900681 args = (ListenerArgs) msg.obj;
682 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000683 // If the binder death notification for a INsdManagerCallback was received
684 // before any calls are received by NsdService, the clientInfo would be
685 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900686 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800687 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700688 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700689 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900690 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
691 if (request == null) {
692 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
693 break;
694 }
695 id = request.mGlobalId;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900696 removeRequestMap(clientId, id, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900697
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900698 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
699 // so this needs to check the type of the original request to unregister
700 // instead of looking at the flag value.
701 if (request instanceof AdvertiserClientRequest) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900702 mAdvertiser.removeService(id);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900703 clientInfo.onUnregisterServiceSucceeded(clientId);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700704 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900705 if (unregisterService(id)) {
706 clientInfo.onUnregisterServiceSucceeded(clientId);
707 } else {
708 clientInfo.onUnregisterServiceFailed(
709 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
710 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700711 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700712 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900713 }
Paul Hu75069ed2023-01-14 00:31:09 +0800714 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800715 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900716 args = (ListenerArgs) msg.obj;
717 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000718 // If the binder death notification for a INsdManagerCallback was received
719 // before any calls are received by NsdService, the clientInfo would be
720 // cleared and cause NPE. Add a null check here to prevent this corner case.
721 if (clientInfo == null) {
722 Log.e(TAG, "Unknown connector in resolution");
723 break;
724 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700725
Paul Hu75069ed2023-01-14 00:31:09 +0800726 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700727 id = getUniqueId();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900728 if (mDeps.isMdnsDiscoveryManagerEnabled(mContext)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800729 final String serviceType = constructServiceType(info.getServiceType());
730 if (serviceType == null) {
731 clientInfo.onResolveServiceFailed(clientId,
732 NsdManager.FAILURE_INTERNAL_ERROR);
733 break;
734 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900735 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +0800736
737 maybeStartMonitoringSockets();
738 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900739 new ResolutionListener(clientId, id, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800740 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
741 .setNetwork(info.getNetwork())
742 .setIsPassiveMode(true)
743 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900744 mMdnsDiscoveryManager.registerListener(
745 resolveServiceType, listener, options);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900746 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Irfan Sheriff75006652012-04-17 23:15:29 -0700747 } else {
Paul Hu75069ed2023-01-14 00:31:09 +0800748 if (clientInfo.mResolvedService != null) {
749 clientInfo.onResolveServiceFailed(
750 clientId, NsdManager.FAILURE_ALREADY_ACTIVE);
751 break;
752 }
753
754 maybeStartDaemon();
755 if (resolveService(id, args.serviceInfo)) {
756 clientInfo.mResolvedService = new NsdServiceInfo();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900757 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu75069ed2023-01-14 00:31:09 +0800758 } else {
759 clientInfo.onResolveServiceFailed(
760 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
761 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700762 }
763 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800764 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900765 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +0000766 if (DBG) Log.d(TAG, "Stop service resolution");
767 args = (ListenerArgs) msg.obj;
768 clientInfo = mClients.get(args.connector);
769 // If the binder death notification for a INsdManagerCallback was received
770 // before any calls are received by NsdService, the clientInfo would be
771 // cleared and cause NPE. Add a null check here to prevent this corner case.
772 if (clientInfo == null) {
773 Log.e(TAG, "Unknown connector in stop resolution");
774 break;
775 }
776
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900777 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
778 if (request == null) {
779 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
780 break;
781 }
782 id = request.mGlobalId;
Paul Hue4f5f252023-02-16 21:13:47 +0800783 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
784 // point, so this needs to check the type of the original request to
785 // unregister instead of looking at the flag value.
786 if (request instanceof DiscoveryManagerRequest) {
787 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Paul Hub58deb72022-12-26 09:24:42 +0000788 clientInfo.onStopResolutionSucceeded(clientId);
789 } else {
Paul Hue4f5f252023-02-16 21:13:47 +0800790 removeRequestMap(clientId, id, clientInfo);
791 if (stopResolveService(id)) {
792 clientInfo.onStopResolutionSucceeded(clientId);
793 } else {
794 clientInfo.onStopResolutionFailed(
795 clientId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
796 }
797 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +0000798 }
Paul Hub58deb72022-12-26 09:24:42 +0000799 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900800 }
Paul Hu18aeccc2022-12-27 08:48:48 +0000801 case NsdManager.REGISTER_SERVICE_CALLBACK:
802 if (DBG) Log.d(TAG, "Register a service callback");
803 args = (ListenerArgs) msg.obj;
804 clientInfo = mClients.get(args.connector);
805 // If the binder death notification for a INsdManagerCallback was received
806 // before any calls are received by NsdService, the clientInfo would be
807 // cleared and cause NPE. Add a null check here to prevent this corner case.
808 if (clientInfo == null) {
809 Log.e(TAG, "Unknown connector in callback registration");
810 break;
811 }
812
813 if (clientInfo.mRegisteredService != null) {
814 clientInfo.onServiceInfoCallbackRegistrationFailed(
815 clientId, NsdManager.FAILURE_ALREADY_ACTIVE);
816 break;
817 }
818
819 maybeStartDaemon();
820 id = getUniqueId();
821 if (resolveService(id, args.serviceInfo)) {
822 clientInfo.mRegisteredService = new NsdServiceInfo();
823 clientInfo.mClientIdForServiceUpdates = clientId;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900824 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu18aeccc2022-12-27 08:48:48 +0000825 } else {
826 clientInfo.onServiceInfoCallbackRegistrationFailed(
827 clientId, NsdManager.FAILURE_BAD_PARAMETERS);
828 }
829 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900830 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +0000831 if (DBG) Log.d(TAG, "Unregister a service callback");
832 args = (ListenerArgs) msg.obj;
833 clientInfo = mClients.get(args.connector);
834 // If the binder death notification for a INsdManagerCallback was received
835 // before any calls are received by NsdService, the clientInfo would be
836 // cleared and cause NPE. Add a null check here to prevent this corner case.
837 if (clientInfo == null) {
838 Log.e(TAG, "Unknown connector in callback unregistration");
839 break;
840 }
841
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900842 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
843 if (request == null) {
844 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
845 break;
846 }
847 id = request.mGlobalId;
Paul Hu18aeccc2022-12-27 08:48:48 +0000848 removeRequestMap(clientId, id, clientInfo);
849 if (stopResolveService(id)) {
850 clientInfo.onServiceInfoCallbackUnregistered(clientId);
851 } else {
852 Log.e(TAG, "Failed to unregister service info callback");
853 }
854 clearRegisteredServiceInfo(clientInfo);
855 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900856 }
paulhu2b9ed952022-02-10 21:58:32 +0800857 case MDNS_SERVICE_EVENT:
858 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +0900859 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700860 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700861 break;
Paul Hu019621e2023-01-13 23:26:49 +0800862 case MDNS_DISCOVERY_MANAGER_EVENT:
863 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
864 return NOT_HANDLED;
865 }
866 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700867 default:
Hugo Benichif0c84092017-04-05 14:43:29 +0900868 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700869 }
Hugo Benichif0c84092017-04-05 14:43:29 +0900870 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700871 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700872
Paul Hu18aeccc2022-12-27 08:48:48 +0000873 private void notifyResolveFailedResult(boolean isListenedToUpdates, int clientId,
874 ClientInfo clientInfo, int error) {
875 if (isListenedToUpdates) {
876 clientInfo.onServiceInfoCallbackRegistrationFailed(clientId, error);
877 clearRegisteredServiceInfo(clientInfo);
878 } else {
879 // The resolve API always returned FAILURE_INTERNAL_ERROR on error; keep it
880 // for backwards compatibility.
881 clientInfo.onResolveServiceFailed(clientId, NsdManager.FAILURE_INTERNAL_ERROR);
882 clientInfo.mResolvedService = null;
883 }
884 }
885
paulhu2b9ed952022-02-10 21:58:32 +0800886 private boolean handleMDnsServiceEvent(int code, int id, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700887 NsdServiceInfo servInfo;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700888 ClientInfo clientInfo = mIdToClientInfoMap.get(id);
889 if (clientInfo == null) {
paulhu2b9ed952022-02-10 21:58:32 +0800890 Log.e(TAG, String.format("id %d for %d has no client mapping", id, code));
Hugo Benichif0c84092017-04-05 14:43:29 +0900891 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700892 }
893
894 /* This goes in response as msg.arg2 */
Christopher Lane74411222014-04-25 18:39:07 -0700895 int clientId = clientInfo.getClientId(id);
896 if (clientId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -0700897 // This can happen because of race conditions. For example,
898 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
899 // and we may get in this situation.
paulhu2b9ed952022-02-10 21:58:32 +0800900 Log.d(TAG, String.format("%d for listener id %d that is no longer active",
901 code, id));
Hugo Benichif0c84092017-04-05 14:43:29 +0900902 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700903 }
Hugo Benichi32be63d2017-04-05 14:06:11 +0900904 if (DBG) {
paulhu2b9ed952022-02-10 21:58:32 +0800905 Log.d(TAG, String.format("MDns service event code:%d id=%d", code, id));
Hugo Benichi32be63d2017-04-05 14:06:11 +0900906 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700907 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +0800908 case IMDnsEventListener.SERVICE_FOUND: {
909 final DiscoveryInfo info = (DiscoveryInfo) obj;
910 final String name = info.serviceName;
911 final String type = info.registrationType;
912 servInfo = new NsdServiceInfo(name, type);
913 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900914 if (foundNetId == 0L) {
915 // Ignore services that do not have a Network: they are not usable
916 // by apps, as they would need privileged permissions to use
917 // interfaces that do not have an associated Network.
918 break;
919 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +0900920 if (foundNetId == INetd.DUMMY_NET_ID) {
921 // Ignore services on the dummy0 interface: they are only seen when
922 // discovering locally advertised services, and are not reachable
923 // through that interface.
924 break;
925 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900926 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900927 clientInfo.onServiceFound(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700928 break;
paulhu2b9ed952022-02-10 21:58:32 +0800929 }
930 case IMDnsEventListener.SERVICE_LOST: {
931 final DiscoveryInfo info = (DiscoveryInfo) obj;
932 final String name = info.serviceName;
933 final String type = info.registrationType;
934 final int lostNetId = info.netId;
935 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900936 // The network could be set to null (netId 0) if it was torn down when the
937 // service is lost
938 // TODO: avoid returning null in that case, possibly by remembering
939 // found services on the same interface index and their network at the time
940 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900941 clientInfo.onServiceLost(clientId, servInfo);
Paul Hu18aeccc2022-12-27 08:48:48 +0000942 // TODO: also support registered service lost when not discovering
943 clientInfo.maybeNotifyRegisteredServiceLost(servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700944 break;
paulhu2b9ed952022-02-10 21:58:32 +0800945 }
946 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900947 clientInfo.onDiscoverServicesFailed(
948 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700949 break;
paulhu2b9ed952022-02-10 21:58:32 +0800950 case IMDnsEventListener.SERVICE_REGISTERED: {
951 final RegistrationInfo info = (RegistrationInfo) obj;
952 final String name = info.serviceName;
953 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900954 clientInfo.onRegisterServiceSucceeded(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700955 break;
paulhu2b9ed952022-02-10 21:58:32 +0800956 }
957 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900958 clientInfo.onRegisterServiceFailed(
959 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700960 break;
paulhu2b9ed952022-02-10 21:58:32 +0800961 case IMDnsEventListener.SERVICE_RESOLVED: {
962 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -0700963 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +0800964 final String fullName = info.serviceFullName;
965 while (index < fullName.length() && fullName.charAt(index) != '.') {
966 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -0700967 ++index;
968 }
969 ++index;
970 }
paulhu2b9ed952022-02-10 21:58:32 +0800971 if (index >= fullName.length()) {
972 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700973 break;
974 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900975
paulhube186602022-04-12 07:18:23 +0000976 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +0800977 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700978 String type = rest.replace(".local.", "");
979
Paul Hu18aeccc2022-12-27 08:48:48 +0000980 final boolean isListenedToUpdates =
981 clientId == clientInfo.mClientIdForServiceUpdates;
982 final NsdServiceInfo serviceInfo = isListenedToUpdates
983 ? clientInfo.mRegisteredService : clientInfo.mResolvedService;
984
985 serviceInfo.setServiceName(name);
986 serviceInfo.setServiceType(type);
987 serviceInfo.setPort(info.port);
988 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900989 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700990
991 stopResolveService(id);
Vinit Deshapnde4429e872013-11-12 15:36:37 -0800992 removeRequestMap(clientId, id, clientInfo);
993
paulhu2b9ed952022-02-10 21:58:32 +0800994 final int id2 = getUniqueId();
995 if (getAddrInfo(id2, info.hostname, info.interfaceIdx)) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900996 storeLegacyRequestMap(clientId, id2, clientInfo,
997 NsdManager.RESOLVE_SERVICE);
Vinit Deshapnde4429e872013-11-12 15:36:37 -0800998 } else {
Paul Hu18aeccc2022-12-27 08:48:48 +0000999 notifyResolveFailedResult(isListenedToUpdates, clientId, clientInfo,
1000 NsdManager.FAILURE_BAD_PARAMETERS);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001001 }
1002 break;
paulhu2b9ed952022-02-10 21:58:32 +08001003 }
1004 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001005 /* NNN resolveId errorCode */
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001006 stopResolveService(id);
1007 removeRequestMap(clientId, id, clientInfo);
Paul Hu18aeccc2022-12-27 08:48:48 +00001008 notifyResolveFailedResult(
1009 clientId == clientInfo.mClientIdForServiceUpdates,
1010 clientId, clientInfo, NsdManager.FAILURE_BAD_PARAMETERS);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001011 break;
paulhu2b9ed952022-02-10 21:58:32 +08001012 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001013 /* NNN resolveId errorCode */
1014 stopGetAddrInfo(id);
1015 removeRequestMap(clientId, id, clientInfo);
Paul Hu18aeccc2022-12-27 08:48:48 +00001016 notifyResolveFailedResult(
1017 clientId == clientInfo.mClientIdForServiceUpdates,
1018 clientId, clientInfo, NsdManager.FAILURE_BAD_PARAMETERS);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001019 break;
paulhu2b9ed952022-02-10 21:58:32 +08001020 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001021 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001022 final GetAddressInfo info = (GetAddressInfo) obj;
1023 final String address = info.address;
1024 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001025 InetAddress serviceHost = null;
1026 try {
paulhu2b9ed952022-02-10 21:58:32 +08001027 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001028 } catch (UnknownHostException e) {
1029 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1030 }
1031
1032 // If the resolved service is on an interface without a network, consider it
1033 // as a failure: it would not be usable by apps as they would need
1034 // privileged permissions.
Paul Hu18aeccc2022-12-27 08:48:48 +00001035 if (clientId == clientInfo.mClientIdForServiceUpdates) {
1036 if (netId != NETID_UNSET && serviceHost != null) {
1037 setServiceNetworkForCallback(clientInfo.mRegisteredService,
1038 netId, info.interfaceIdx);
1039 final List<InetAddress> addresses =
1040 clientInfo.mRegisteredService.getHostAddresses();
1041 addresses.add(serviceHost);
1042 clientInfo.mRegisteredService.setHostAddresses(addresses);
1043 clientInfo.onServiceUpdated(
1044 clientId, clientInfo.mRegisteredService);
1045 } else {
1046 stopGetAddrInfo(id);
1047 removeRequestMap(clientId, id, clientInfo);
1048 clearRegisteredServiceInfo(clientInfo);
1049 clientInfo.onServiceInfoCallbackRegistrationFailed(
1050 clientId, NsdManager.FAILURE_BAD_PARAMETERS);
1051 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001052 } else {
Paul Hu18aeccc2022-12-27 08:48:48 +00001053 if (netId != NETID_UNSET && serviceHost != null) {
1054 clientInfo.mResolvedService.setHost(serviceHost);
1055 setServiceNetworkForCallback(clientInfo.mResolvedService,
1056 netId, info.interfaceIdx);
1057 clientInfo.onResolveServiceSucceeded(
1058 clientId, clientInfo.mResolvedService);
1059 } else {
1060 clientInfo.onResolveServiceFailed(
1061 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1062 }
1063 stopGetAddrInfo(id);
1064 removeRequestMap(clientId, id, clientInfo);
1065 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001066 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001067 break;
paulhu2b9ed952022-02-10 21:58:32 +08001068 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001069 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001070 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001071 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001072 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001073 }
Paul Hu019621e2023-01-13 23:26:49 +08001074
1075 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(final MdnsEvent event) {
1076 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1077 final String serviceType = event.mRequestedServiceType;
1078 final String serviceName = serviceInfo.getServiceInstanceName();
1079 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1080 final Network network = serviceInfo.getNetwork();
1081 setServiceNetworkForCallback(
1082 servInfo,
1083 network == null ? NETID_UNSET : network.netId,
1084 serviceInfo.getInterfaceIndex());
1085 return servInfo;
1086 }
1087
1088 private boolean handleMdnsDiscoveryManagerEvent(
1089 int transactionId, int code, Object obj) {
1090 final ClientInfo clientInfo = mIdToClientInfoMap.get(transactionId);
1091 if (clientInfo == null) {
1092 Log.e(TAG, String.format(
1093 "id %d for %d has no client mapping", transactionId, code));
1094 return false;
1095 }
1096
1097 final MdnsEvent event = (MdnsEvent) obj;
1098 final int clientId = event.mClientId;
Paul Hu319751a2023-01-13 23:56:34 +08001099 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event);
Paul Hu019621e2023-01-13 23:26:49 +08001100 if (DBG) {
1101 Log.d(TAG, String.format("MdnsDiscoveryManager event code=%s transactionId=%d",
1102 NsdManager.nameOf(code), transactionId));
1103 }
1104 switch (code) {
1105 case NsdManager.SERVICE_FOUND:
Paul Hu319751a2023-01-13 23:56:34 +08001106 clientInfo.onServiceFound(clientId, info);
1107 break;
1108 case NsdManager.SERVICE_LOST:
1109 clientInfo.onServiceLost(clientId, info);
Paul Hu019621e2023-01-13 23:26:49 +08001110 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001111 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001112 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
1113 if (request == null) {
1114 Log.e(TAG, "Unknown client request in RESOLVE_SERVICE_SUCCEEDED");
1115 break;
1116 }
Paul Hu75069ed2023-01-14 00:31:09 +08001117 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1118 // Add '.' in front of the service type that aligns with historical behavior
1119 info.setServiceType("." + event.mRequestedServiceType);
1120 info.setPort(serviceInfo.getPort());
1121
1122 Map<String, String> attrs = serviceInfo.getAttributes();
1123 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1124 final String key = kv.getKey();
1125 try {
1126 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1127 } catch (IllegalArgumentException e) {
1128 Log.e(TAG, "Invalid attribute", e);
1129 }
1130 }
1131 try {
1132 if (serviceInfo.getIpv4Address() != null) {
1133 info.setHost(InetAddresses.parseNumericAddress(
1134 serviceInfo.getIpv4Address()));
1135 } else {
1136 info.setHost(InetAddresses.parseNumericAddress(
1137 serviceInfo.getIpv6Address()));
1138 }
1139 clientInfo.onResolveServiceSucceeded(clientId, info);
1140 } catch (IllegalArgumentException e) {
1141 Log.wtf(TAG, "Invalid address in RESOLVE_SERVICE_SUCCEEDED", e);
1142 clientInfo.onResolveServiceFailed(
1143 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1144 }
1145
1146 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001147 if (!(request instanceof DiscoveryManagerRequest)) {
1148 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1149 break;
1150 }
Paul Hue4f5f252023-02-16 21:13:47 +08001151 stopDiscoveryManagerRequest(request, clientId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001152 break;
1153 }
Paul Hu019621e2023-01-13 23:26:49 +08001154 default:
1155 return false;
1156 }
1157 return true;
1158 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001159 }
1160 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001161
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001162 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1163 switch (netId) {
1164 case NETID_UNSET:
1165 info.setNetwork(null);
1166 break;
1167 case INetd.LOCAL_NET_ID:
1168 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1169 // visible / usable for apps, so do not return it. Store the interface
1170 // index instead, so at least if the client tries to resolve the service
1171 // with that NsdServiceInfo, it will be done on the same interface.
1172 // If they recreate the NsdServiceInfo themselves, resolution would be
1173 // done on all interfaces as before T, which should also work.
1174 info.setNetwork(null);
1175 info.setInterfaceIndex(ifaceIdx);
1176 break;
1177 default:
1178 info.setNetwork(new Network(netId));
1179 }
1180 }
1181
paulhube186602022-04-12 07:18:23 +00001182 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1183 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1184 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1185 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1186 private String unescape(String s) {
1187 StringBuilder sb = new StringBuilder(s.length());
1188 for (int i = 0; i < s.length(); ++i) {
1189 char c = s.charAt(i);
1190 if (c == '\\') {
1191 if (++i >= s.length()) {
1192 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1193 break;
1194 }
1195 c = s.charAt(i);
1196 if (c != '.' && c != '\\') {
1197 if (i + 2 >= s.length()) {
1198 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1199 break;
1200 }
1201 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1202 + (s.charAt(i + 2) - '0'));
1203 i += 2;
1204 }
1205 }
1206 sb.append(c);
1207 }
1208 return sb.toString();
1209 }
1210
Paul Hu7445e3d2023-03-03 15:14:00 +08001211 /**
1212 * Check the given service type is valid and construct it to a service type
1213 * which can use for discovery / resolution service.
1214 *
1215 * <p> The valid service type should be 2 labels, or 3 labels if the query is for a
1216 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1217 * underscore; they are alphanumerical characters or dashes or underscore, except the
1218 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1219 *
1220 * @param serviceType the request service type for discovery / resolution service
1221 * @return constructed service type or null if the given service type is invalid.
1222 */
1223 @Nullable
1224 public static String constructServiceType(String serviceType) {
1225 if (TextUtils.isEmpty(serviceType)) return null;
1226
1227 final Pattern serviceTypePattern = Pattern.compile(
1228 "^(_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]\\.)?"
1229 + "(_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]\\._(?:tcp|udp))"
1230 // Drop '.' at the end of service type that is compatible with old backend.
1231 + "\\.?$");
1232 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1233 if (!matcher.matches()) return null;
1234 return matcher.group(1) == null
1235 ? matcher.group(2)
1236 : matcher.group(1) + "_sub." + matcher.group(2);
1237 }
1238
Hugo Benichi803a2f02017-04-24 11:35:06 +09001239 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001240 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001241 this(ctx, handler, cleanupDelayMs, new Dependencies());
1242 }
1243
1244 @VisibleForTesting
1245 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001246 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001247 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001248 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001249 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001250 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1251 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001252 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001253
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001254 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper());
1255 mMdnsSocketClient =
1256 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider);
1257 mMdnsDiscoveryManager =
1258 deps.makeMdnsDiscoveryManager(new ExecutorProvider(), mMdnsSocketClient);
1259 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1260 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
1261 new AdvertiserCallback());
Paul Hu4bd98ef2023-01-12 13:42:07 +08001262 }
1263
1264 /**
1265 * Dependencies of NsdService, for injection in tests.
1266 */
1267 @VisibleForTesting
1268 public static class Dependencies {
1269 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001270 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001271 *
1272 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001273 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001274 */
1275 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
1276 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY,
1277 MDNS_DISCOVERY_MANAGER_VERSION, false /* defaultEnabled */);
1278 }
1279
1280 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001281 * Check whether the MdnsAdvertiser feature is enabled.
1282 *
1283 * @param context The global context information about an app environment.
1284 * @return true if the MdnsAdvertiser feature is enabled.
1285 */
1286 public boolean isMdnsAdvertiserEnabled(Context context) {
1287 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY,
1288 MDNS_ADVERTISER_VERSION, false /* defaultEnabled */);
1289 }
1290
1291 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001292 * @see MdnsDiscoveryManager
1293 */
1294 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
1295 ExecutorProvider executorProvider, MdnsSocketClientBase socketClient) {
1296 return new MdnsDiscoveryManager(executorProvider, socketClient);
1297 }
1298
1299 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001300 * @see MdnsAdvertiser
1301 */
1302 public MdnsAdvertiser makeMdnsAdvertiser(
1303 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
1304 @NonNull MdnsAdvertiser.AdvertiserCallback cb) {
1305 return new MdnsAdvertiser(looper, socketProvider, cb);
1306 }
1307
1308 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001309 * @see MdnsSocketProvider
1310 */
1311 public MdnsSocketProvider makeMdnsSocketProvider(Context context, Looper looper) {
1312 return new MdnsSocketProvider(context, looper);
1313 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001314 }
1315
paulhu1b35e822022-04-08 14:48:41 +08001316 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001317 HandlerThread thread = new HandlerThread(TAG);
1318 thread.start();
1319 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001320 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001321 return service;
1322 }
1323
paulhu2b9ed952022-02-10 21:58:32 +08001324 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1325 private final StateMachine mStateMachine;
1326
1327 MDnsEventCallback(StateMachine sm) {
1328 mStateMachine = sm;
1329 }
1330
1331 @Override
1332 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1333 mStateMachine.sendMessage(
1334 MDNS_SERVICE_EVENT, status.result, status.id, status);
1335 }
1336
1337 @Override
1338 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1339 mStateMachine.sendMessage(
1340 MDNS_SERVICE_EVENT, status.result, status.id, status);
1341 }
1342
1343 @Override
1344 public void onServiceResolutionStatus(final ResolutionInfo status) {
1345 mStateMachine.sendMessage(
1346 MDNS_SERVICE_EVENT, status.result, status.id, status);
1347 }
1348
1349 @Override
1350 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1351 mStateMachine.sendMessage(
1352 MDNS_SERVICE_EVENT, status.result, status.id, status);
1353 }
1354
1355 @Override
1356 public int getInterfaceVersion() throws RemoteException {
1357 return this.VERSION;
1358 }
1359
1360 @Override
1361 public String getInterfaceHash() throws RemoteException {
1362 return this.HASH;
1363 }
1364 }
1365
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001366 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
1367 @Override
1368 public void onRegisterServiceSucceeded(int serviceId, NsdServiceInfo registeredInfo) {
1369 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1370 if (clientInfo == null) return;
1371
1372 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1373 if (clientId < 0) return;
1374
1375 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1376 // historical behavior.
1377 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
1378 clientInfo.onRegisterServiceSucceeded(clientId, cbInfo);
1379 }
1380
1381 @Override
1382 public void onRegisterServiceFailed(int serviceId, int errorCode) {
1383 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1384 if (clientInfo == null) return;
1385
1386 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1387 if (clientId < 0) return;
1388
1389 clientInfo.onRegisterServiceFailed(clientId, errorCode);
1390 }
1391
1392 private ClientInfo getClientInfoOrLog(int serviceId) {
1393 final ClientInfo clientInfo = mIdToClientInfoMap.get(serviceId);
1394 if (clientInfo == null) {
1395 Log.e(TAG, String.format("Callback for service %d has no client", serviceId));
1396 }
1397 return clientInfo;
1398 }
1399
1400 private int getClientIdOrLog(@NonNull ClientInfo info, int serviceId) {
1401 final int clientId = info.getClientId(serviceId);
1402 if (clientId < 0) {
1403 Log.e(TAG, String.format("Client ID not found for service %d", serviceId));
1404 }
1405 return clientId;
1406 }
1407 }
1408
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001409 @Override
1410 public INsdServiceConnector connect(INsdManagerCallback cb) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001411 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001412 final INsdServiceConnector connector = new NsdServiceConnector();
1413 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1414 NsdManager.REGISTER_CLIENT, new Pair<>(connector, cb)));
1415 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07001416 }
1417
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001418 private static class ListenerArgs {
1419 public final NsdServiceConnector connector;
1420 public final NsdServiceInfo serviceInfo;
1421 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
1422 this.connector = connector;
1423 this.serviceInfo = serviceInfo;
1424 }
1425 }
1426
1427 private class NsdServiceConnector extends INsdServiceConnector.Stub
1428 implements IBinder.DeathRecipient {
1429 @Override
1430 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
1431 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1432 NsdManager.REGISTER_SERVICE, 0, listenerKey,
1433 new ListenerArgs(this, serviceInfo)));
1434 }
1435
1436 @Override
1437 public void unregisterService(int listenerKey) {
1438 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1439 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
1440 new ListenerArgs(this, null)));
1441 }
1442
1443 @Override
1444 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
1445 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1446 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
1447 new ListenerArgs(this, serviceInfo)));
1448 }
1449
1450 @Override
1451 public void stopDiscovery(int listenerKey) {
1452 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1453 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
1454 }
1455
1456 @Override
1457 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
1458 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1459 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
1460 new ListenerArgs(this, serviceInfo)));
1461 }
1462
1463 @Override
Paul Hub58deb72022-12-26 09:24:42 +00001464 public void stopResolution(int listenerKey) {
1465 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1466 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
1467 }
1468
1469 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00001470 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
1471 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1472 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
1473 new ListenerArgs(this, serviceInfo)));
1474 }
1475
1476 @Override
1477 public void unregisterServiceInfoCallback(int listenerKey) {
1478 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1479 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
1480 new ListenerArgs(this, null)));
1481 }
1482
1483 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001484 public void startDaemon() {
1485 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1486 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
1487 }
1488
1489 @Override
1490 public void binderDied() {
1491 mNsdStateMachine.sendMessage(
1492 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
1493 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001494 }
1495
Hugo Benichi912db992017-04-24 16:41:03 +09001496 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07001497 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07001498 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09001499 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
1500 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07001501 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07001502 }
1503
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001504 private int getUniqueId() {
1505 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
1506 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001507 }
1508
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001509 private boolean registerService(int regId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09001510 if (DBG) {
paulhub2225702021-11-17 09:35:33 +08001511 Log.d(TAG, "registerService: " + regId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001512 }
Hugo Benichi6d706442017-04-24 16:19:58 +09001513 String name = service.getServiceName();
1514 String type = service.getServiceType();
1515 int port = service.getPort();
1516 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001517 final int registerInterface = getNetworkInterfaceIndex(service);
1518 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08001519 Log.e(TAG, "Interface to register service on not found");
1520 return false;
1521 }
1522 return mMDnsManager.registerService(regId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001523 }
1524
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001525 private boolean unregisterService(int regId) {
paulhu2b9ed952022-02-10 21:58:32 +08001526 return mMDnsManager.stopOperation(regId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001527 }
1528
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001529 private boolean discoverServices(int discoveryId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08001530 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001531 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
1532 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001533 Log.e(TAG, "Interface to discover service on not found");
1534 return false;
1535 }
paulhu2b9ed952022-02-10 21:58:32 +08001536 return mMDnsManager.discover(discoveryId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001537 }
1538
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001539 private boolean stopServiceDiscovery(int discoveryId) {
paulhu2b9ed952022-02-10 21:58:32 +08001540 return mMDnsManager.stopOperation(discoveryId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001541 }
1542
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001543 private boolean resolveService(int resolveId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001544 final String name = service.getServiceName();
1545 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001546 final int resolveInterface = getNetworkInterfaceIndex(service);
1547 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001548 Log.e(TAG, "Interface to resolve service on not found");
1549 return false;
1550 }
paulhu2b9ed952022-02-10 21:58:32 +08001551 return mMDnsManager.resolve(resolveId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001552 }
1553
1554 /**
1555 * Guess the interface to use to resolve or discover a service on a specific network.
1556 *
1557 * This is an imperfect guess, as for example the network may be gone or not yet fully
1558 * registered. This is fine as failing is correct if the network is gone, and a client
1559 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
1560 * this is to support the legacy mdnsresponder implementation, which historically resolved
1561 * services on an unspecified network.
1562 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001563 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
1564 final Network network = serviceInfo.getNetwork();
1565 if (network == null) {
1566 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
1567 // provided by NsdService from discovery results, and the service was found on an
1568 // interface that has no app-usable Network).
1569 if (serviceInfo.getInterfaceIndex() != 0) {
1570 return serviceInfo.getInterfaceIndex();
1571 }
1572 return IFACE_IDX_ANY;
1573 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001574
1575 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
1576 if (cm == null) {
1577 Log.wtf(TAG, "No ConnectivityManager for resolveService");
1578 return IFACE_IDX_ANY;
1579 }
1580 final LinkProperties lp = cm.getLinkProperties(network);
1581 if (lp == null) return IFACE_IDX_ANY;
1582
1583 // Only resolve on non-stacked interfaces
1584 final NetworkInterface iface;
1585 try {
1586 iface = NetworkInterface.getByName(lp.getInterfaceName());
1587 } catch (SocketException e) {
1588 Log.e(TAG, "Error querying interface", e);
1589 return IFACE_IDX_ANY;
1590 }
1591
1592 if (iface == null) {
1593 Log.e(TAG, "Interface not found: " + lp.getInterfaceName());
1594 return IFACE_IDX_ANY;
1595 }
1596
1597 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001598 }
1599
1600 private boolean stopResolveService(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001601 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001602 }
1603
paulhu2b9ed952022-02-10 21:58:32 +08001604 private boolean getAddrInfo(int resolveId, String hostname, int interfaceIdx) {
1605 return mMDnsManager.getServiceAddress(resolveId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001606 }
1607
1608 private boolean stopGetAddrInfo(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001609 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001610 }
1611
1612 @Override
Irfan Sheriff75006652012-04-17 23:15:29 -07001613 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
paulhu3ffffe72021-09-16 10:15:22 +08001614 if (!PermissionUtils.checkDumpPermission(mContext, TAG, pw)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001615
Irfan Sheriff75006652012-04-17 23:15:29 -07001616 for (ClientInfo client : mClients.values()) {
1617 pw.println("Client Info");
1618 pw.println(client);
1619 }
1620
1621 mNsdStateMachine.dump(fd, pw, args);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001622 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001623
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001624 private abstract static class ClientRequest {
1625 private final int mGlobalId;
1626
1627 private ClientRequest(int globalId) {
1628 mGlobalId = globalId;
1629 }
1630 }
1631
1632 private static class LegacyClientRequest extends ClientRequest {
1633 private final int mRequestCode;
1634
1635 private LegacyClientRequest(int globalId, int requestCode) {
1636 super(globalId);
1637 mRequestCode = requestCode;
1638 }
1639 }
1640
1641 private static class AdvertiserClientRequest extends ClientRequest {
1642 private AdvertiserClientRequest(int globalId) {
1643 super(globalId);
1644 }
1645 }
1646
1647 private static class DiscoveryManagerRequest extends ClientRequest {
1648 @NonNull
1649 private final MdnsListener mListener;
1650
1651 private DiscoveryManagerRequest(int globalId, @NonNull MdnsListener listener) {
1652 super(globalId);
1653 mListener = listener;
1654 }
1655 }
1656
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001657 /* Information tracked per client */
1658 private class ClientInfo {
1659
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001660 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001661 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001662 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001663 private NsdServiceInfo mResolvedService;
1664
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001665 /* A map from client-side ID (listenerKey) to the request */
1666 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08001667
Luke Huangf7277ed2021-07-12 21:15:10 +08001668 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001669 private boolean mIsPreSClient = false;
Luke Huangf7277ed2021-07-12 21:15:10 +08001670
Paul Hu18aeccc2022-12-27 08:48:48 +00001671 /*** The service that is registered to listen to its updates */
1672 private NsdServiceInfo mRegisteredService;
1673 /*** The client id that listen to updates */
1674 private int mClientIdForServiceUpdates;
1675
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001676 private ClientInfo(INsdManagerCallback cb) {
1677 mCb = cb;
paulhub2225702021-11-17 09:35:33 +08001678 if (DBG) Log.d(TAG, "New client");
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001679 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001680
1681 @Override
1682 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06001683 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07001684 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001685 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
1686 for (int i = 0; i < mClientRequests.size(); i++) {
1687 int clientID = mClientRequests.keyAt(i);
1688 sb.append("clientId ")
1689 .append(clientID)
1690 .append(" mDnsId ").append(mClientRequests.valueAt(i).mGlobalId)
1691 .append(" type ").append(
1692 mClientRequests.valueAt(i).getClass().getSimpleName())
1693 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07001694 }
1695 return sb.toString();
1696 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001697
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001698 private boolean isPreSClient() {
1699 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08001700 }
1701
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001702 private void setPreSClient() {
1703 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08001704 }
1705
Paul Hue4f5f252023-02-16 21:13:47 +08001706 private void unregisterMdnsListenerFromRequest(ClientRequest request) {
1707 final MdnsListener listener =
1708 ((DiscoveryManagerRequest) request).mListener;
1709 mMdnsDiscoveryManager.unregisterListener(
1710 listener.getListenedServiceType(), listener);
1711 }
1712
Dave Plattfeff2af2014-03-07 14:48:22 -08001713 // Remove any pending requests from the global map when we get rid of a client,
1714 // and send cancellations to the daemon.
1715 private void expungeAllRequests() {
Hugo Benichid2552ae2017-04-11 14:42:47 +09001716 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001717 for (int i = 0; i < mClientRequests.size(); i++) {
1718 final int clientId = mClientRequests.keyAt(i);
1719 final ClientRequest request = mClientRequests.valueAt(i);
1720 final int globalId = request.mGlobalId;
Dave Plattfeff2af2014-03-07 14:48:22 -08001721 mIdToClientInfoMap.remove(globalId);
paulhub2225702021-11-17 09:35:33 +08001722 if (DBG) {
1723 Log.d(TAG, "Terminating client-ID " + clientId
1724 + " global-ID " + globalId + " type " + mClientRequests.get(clientId));
1725 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001726
1727 if (request instanceof DiscoveryManagerRequest) {
Paul Hue4f5f252023-02-16 21:13:47 +08001728 unregisterMdnsListenerFromRequest(request);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001729 continue;
1730 }
1731
1732 if (request instanceof AdvertiserClientRequest) {
1733 mAdvertiser.removeService(globalId);
1734 continue;
1735 }
1736
1737 if (!(request instanceof LegacyClientRequest)) {
1738 throw new IllegalStateException("Unknown request type: " + request.getClass());
1739 }
1740
1741 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08001742 case NsdManager.DISCOVER_SERVICES:
1743 stopServiceDiscovery(globalId);
1744 break;
1745 case NsdManager.RESOLVE_SERVICE:
1746 stopResolveService(globalId);
1747 break;
1748 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001749 unregisterService(globalId);
Dave Plattfeff2af2014-03-07 14:48:22 -08001750 break;
1751 default:
1752 break;
1753 }
1754 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001755 mClientRequests.clear();
1756 }
1757
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001758 // mClientRequests is a sparse array of listener id -> ClientRequest. For a given
1759 // mDnsClient id, return the corresponding listener id. mDnsClient id is also called a
1760 // global id.
Christopher Lane74411222014-04-25 18:39:07 -07001761 private int getClientId(final int globalId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001762 for (int i = 0; i < mClientRequests.size(); i++) {
1763 if (mClientRequests.valueAt(i).mGlobalId == globalId) {
1764 return mClientRequests.keyAt(i);
1765 }
Christopher Lane74411222014-04-25 18:39:07 -07001766 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001767 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07001768 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001769
Paul Hu18aeccc2022-12-27 08:48:48 +00001770 private void maybeNotifyRegisteredServiceLost(@NonNull NsdServiceInfo info) {
1771 if (mRegisteredService == null) return;
1772 if (!Objects.equals(mRegisteredService.getServiceName(), info.getServiceName())) return;
1773 // Resolved services have a leading dot appended at the beginning of their type, but in
1774 // discovered info it's at the end
1775 if (!Objects.equals(
1776 mRegisteredService.getServiceType() + ".", "." + info.getServiceType())) {
1777 return;
1778 }
1779 onServiceUpdatedLost(mClientIdForServiceUpdates);
1780 }
1781
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001782 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info) {
1783 try {
1784 mCb.onDiscoverServicesStarted(listenerKey, info);
1785 } catch (RemoteException e) {
1786 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
1787 }
1788 }
1789
1790 void onDiscoverServicesFailed(int listenerKey, int error) {
1791 try {
1792 mCb.onDiscoverServicesFailed(listenerKey, error);
1793 } catch (RemoteException e) {
1794 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
1795 }
1796 }
1797
1798 void onServiceFound(int listenerKey, NsdServiceInfo info) {
1799 try {
1800 mCb.onServiceFound(listenerKey, info);
1801 } catch (RemoteException e) {
1802 Log.e(TAG, "Error calling onServiceFound(", e);
1803 }
1804 }
1805
1806 void onServiceLost(int listenerKey, NsdServiceInfo info) {
1807 try {
1808 mCb.onServiceLost(listenerKey, info);
1809 } catch (RemoteException e) {
1810 Log.e(TAG, "Error calling onServiceLost(", e);
1811 }
1812 }
1813
1814 void onStopDiscoveryFailed(int listenerKey, int error) {
1815 try {
1816 mCb.onStopDiscoveryFailed(listenerKey, error);
1817 } catch (RemoteException e) {
1818 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
1819 }
1820 }
1821
1822 void onStopDiscoverySucceeded(int listenerKey) {
1823 try {
1824 mCb.onStopDiscoverySucceeded(listenerKey);
1825 } catch (RemoteException e) {
1826 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
1827 }
1828 }
1829
1830 void onRegisterServiceFailed(int listenerKey, int error) {
1831 try {
1832 mCb.onRegisterServiceFailed(listenerKey, error);
1833 } catch (RemoteException e) {
1834 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
1835 }
1836 }
1837
1838 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info) {
1839 try {
1840 mCb.onRegisterServiceSucceeded(listenerKey, info);
1841 } catch (RemoteException e) {
1842 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
1843 }
1844 }
1845
1846 void onUnregisterServiceFailed(int listenerKey, int error) {
1847 try {
1848 mCb.onUnregisterServiceFailed(listenerKey, error);
1849 } catch (RemoteException e) {
1850 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
1851 }
1852 }
1853
1854 void onUnregisterServiceSucceeded(int listenerKey) {
1855 try {
1856 mCb.onUnregisterServiceSucceeded(listenerKey);
1857 } catch (RemoteException e) {
1858 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
1859 }
1860 }
1861
1862 void onResolveServiceFailed(int listenerKey, int error) {
1863 try {
1864 mCb.onResolveServiceFailed(listenerKey, error);
1865 } catch (RemoteException e) {
1866 Log.e(TAG, "Error calling onResolveServiceFailed", e);
1867 }
1868 }
1869
1870 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info) {
1871 try {
1872 mCb.onResolveServiceSucceeded(listenerKey, info);
1873 } catch (RemoteException e) {
1874 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
1875 }
1876 }
Paul Hub58deb72022-12-26 09:24:42 +00001877
1878 void onStopResolutionFailed(int listenerKey, int error) {
1879 try {
1880 mCb.onStopResolutionFailed(listenerKey, error);
1881 } catch (RemoteException e) {
1882 Log.e(TAG, "Error calling onStopResolutionFailed", e);
1883 }
1884 }
1885
1886 void onStopResolutionSucceeded(int listenerKey) {
1887 try {
1888 mCb.onStopResolutionSucceeded(listenerKey);
1889 } catch (RemoteException e) {
1890 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
1891 }
1892 }
Paul Hu18aeccc2022-12-27 08:48:48 +00001893
1894 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
1895 try {
1896 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
1897 } catch (RemoteException e) {
1898 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
1899 }
1900 }
1901
1902 void onServiceUpdated(int listenerKey, NsdServiceInfo info) {
1903 try {
1904 mCb.onServiceUpdated(listenerKey, info);
1905 } catch (RemoteException e) {
1906 Log.e(TAG, "Error calling onServiceUpdated", e);
1907 }
1908 }
1909
1910 void onServiceUpdatedLost(int listenerKey) {
1911 try {
1912 mCb.onServiceUpdatedLost(listenerKey);
1913 } catch (RemoteException e) {
1914 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
1915 }
1916 }
1917
1918 void onServiceInfoCallbackUnregistered(int listenerKey) {
1919 try {
1920 mCb.onServiceInfoCallbackUnregistered(listenerKey);
1921 } catch (RemoteException e) {
1922 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
1923 }
1924 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001925 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001926}