blob: f5215d91d6699cde53d3b99abe561ba57de71bfc [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
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090024import static com.android.modules.utils.build.SdkLevel.isAtLeastU;
25
Paul Hu23fa2022023-01-13 22:57:24 +080026import android.annotation.NonNull;
Paul Hu4bd98ef2023-01-12 13:42:07 +080027import android.annotation.Nullable;
paulhua262cc12019-08-12 16:25:11 +080028import android.content.Context;
Irfan Sheriff75006652012-04-17 23:15:29 -070029import android.content.Intent;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090030import android.net.ConnectivityManager;
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +090031import android.net.INetd;
Paul Hu75069ed2023-01-14 00:31:09 +080032import android.net.InetAddresses;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090033import android.net.LinkProperties;
34import android.net.Network;
paulhu2b9ed952022-02-10 21:58:32 +080035import android.net.mdns.aidl.DiscoveryInfo;
36import android.net.mdns.aidl.GetAddressInfo;
37import android.net.mdns.aidl.IMDnsEventListener;
38import android.net.mdns.aidl.RegistrationInfo;
39import android.net.mdns.aidl.ResolutionInfo;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070040import android.net.nsd.INsdManager;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090041import android.net.nsd.INsdManagerCallback;
42import android.net.nsd.INsdServiceConnector;
paulhu2b9ed952022-02-10 21:58:32 +080043import android.net.nsd.MDnsManager;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070044import android.net.nsd.NsdManager;
paulhua262cc12019-08-12 16:25:11 +080045import android.net.nsd.NsdServiceInfo;
Hugo Benichi803a2f02017-04-24 11:35:06 +090046import android.os.Handler;
paulhua262cc12019-08-12 16:25:11 +080047import android.os.HandlerThread;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090048import android.os.IBinder;
Paul Hu4bd98ef2023-01-12 13:42:07 +080049import android.os.Looper;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070050import android.os.Message;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090051import android.os.RemoteException;
Dianne Hackborn692107e2012-08-29 18:32:08 -070052import android.os.UserHandle;
Paul Hu23fa2022023-01-13 22:57:24 +080053import android.text.TextUtils;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090054import android.util.Log;
55import android.util.Pair;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070056import android.util.SparseArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070057
paulhua262cc12019-08-12 16:25:11 +080058import com.android.internal.annotations.VisibleForTesting;
paulhua262cc12019-08-12 16:25:11 +080059import com.android.internal.util.State;
60import com.android.internal.util.StateMachine;
Paul Hu4bd98ef2023-01-12 13:42:07 +080061import com.android.net.module.util.DeviceConfigUtils;
paulhu3ffffe72021-09-16 10:15:22 +080062import com.android.net.module.util.PermissionUtils;
Paul Hu4bd98ef2023-01-12 13:42:07 +080063import com.android.server.connectivity.mdns.ExecutorProvider;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090064import com.android.server.connectivity.mdns.MdnsAdvertiser;
Paul Hu4bd98ef2023-01-12 13:42:07 +080065import com.android.server.connectivity.mdns.MdnsDiscoveryManager;
66import com.android.server.connectivity.mdns.MdnsMultinetworkSocketClient;
Paul Hu23fa2022023-01-13 22:57:24 +080067import com.android.server.connectivity.mdns.MdnsSearchOptions;
68import com.android.server.connectivity.mdns.MdnsServiceBrowserListener;
69import com.android.server.connectivity.mdns.MdnsServiceInfo;
Paul Hu4bd98ef2023-01-12 13:42:07 +080070import com.android.server.connectivity.mdns.MdnsSocketClientBase;
71import com.android.server.connectivity.mdns.MdnsSocketProvider;
paulhua262cc12019-08-12 16:25:11 +080072
Irfan Sheriff77ec5582012-03-22 17:01:39 -070073import java.io.FileDescriptor;
74import java.io.PrintWriter;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070075import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090076import java.net.NetworkInterface;
77import java.net.SocketException;
78import java.net.UnknownHostException;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090079import java.nio.ByteBuffer;
80import java.nio.CharBuffer;
81import java.nio.charset.Charset;
82import java.nio.charset.CharsetEncoder;
83import java.nio.charset.StandardCharsets;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070084import java.util.HashMap;
Paul Hu23fa2022023-01-13 22:57:24 +080085import java.util.List;
Paul Hu75069ed2023-01-14 00:31:09 +080086import java.util.Map;
Paul Hu18aeccc2022-12-27 08:48:48 +000087import java.util.Objects;
Paul Hu23fa2022023-01-13 22:57:24 +080088import java.util.regex.Matcher;
89import java.util.regex.Pattern;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070090
Irfan Sheriff77ec5582012-03-22 17:01:39 -070091/**
92 * Network Service Discovery Service handles remote service discovery operation requests by
93 * implementing the INsdManager interface.
94 *
95 * @hide
96 */
97public class NsdService extends INsdManager.Stub {
98 private static final String TAG = "NsdService";
99 private static final String MDNS_TAG = "mDnsConnector";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900100 /**
101 * Enable discovery using the Java DiscoveryManager, instead of the legacy mdnsresponder
102 * implementation.
103 */
Paul Hu4bd98ef2023-01-12 13:42:07 +0800104 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Paul Hu23fa2022023-01-13 22:57:24 +0800105 private static final String LOCAL_DOMAIN_NAME = "local";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900106 // Max label length as per RFC 1034/1035
107 private static final int MAX_LABEL_LENGTH = 63;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700108
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900109 /**
110 * Enable advertising using the Java MdnsAdvertiser, instead of the legacy mdnsresponder
111 * implementation.
112 */
113 private static final String MDNS_ADVERTISER_VERSION = "mdns_advertiser_version";
114
115 public static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +0000116 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900117 private static final int IFACE_IDX_ANY = 0;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700118
Hugo Benichi32be63d2017-04-05 14:06:11 +0900119 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900120 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +0800121 private final MDnsManager mMDnsManager;
122 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900123 @NonNull
124 private final Dependencies mDeps;
125 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800126 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900127 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800128 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900129 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800130 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900131 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900132 private final MdnsAdvertiser mAdvertiser;
Paul Hu23fa2022023-01-13 22:57:24 +0800133 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800134 // state machine thread. If change this outside state machine, it will need to introduce
135 // synchronization.
136 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800137 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700138
139 /**
140 * Clients receiving asynchronous messages
141 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900142 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700143
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700144 /* A map from unique id to client info */
Hugo Benichi32be63d2017-04-05 14:06:11 +0900145 private final SparseArray<ClientInfo> mIdToClientInfoMap= new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700146
Luke Huang05298582021-06-13 16:52:05 +0000147 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700148
Hugo Benichi32be63d2017-04-05 14:06:11 +0900149 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700150 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800151 // The count of the connected legacy clients.
152 private int mLegacyClientCount = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700153
Paul Hu23fa2022023-01-13 22:57:24 +0800154 private static class MdnsListener implements MdnsServiceBrowserListener {
155 protected final int mClientId;
156 protected final int mTransactionId;
157 @NonNull
158 protected final NsdServiceInfo mReqServiceInfo;
159 @NonNull
160 protected final String mListenedServiceType;
161
162 MdnsListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
163 @NonNull String listenedServiceType) {
164 mClientId = clientId;
165 mTransactionId = transactionId;
166 mReqServiceInfo = reqServiceInfo;
167 mListenedServiceType = listenedServiceType;
168 }
169
170 @NonNull
171 public String getListenedServiceType() {
172 return mListenedServiceType;
173 }
174
175 @Override
176 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo) { }
177
178 @Override
179 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
180
181 @Override
182 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
183
184 @Override
185 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) { }
186
187 @Override
188 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
189
190 @Override
191 public void onSearchStoppedWithError(int error) { }
192
193 @Override
194 public void onSearchFailedToStart() { }
195
196 @Override
197 public void onDiscoveryQuerySent(@NonNull List<String> subtypes, int transactionId) { }
198
199 @Override
200 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
201 }
202
203 private class DiscoveryListener extends MdnsListener {
204
205 DiscoveryListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
206 @NonNull String listenServiceType) {
207 super(clientId, transactionId, reqServiceInfo, listenServiceType);
208 }
209
210 @Override
211 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu019621e2023-01-13 23:26:49 +0800212 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
213 NsdManager.SERVICE_FOUND,
214 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800215 }
216
217 @Override
218 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800219 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
220 NsdManager.SERVICE_LOST,
221 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800222 }
223 }
224
Paul Hu75069ed2023-01-14 00:31:09 +0800225 private class ResolutionListener extends MdnsListener {
226
227 ResolutionListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
228 @NonNull String listenServiceType) {
229 super(clientId, transactionId, reqServiceInfo, listenServiceType);
230 }
231
232 @Override
233 public void onServiceFound(MdnsServiceInfo serviceInfo) {
234 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
235 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
236 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
237 }
238 }
239
Paul Hu019621e2023-01-13 23:26:49 +0800240 /**
241 * Data class of mdns service callback information.
242 */
243 private static class MdnsEvent {
244 final int mClientId;
245 @NonNull
246 final String mRequestedServiceType;
247 @NonNull
248 final MdnsServiceInfo mMdnsServiceInfo;
249
250 MdnsEvent(int clientId, @NonNull String requestedServiceType,
251 @NonNull MdnsServiceInfo mdnsServiceInfo) {
252 mClientId = clientId;
253 mRequestedServiceType = requestedServiceType;
254 mMdnsServiceInfo = mdnsServiceInfo;
255 }
256 }
257
Irfan Sheriff75006652012-04-17 23:15:29 -0700258 private class NsdStateMachine extends StateMachine {
259
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700260 private final DefaultState mDefaultState = new DefaultState();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700261 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700262
263 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700264 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900265 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700266 }
267
Luke Huang92860f92021-06-23 06:29:30 +0000268 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800269 if (mIsDaemonStarted) {
270 if (DBG) Log.d(TAG, "Daemon is already started.");
271 return;
272 }
273 mMDnsManager.registerEventListener(mMDnsEventCallback);
274 mMDnsManager.startDaemon();
275 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000276 maybeScheduleStop();
277 }
278
paulhu2b9ed952022-02-10 21:58:32 +0800279 private void maybeStopDaemon() {
280 if (!mIsDaemonStarted) {
281 if (DBG) Log.d(TAG, "Daemon has not been started.");
282 return;
283 }
284 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
285 mMDnsManager.stopDaemon();
286 mIsDaemonStarted = false;
287 }
288
Luke Huang92860f92021-06-23 06:29:30 +0000289 private boolean isAnyRequestActive() {
290 return mIdToClientInfoMap.size() != 0;
291 }
292
293 private void scheduleStop() {
294 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
295 }
296 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800297 // The native daemon should stay alive and can't be cleanup
298 // if any legacy client connected.
299 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000300 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000301 }
302 }
303
Luke Huang92860f92021-06-23 06:29:30 +0000304 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000305 this.removeMessages(NsdManager.DAEMON_CLEANUP);
306 }
307
Paul Hu23fa2022023-01-13 22:57:24 +0800308 private void maybeStartMonitoringSockets() {
309 if (mIsMonitoringSocketsStarted) {
310 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
311 return;
312 }
313
314 mMdnsSocketProvider.startMonitoringSockets();
315 mIsMonitoringSocketsStarted = true;
316 }
317
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900318 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
319 if (!mIsMonitoringSocketsStarted) return;
320 if (isAnyRequestActive()) return;
321
Paul Hu58f20602023-02-18 11:41:07 +0800322 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800323 mIsMonitoringSocketsStarted = false;
324 }
325
Hugo Benichi803a2f02017-04-24 11:35:06 +0900326 NsdStateMachine(String name, Handler handler) {
327 super(name, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -0700328 addState(mDefaultState);
Irfan Sheriff75006652012-04-17 23:15:29 -0700329 addState(mEnabledState, mDefaultState);
paulhu5568f452021-11-30 13:31:29 +0800330 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900331 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700332 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700333 }
334
335 class DefaultState extends State {
336 @Override
337 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900338 final ClientInfo cInfo;
339 final int clientId = msg.arg2;
Irfan Sheriff75006652012-04-17 23:15:29 -0700340 switch (msg.what) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900341 case NsdManager.REGISTER_CLIENT:
342 final Pair<NsdServiceConnector, INsdManagerCallback> arg =
343 (Pair<NsdServiceConnector, INsdManagerCallback>) msg.obj;
344 final INsdManagerCallback cb = arg.second;
345 try {
346 cb.asBinder().linkToDeath(arg.first, 0);
347 cInfo = new ClientInfo(cb);
348 mClients.put(arg.first, cInfo);
349 } catch (RemoteException e) {
350 Log.w(TAG, "Client " + clientId + " has already died");
Irfan Sheriff75006652012-04-17 23:15:29 -0700351 }
352 break;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900353 case NsdManager.UNREGISTER_CLIENT:
354 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
355 cInfo = mClients.remove(connector);
Dave Plattfeff2af2014-03-07 14:48:22 -0800356 if (cInfo != null) {
357 cInfo.expungeAllRequests();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900358 if (cInfo.isPreSClient()) {
Luke Huangf7277ed2021-07-12 21:15:10 +0800359 mLegacyClientCount -= 1;
360 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800361 }
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900362 maybeStopMonitoringSocketsIfNoActiveRequest();
Luke Huangf7277ed2021-07-12 21:15:10 +0800363 maybeScheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700364 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700365 case NsdManager.DISCOVER_SERVICES:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900366 cInfo = getClientInfoForReply(msg);
367 if (cInfo != null) {
368 cInfo.onDiscoverServicesFailed(
369 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
370 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700371 break;
372 case NsdManager.STOP_DISCOVERY:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900373 cInfo = getClientInfoForReply(msg);
374 if (cInfo != null) {
375 cInfo.onStopDiscoveryFailed(
376 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
377 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700378 break;
379 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900380 cInfo = getClientInfoForReply(msg);
381 if (cInfo != null) {
382 cInfo.onRegisterServiceFailed(
383 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
384 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700385 break;
386 case NsdManager.UNREGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900387 cInfo = getClientInfoForReply(msg);
388 if (cInfo != null) {
389 cInfo.onUnregisterServiceFailed(
390 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
391 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700392 break;
393 case NsdManager.RESOLVE_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900394 cInfo = getClientInfoForReply(msg);
395 if (cInfo != null) {
396 cInfo.onResolveServiceFailed(
397 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
398 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700399 break;
Paul Hub58deb72022-12-26 09:24:42 +0000400 case NsdManager.STOP_RESOLUTION:
401 cInfo = getClientInfoForReply(msg);
402 if (cInfo != null) {
403 cInfo.onStopResolutionFailed(
404 clientId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
405 }
406 break;
Paul Hu18aeccc2022-12-27 08:48:48 +0000407 case NsdManager.REGISTER_SERVICE_CALLBACK:
408 cInfo = getClientInfoForReply(msg);
409 if (cInfo != null) {
410 cInfo.onServiceInfoCallbackRegistrationFailed(
411 clientId, NsdManager.FAILURE_BAD_PARAMETERS);
412 }
413 break;
Luke Huang05298582021-06-13 16:52:05 +0000414 case NsdManager.DAEMON_CLEANUP:
paulhu2b9ed952022-02-10 21:58:32 +0800415 maybeStopDaemon();
Luke Huang05298582021-06-13 16:52:05 +0000416 break;
Luke Huangf7277ed2021-07-12 21:15:10 +0800417 // This event should be only sent by the legacy (target SDK < S) clients.
418 // Mark the sending client as legacy.
419 case NsdManager.DAEMON_STARTUP:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900420 cInfo = getClientInfoForReply(msg);
Luke Huangf7277ed2021-07-12 21:15:10 +0800421 if (cInfo != null) {
422 cancelStop();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900423 cInfo.setPreSClient();
Luke Huangf7277ed2021-07-12 21:15:10 +0800424 mLegacyClientCount += 1;
425 maybeStartDaemon();
426 }
427 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700428 default:
paulhub2225702021-11-17 09:35:33 +0800429 Log.e(TAG, "Unhandled " + msg);
Irfan Sheriff75006652012-04-17 23:15:29 -0700430 return NOT_HANDLED;
431 }
432 return HANDLED;
433 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900434
435 private ClientInfo getClientInfoForReply(Message msg) {
436 final ListenerArgs args = (ListenerArgs) msg.obj;
437 return mClients.get(args.connector);
438 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700439 }
440
Irfan Sheriff75006652012-04-17 23:15:29 -0700441 class EnabledState extends State {
442 @Override
443 public void enter() {
444 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700445 }
446
447 @Override
448 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000449 // TODO: it is incorrect to stop the daemon without expunging all requests
450 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000451 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700452 }
453
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700454 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900455 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800456 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700457 return true;
458 }
459 return false;
460 }
461
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900462 private void storeLegacyRequestMap(int clientId, int globalId, ClientInfo clientInfo,
463 int what) {
464 clientInfo.mClientRequests.put(clientId, new LegacyClientRequest(globalId, what));
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700465 mIdToClientInfoMap.put(globalId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000466 // Remove the cleanup event because here comes a new request.
467 cancelStop();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700468 }
469
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900470 private void storeAdvertiserRequestMap(int clientId, int globalId,
Paul Hu23fa2022023-01-13 22:57:24 +0800471 ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900472 clientInfo.mClientRequests.put(clientId, new AdvertiserClientRequest(globalId));
473 mIdToClientInfoMap.put(globalId, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800474 }
475
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900476 private void removeRequestMap(int clientId, int globalId, ClientInfo clientInfo) {
477 final ClientRequest existing = clientInfo.mClientRequests.get(clientId);
478 if (existing == null) return;
479 clientInfo.mClientRequests.remove(clientId);
480 mIdToClientInfoMap.remove(globalId);
481
482 if (existing instanceof LegacyClientRequest) {
483 maybeScheduleStop();
484 } else {
485 maybeStopMonitoringSocketsIfNoActiveRequest();
486 }
487 }
488
489 private void storeDiscoveryManagerRequestMap(int clientId, int globalId,
490 MdnsListener listener, ClientInfo clientInfo) {
491 clientInfo.mClientRequests.put(clientId,
492 new DiscoveryManagerRequest(globalId, listener));
493 mIdToClientInfoMap.put(globalId, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800494 }
495
Paul Hu18aeccc2022-12-27 08:48:48 +0000496 private void clearRegisteredServiceInfo(ClientInfo clientInfo) {
497 clientInfo.mRegisteredService = null;
498 clientInfo.mClientIdForServiceUpdates = 0;
499 }
500
Paul Hu23fa2022023-01-13 22:57:24 +0800501 /**
502 * Check the given service type is valid and construct it to a service type
503 * which can use for discovery / resolution service.
504 *
505 * <p> The valid service type should be 2 labels, or 3 labels if the query is for a
506 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
507 * underscore; they are alphanumerical characters or dashes or underscore, except the
508 * last one that is just alphanumerical. The last label must be _tcp or _udp.
509 *
510 * @param serviceType the request service type for discovery / resolution service
511 * @return constructed service type or null if the given service type is invalid.
512 */
513 @Nullable
514 private String constructServiceType(String serviceType) {
515 if (TextUtils.isEmpty(serviceType)) return null;
516
517 final Pattern serviceTypePattern = Pattern.compile(
518 "^(_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]\\.)?"
519 + "(_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]\\._(?:tcp|udp))$");
520 final Matcher matcher = serviceTypePattern.matcher(serviceType);
521 if (!matcher.matches()) return null;
522 return matcher.group(1) == null
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900523 ? serviceType
524 : matcher.group(1) + "_sub." + matcher.group(2);
525 }
526
527 /**
528 * Truncate a service name to up to 63 UTF-8 bytes.
529 *
530 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
531 * names used in registerService follows historical behavior (see mdnsresponder
532 * handle_regservice_request).
533 */
534 @NonNull
535 private String truncateServiceName(@NonNull String originalName) {
536 // UTF-8 is at most 4 bytes per character; return early in the common case where
537 // the name can't possibly be over the limit given its string length.
538 if (originalName.length() <= MAX_LABEL_LENGTH / 4) return originalName;
539
540 final Charset utf8 = StandardCharsets.UTF_8;
541 final CharsetEncoder encoder = utf8.newEncoder();
542 final ByteBuffer out = ByteBuffer.allocate(MAX_LABEL_LENGTH);
543 // encode will write as many characters as possible to the out buffer, and just
544 // return an overflow code if there were too many characters (no need to check the
545 // return code here, this method truncates the name on purpose).
546 encoder.encode(CharBuffer.wrap(originalName), out, true /* endOfInput */);
547 return new String(out.array(), 0, out.position(), utf8);
Paul Hu23fa2022023-01-13 22:57:24 +0800548 }
549
Irfan Sheriff75006652012-04-17 23:15:29 -0700550 @Override
551 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900552 final ClientInfo clientInfo;
553 final int id;
554 final int clientId = msg.arg2;
555 final ListenerArgs args;
Irfan Sheriff75006652012-04-17 23:15:29 -0700556 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800557 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800558 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900559 args = (ListenerArgs) msg.obj;
560 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000561 // If the binder death notification for a INsdManagerCallback was received
562 // before any calls are received by NsdService, the clientInfo would be
563 // cleared and cause NPE. Add a null check here to prevent this corner case.
564 if (clientInfo == null) {
565 Log.e(TAG, "Unknown connector in discovery");
566 break;
567 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700568
569 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900570 clientInfo.onDiscoverServicesFailed(
571 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriff75006652012-04-17 23:15:29 -0700572 break;
573 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700574
Paul Hu23fa2022023-01-13 22:57:24 +0800575 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700576 id = getUniqueId();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900577 if (mDeps.isMdnsDiscoveryManagerEnabled(mContext)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800578 final String serviceType = constructServiceType(info.getServiceType());
579 if (serviceType == null) {
580 clientInfo.onDiscoverServicesFailed(clientId,
581 NsdManager.FAILURE_INTERNAL_ERROR);
582 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700583 }
Paul Hu23fa2022023-01-13 22:57:24 +0800584
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900585 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800586 maybeStartMonitoringSockets();
587 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900588 new DiscoveryListener(clientId, id, info, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800589 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
590 .setNetwork(info.getNetwork())
591 .setIsPassiveMode(true)
592 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900593 mMdnsDiscoveryManager.registerListener(
594 listenServiceType, listener, options);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900595 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800596 clientInfo.onDiscoverServicesStarted(clientId, info);
Irfan Sheriff75006652012-04-17 23:15:29 -0700597 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800598 maybeStartDaemon();
599 if (discoverServices(id, info)) {
600 if (DBG) {
601 Log.d(TAG, "Discover " + msg.arg2 + " " + id
602 + info.getServiceType());
603 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900604 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu23fa2022023-01-13 22:57:24 +0800605 clientInfo.onDiscoverServicesStarted(clientId, info);
606 } else {
607 stopServiceDiscovery(id);
608 clientInfo.onDiscoverServicesFailed(clientId,
609 NsdManager.FAILURE_INTERNAL_ERROR);
610 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700611 }
612 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800613 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900614 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800615 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900616 args = (ListenerArgs) msg.obj;
617 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000618 // If the binder death notification for a INsdManagerCallback was received
619 // before any calls are received by NsdService, the clientInfo would be
620 // cleared and cause NPE. Add a null check here to prevent this corner case.
621 if (clientInfo == null) {
622 Log.e(TAG, "Unknown connector in stop discovery");
623 break;
624 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700625
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900626 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
627 if (request == null) {
628 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700629 break;
630 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900631 id = request.mGlobalId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900632 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
633 // point, so this needs to check the type of the original request to
634 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900635 if (request instanceof DiscoveryManagerRequest) {
Ahmad Khalil4b8d45a2023-03-02 11:43:25 +0000636 final MdnsListener listener =
637 ((DiscoveryManagerRequest) request).mListener;
638 mMdnsDiscoveryManager.unregisterListener(
639 listener.getListenedServiceType(), listener);
640 removeRequestMap(clientId, id, clientInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900641 clientInfo.onStopDiscoverySucceeded(clientId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700642 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800643 removeRequestMap(clientId, id, clientInfo);
644 if (stopServiceDiscovery(id)) {
645 clientInfo.onStopDiscoverySucceeded(clientId);
646 } else {
647 clientInfo.onStopDiscoveryFailed(
648 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
649 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700650 }
651 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900652 }
653 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800654 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900655 args = (ListenerArgs) msg.obj;
656 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000657 // If the binder death notification for a INsdManagerCallback was received
658 // before any calls are received by NsdService, the clientInfo would be
659 // cleared and cause NPE. Add a null check here to prevent this corner case.
660 if (clientInfo == null) {
661 Log.e(TAG, "Unknown connector in registration");
662 break;
663 }
664
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700665 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900666 clientInfo.onRegisterServiceFailed(
667 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700668 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700669 }
670
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700671 id = getUniqueId();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900672 if (mDeps.isMdnsAdvertiserEnabled(mContext)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900673 final NsdServiceInfo serviceInfo = args.serviceInfo;
674 final String serviceType = serviceInfo.getServiceType();
675 final String registerServiceType = constructServiceType(serviceType);
676 if (registerServiceType == null) {
677 Log.e(TAG, "Invalid service type: " + serviceType);
678 clientInfo.onRegisterServiceFailed(clientId,
679 NsdManager.FAILURE_INTERNAL_ERROR);
680 break;
681 }
682 serviceInfo.setServiceType(registerServiceType);
683 serviceInfo.setServiceName(truncateServiceName(
684 serviceInfo.getServiceName()));
685
686 maybeStartMonitoringSockets();
687 mAdvertiser.addService(id, serviceInfo);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900688 storeAdvertiserRequestMap(clientId, id, clientInfo);
Irfan Sheriff75006652012-04-17 23:15:29 -0700689 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900690 maybeStartDaemon();
691 if (registerService(id, args.serviceInfo)) {
692 if (DBG) Log.d(TAG, "Register " + clientId + " " + id);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900693 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900694 // Return success after mDns reports success
695 } else {
696 unregisterService(id);
697 clientInfo.onRegisterServiceFailed(
698 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
699 }
700
Irfan Sheriff75006652012-04-17 23:15:29 -0700701 }
702 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900703 }
704 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800705 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900706 args = (ListenerArgs) msg.obj;
707 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000708 // If the binder death notification for a INsdManagerCallback was received
709 // before any calls are received by NsdService, the clientInfo would be
710 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900711 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800712 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700713 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700714 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900715 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
716 if (request == null) {
717 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
718 break;
719 }
720 id = request.mGlobalId;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900721 removeRequestMap(clientId, id, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900722
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900723 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
724 // so this needs to check the type of the original request to unregister
725 // instead of looking at the flag value.
726 if (request instanceof AdvertiserClientRequest) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900727 mAdvertiser.removeService(id);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900728 clientInfo.onUnregisterServiceSucceeded(clientId);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700729 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900730 if (unregisterService(id)) {
731 clientInfo.onUnregisterServiceSucceeded(clientId);
732 } else {
733 clientInfo.onUnregisterServiceFailed(
734 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
735 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700736 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700737 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900738 }
Paul Hu75069ed2023-01-14 00:31:09 +0800739 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800740 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900741 args = (ListenerArgs) msg.obj;
742 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000743 // If the binder death notification for a INsdManagerCallback was received
744 // before any calls are received by NsdService, the clientInfo would be
745 // cleared and cause NPE. Add a null check here to prevent this corner case.
746 if (clientInfo == null) {
747 Log.e(TAG, "Unknown connector in resolution");
748 break;
749 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700750
Paul Hu75069ed2023-01-14 00:31:09 +0800751 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700752 id = getUniqueId();
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900753 if (mDeps.isMdnsDiscoveryManagerEnabled(mContext)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800754 final String serviceType = constructServiceType(info.getServiceType());
755 if (serviceType == null) {
756 clientInfo.onResolveServiceFailed(clientId,
757 NsdManager.FAILURE_INTERNAL_ERROR);
758 break;
759 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900760 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +0800761
762 maybeStartMonitoringSockets();
763 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900764 new ResolutionListener(clientId, id, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800765 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
766 .setNetwork(info.getNetwork())
767 .setIsPassiveMode(true)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900768 .setResolveInstanceName(info.getServiceName())
Paul Hu75069ed2023-01-14 00:31:09 +0800769 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900770 mMdnsDiscoveryManager.registerListener(
771 resolveServiceType, listener, options);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900772 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Irfan Sheriff75006652012-04-17 23:15:29 -0700773 } else {
Paul Hu75069ed2023-01-14 00:31:09 +0800774 if (clientInfo.mResolvedService != null) {
775 clientInfo.onResolveServiceFailed(
776 clientId, NsdManager.FAILURE_ALREADY_ACTIVE);
777 break;
778 }
779
780 maybeStartDaemon();
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900781 if (resolveService(id, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800782 clientInfo.mResolvedService = new NsdServiceInfo();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900783 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu75069ed2023-01-14 00:31:09 +0800784 } else {
785 clientInfo.onResolveServiceFailed(
786 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
787 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700788 }
789 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800790 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900791 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +0000792 if (DBG) Log.d(TAG, "Stop service resolution");
793 args = (ListenerArgs) msg.obj;
794 clientInfo = mClients.get(args.connector);
795 // If the binder death notification for a INsdManagerCallback was received
796 // before any calls are received by NsdService, the clientInfo would be
797 // cleared and cause NPE. Add a null check here to prevent this corner case.
798 if (clientInfo == null) {
799 Log.e(TAG, "Unknown connector in stop resolution");
800 break;
801 }
802
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900803 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
804 if (request == null) {
805 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
806 break;
807 }
808 id = request.mGlobalId;
Ahmad Khalil4b8d45a2023-03-02 11:43:25 +0000809 removeRequestMap(clientId, id, clientInfo);
810 if (stopResolveService(id)) {
Paul Hub58deb72022-12-26 09:24:42 +0000811 clientInfo.onStopResolutionSucceeded(clientId);
812 } else {
Ahmad Khalil4b8d45a2023-03-02 11:43:25 +0000813 clientInfo.onStopResolutionFailed(
814 clientId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
Paul Hub58deb72022-12-26 09:24:42 +0000815 }
Ahmad Khalil4b8d45a2023-03-02 11:43:25 +0000816 clientInfo.mResolvedService = null;
817 // TODO: Implement the stop resolution with MdnsDiscoveryManager.
Paul Hub58deb72022-12-26 09:24:42 +0000818 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900819 }
Paul Hu18aeccc2022-12-27 08:48:48 +0000820 case NsdManager.REGISTER_SERVICE_CALLBACK:
821 if (DBG) Log.d(TAG, "Register a service callback");
822 args = (ListenerArgs) msg.obj;
823 clientInfo = mClients.get(args.connector);
824 // If the binder death notification for a INsdManagerCallback was received
825 // before any calls are received by NsdService, the clientInfo would be
826 // cleared and cause NPE. Add a null check here to prevent this corner case.
827 if (clientInfo == null) {
828 Log.e(TAG, "Unknown connector in callback registration");
829 break;
830 }
831
832 if (clientInfo.mRegisteredService != null) {
833 clientInfo.onServiceInfoCallbackRegistrationFailed(
834 clientId, NsdManager.FAILURE_ALREADY_ACTIVE);
835 break;
836 }
837
838 maybeStartDaemon();
839 id = getUniqueId();
840 if (resolveService(id, args.serviceInfo)) {
841 clientInfo.mRegisteredService = new NsdServiceInfo();
842 clientInfo.mClientIdForServiceUpdates = clientId;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900843 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu18aeccc2022-12-27 08:48:48 +0000844 } else {
845 clientInfo.onServiceInfoCallbackRegistrationFailed(
846 clientId, NsdManager.FAILURE_BAD_PARAMETERS);
847 }
848 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900849 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +0000850 if (DBG) Log.d(TAG, "Unregister a service callback");
851 args = (ListenerArgs) msg.obj;
852 clientInfo = mClients.get(args.connector);
853 // If the binder death notification for a INsdManagerCallback was received
854 // before any calls are received by NsdService, the clientInfo would be
855 // cleared and cause NPE. Add a null check here to prevent this corner case.
856 if (clientInfo == null) {
857 Log.e(TAG, "Unknown connector in callback unregistration");
858 break;
859 }
860
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900861 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
862 if (request == null) {
863 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
864 break;
865 }
866 id = request.mGlobalId;
Paul Hu18aeccc2022-12-27 08:48:48 +0000867 removeRequestMap(clientId, id, clientInfo);
868 if (stopResolveService(id)) {
869 clientInfo.onServiceInfoCallbackUnregistered(clientId);
870 } else {
871 Log.e(TAG, "Failed to unregister service info callback");
872 }
873 clearRegisteredServiceInfo(clientInfo);
874 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900875 }
paulhu2b9ed952022-02-10 21:58:32 +0800876 case MDNS_SERVICE_EVENT:
877 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +0900878 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700879 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700880 break;
Paul Hu019621e2023-01-13 23:26:49 +0800881 case MDNS_DISCOVERY_MANAGER_EVENT:
882 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
883 return NOT_HANDLED;
884 }
885 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700886 default:
Hugo Benichif0c84092017-04-05 14:43:29 +0900887 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700888 }
Hugo Benichif0c84092017-04-05 14:43:29 +0900889 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700890 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700891
Paul Hu18aeccc2022-12-27 08:48:48 +0000892 private void notifyResolveFailedResult(boolean isListenedToUpdates, int clientId,
893 ClientInfo clientInfo, int error) {
894 if (isListenedToUpdates) {
895 clientInfo.onServiceInfoCallbackRegistrationFailed(clientId, error);
896 clearRegisteredServiceInfo(clientInfo);
897 } else {
898 // The resolve API always returned FAILURE_INTERNAL_ERROR on error; keep it
899 // for backwards compatibility.
900 clientInfo.onResolveServiceFailed(clientId, NsdManager.FAILURE_INTERNAL_ERROR);
901 clientInfo.mResolvedService = null;
902 }
903 }
904
paulhu2b9ed952022-02-10 21:58:32 +0800905 private boolean handleMDnsServiceEvent(int code, int id, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700906 NsdServiceInfo servInfo;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700907 ClientInfo clientInfo = mIdToClientInfoMap.get(id);
908 if (clientInfo == null) {
paulhu2b9ed952022-02-10 21:58:32 +0800909 Log.e(TAG, String.format("id %d for %d has no client mapping", id, code));
Hugo Benichif0c84092017-04-05 14:43:29 +0900910 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700911 }
912
913 /* This goes in response as msg.arg2 */
Christopher Lane74411222014-04-25 18:39:07 -0700914 int clientId = clientInfo.getClientId(id);
915 if (clientId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -0700916 // This can happen because of race conditions. For example,
917 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
918 // and we may get in this situation.
paulhu2b9ed952022-02-10 21:58:32 +0800919 Log.d(TAG, String.format("%d for listener id %d that is no longer active",
920 code, id));
Hugo Benichif0c84092017-04-05 14:43:29 +0900921 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700922 }
Hugo Benichi32be63d2017-04-05 14:06:11 +0900923 if (DBG) {
paulhu2b9ed952022-02-10 21:58:32 +0800924 Log.d(TAG, String.format("MDns service event code:%d id=%d", code, id));
Hugo Benichi32be63d2017-04-05 14:06:11 +0900925 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700926 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +0800927 case IMDnsEventListener.SERVICE_FOUND: {
928 final DiscoveryInfo info = (DiscoveryInfo) obj;
929 final String name = info.serviceName;
930 final String type = info.registrationType;
931 servInfo = new NsdServiceInfo(name, type);
932 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900933 if (foundNetId == 0L) {
934 // Ignore services that do not have a Network: they are not usable
935 // by apps, as they would need privileged permissions to use
936 // interfaces that do not have an associated Network.
937 break;
938 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +0900939 if (foundNetId == INetd.DUMMY_NET_ID) {
940 // Ignore services on the dummy0 interface: they are only seen when
941 // discovering locally advertised services, and are not reachable
942 // through that interface.
943 break;
944 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900945 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900946 clientInfo.onServiceFound(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700947 break;
paulhu2b9ed952022-02-10 21:58:32 +0800948 }
949 case IMDnsEventListener.SERVICE_LOST: {
950 final DiscoveryInfo info = (DiscoveryInfo) obj;
951 final String name = info.serviceName;
952 final String type = info.registrationType;
953 final int lostNetId = info.netId;
954 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900955 // The network could be set to null (netId 0) if it was torn down when the
956 // service is lost
957 // TODO: avoid returning null in that case, possibly by remembering
958 // found services on the same interface index and their network at the time
959 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900960 clientInfo.onServiceLost(clientId, servInfo);
Paul Hu18aeccc2022-12-27 08:48:48 +0000961 // TODO: also support registered service lost when not discovering
962 clientInfo.maybeNotifyRegisteredServiceLost(servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700963 break;
paulhu2b9ed952022-02-10 21:58:32 +0800964 }
965 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900966 clientInfo.onDiscoverServicesFailed(
967 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700968 break;
paulhu2b9ed952022-02-10 21:58:32 +0800969 case IMDnsEventListener.SERVICE_REGISTERED: {
970 final RegistrationInfo info = (RegistrationInfo) obj;
971 final String name = info.serviceName;
972 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900973 clientInfo.onRegisterServiceSucceeded(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700974 break;
paulhu2b9ed952022-02-10 21:58:32 +0800975 }
976 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900977 clientInfo.onRegisterServiceFailed(
978 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700979 break;
paulhu2b9ed952022-02-10 21:58:32 +0800980 case IMDnsEventListener.SERVICE_RESOLVED: {
981 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -0700982 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +0800983 final String fullName = info.serviceFullName;
984 while (index < fullName.length() && fullName.charAt(index) != '.') {
985 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -0700986 ++index;
987 }
988 ++index;
989 }
paulhu2b9ed952022-02-10 21:58:32 +0800990 if (index >= fullName.length()) {
991 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700992 break;
993 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900994
paulhube186602022-04-12 07:18:23 +0000995 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +0800996 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700997 String type = rest.replace(".local.", "");
998
Paul Hu18aeccc2022-12-27 08:48:48 +0000999 final boolean isListenedToUpdates =
1000 clientId == clientInfo.mClientIdForServiceUpdates;
1001 final NsdServiceInfo serviceInfo = isListenedToUpdates
1002 ? clientInfo.mRegisteredService : clientInfo.mResolvedService;
1003
1004 serviceInfo.setServiceName(name);
1005 serviceInfo.setServiceType(type);
1006 serviceInfo.setPort(info.port);
1007 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001008 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001009
1010 stopResolveService(id);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001011 removeRequestMap(clientId, id, clientInfo);
1012
paulhu2b9ed952022-02-10 21:58:32 +08001013 final int id2 = getUniqueId();
1014 if (getAddrInfo(id2, info.hostname, info.interfaceIdx)) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001015 storeLegacyRequestMap(clientId, id2, clientInfo,
1016 NsdManager.RESOLVE_SERVICE);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001017 } else {
Paul Hu18aeccc2022-12-27 08:48:48 +00001018 notifyResolveFailedResult(isListenedToUpdates, clientId, clientInfo,
1019 NsdManager.FAILURE_BAD_PARAMETERS);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001020 }
1021 break;
paulhu2b9ed952022-02-10 21:58:32 +08001022 }
1023 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001024 /* NNN resolveId errorCode */
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001025 stopResolveService(id);
1026 removeRequestMap(clientId, id, clientInfo);
Paul Hu18aeccc2022-12-27 08:48:48 +00001027 notifyResolveFailedResult(
1028 clientId == clientInfo.mClientIdForServiceUpdates,
1029 clientId, clientInfo, NsdManager.FAILURE_BAD_PARAMETERS);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001030 break;
paulhu2b9ed952022-02-10 21:58:32 +08001031 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001032 /* NNN resolveId errorCode */
1033 stopGetAddrInfo(id);
1034 removeRequestMap(clientId, id, clientInfo);
Paul Hu18aeccc2022-12-27 08:48:48 +00001035 notifyResolveFailedResult(
1036 clientId == clientInfo.mClientIdForServiceUpdates,
1037 clientId, clientInfo, NsdManager.FAILURE_BAD_PARAMETERS);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001038 break;
paulhu2b9ed952022-02-10 21:58:32 +08001039 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001040 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001041 final GetAddressInfo info = (GetAddressInfo) obj;
1042 final String address = info.address;
1043 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001044 InetAddress serviceHost = null;
1045 try {
paulhu2b9ed952022-02-10 21:58:32 +08001046 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001047 } catch (UnknownHostException e) {
1048 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1049 }
1050
1051 // If the resolved service is on an interface without a network, consider it
1052 // as a failure: it would not be usable by apps as they would need
1053 // privileged permissions.
Paul Hu18aeccc2022-12-27 08:48:48 +00001054 if (clientId == clientInfo.mClientIdForServiceUpdates) {
1055 if (netId != NETID_UNSET && serviceHost != null) {
1056 setServiceNetworkForCallback(clientInfo.mRegisteredService,
1057 netId, info.interfaceIdx);
1058 final List<InetAddress> addresses =
1059 clientInfo.mRegisteredService.getHostAddresses();
1060 addresses.add(serviceHost);
1061 clientInfo.mRegisteredService.setHostAddresses(addresses);
1062 clientInfo.onServiceUpdated(
1063 clientId, clientInfo.mRegisteredService);
1064 } else {
1065 stopGetAddrInfo(id);
1066 removeRequestMap(clientId, id, clientInfo);
1067 clearRegisteredServiceInfo(clientInfo);
1068 clientInfo.onServiceInfoCallbackRegistrationFailed(
1069 clientId, NsdManager.FAILURE_BAD_PARAMETERS);
1070 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001071 } else {
Paul Hu18aeccc2022-12-27 08:48:48 +00001072 if (netId != NETID_UNSET && serviceHost != null) {
1073 clientInfo.mResolvedService.setHost(serviceHost);
1074 setServiceNetworkForCallback(clientInfo.mResolvedService,
1075 netId, info.interfaceIdx);
1076 clientInfo.onResolveServiceSucceeded(
1077 clientId, clientInfo.mResolvedService);
1078 } else {
1079 clientInfo.onResolveServiceFailed(
1080 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1081 }
1082 stopGetAddrInfo(id);
1083 removeRequestMap(clientId, id, clientInfo);
1084 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001085 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001086 break;
paulhu2b9ed952022-02-10 21:58:32 +08001087 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001088 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001089 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001090 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001091 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001092 }
Paul Hu019621e2023-01-13 23:26:49 +08001093
1094 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(final MdnsEvent event) {
1095 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1096 final String serviceType = event.mRequestedServiceType;
1097 final String serviceName = serviceInfo.getServiceInstanceName();
1098 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1099 final Network network = serviceInfo.getNetwork();
1100 setServiceNetworkForCallback(
1101 servInfo,
1102 network == null ? NETID_UNSET : network.netId,
1103 serviceInfo.getInterfaceIndex());
1104 return servInfo;
1105 }
1106
1107 private boolean handleMdnsDiscoveryManagerEvent(
1108 int transactionId, int code, Object obj) {
1109 final ClientInfo clientInfo = mIdToClientInfoMap.get(transactionId);
1110 if (clientInfo == null) {
1111 Log.e(TAG, String.format(
1112 "id %d for %d has no client mapping", transactionId, code));
1113 return false;
1114 }
1115
1116 final MdnsEvent event = (MdnsEvent) obj;
1117 final int clientId = event.mClientId;
Paul Hu319751a2023-01-13 23:56:34 +08001118 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event);
Paul Hu019621e2023-01-13 23:26:49 +08001119 if (DBG) {
1120 Log.d(TAG, String.format("MdnsDiscoveryManager event code=%s transactionId=%d",
1121 NsdManager.nameOf(code), transactionId));
1122 }
1123 switch (code) {
1124 case NsdManager.SERVICE_FOUND:
Paul Hu319751a2023-01-13 23:56:34 +08001125 clientInfo.onServiceFound(clientId, info);
1126 break;
1127 case NsdManager.SERVICE_LOST:
1128 clientInfo.onServiceLost(clientId, info);
Paul Hu019621e2023-01-13 23:26:49 +08001129 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001130 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001131 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
1132 if (request == null) {
1133 Log.e(TAG, "Unknown client request in RESOLVE_SERVICE_SUCCEEDED");
1134 break;
1135 }
Paul Hu75069ed2023-01-14 00:31:09 +08001136 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1137 // Add '.' in front of the service type that aligns with historical behavior
1138 info.setServiceType("." + event.mRequestedServiceType);
1139 info.setPort(serviceInfo.getPort());
1140
1141 Map<String, String> attrs = serviceInfo.getAttributes();
1142 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1143 final String key = kv.getKey();
1144 try {
1145 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1146 } catch (IllegalArgumentException e) {
1147 Log.e(TAG, "Invalid attribute", e);
1148 }
1149 }
1150 try {
1151 if (serviceInfo.getIpv4Address() != null) {
1152 info.setHost(InetAddresses.parseNumericAddress(
1153 serviceInfo.getIpv4Address()));
1154 } else {
1155 info.setHost(InetAddresses.parseNumericAddress(
1156 serviceInfo.getIpv6Address()));
1157 }
1158 clientInfo.onResolveServiceSucceeded(clientId, info);
1159 } catch (IllegalArgumentException e) {
1160 Log.wtf(TAG, "Invalid address in RESOLVE_SERVICE_SUCCEEDED", e);
1161 clientInfo.onResolveServiceFailed(
1162 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1163 }
1164
1165 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001166 if (!(request instanceof DiscoveryManagerRequest)) {
1167 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1168 break;
1169 }
Ahmad Khalil4b8d45a2023-03-02 11:43:25 +00001170 final MdnsListener listener = ((DiscoveryManagerRequest) request).mListener;
1171 mMdnsDiscoveryManager.unregisterListener(
1172 listener.getListenedServiceType(), listener);
1173 removeRequestMap(clientId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001174 break;
1175 }
Paul Hu019621e2023-01-13 23:26:49 +08001176 default:
1177 return false;
1178 }
1179 return true;
1180 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001181 }
1182 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001183
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001184 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1185 switch (netId) {
1186 case NETID_UNSET:
1187 info.setNetwork(null);
1188 break;
1189 case INetd.LOCAL_NET_ID:
1190 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1191 // visible / usable for apps, so do not return it. Store the interface
1192 // index instead, so at least if the client tries to resolve the service
1193 // with that NsdServiceInfo, it will be done on the same interface.
1194 // If they recreate the NsdServiceInfo themselves, resolution would be
1195 // done on all interfaces as before T, which should also work.
1196 info.setNetwork(null);
1197 info.setInterfaceIndex(ifaceIdx);
1198 break;
1199 default:
1200 info.setNetwork(new Network(netId));
1201 }
1202 }
1203
paulhube186602022-04-12 07:18:23 +00001204 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1205 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1206 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1207 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1208 private String unescape(String s) {
1209 StringBuilder sb = new StringBuilder(s.length());
1210 for (int i = 0; i < s.length(); ++i) {
1211 char c = s.charAt(i);
1212 if (c == '\\') {
1213 if (++i >= s.length()) {
1214 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1215 break;
1216 }
1217 c = s.charAt(i);
1218 if (c != '.' && c != '\\') {
1219 if (i + 2 >= s.length()) {
1220 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1221 break;
1222 }
1223 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1224 + (s.charAt(i + 2) - '0'));
1225 i += 2;
1226 }
1227 }
1228 sb.append(c);
1229 }
1230 return sb.toString();
1231 }
1232
Hugo Benichi803a2f02017-04-24 11:35:06 +09001233 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001234 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001235 this(ctx, handler, cleanupDelayMs, new Dependencies());
1236 }
1237
1238 @VisibleForTesting
1239 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001240 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001241 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001242 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001243 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001244 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1245 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001246 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001247
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001248 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper());
1249 mMdnsSocketClient =
1250 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider);
1251 mMdnsDiscoveryManager =
1252 deps.makeMdnsDiscoveryManager(new ExecutorProvider(), mMdnsSocketClient);
1253 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1254 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
1255 new AdvertiserCallback());
Paul Hu4bd98ef2023-01-12 13:42:07 +08001256 }
1257
1258 /**
1259 * Dependencies of NsdService, for injection in tests.
1260 */
1261 @VisibleForTesting
1262 public static class Dependencies {
1263 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001264 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001265 *
1266 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001267 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001268 */
1269 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +09001270 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context,
1271 NAMESPACE_CONNECTIVITY, MDNS_DISCOVERY_MANAGER_VERSION,
1272 false /* defaultEnabled */);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001273 }
1274
1275 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001276 * Check whether the MdnsAdvertiser feature is enabled.
1277 *
1278 * @param context The global context information about an app environment.
1279 * @return true if the MdnsAdvertiser feature is enabled.
1280 */
1281 public boolean isMdnsAdvertiserEnabled(Context context) {
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +09001282 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context,
1283 NAMESPACE_CONNECTIVITY, MDNS_ADVERTISER_VERSION, false /* defaultEnabled */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001284 }
1285
1286 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001287 * @see MdnsDiscoveryManager
1288 */
1289 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
1290 ExecutorProvider executorProvider, MdnsSocketClientBase socketClient) {
1291 return new MdnsDiscoveryManager(executorProvider, socketClient);
1292 }
1293
1294 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001295 * @see MdnsAdvertiser
1296 */
1297 public MdnsAdvertiser makeMdnsAdvertiser(
1298 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
1299 @NonNull MdnsAdvertiser.AdvertiserCallback cb) {
1300 return new MdnsAdvertiser(looper, socketProvider, cb);
1301 }
1302
1303 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001304 * @see MdnsSocketProvider
1305 */
1306 public MdnsSocketProvider makeMdnsSocketProvider(Context context, Looper looper) {
1307 return new MdnsSocketProvider(context, looper);
1308 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001309 }
1310
paulhu1b35e822022-04-08 14:48:41 +08001311 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001312 HandlerThread thread = new HandlerThread(TAG);
1313 thread.start();
1314 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001315 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001316 return service;
1317 }
1318
paulhu2b9ed952022-02-10 21:58:32 +08001319 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1320 private final StateMachine mStateMachine;
1321
1322 MDnsEventCallback(StateMachine sm) {
1323 mStateMachine = sm;
1324 }
1325
1326 @Override
1327 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1328 mStateMachine.sendMessage(
1329 MDNS_SERVICE_EVENT, status.result, status.id, status);
1330 }
1331
1332 @Override
1333 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1334 mStateMachine.sendMessage(
1335 MDNS_SERVICE_EVENT, status.result, status.id, status);
1336 }
1337
1338 @Override
1339 public void onServiceResolutionStatus(final ResolutionInfo status) {
1340 mStateMachine.sendMessage(
1341 MDNS_SERVICE_EVENT, status.result, status.id, status);
1342 }
1343
1344 @Override
1345 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1346 mStateMachine.sendMessage(
1347 MDNS_SERVICE_EVENT, status.result, status.id, status);
1348 }
1349
1350 @Override
1351 public int getInterfaceVersion() throws RemoteException {
1352 return this.VERSION;
1353 }
1354
1355 @Override
1356 public String getInterfaceHash() throws RemoteException {
1357 return this.HASH;
1358 }
1359 }
1360
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001361 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
1362 @Override
1363 public void onRegisterServiceSucceeded(int serviceId, NsdServiceInfo registeredInfo) {
1364 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1365 if (clientInfo == null) return;
1366
1367 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1368 if (clientId < 0) return;
1369
1370 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1371 // historical behavior.
1372 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
1373 clientInfo.onRegisterServiceSucceeded(clientId, cbInfo);
1374 }
1375
1376 @Override
1377 public void onRegisterServiceFailed(int serviceId, int errorCode) {
1378 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1379 if (clientInfo == null) return;
1380
1381 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1382 if (clientId < 0) return;
1383
1384 clientInfo.onRegisterServiceFailed(clientId, errorCode);
1385 }
1386
1387 private ClientInfo getClientInfoOrLog(int serviceId) {
1388 final ClientInfo clientInfo = mIdToClientInfoMap.get(serviceId);
1389 if (clientInfo == null) {
1390 Log.e(TAG, String.format("Callback for service %d has no client", serviceId));
1391 }
1392 return clientInfo;
1393 }
1394
1395 private int getClientIdOrLog(@NonNull ClientInfo info, int serviceId) {
1396 final int clientId = info.getClientId(serviceId);
1397 if (clientId < 0) {
1398 Log.e(TAG, String.format("Client ID not found for service %d", serviceId));
1399 }
1400 return clientId;
1401 }
1402 }
1403
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001404 @Override
1405 public INsdServiceConnector connect(INsdManagerCallback cb) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001406 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001407 final INsdServiceConnector connector = new NsdServiceConnector();
1408 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1409 NsdManager.REGISTER_CLIENT, new Pair<>(connector, cb)));
1410 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07001411 }
1412
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001413 private static class ListenerArgs {
1414 public final NsdServiceConnector connector;
1415 public final NsdServiceInfo serviceInfo;
1416 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
1417 this.connector = connector;
1418 this.serviceInfo = serviceInfo;
1419 }
1420 }
1421
1422 private class NsdServiceConnector extends INsdServiceConnector.Stub
1423 implements IBinder.DeathRecipient {
1424 @Override
1425 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
1426 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1427 NsdManager.REGISTER_SERVICE, 0, listenerKey,
1428 new ListenerArgs(this, serviceInfo)));
1429 }
1430
1431 @Override
1432 public void unregisterService(int listenerKey) {
1433 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1434 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
1435 new ListenerArgs(this, null)));
1436 }
1437
1438 @Override
1439 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
1440 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1441 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
1442 new ListenerArgs(this, serviceInfo)));
1443 }
1444
1445 @Override
1446 public void stopDiscovery(int listenerKey) {
1447 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1448 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
1449 }
1450
1451 @Override
1452 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
1453 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1454 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
1455 new ListenerArgs(this, serviceInfo)));
1456 }
1457
1458 @Override
Paul Hub58deb72022-12-26 09:24:42 +00001459 public void stopResolution(int listenerKey) {
1460 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1461 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
1462 }
1463
1464 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00001465 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
1466 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1467 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
1468 new ListenerArgs(this, serviceInfo)));
1469 }
1470
1471 @Override
1472 public void unregisterServiceInfoCallback(int listenerKey) {
1473 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1474 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
1475 new ListenerArgs(this, null)));
1476 }
1477
1478 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001479 public void startDaemon() {
1480 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1481 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
1482 }
1483
1484 @Override
1485 public void binderDied() {
1486 mNsdStateMachine.sendMessage(
1487 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
1488 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001489 }
1490
Hugo Benichi912db992017-04-24 16:41:03 +09001491 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07001492 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07001493 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09001494 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
1495 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07001496 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07001497 }
1498
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001499 private int getUniqueId() {
1500 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
1501 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001502 }
1503
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001504 private boolean registerService(int regId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09001505 if (DBG) {
paulhub2225702021-11-17 09:35:33 +08001506 Log.d(TAG, "registerService: " + regId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001507 }
Hugo Benichi6d706442017-04-24 16:19:58 +09001508 String name = service.getServiceName();
1509 String type = service.getServiceType();
1510 int port = service.getPort();
1511 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001512 final int registerInterface = getNetworkInterfaceIndex(service);
1513 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08001514 Log.e(TAG, "Interface to register service on not found");
1515 return false;
1516 }
1517 return mMDnsManager.registerService(regId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001518 }
1519
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001520 private boolean unregisterService(int regId) {
paulhu2b9ed952022-02-10 21:58:32 +08001521 return mMDnsManager.stopOperation(regId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001522 }
1523
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001524 private boolean discoverServices(int discoveryId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08001525 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001526 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
1527 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001528 Log.e(TAG, "Interface to discover service on not found");
1529 return false;
1530 }
paulhu2b9ed952022-02-10 21:58:32 +08001531 return mMDnsManager.discover(discoveryId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001532 }
1533
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001534 private boolean stopServiceDiscovery(int discoveryId) {
paulhu2b9ed952022-02-10 21:58:32 +08001535 return mMDnsManager.stopOperation(discoveryId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001536 }
1537
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001538 private boolean resolveService(int resolveId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001539 final String name = service.getServiceName();
1540 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001541 final int resolveInterface = getNetworkInterfaceIndex(service);
1542 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001543 Log.e(TAG, "Interface to resolve service on not found");
1544 return false;
1545 }
paulhu2b9ed952022-02-10 21:58:32 +08001546 return mMDnsManager.resolve(resolveId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001547 }
1548
1549 /**
1550 * Guess the interface to use to resolve or discover a service on a specific network.
1551 *
1552 * This is an imperfect guess, as for example the network may be gone or not yet fully
1553 * registered. This is fine as failing is correct if the network is gone, and a client
1554 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
1555 * this is to support the legacy mdnsresponder implementation, which historically resolved
1556 * services on an unspecified network.
1557 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001558 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
1559 final Network network = serviceInfo.getNetwork();
1560 if (network == null) {
1561 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
1562 // provided by NsdService from discovery results, and the service was found on an
1563 // interface that has no app-usable Network).
1564 if (serviceInfo.getInterfaceIndex() != 0) {
1565 return serviceInfo.getInterfaceIndex();
1566 }
1567 return IFACE_IDX_ANY;
1568 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001569
1570 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
1571 if (cm == null) {
1572 Log.wtf(TAG, "No ConnectivityManager for resolveService");
1573 return IFACE_IDX_ANY;
1574 }
1575 final LinkProperties lp = cm.getLinkProperties(network);
1576 if (lp == null) return IFACE_IDX_ANY;
1577
1578 // Only resolve on non-stacked interfaces
1579 final NetworkInterface iface;
1580 try {
1581 iface = NetworkInterface.getByName(lp.getInterfaceName());
1582 } catch (SocketException e) {
1583 Log.e(TAG, "Error querying interface", e);
1584 return IFACE_IDX_ANY;
1585 }
1586
1587 if (iface == null) {
1588 Log.e(TAG, "Interface not found: " + lp.getInterfaceName());
1589 return IFACE_IDX_ANY;
1590 }
1591
1592 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001593 }
1594
1595 private boolean stopResolveService(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001596 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001597 }
1598
paulhu2b9ed952022-02-10 21:58:32 +08001599 private boolean getAddrInfo(int resolveId, String hostname, int interfaceIdx) {
1600 return mMDnsManager.getServiceAddress(resolveId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001601 }
1602
1603 private boolean stopGetAddrInfo(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001604 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001605 }
1606
1607 @Override
Irfan Sheriff75006652012-04-17 23:15:29 -07001608 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
paulhu3ffffe72021-09-16 10:15:22 +08001609 if (!PermissionUtils.checkDumpPermission(mContext, TAG, pw)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001610
Irfan Sheriff75006652012-04-17 23:15:29 -07001611 for (ClientInfo client : mClients.values()) {
1612 pw.println("Client Info");
1613 pw.println(client);
1614 }
1615
1616 mNsdStateMachine.dump(fd, pw, args);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001617 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001618
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001619 private abstract static class ClientRequest {
1620 private final int mGlobalId;
1621
1622 private ClientRequest(int globalId) {
1623 mGlobalId = globalId;
1624 }
1625 }
1626
1627 private static class LegacyClientRequest extends ClientRequest {
1628 private final int mRequestCode;
1629
1630 private LegacyClientRequest(int globalId, int requestCode) {
1631 super(globalId);
1632 mRequestCode = requestCode;
1633 }
1634 }
1635
1636 private static class AdvertiserClientRequest extends ClientRequest {
1637 private AdvertiserClientRequest(int globalId) {
1638 super(globalId);
1639 }
1640 }
1641
1642 private static class DiscoveryManagerRequest extends ClientRequest {
1643 @NonNull
1644 private final MdnsListener mListener;
1645
1646 private DiscoveryManagerRequest(int globalId, @NonNull MdnsListener listener) {
1647 super(globalId);
1648 mListener = listener;
1649 }
1650 }
1651
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001652 /* Information tracked per client */
1653 private class ClientInfo {
1654
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001655 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001656 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001657 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001658 private NsdServiceInfo mResolvedService;
1659
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001660 /* A map from client-side ID (listenerKey) to the request */
1661 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08001662
Luke Huangf7277ed2021-07-12 21:15:10 +08001663 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001664 private boolean mIsPreSClient = false;
Luke Huangf7277ed2021-07-12 21:15:10 +08001665
Paul Hu18aeccc2022-12-27 08:48:48 +00001666 /*** The service that is registered to listen to its updates */
1667 private NsdServiceInfo mRegisteredService;
1668 /*** The client id that listen to updates */
1669 private int mClientIdForServiceUpdates;
1670
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001671 private ClientInfo(INsdManagerCallback cb) {
1672 mCb = cb;
paulhub2225702021-11-17 09:35:33 +08001673 if (DBG) Log.d(TAG, "New client");
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001674 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001675
1676 @Override
1677 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06001678 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07001679 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001680 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
1681 for (int i = 0; i < mClientRequests.size(); i++) {
1682 int clientID = mClientRequests.keyAt(i);
1683 sb.append("clientId ")
1684 .append(clientID)
1685 .append(" mDnsId ").append(mClientRequests.valueAt(i).mGlobalId)
1686 .append(" type ").append(
1687 mClientRequests.valueAt(i).getClass().getSimpleName())
1688 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07001689 }
1690 return sb.toString();
1691 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001692
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001693 private boolean isPreSClient() {
1694 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08001695 }
1696
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001697 private void setPreSClient() {
1698 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08001699 }
1700
Dave Plattfeff2af2014-03-07 14:48:22 -08001701 // Remove any pending requests from the global map when we get rid of a client,
1702 // and send cancellations to the daemon.
1703 private void expungeAllRequests() {
Hugo Benichid2552ae2017-04-11 14:42:47 +09001704 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001705 for (int i = 0; i < mClientRequests.size(); i++) {
1706 final int clientId = mClientRequests.keyAt(i);
1707 final ClientRequest request = mClientRequests.valueAt(i);
1708 final int globalId = request.mGlobalId;
Dave Plattfeff2af2014-03-07 14:48:22 -08001709 mIdToClientInfoMap.remove(globalId);
paulhub2225702021-11-17 09:35:33 +08001710 if (DBG) {
1711 Log.d(TAG, "Terminating client-ID " + clientId
1712 + " global-ID " + globalId + " type " + mClientRequests.get(clientId));
1713 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001714
1715 if (request instanceof DiscoveryManagerRequest) {
Ahmad Khalil4b8d45a2023-03-02 11:43:25 +00001716 final MdnsListener listener =
1717 ((DiscoveryManagerRequest) request).mListener;
1718 mMdnsDiscoveryManager.unregisterListener(
1719 listener.getListenedServiceType(), listener);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001720 continue;
1721 }
1722
1723 if (request instanceof AdvertiserClientRequest) {
1724 mAdvertiser.removeService(globalId);
1725 continue;
1726 }
1727
1728 if (!(request instanceof LegacyClientRequest)) {
1729 throw new IllegalStateException("Unknown request type: " + request.getClass());
1730 }
1731
1732 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08001733 case NsdManager.DISCOVER_SERVICES:
1734 stopServiceDiscovery(globalId);
1735 break;
1736 case NsdManager.RESOLVE_SERVICE:
1737 stopResolveService(globalId);
1738 break;
1739 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001740 unregisterService(globalId);
Dave Plattfeff2af2014-03-07 14:48:22 -08001741 break;
1742 default:
1743 break;
1744 }
1745 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001746 mClientRequests.clear();
1747 }
1748
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001749 // mClientRequests is a sparse array of listener id -> ClientRequest. For a given
1750 // mDnsClient id, return the corresponding listener id. mDnsClient id is also called a
1751 // global id.
Christopher Lane74411222014-04-25 18:39:07 -07001752 private int getClientId(final int globalId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001753 for (int i = 0; i < mClientRequests.size(); i++) {
1754 if (mClientRequests.valueAt(i).mGlobalId == globalId) {
1755 return mClientRequests.keyAt(i);
1756 }
Christopher Lane74411222014-04-25 18:39:07 -07001757 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001758 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07001759 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001760
Paul Hu18aeccc2022-12-27 08:48:48 +00001761 private void maybeNotifyRegisteredServiceLost(@NonNull NsdServiceInfo info) {
1762 if (mRegisteredService == null) return;
1763 if (!Objects.equals(mRegisteredService.getServiceName(), info.getServiceName())) return;
1764 // Resolved services have a leading dot appended at the beginning of their type, but in
1765 // discovered info it's at the end
1766 if (!Objects.equals(
1767 mRegisteredService.getServiceType() + ".", "." + info.getServiceType())) {
1768 return;
1769 }
1770 onServiceUpdatedLost(mClientIdForServiceUpdates);
1771 }
1772
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001773 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info) {
1774 try {
1775 mCb.onDiscoverServicesStarted(listenerKey, info);
1776 } catch (RemoteException e) {
1777 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
1778 }
1779 }
1780
1781 void onDiscoverServicesFailed(int listenerKey, int error) {
1782 try {
1783 mCb.onDiscoverServicesFailed(listenerKey, error);
1784 } catch (RemoteException e) {
1785 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
1786 }
1787 }
1788
1789 void onServiceFound(int listenerKey, NsdServiceInfo info) {
1790 try {
1791 mCb.onServiceFound(listenerKey, info);
1792 } catch (RemoteException e) {
1793 Log.e(TAG, "Error calling onServiceFound(", e);
1794 }
1795 }
1796
1797 void onServiceLost(int listenerKey, NsdServiceInfo info) {
1798 try {
1799 mCb.onServiceLost(listenerKey, info);
1800 } catch (RemoteException e) {
1801 Log.e(TAG, "Error calling onServiceLost(", e);
1802 }
1803 }
1804
1805 void onStopDiscoveryFailed(int listenerKey, int error) {
1806 try {
1807 mCb.onStopDiscoveryFailed(listenerKey, error);
1808 } catch (RemoteException e) {
1809 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
1810 }
1811 }
1812
1813 void onStopDiscoverySucceeded(int listenerKey) {
1814 try {
1815 mCb.onStopDiscoverySucceeded(listenerKey);
1816 } catch (RemoteException e) {
1817 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
1818 }
1819 }
1820
1821 void onRegisterServiceFailed(int listenerKey, int error) {
1822 try {
1823 mCb.onRegisterServiceFailed(listenerKey, error);
1824 } catch (RemoteException e) {
1825 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
1826 }
1827 }
1828
1829 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info) {
1830 try {
1831 mCb.onRegisterServiceSucceeded(listenerKey, info);
1832 } catch (RemoteException e) {
1833 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
1834 }
1835 }
1836
1837 void onUnregisterServiceFailed(int listenerKey, int error) {
1838 try {
1839 mCb.onUnregisterServiceFailed(listenerKey, error);
1840 } catch (RemoteException e) {
1841 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
1842 }
1843 }
1844
1845 void onUnregisterServiceSucceeded(int listenerKey) {
1846 try {
1847 mCb.onUnregisterServiceSucceeded(listenerKey);
1848 } catch (RemoteException e) {
1849 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
1850 }
1851 }
1852
1853 void onResolveServiceFailed(int listenerKey, int error) {
1854 try {
1855 mCb.onResolveServiceFailed(listenerKey, error);
1856 } catch (RemoteException e) {
1857 Log.e(TAG, "Error calling onResolveServiceFailed", e);
1858 }
1859 }
1860
1861 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info) {
1862 try {
1863 mCb.onResolveServiceSucceeded(listenerKey, info);
1864 } catch (RemoteException e) {
1865 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
1866 }
1867 }
Paul Hub58deb72022-12-26 09:24:42 +00001868
1869 void onStopResolutionFailed(int listenerKey, int error) {
1870 try {
1871 mCb.onStopResolutionFailed(listenerKey, error);
1872 } catch (RemoteException e) {
1873 Log.e(TAG, "Error calling onStopResolutionFailed", e);
1874 }
1875 }
1876
1877 void onStopResolutionSucceeded(int listenerKey) {
1878 try {
1879 mCb.onStopResolutionSucceeded(listenerKey);
1880 } catch (RemoteException e) {
1881 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
1882 }
1883 }
Paul Hu18aeccc2022-12-27 08:48:48 +00001884
1885 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
1886 try {
1887 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
1888 } catch (RemoteException e) {
1889 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
1890 }
1891 }
1892
1893 void onServiceUpdated(int listenerKey, NsdServiceInfo info) {
1894 try {
1895 mCb.onServiceUpdated(listenerKey, info);
1896 } catch (RemoteException e) {
1897 Log.e(TAG, "Error calling onServiceUpdated", e);
1898 }
1899 }
1900
1901 void onServiceUpdatedLost(int listenerKey) {
1902 try {
1903 mCb.onServiceUpdatedLost(listenerKey);
1904 } catch (RemoteException e) {
1905 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
1906 }
1907 }
1908
1909 void onServiceInfoCallbackUnregistered(int listenerKey) {
1910 try {
1911 mCb.onServiceInfoCallbackUnregistered(listenerKey);
1912 } catch (RemoteException e) {
1913 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
1914 }
1915 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001916 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001917}