blob: 619b64d851e07c4dafdcaa4747c812d78112dbe2 [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;
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +090023import static android.provider.DeviceConfig.NAMESPACE_TETHERING;
paulhu2b9ed952022-02-10 21:58:32 +080024
Paul Hu23fa2022023-01-13 22:57:24 +080025import android.annotation.NonNull;
Paul Hu4bd98ef2023-01-12 13:42:07 +080026import android.annotation.Nullable;
paulhua262cc12019-08-12 16:25:11 +080027import android.content.Context;
Irfan Sheriff75006652012-04-17 23:15:29 -070028import android.content.Intent;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090029import android.net.ConnectivityManager;
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +090030import android.net.INetd;
Paul Hu75069ed2023-01-14 00:31:09 +080031import android.net.InetAddresses;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090032import android.net.LinkProperties;
33import android.net.Network;
paulhu2b9ed952022-02-10 21:58:32 +080034import android.net.mdns.aidl.DiscoveryInfo;
35import android.net.mdns.aidl.GetAddressInfo;
36import android.net.mdns.aidl.IMDnsEventListener;
37import android.net.mdns.aidl.RegistrationInfo;
38import android.net.mdns.aidl.ResolutionInfo;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070039import android.net.nsd.INsdManager;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090040import android.net.nsd.INsdManagerCallback;
41import android.net.nsd.INsdServiceConnector;
paulhu2b9ed952022-02-10 21:58:32 +080042import android.net.nsd.MDnsManager;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070043import android.net.nsd.NsdManager;
paulhua262cc12019-08-12 16:25:11 +080044import android.net.nsd.NsdServiceInfo;
Hugo Benichi803a2f02017-04-24 11:35:06 +090045import android.os.Handler;
paulhua262cc12019-08-12 16:25:11 +080046import android.os.HandlerThread;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090047import android.os.IBinder;
Paul Hu4bd98ef2023-01-12 13:42:07 +080048import android.os.Looper;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070049import android.os.Message;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090050import android.os.RemoteException;
Dianne Hackborn692107e2012-08-29 18:32:08 -070051import android.os.UserHandle;
Paul Hu23fa2022023-01-13 22:57:24 +080052import android.text.TextUtils;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090053import android.util.Log;
54import android.util.Pair;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070055import android.util.SparseArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070056
paulhua262cc12019-08-12 16:25:11 +080057import com.android.internal.annotations.VisibleForTesting;
paulhua262cc12019-08-12 16:25:11 +080058import com.android.internal.util.State;
59import com.android.internal.util.StateMachine;
Paul Hu4bd98ef2023-01-12 13:42:07 +080060import com.android.net.module.util.DeviceConfigUtils;
paulhu3ffffe72021-09-16 10:15:22 +080061import com.android.net.module.util.PermissionUtils;
Paul Hu4bd98ef2023-01-12 13:42:07 +080062import com.android.server.connectivity.mdns.ExecutorProvider;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090063import com.android.server.connectivity.mdns.MdnsAdvertiser;
Paul Hu4bd98ef2023-01-12 13:42:07 +080064import com.android.server.connectivity.mdns.MdnsDiscoveryManager;
65import com.android.server.connectivity.mdns.MdnsMultinetworkSocketClient;
Paul Hu23fa2022023-01-13 22:57:24 +080066import com.android.server.connectivity.mdns.MdnsSearchOptions;
67import com.android.server.connectivity.mdns.MdnsServiceBrowserListener;
68import com.android.server.connectivity.mdns.MdnsServiceInfo;
Paul Hu4bd98ef2023-01-12 13:42:07 +080069import com.android.server.connectivity.mdns.MdnsSocketClientBase;
70import com.android.server.connectivity.mdns.MdnsSocketProvider;
paulhua262cc12019-08-12 16:25:11 +080071
Irfan Sheriff77ec5582012-03-22 17:01:39 -070072import java.io.FileDescriptor;
73import java.io.PrintWriter;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070074import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090075import java.net.NetworkInterface;
76import java.net.SocketException;
77import java.net.UnknownHostException;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090078import java.nio.ByteBuffer;
79import java.nio.CharBuffer;
80import java.nio.charset.Charset;
81import java.nio.charset.CharsetEncoder;
82import java.nio.charset.StandardCharsets;
Paul Hu2b865912023-03-06 14:27:53 +080083import java.util.ArrayList;
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
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900115 /**
116 * Comma-separated list of type:flag mappings indicating the flags to use to allowlist
117 * discovery/advertising using MdnsDiscoveryManager / MdnsAdvertiser for a given type.
118 *
119 * For example _mytype._tcp.local and _othertype._tcp.local would be configured with:
120 * _mytype._tcp:mytype,_othertype._tcp.local:othertype
121 *
122 * In which case the flags:
123 * "mdns_discovery_manager_allowlist_mytype_version",
124 * "mdns_advertiser_allowlist_mytype_version",
125 * "mdns_discovery_manager_allowlist_othertype_version",
126 * "mdns_advertiser_allowlist_othertype_version"
127 * would be used to toggle MdnsDiscoveryManager / MdnsAdvertiser for each type. The flags will
128 * be read with
129 * {@link DeviceConfigUtils#isFeatureEnabled(Context, String, String, String, boolean)}.
130 *
131 * @see #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX
132 * @see #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX
133 * @see #MDNS_ALLOWLIST_FLAG_SUFFIX
134 */
135 private static final String MDNS_TYPE_ALLOWLIST_FLAGS = "mdns_type_allowlist_flags";
136
137 private static final String MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX =
138 "mdns_discovery_manager_allowlist_";
139 private static final String MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX =
140 "mdns_advertiser_allowlist_";
141 private static final String MDNS_ALLOWLIST_FLAG_SUFFIX = "_version";
142
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900143 public static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +0000144 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900145 private static final int IFACE_IDX_ANY = 0;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700146
Hugo Benichi32be63d2017-04-05 14:06:11 +0900147 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900148 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +0800149 private final MDnsManager mMDnsManager;
150 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900151 @NonNull
152 private final Dependencies mDeps;
153 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800154 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900155 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800156 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900157 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800158 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900159 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900160 private final MdnsAdvertiser mAdvertiser;
Paul Hu23fa2022023-01-13 22:57:24 +0800161 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800162 // state machine thread. If change this outside state machine, it will need to introduce
163 // synchronization.
164 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800165 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700166
167 /**
168 * Clients receiving asynchronous messages
169 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900170 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700171
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700172 /* A map from unique id to client info */
Hugo Benichi32be63d2017-04-05 14:06:11 +0900173 private final SparseArray<ClientInfo> mIdToClientInfoMap= new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700174
Luke Huang05298582021-06-13 16:52:05 +0000175 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700176
Hugo Benichi32be63d2017-04-05 14:06:11 +0900177 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700178 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800179 // The count of the connected legacy clients.
180 private int mLegacyClientCount = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700181
Paul Hu23fa2022023-01-13 22:57:24 +0800182 private static class MdnsListener implements MdnsServiceBrowserListener {
183 protected final int mClientId;
184 protected final int mTransactionId;
185 @NonNull
186 protected final NsdServiceInfo mReqServiceInfo;
187 @NonNull
188 protected final String mListenedServiceType;
189
190 MdnsListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
191 @NonNull String listenedServiceType) {
192 mClientId = clientId;
193 mTransactionId = transactionId;
194 mReqServiceInfo = reqServiceInfo;
195 mListenedServiceType = listenedServiceType;
196 }
197
198 @NonNull
199 public String getListenedServiceType() {
200 return mListenedServiceType;
201 }
202
203 @Override
204 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo) { }
205
206 @Override
207 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
208
209 @Override
210 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
211
212 @Override
213 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) { }
214
215 @Override
216 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
217
218 @Override
219 public void onSearchStoppedWithError(int error) { }
220
221 @Override
222 public void onSearchFailedToStart() { }
223
224 @Override
225 public void onDiscoveryQuerySent(@NonNull List<String> subtypes, int transactionId) { }
226
227 @Override
228 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
229 }
230
231 private class DiscoveryListener extends MdnsListener {
232
233 DiscoveryListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
234 @NonNull String listenServiceType) {
235 super(clientId, transactionId, reqServiceInfo, listenServiceType);
236 }
237
238 @Override
239 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu019621e2023-01-13 23:26:49 +0800240 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
241 NsdManager.SERVICE_FOUND,
242 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800243 }
244
245 @Override
246 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800247 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
248 NsdManager.SERVICE_LOST,
249 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800250 }
251 }
252
Paul Hu75069ed2023-01-14 00:31:09 +0800253 private class ResolutionListener extends MdnsListener {
254
255 ResolutionListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
256 @NonNull String listenServiceType) {
257 super(clientId, transactionId, reqServiceInfo, listenServiceType);
258 }
259
260 @Override
261 public void onServiceFound(MdnsServiceInfo serviceInfo) {
262 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
263 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
264 new MdnsEvent(mClientId, mReqServiceInfo.getServiceType(), serviceInfo));
265 }
266 }
267
Paul Hu019621e2023-01-13 23:26:49 +0800268 /**
269 * Data class of mdns service callback information.
270 */
271 private static class MdnsEvent {
272 final int mClientId;
273 @NonNull
274 final String mRequestedServiceType;
275 @NonNull
276 final MdnsServiceInfo mMdnsServiceInfo;
277
278 MdnsEvent(int clientId, @NonNull String requestedServiceType,
279 @NonNull MdnsServiceInfo mdnsServiceInfo) {
280 mClientId = clientId;
281 mRequestedServiceType = requestedServiceType;
282 mMdnsServiceInfo = mdnsServiceInfo;
283 }
284 }
285
Irfan Sheriff75006652012-04-17 23:15:29 -0700286 private class NsdStateMachine extends StateMachine {
287
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700288 private final DefaultState mDefaultState = new DefaultState();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700289 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700290
291 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700292 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900293 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700294 }
295
Luke Huang92860f92021-06-23 06:29:30 +0000296 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800297 if (mIsDaemonStarted) {
298 if (DBG) Log.d(TAG, "Daemon is already started.");
299 return;
300 }
301 mMDnsManager.registerEventListener(mMDnsEventCallback);
302 mMDnsManager.startDaemon();
303 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000304 maybeScheduleStop();
305 }
306
paulhu2b9ed952022-02-10 21:58:32 +0800307 private void maybeStopDaemon() {
308 if (!mIsDaemonStarted) {
309 if (DBG) Log.d(TAG, "Daemon has not been started.");
310 return;
311 }
312 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
313 mMDnsManager.stopDaemon();
314 mIsDaemonStarted = false;
315 }
316
Luke Huang92860f92021-06-23 06:29:30 +0000317 private boolean isAnyRequestActive() {
318 return mIdToClientInfoMap.size() != 0;
319 }
320
321 private void scheduleStop() {
322 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
323 }
324 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800325 // The native daemon should stay alive and can't be cleanup
326 // if any legacy client connected.
327 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000328 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000329 }
330 }
331
Luke Huang92860f92021-06-23 06:29:30 +0000332 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000333 this.removeMessages(NsdManager.DAEMON_CLEANUP);
334 }
335
Paul Hu23fa2022023-01-13 22:57:24 +0800336 private void maybeStartMonitoringSockets() {
337 if (mIsMonitoringSocketsStarted) {
338 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
339 return;
340 }
341
342 mMdnsSocketProvider.startMonitoringSockets();
343 mIsMonitoringSocketsStarted = true;
344 }
345
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900346 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
347 if (!mIsMonitoringSocketsStarted) return;
348 if (isAnyRequestActive()) return;
349
Paul Hu58f20602023-02-18 11:41:07 +0800350 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800351 mIsMonitoringSocketsStarted = false;
352 }
353
Hugo Benichi803a2f02017-04-24 11:35:06 +0900354 NsdStateMachine(String name, Handler handler) {
355 super(name, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -0700356 addState(mDefaultState);
Irfan Sheriff75006652012-04-17 23:15:29 -0700357 addState(mEnabledState, mDefaultState);
paulhu5568f452021-11-30 13:31:29 +0800358 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900359 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700360 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700361 }
362
363 class DefaultState extends State {
364 @Override
365 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900366 final ClientInfo cInfo;
367 final int clientId = msg.arg2;
Irfan Sheriff75006652012-04-17 23:15:29 -0700368 switch (msg.what) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900369 case NsdManager.REGISTER_CLIENT:
370 final Pair<NsdServiceConnector, INsdManagerCallback> arg =
371 (Pair<NsdServiceConnector, INsdManagerCallback>) msg.obj;
372 final INsdManagerCallback cb = arg.second;
373 try {
374 cb.asBinder().linkToDeath(arg.first, 0);
375 cInfo = new ClientInfo(cb);
376 mClients.put(arg.first, cInfo);
377 } catch (RemoteException e) {
378 Log.w(TAG, "Client " + clientId + " has already died");
Irfan Sheriff75006652012-04-17 23:15:29 -0700379 }
380 break;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900381 case NsdManager.UNREGISTER_CLIENT:
382 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
383 cInfo = mClients.remove(connector);
Dave Plattfeff2af2014-03-07 14:48:22 -0800384 if (cInfo != null) {
385 cInfo.expungeAllRequests();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900386 if (cInfo.isPreSClient()) {
Luke Huangf7277ed2021-07-12 21:15:10 +0800387 mLegacyClientCount -= 1;
388 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800389 }
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900390 maybeStopMonitoringSocketsIfNoActiveRequest();
Luke Huangf7277ed2021-07-12 21:15:10 +0800391 maybeScheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700392 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700393 case NsdManager.DISCOVER_SERVICES:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900394 cInfo = getClientInfoForReply(msg);
395 if (cInfo != null) {
396 cInfo.onDiscoverServicesFailed(
397 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
398 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700399 break;
400 case NsdManager.STOP_DISCOVERY:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900401 cInfo = getClientInfoForReply(msg);
402 if (cInfo != null) {
403 cInfo.onStopDiscoveryFailed(
404 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
405 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700406 break;
407 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900408 cInfo = getClientInfoForReply(msg);
409 if (cInfo != null) {
410 cInfo.onRegisterServiceFailed(
411 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
412 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700413 break;
414 case NsdManager.UNREGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900415 cInfo = getClientInfoForReply(msg);
416 if (cInfo != null) {
417 cInfo.onUnregisterServiceFailed(
418 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
419 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700420 break;
421 case NsdManager.RESOLVE_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900422 cInfo = getClientInfoForReply(msg);
423 if (cInfo != null) {
424 cInfo.onResolveServiceFailed(
425 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
426 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700427 break;
Paul Hub58deb72022-12-26 09:24:42 +0000428 case NsdManager.STOP_RESOLUTION:
429 cInfo = getClientInfoForReply(msg);
430 if (cInfo != null) {
431 cInfo.onStopResolutionFailed(
432 clientId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
433 }
434 break;
Paul Hu18aeccc2022-12-27 08:48:48 +0000435 case NsdManager.REGISTER_SERVICE_CALLBACK:
436 cInfo = getClientInfoForReply(msg);
437 if (cInfo != null) {
438 cInfo.onServiceInfoCallbackRegistrationFailed(
439 clientId, NsdManager.FAILURE_BAD_PARAMETERS);
440 }
441 break;
Luke Huang05298582021-06-13 16:52:05 +0000442 case NsdManager.DAEMON_CLEANUP:
paulhu2b9ed952022-02-10 21:58:32 +0800443 maybeStopDaemon();
Luke Huang05298582021-06-13 16:52:05 +0000444 break;
Luke Huangf7277ed2021-07-12 21:15:10 +0800445 // This event should be only sent by the legacy (target SDK < S) clients.
446 // Mark the sending client as legacy.
447 case NsdManager.DAEMON_STARTUP:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900448 cInfo = getClientInfoForReply(msg);
Luke Huangf7277ed2021-07-12 21:15:10 +0800449 if (cInfo != null) {
450 cancelStop();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900451 cInfo.setPreSClient();
Luke Huangf7277ed2021-07-12 21:15:10 +0800452 mLegacyClientCount += 1;
453 maybeStartDaemon();
454 }
455 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700456 default:
paulhub2225702021-11-17 09:35:33 +0800457 Log.e(TAG, "Unhandled " + msg);
Irfan Sheriff75006652012-04-17 23:15:29 -0700458 return NOT_HANDLED;
459 }
460 return HANDLED;
461 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900462
463 private ClientInfo getClientInfoForReply(Message msg) {
464 final ListenerArgs args = (ListenerArgs) msg.obj;
465 return mClients.get(args.connector);
466 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700467 }
468
Irfan Sheriff75006652012-04-17 23:15:29 -0700469 class EnabledState extends State {
470 @Override
471 public void enter() {
472 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700473 }
474
475 @Override
476 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000477 // TODO: it is incorrect to stop the daemon without expunging all requests
478 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000479 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700480 }
481
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700482 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900483 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800484 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700485 return true;
486 }
487 return false;
488 }
489
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900490 private void storeLegacyRequestMap(int clientId, int globalId, ClientInfo clientInfo,
491 int what) {
492 clientInfo.mClientRequests.put(clientId, new LegacyClientRequest(globalId, what));
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700493 mIdToClientInfoMap.put(globalId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000494 // Remove the cleanup event because here comes a new request.
495 cancelStop();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700496 }
497
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900498 private void storeAdvertiserRequestMap(int clientId, int globalId,
Paul Hu23fa2022023-01-13 22:57:24 +0800499 ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900500 clientInfo.mClientRequests.put(clientId, new AdvertiserClientRequest(globalId));
501 mIdToClientInfoMap.put(globalId, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800502 }
503
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900504 private void removeRequestMap(int clientId, int globalId, ClientInfo clientInfo) {
505 final ClientRequest existing = clientInfo.mClientRequests.get(clientId);
506 if (existing == null) return;
507 clientInfo.mClientRequests.remove(clientId);
508 mIdToClientInfoMap.remove(globalId);
509
510 if (existing instanceof LegacyClientRequest) {
511 maybeScheduleStop();
512 } else {
513 maybeStopMonitoringSocketsIfNoActiveRequest();
514 }
515 }
516
517 private void storeDiscoveryManagerRequestMap(int clientId, int globalId,
518 MdnsListener listener, ClientInfo clientInfo) {
519 clientInfo.mClientRequests.put(clientId,
520 new DiscoveryManagerRequest(globalId, listener));
521 mIdToClientInfoMap.put(globalId, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800522 }
523
Paul Hu18aeccc2022-12-27 08:48:48 +0000524 private void clearRegisteredServiceInfo(ClientInfo clientInfo) {
525 clientInfo.mRegisteredService = null;
526 clientInfo.mClientIdForServiceUpdates = 0;
527 }
528
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900529
530 /**
531 * Truncate a service name to up to 63 UTF-8 bytes.
532 *
533 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
534 * names used in registerService follows historical behavior (see mdnsresponder
535 * handle_regservice_request).
536 */
537 @NonNull
538 private String truncateServiceName(@NonNull String originalName) {
539 // UTF-8 is at most 4 bytes per character; return early in the common case where
540 // the name can't possibly be over the limit given its string length.
541 if (originalName.length() <= MAX_LABEL_LENGTH / 4) return originalName;
542
543 final Charset utf8 = StandardCharsets.UTF_8;
544 final CharsetEncoder encoder = utf8.newEncoder();
545 final ByteBuffer out = ByteBuffer.allocate(MAX_LABEL_LENGTH);
546 // encode will write as many characters as possible to the out buffer, and just
547 // return an overflow code if there were too many characters (no need to check the
548 // return code here, this method truncates the name on purpose).
549 encoder.encode(CharBuffer.wrap(originalName), out, true /* endOfInput */);
550 return new String(out.array(), 0, out.position(), utf8);
Paul Hu23fa2022023-01-13 22:57:24 +0800551 }
552
Paul Hue4f5f252023-02-16 21:13:47 +0800553 private void stopDiscoveryManagerRequest(ClientRequest request, int clientId, int id,
554 ClientInfo clientInfo) {
555 clientInfo.unregisterMdnsListenerFromRequest(request);
556 removeRequestMap(clientId, id, clientInfo);
557 }
558
Irfan Sheriff75006652012-04-17 23:15:29 -0700559 @Override
560 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900561 final ClientInfo clientInfo;
562 final int id;
563 final int clientId = msg.arg2;
564 final ListenerArgs args;
Irfan Sheriff75006652012-04-17 23:15:29 -0700565 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800566 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800567 if (DBG) Log.d(TAG, "Discover services");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900568 args = (ListenerArgs) msg.obj;
569 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000570 // If the binder death notification for a INsdManagerCallback was received
571 // before any calls are received by NsdService, the clientInfo would be
572 // cleared and cause NPE. Add a null check here to prevent this corner case.
573 if (clientInfo == null) {
574 Log.e(TAG, "Unknown connector in discovery");
575 break;
576 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700577
578 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900579 clientInfo.onDiscoverServicesFailed(
580 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriff75006652012-04-17 23:15:29 -0700581 break;
582 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700583
Paul Hu23fa2022023-01-13 22:57:24 +0800584 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700585 id = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900586 final String serviceType = constructServiceType(info.getServiceType());
587 if (mDeps.isMdnsDiscoveryManagerEnabled(mContext)
588 || useDiscoveryManagerForType(serviceType)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800589 if (serviceType == null) {
590 clientInfo.onDiscoverServicesFailed(clientId,
591 NsdManager.FAILURE_INTERNAL_ERROR);
592 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700593 }
Paul Hu23fa2022023-01-13 22:57:24 +0800594
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900595 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800596 maybeStartMonitoringSockets();
597 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900598 new DiscoveryListener(clientId, id, info, listenServiceType);
Paul Hu23fa2022023-01-13 22:57:24 +0800599 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
600 .setNetwork(info.getNetwork())
601 .setIsPassiveMode(true)
602 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900603 mMdnsDiscoveryManager.registerListener(
604 listenServiceType, listener, options);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900605 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Paul Hu23fa2022023-01-13 22:57:24 +0800606 clientInfo.onDiscoverServicesStarted(clientId, info);
Irfan Sheriff75006652012-04-17 23:15:29 -0700607 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800608 maybeStartDaemon();
609 if (discoverServices(id, info)) {
610 if (DBG) {
611 Log.d(TAG, "Discover " + msg.arg2 + " " + id
612 + info.getServiceType());
613 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900614 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu23fa2022023-01-13 22:57:24 +0800615 clientInfo.onDiscoverServicesStarted(clientId, info);
616 } else {
617 stopServiceDiscovery(id);
618 clientInfo.onDiscoverServicesFailed(clientId,
619 NsdManager.FAILURE_INTERNAL_ERROR);
620 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700621 }
622 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800623 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900624 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800625 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900626 args = (ListenerArgs) msg.obj;
627 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000628 // If the binder death notification for a INsdManagerCallback was received
629 // before any calls are received by NsdService, the clientInfo would be
630 // cleared and cause NPE. Add a null check here to prevent this corner case.
631 if (clientInfo == null) {
632 Log.e(TAG, "Unknown connector in stop discovery");
633 break;
634 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700635
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900636 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
637 if (request == null) {
638 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700639 break;
640 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900641 id = request.mGlobalId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900642 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
643 // point, so this needs to check the type of the original request to
644 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900645 if (request instanceof DiscoveryManagerRequest) {
Paul Hue4f5f252023-02-16 21:13:47 +0800646 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900647 clientInfo.onStopDiscoverySucceeded(clientId);
Irfan Sheriff75006652012-04-17 23:15:29 -0700648 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800649 removeRequestMap(clientId, id, clientInfo);
650 if (stopServiceDiscovery(id)) {
651 clientInfo.onStopDiscoverySucceeded(clientId);
652 } else {
653 clientInfo.onStopDiscoveryFailed(
654 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
655 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700656 }
657 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900658 }
659 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800660 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900661 args = (ListenerArgs) msg.obj;
662 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000663 // If the binder death notification for a INsdManagerCallback was received
664 // before any calls are received by NsdService, the clientInfo would be
665 // cleared and cause NPE. Add a null check here to prevent this corner case.
666 if (clientInfo == null) {
667 Log.e(TAG, "Unknown connector in registration");
668 break;
669 }
670
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700671 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900672 clientInfo.onRegisterServiceFailed(
673 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700674 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700675 }
676
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700677 id = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900678 final NsdServiceInfo serviceInfo = args.serviceInfo;
679 final String serviceType = serviceInfo.getServiceType();
680 final String registerServiceType = constructServiceType(serviceType);
681 if (mDeps.isMdnsAdvertiserEnabled(mContext)
682 || useAdvertiserForType(registerServiceType)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900683 if (registerServiceType == null) {
684 Log.e(TAG, "Invalid service type: " + serviceType);
685 clientInfo.onRegisterServiceFailed(clientId,
686 NsdManager.FAILURE_INTERNAL_ERROR);
687 break;
688 }
689 serviceInfo.setServiceType(registerServiceType);
690 serviceInfo.setServiceName(truncateServiceName(
691 serviceInfo.getServiceName()));
692
693 maybeStartMonitoringSockets();
694 mAdvertiser.addService(id, serviceInfo);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900695 storeAdvertiserRequestMap(clientId, id, clientInfo);
Irfan Sheriff75006652012-04-17 23:15:29 -0700696 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900697 maybeStartDaemon();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900698 if (registerService(id, serviceInfo)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900699 if (DBG) Log.d(TAG, "Register " + clientId + " " + id);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900700 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900701 // Return success after mDns reports success
702 } else {
703 unregisterService(id);
704 clientInfo.onRegisterServiceFailed(
705 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
706 }
707
Irfan Sheriff75006652012-04-17 23:15:29 -0700708 }
709 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900710 }
711 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800712 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900713 args = (ListenerArgs) msg.obj;
714 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000715 // If the binder death notification for a INsdManagerCallback was received
716 // before any calls are received by NsdService, the clientInfo would be
717 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900718 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800719 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700720 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700721 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900722 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
723 if (request == null) {
724 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
725 break;
726 }
727 id = request.mGlobalId;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900728 removeRequestMap(clientId, id, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900729
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900730 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
731 // so this needs to check the type of the original request to unregister
732 // instead of looking at the flag value.
733 if (request instanceof AdvertiserClientRequest) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900734 mAdvertiser.removeService(id);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900735 clientInfo.onUnregisterServiceSucceeded(clientId);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700736 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900737 if (unregisterService(id)) {
738 clientInfo.onUnregisterServiceSucceeded(clientId);
739 } else {
740 clientInfo.onUnregisterServiceFailed(
741 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
742 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700743 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700744 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900745 }
Paul Hu75069ed2023-01-14 00:31:09 +0800746 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800747 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900748 args = (ListenerArgs) msg.obj;
749 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000750 // If the binder death notification for a INsdManagerCallback was received
751 // before any calls are received by NsdService, the clientInfo would be
752 // cleared and cause NPE. Add a null check here to prevent this corner case.
753 if (clientInfo == null) {
754 Log.e(TAG, "Unknown connector in resolution");
755 break;
756 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700757
Paul Hu75069ed2023-01-14 00:31:09 +0800758 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700759 id = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900760 final String serviceType = constructServiceType(info.getServiceType());
761 if (mDeps.isMdnsDiscoveryManagerEnabled(mContext)
762 || useDiscoveryManagerForType(serviceType)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800763 if (serviceType == null) {
764 clientInfo.onResolveServiceFailed(clientId,
765 NsdManager.FAILURE_INTERNAL_ERROR);
766 break;
767 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900768 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +0800769
770 maybeStartMonitoringSockets();
771 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900772 new ResolutionListener(clientId, id, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800773 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
774 .setNetwork(info.getNetwork())
775 .setIsPassiveMode(true)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900776 .setResolveInstanceName(info.getServiceName())
Paul Hu75069ed2023-01-14 00:31:09 +0800777 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900778 mMdnsDiscoveryManager.registerListener(
779 resolveServiceType, listener, options);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900780 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo);
Irfan Sheriff75006652012-04-17 23:15:29 -0700781 } else {
Paul Hu75069ed2023-01-14 00:31:09 +0800782 if (clientInfo.mResolvedService != null) {
783 clientInfo.onResolveServiceFailed(
784 clientId, NsdManager.FAILURE_ALREADY_ACTIVE);
785 break;
786 }
787
788 maybeStartDaemon();
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900789 if (resolveService(id, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800790 clientInfo.mResolvedService = new NsdServiceInfo();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900791 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu75069ed2023-01-14 00:31:09 +0800792 } else {
793 clientInfo.onResolveServiceFailed(
794 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
795 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700796 }
797 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800798 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900799 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +0000800 if (DBG) Log.d(TAG, "Stop service resolution");
801 args = (ListenerArgs) msg.obj;
802 clientInfo = mClients.get(args.connector);
803 // If the binder death notification for a INsdManagerCallback was received
804 // before any calls are received by NsdService, the clientInfo would be
805 // cleared and cause NPE. Add a null check here to prevent this corner case.
806 if (clientInfo == null) {
807 Log.e(TAG, "Unknown connector in stop resolution");
808 break;
809 }
810
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900811 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
812 if (request == null) {
813 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
814 break;
815 }
816 id = request.mGlobalId;
Paul Hue4f5f252023-02-16 21:13:47 +0800817 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
818 // point, so this needs to check the type of the original request to
819 // unregister instead of looking at the flag value.
820 if (request instanceof DiscoveryManagerRequest) {
821 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Paul Hub58deb72022-12-26 09:24:42 +0000822 clientInfo.onStopResolutionSucceeded(clientId);
823 } else {
Paul Hue4f5f252023-02-16 21:13:47 +0800824 removeRequestMap(clientId, id, clientInfo);
825 if (stopResolveService(id)) {
826 clientInfo.onStopResolutionSucceeded(clientId);
827 } else {
828 clientInfo.onStopResolutionFailed(
829 clientId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
830 }
831 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +0000832 }
Paul Hub58deb72022-12-26 09:24:42 +0000833 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900834 }
Paul Hu18aeccc2022-12-27 08:48:48 +0000835 case NsdManager.REGISTER_SERVICE_CALLBACK:
836 if (DBG) Log.d(TAG, "Register a service callback");
837 args = (ListenerArgs) msg.obj;
838 clientInfo = mClients.get(args.connector);
839 // If the binder death notification for a INsdManagerCallback was received
840 // before any calls are received by NsdService, the clientInfo would be
841 // cleared and cause NPE. Add a null check here to prevent this corner case.
842 if (clientInfo == null) {
843 Log.e(TAG, "Unknown connector in callback registration");
844 break;
845 }
846
847 if (clientInfo.mRegisteredService != null) {
848 clientInfo.onServiceInfoCallbackRegistrationFailed(
849 clientId, NsdManager.FAILURE_ALREADY_ACTIVE);
850 break;
851 }
852
853 maybeStartDaemon();
854 id = getUniqueId();
855 if (resolveService(id, args.serviceInfo)) {
856 clientInfo.mRegisteredService = new NsdServiceInfo();
857 clientInfo.mClientIdForServiceUpdates = clientId;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900858 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu18aeccc2022-12-27 08:48:48 +0000859 } else {
860 clientInfo.onServiceInfoCallbackRegistrationFailed(
861 clientId, NsdManager.FAILURE_BAD_PARAMETERS);
862 }
863 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900864 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +0000865 if (DBG) Log.d(TAG, "Unregister a service callback");
866 args = (ListenerArgs) msg.obj;
867 clientInfo = mClients.get(args.connector);
868 // If the binder death notification for a INsdManagerCallback was received
869 // before any calls are received by NsdService, the clientInfo would be
870 // cleared and cause NPE. Add a null check here to prevent this corner case.
871 if (clientInfo == null) {
872 Log.e(TAG, "Unknown connector in callback unregistration");
873 break;
874 }
875
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900876 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
877 if (request == null) {
878 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
879 break;
880 }
881 id = request.mGlobalId;
Paul Hu18aeccc2022-12-27 08:48:48 +0000882 removeRequestMap(clientId, id, clientInfo);
883 if (stopResolveService(id)) {
884 clientInfo.onServiceInfoCallbackUnregistered(clientId);
885 } else {
886 Log.e(TAG, "Failed to unregister service info callback");
887 }
888 clearRegisteredServiceInfo(clientInfo);
889 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900890 }
paulhu2b9ed952022-02-10 21:58:32 +0800891 case MDNS_SERVICE_EVENT:
892 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +0900893 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700894 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700895 break;
Paul Hu019621e2023-01-13 23:26:49 +0800896 case MDNS_DISCOVERY_MANAGER_EVENT:
897 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
898 return NOT_HANDLED;
899 }
900 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700901 default:
Hugo Benichif0c84092017-04-05 14:43:29 +0900902 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700903 }
Hugo Benichif0c84092017-04-05 14:43:29 +0900904 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -0700905 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700906
Paul Hu18aeccc2022-12-27 08:48:48 +0000907 private void notifyResolveFailedResult(boolean isListenedToUpdates, int clientId,
908 ClientInfo clientInfo, int error) {
909 if (isListenedToUpdates) {
910 clientInfo.onServiceInfoCallbackRegistrationFailed(clientId, error);
911 clearRegisteredServiceInfo(clientInfo);
912 } else {
913 // The resolve API always returned FAILURE_INTERNAL_ERROR on error; keep it
914 // for backwards compatibility.
915 clientInfo.onResolveServiceFailed(clientId, NsdManager.FAILURE_INTERNAL_ERROR);
916 clientInfo.mResolvedService = null;
917 }
918 }
919
paulhu2b9ed952022-02-10 21:58:32 +0800920 private boolean handleMDnsServiceEvent(int code, int id, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700921 NsdServiceInfo servInfo;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700922 ClientInfo clientInfo = mIdToClientInfoMap.get(id);
923 if (clientInfo == null) {
paulhu2b9ed952022-02-10 21:58:32 +0800924 Log.e(TAG, String.format("id %d for %d has no client mapping", id, code));
Hugo Benichif0c84092017-04-05 14:43:29 +0900925 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700926 }
927
928 /* This goes in response as msg.arg2 */
Christopher Lane74411222014-04-25 18:39:07 -0700929 int clientId = clientInfo.getClientId(id);
930 if (clientId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -0700931 // This can happen because of race conditions. For example,
932 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
933 // and we may get in this situation.
paulhu2b9ed952022-02-10 21:58:32 +0800934 Log.d(TAG, String.format("%d for listener id %d that is no longer active",
935 code, id));
Hugo Benichif0c84092017-04-05 14:43:29 +0900936 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700937 }
Hugo Benichi32be63d2017-04-05 14:06:11 +0900938 if (DBG) {
paulhu2b9ed952022-02-10 21:58:32 +0800939 Log.d(TAG, String.format("MDns service event code:%d id=%d", code, id));
Hugo Benichi32be63d2017-04-05 14:06:11 +0900940 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700941 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +0800942 case IMDnsEventListener.SERVICE_FOUND: {
943 final DiscoveryInfo info = (DiscoveryInfo) obj;
944 final String name = info.serviceName;
945 final String type = info.registrationType;
946 servInfo = new NsdServiceInfo(name, type);
947 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900948 if (foundNetId == 0L) {
949 // Ignore services that do not have a Network: they are not usable
950 // by apps, as they would need privileged permissions to use
951 // interfaces that do not have an associated Network.
952 break;
953 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +0900954 if (foundNetId == INetd.DUMMY_NET_ID) {
955 // Ignore services on the dummy0 interface: they are only seen when
956 // discovering locally advertised services, and are not reachable
957 // through that interface.
958 break;
959 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900960 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900961 clientInfo.onServiceFound(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700962 break;
paulhu2b9ed952022-02-10 21:58:32 +0800963 }
964 case IMDnsEventListener.SERVICE_LOST: {
965 final DiscoveryInfo info = (DiscoveryInfo) obj;
966 final String name = info.serviceName;
967 final String type = info.registrationType;
968 final int lostNetId = info.netId;
969 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +0900970 // The network could be set to null (netId 0) if it was torn down when the
971 // service is lost
972 // TODO: avoid returning null in that case, possibly by remembering
973 // found services on the same interface index and their network at the time
974 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900975 clientInfo.onServiceLost(clientId, servInfo);
Paul Hu18aeccc2022-12-27 08:48:48 +0000976 // TODO: also support registered service lost when not discovering
977 clientInfo.maybeNotifyRegisteredServiceLost(servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700978 break;
paulhu2b9ed952022-02-10 21:58:32 +0800979 }
980 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900981 clientInfo.onDiscoverServicesFailed(
982 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700983 break;
paulhu2b9ed952022-02-10 21:58:32 +0800984 case IMDnsEventListener.SERVICE_REGISTERED: {
985 final RegistrationInfo info = (RegistrationInfo) obj;
986 final String name = info.serviceName;
987 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900988 clientInfo.onRegisterServiceSucceeded(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700989 break;
paulhu2b9ed952022-02-10 21:58:32 +0800990 }
991 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900992 clientInfo.onRegisterServiceFailed(
993 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -0700994 break;
paulhu2b9ed952022-02-10 21:58:32 +0800995 case IMDnsEventListener.SERVICE_RESOLVED: {
996 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -0700997 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +0800998 final String fullName = info.serviceFullName;
999 while (index < fullName.length() && fullName.charAt(index) != '.') {
1000 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001001 ++index;
1002 }
1003 ++index;
1004 }
paulhu2b9ed952022-02-10 21:58:32 +08001005 if (index >= fullName.length()) {
1006 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001007 break;
1008 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001009
paulhube186602022-04-12 07:18:23 +00001010 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001011 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001012 String type = rest.replace(".local.", "");
1013
Paul Hu18aeccc2022-12-27 08:48:48 +00001014 final boolean isListenedToUpdates =
1015 clientId == clientInfo.mClientIdForServiceUpdates;
1016 final NsdServiceInfo serviceInfo = isListenedToUpdates
1017 ? clientInfo.mRegisteredService : clientInfo.mResolvedService;
1018
1019 serviceInfo.setServiceName(name);
1020 serviceInfo.setServiceType(type);
1021 serviceInfo.setPort(info.port);
1022 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001023 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001024
1025 stopResolveService(id);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001026 removeRequestMap(clientId, id, clientInfo);
1027
paulhu2b9ed952022-02-10 21:58:32 +08001028 final int id2 = getUniqueId();
1029 if (getAddrInfo(id2, info.hostname, info.interfaceIdx)) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001030 storeLegacyRequestMap(clientId, id2, clientInfo,
1031 NsdManager.RESOLVE_SERVICE);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001032 } else {
Paul Hu18aeccc2022-12-27 08:48:48 +00001033 notifyResolveFailedResult(isListenedToUpdates, clientId, clientInfo,
1034 NsdManager.FAILURE_BAD_PARAMETERS);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001035 }
1036 break;
paulhu2b9ed952022-02-10 21:58:32 +08001037 }
1038 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001039 /* NNN resolveId errorCode */
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001040 stopResolveService(id);
1041 removeRequestMap(clientId, id, clientInfo);
Paul Hu18aeccc2022-12-27 08:48:48 +00001042 notifyResolveFailedResult(
1043 clientId == clientInfo.mClientIdForServiceUpdates,
1044 clientId, clientInfo, NsdManager.FAILURE_BAD_PARAMETERS);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001045 break;
paulhu2b9ed952022-02-10 21:58:32 +08001046 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001047 /* NNN resolveId errorCode */
1048 stopGetAddrInfo(id);
1049 removeRequestMap(clientId, id, clientInfo);
Paul Hu18aeccc2022-12-27 08:48:48 +00001050 notifyResolveFailedResult(
1051 clientId == clientInfo.mClientIdForServiceUpdates,
1052 clientId, clientInfo, NsdManager.FAILURE_BAD_PARAMETERS);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001053 break;
paulhu2b9ed952022-02-10 21:58:32 +08001054 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001055 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001056 final GetAddressInfo info = (GetAddressInfo) obj;
1057 final String address = info.address;
1058 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001059 InetAddress serviceHost = null;
1060 try {
paulhu2b9ed952022-02-10 21:58:32 +08001061 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001062 } catch (UnknownHostException e) {
1063 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1064 }
1065
1066 // If the resolved service is on an interface without a network, consider it
1067 // as a failure: it would not be usable by apps as they would need
1068 // privileged permissions.
Paul Hu18aeccc2022-12-27 08:48:48 +00001069 if (clientId == clientInfo.mClientIdForServiceUpdates) {
1070 if (netId != NETID_UNSET && serviceHost != null) {
1071 setServiceNetworkForCallback(clientInfo.mRegisteredService,
1072 netId, info.interfaceIdx);
1073 final List<InetAddress> addresses =
1074 clientInfo.mRegisteredService.getHostAddresses();
1075 addresses.add(serviceHost);
1076 clientInfo.mRegisteredService.setHostAddresses(addresses);
1077 clientInfo.onServiceUpdated(
1078 clientId, clientInfo.mRegisteredService);
1079 } else {
1080 stopGetAddrInfo(id);
1081 removeRequestMap(clientId, id, clientInfo);
1082 clearRegisteredServiceInfo(clientInfo);
1083 clientInfo.onServiceInfoCallbackRegistrationFailed(
1084 clientId, NsdManager.FAILURE_BAD_PARAMETERS);
1085 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001086 } else {
Paul Hu18aeccc2022-12-27 08:48:48 +00001087 if (netId != NETID_UNSET && serviceHost != null) {
1088 clientInfo.mResolvedService.setHost(serviceHost);
1089 setServiceNetworkForCallback(clientInfo.mResolvedService,
1090 netId, info.interfaceIdx);
1091 clientInfo.onResolveServiceSucceeded(
1092 clientId, clientInfo.mResolvedService);
1093 } else {
1094 clientInfo.onResolveServiceFailed(
1095 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1096 }
1097 stopGetAddrInfo(id);
1098 removeRequestMap(clientId, id, clientInfo);
1099 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001100 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001101 break;
paulhu2b9ed952022-02-10 21:58:32 +08001102 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001103 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001104 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001105 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001106 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001107 }
Paul Hu019621e2023-01-13 23:26:49 +08001108
1109 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(final MdnsEvent event) {
1110 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1111 final String serviceType = event.mRequestedServiceType;
1112 final String serviceName = serviceInfo.getServiceInstanceName();
1113 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1114 final Network network = serviceInfo.getNetwork();
1115 setServiceNetworkForCallback(
1116 servInfo,
1117 network == null ? NETID_UNSET : network.netId,
1118 serviceInfo.getInterfaceIndex());
1119 return servInfo;
1120 }
1121
1122 private boolean handleMdnsDiscoveryManagerEvent(
1123 int transactionId, int code, Object obj) {
1124 final ClientInfo clientInfo = mIdToClientInfoMap.get(transactionId);
1125 if (clientInfo == null) {
1126 Log.e(TAG, String.format(
1127 "id %d for %d has no client mapping", transactionId, code));
1128 return false;
1129 }
1130
1131 final MdnsEvent event = (MdnsEvent) obj;
1132 final int clientId = event.mClientId;
Paul Hu319751a2023-01-13 23:56:34 +08001133 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event);
Paul Hu019621e2023-01-13 23:26:49 +08001134 if (DBG) {
1135 Log.d(TAG, String.format("MdnsDiscoveryManager event code=%s transactionId=%d",
1136 NsdManager.nameOf(code), transactionId));
1137 }
1138 switch (code) {
1139 case NsdManager.SERVICE_FOUND:
Paul Hu319751a2023-01-13 23:56:34 +08001140 clientInfo.onServiceFound(clientId, info);
1141 break;
1142 case NsdManager.SERVICE_LOST:
1143 clientInfo.onServiceLost(clientId, info);
Paul Hu019621e2023-01-13 23:26:49 +08001144 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001145 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001146 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
1147 if (request == null) {
1148 Log.e(TAG, "Unknown client request in RESOLVE_SERVICE_SUCCEEDED");
1149 break;
1150 }
Paul Hu75069ed2023-01-14 00:31:09 +08001151 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1152 // Add '.' in front of the service type that aligns with historical behavior
1153 info.setServiceType("." + event.mRequestedServiceType);
1154 info.setPort(serviceInfo.getPort());
1155
1156 Map<String, String> attrs = serviceInfo.getAttributes();
1157 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1158 final String key = kv.getKey();
1159 try {
1160 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1161 } catch (IllegalArgumentException e) {
1162 Log.e(TAG, "Invalid attribute", e);
1163 }
1164 }
Paul Hu2b865912023-03-06 14:27:53 +08001165 final List<InetAddress> addresses = new ArrayList<>();
1166 for (String ipv4Address : serviceInfo.getIpv4Addresses()) {
1167 try {
1168 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1169 } catch (IllegalArgumentException e) {
1170 Log.wtf(TAG, "Invalid ipv4 address", e);
Paul Hu75069ed2023-01-14 00:31:09 +08001171 }
Paul Hu2b865912023-03-06 14:27:53 +08001172 }
1173 for (String ipv6Address : serviceInfo.getIpv6Addresses()) {
1174 try {
1175 addresses.add(InetAddresses.parseNumericAddress(ipv6Address));
1176 } catch (IllegalArgumentException e) {
1177 Log.wtf(TAG, "Invalid ipv6 address", e);
1178 }
1179 }
1180
1181 if (addresses.size() != 0) {
1182 info.setHostAddresses(addresses);
Paul Hu75069ed2023-01-14 00:31:09 +08001183 clientInfo.onResolveServiceSucceeded(clientId, info);
Paul Hu2b865912023-03-06 14:27:53 +08001184 } else {
1185 // No address. Notify resolution failure.
Paul Hu75069ed2023-01-14 00:31:09 +08001186 clientInfo.onResolveServiceFailed(
1187 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1188 }
1189
1190 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001191 if (!(request instanceof DiscoveryManagerRequest)) {
1192 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1193 break;
1194 }
Paul Hue4f5f252023-02-16 21:13:47 +08001195 stopDiscoveryManagerRequest(request, clientId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001196 break;
1197 }
Paul Hu019621e2023-01-13 23:26:49 +08001198 default:
1199 return false;
1200 }
1201 return true;
1202 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001203 }
1204 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001205
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001206 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1207 switch (netId) {
1208 case NETID_UNSET:
1209 info.setNetwork(null);
1210 break;
1211 case INetd.LOCAL_NET_ID:
1212 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1213 // visible / usable for apps, so do not return it. Store the interface
1214 // index instead, so at least if the client tries to resolve the service
1215 // with that NsdServiceInfo, it will be done on the same interface.
1216 // If they recreate the NsdServiceInfo themselves, resolution would be
1217 // done on all interfaces as before T, which should also work.
1218 info.setNetwork(null);
1219 info.setInterfaceIndex(ifaceIdx);
1220 break;
1221 default:
1222 info.setNetwork(new Network(netId));
1223 }
1224 }
1225
paulhube186602022-04-12 07:18:23 +00001226 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1227 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1228 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1229 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1230 private String unescape(String s) {
1231 StringBuilder sb = new StringBuilder(s.length());
1232 for (int i = 0; i < s.length(); ++i) {
1233 char c = s.charAt(i);
1234 if (c == '\\') {
1235 if (++i >= s.length()) {
1236 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1237 break;
1238 }
1239 c = s.charAt(i);
1240 if (c != '.' && c != '\\') {
1241 if (i + 2 >= s.length()) {
1242 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1243 break;
1244 }
1245 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1246 + (s.charAt(i + 2) - '0'));
1247 i += 2;
1248 }
1249 }
1250 sb.append(c);
1251 }
1252 return sb.toString();
1253 }
1254
Paul Hu7445e3d2023-03-03 15:14:00 +08001255 /**
1256 * Check the given service type is valid and construct it to a service type
1257 * which can use for discovery / resolution service.
1258 *
1259 * <p> The valid service type should be 2 labels, or 3 labels if the query is for a
1260 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1261 * underscore; they are alphanumerical characters or dashes or underscore, except the
1262 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1263 *
1264 * @param serviceType the request service type for discovery / resolution service
1265 * @return constructed service type or null if the given service type is invalid.
1266 */
1267 @Nullable
1268 public static String constructServiceType(String serviceType) {
1269 if (TextUtils.isEmpty(serviceType)) return null;
1270
1271 final Pattern serviceTypePattern = Pattern.compile(
1272 "^(_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]\\.)?"
1273 + "(_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]\\._(?:tcp|udp))"
1274 // Drop '.' at the end of service type that is compatible with old backend.
1275 + "\\.?$");
1276 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1277 if (!matcher.matches()) return null;
1278 return matcher.group(1) == null
1279 ? matcher.group(2)
1280 : matcher.group(1) + "_sub." + matcher.group(2);
1281 }
1282
Hugo Benichi803a2f02017-04-24 11:35:06 +09001283 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001284 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001285 this(ctx, handler, cleanupDelayMs, new Dependencies());
1286 }
1287
1288 @VisibleForTesting
1289 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001290 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001291 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001292 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001293 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001294 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1295 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001296 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001297
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001298 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper());
1299 mMdnsSocketClient =
1300 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider);
1301 mMdnsDiscoveryManager =
1302 deps.makeMdnsDiscoveryManager(new ExecutorProvider(), mMdnsSocketClient);
1303 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1304 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
1305 new AdvertiserCallback());
Paul Hu4bd98ef2023-01-12 13:42:07 +08001306 }
1307
1308 /**
1309 * Dependencies of NsdService, for injection in tests.
1310 */
1311 @VisibleForTesting
1312 public static class Dependencies {
1313 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001314 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001315 *
1316 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001317 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001318 */
1319 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
1320 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY,
1321 MDNS_DISCOVERY_MANAGER_VERSION, false /* defaultEnabled */);
1322 }
1323
1324 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001325 * Check whether the MdnsAdvertiser feature is enabled.
1326 *
1327 * @param context The global context information about an app environment.
1328 * @return true if the MdnsAdvertiser feature is enabled.
1329 */
1330 public boolean isMdnsAdvertiserEnabled(Context context) {
1331 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY,
1332 MDNS_ADVERTISER_VERSION, false /* defaultEnabled */);
1333 }
1334
1335 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001336 * Get the type allowlist flag value.
1337 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1338 */
1339 @Nullable
1340 public String getTypeAllowlistFlags() {
1341 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1342 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1343 }
1344
1345 /**
1346 * @see DeviceConfigUtils#isFeatureEnabled(Context, String, String, String, boolean)
1347 */
1348 public boolean isFeatureEnabled(Context context, String feature) {
1349 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1350 feature, DeviceConfigUtils.TETHERING_MODULE_NAME, false /* defaultEnabled */);
1351 }
1352
1353 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001354 * @see MdnsDiscoveryManager
1355 */
1356 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
1357 ExecutorProvider executorProvider, MdnsSocketClientBase socketClient) {
1358 return new MdnsDiscoveryManager(executorProvider, socketClient);
1359 }
1360
1361 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001362 * @see MdnsAdvertiser
1363 */
1364 public MdnsAdvertiser makeMdnsAdvertiser(
1365 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
1366 @NonNull MdnsAdvertiser.AdvertiserCallback cb) {
1367 return new MdnsAdvertiser(looper, socketProvider, cb);
1368 }
1369
1370 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001371 * @see MdnsSocketProvider
1372 */
1373 public MdnsSocketProvider makeMdnsSocketProvider(Context context, Looper looper) {
1374 return new MdnsSocketProvider(context, looper);
1375 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001376 }
1377
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001378 /**
1379 * Return whether a type is allowlisted to use the Java backend.
1380 * @param type The service type
1381 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1382 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1383 */
1384 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1385 @NonNull String flagPrefix) {
1386 if (type == null) return false;
1387 final String typesConfig = mDeps.getTypeAllowlistFlags();
1388 if (TextUtils.isEmpty(typesConfig)) return false;
1389
1390 final String mappingPrefix = type + ":";
1391 String mappedFlag = null;
1392 for (String mapping : TextUtils.split(typesConfig, ",")) {
1393 if (mapping.startsWith(mappingPrefix)) {
1394 mappedFlag = mapping.substring(mappingPrefix.length());
1395 break;
1396 }
1397 }
1398
1399 if (mappedFlag == null) return false;
1400
1401 return mDeps.isFeatureEnabled(mContext,
1402 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1403 }
1404
1405 private boolean useDiscoveryManagerForType(@Nullable String type) {
1406 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1407 }
1408
1409 private boolean useAdvertiserForType(@Nullable String type) {
1410 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1411 }
1412
paulhu1b35e822022-04-08 14:48:41 +08001413 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001414 HandlerThread thread = new HandlerThread(TAG);
1415 thread.start();
1416 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001417 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001418 return service;
1419 }
1420
paulhu2b9ed952022-02-10 21:58:32 +08001421 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1422 private final StateMachine mStateMachine;
1423
1424 MDnsEventCallback(StateMachine sm) {
1425 mStateMachine = sm;
1426 }
1427
1428 @Override
1429 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1430 mStateMachine.sendMessage(
1431 MDNS_SERVICE_EVENT, status.result, status.id, status);
1432 }
1433
1434 @Override
1435 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1436 mStateMachine.sendMessage(
1437 MDNS_SERVICE_EVENT, status.result, status.id, status);
1438 }
1439
1440 @Override
1441 public void onServiceResolutionStatus(final ResolutionInfo status) {
1442 mStateMachine.sendMessage(
1443 MDNS_SERVICE_EVENT, status.result, status.id, status);
1444 }
1445
1446 @Override
1447 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1448 mStateMachine.sendMessage(
1449 MDNS_SERVICE_EVENT, status.result, status.id, status);
1450 }
1451
1452 @Override
1453 public int getInterfaceVersion() throws RemoteException {
1454 return this.VERSION;
1455 }
1456
1457 @Override
1458 public String getInterfaceHash() throws RemoteException {
1459 return this.HASH;
1460 }
1461 }
1462
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001463 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
1464 @Override
1465 public void onRegisterServiceSucceeded(int serviceId, NsdServiceInfo registeredInfo) {
1466 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1467 if (clientInfo == null) return;
1468
1469 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1470 if (clientId < 0) return;
1471
1472 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1473 // historical behavior.
1474 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
1475 clientInfo.onRegisterServiceSucceeded(clientId, cbInfo);
1476 }
1477
1478 @Override
1479 public void onRegisterServiceFailed(int serviceId, int errorCode) {
1480 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1481 if (clientInfo == null) return;
1482
1483 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1484 if (clientId < 0) return;
1485
1486 clientInfo.onRegisterServiceFailed(clientId, errorCode);
1487 }
1488
1489 private ClientInfo getClientInfoOrLog(int serviceId) {
1490 final ClientInfo clientInfo = mIdToClientInfoMap.get(serviceId);
1491 if (clientInfo == null) {
1492 Log.e(TAG, String.format("Callback for service %d has no client", serviceId));
1493 }
1494 return clientInfo;
1495 }
1496
1497 private int getClientIdOrLog(@NonNull ClientInfo info, int serviceId) {
1498 final int clientId = info.getClientId(serviceId);
1499 if (clientId < 0) {
1500 Log.e(TAG, String.format("Client ID not found for service %d", serviceId));
1501 }
1502 return clientId;
1503 }
1504 }
1505
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001506 @Override
1507 public INsdServiceConnector connect(INsdManagerCallback cb) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001508 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001509 final INsdServiceConnector connector = new NsdServiceConnector();
1510 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1511 NsdManager.REGISTER_CLIENT, new Pair<>(connector, cb)));
1512 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07001513 }
1514
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001515 private static class ListenerArgs {
1516 public final NsdServiceConnector connector;
1517 public final NsdServiceInfo serviceInfo;
1518 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
1519 this.connector = connector;
1520 this.serviceInfo = serviceInfo;
1521 }
1522 }
1523
1524 private class NsdServiceConnector extends INsdServiceConnector.Stub
1525 implements IBinder.DeathRecipient {
1526 @Override
1527 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
1528 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1529 NsdManager.REGISTER_SERVICE, 0, listenerKey,
1530 new ListenerArgs(this, serviceInfo)));
1531 }
1532
1533 @Override
1534 public void unregisterService(int listenerKey) {
1535 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1536 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
1537 new ListenerArgs(this, null)));
1538 }
1539
1540 @Override
1541 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
1542 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1543 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
1544 new ListenerArgs(this, serviceInfo)));
1545 }
1546
1547 @Override
1548 public void stopDiscovery(int listenerKey) {
1549 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1550 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
1551 }
1552
1553 @Override
1554 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
1555 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1556 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
1557 new ListenerArgs(this, serviceInfo)));
1558 }
1559
1560 @Override
Paul Hub58deb72022-12-26 09:24:42 +00001561 public void stopResolution(int listenerKey) {
1562 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1563 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
1564 }
1565
1566 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00001567 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
1568 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1569 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
1570 new ListenerArgs(this, serviceInfo)));
1571 }
1572
1573 @Override
1574 public void unregisterServiceInfoCallback(int listenerKey) {
1575 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1576 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
1577 new ListenerArgs(this, null)));
1578 }
1579
1580 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001581 public void startDaemon() {
1582 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1583 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
1584 }
1585
1586 @Override
1587 public void binderDied() {
1588 mNsdStateMachine.sendMessage(
1589 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
1590 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001591 }
1592
Hugo Benichi912db992017-04-24 16:41:03 +09001593 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07001594 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07001595 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09001596 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
1597 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07001598 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07001599 }
1600
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001601 private int getUniqueId() {
1602 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
1603 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001604 }
1605
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001606 private boolean registerService(int regId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09001607 if (DBG) {
paulhub2225702021-11-17 09:35:33 +08001608 Log.d(TAG, "registerService: " + regId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001609 }
Hugo Benichi6d706442017-04-24 16:19:58 +09001610 String name = service.getServiceName();
1611 String type = service.getServiceType();
1612 int port = service.getPort();
1613 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001614 final int registerInterface = getNetworkInterfaceIndex(service);
1615 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08001616 Log.e(TAG, "Interface to register service on not found");
1617 return false;
1618 }
1619 return mMDnsManager.registerService(regId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001620 }
1621
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001622 private boolean unregisterService(int regId) {
paulhu2b9ed952022-02-10 21:58:32 +08001623 return mMDnsManager.stopOperation(regId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001624 }
1625
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001626 private boolean discoverServices(int discoveryId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08001627 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001628 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
1629 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001630 Log.e(TAG, "Interface to discover service on not found");
1631 return false;
1632 }
paulhu2b9ed952022-02-10 21:58:32 +08001633 return mMDnsManager.discover(discoveryId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001634 }
1635
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001636 private boolean stopServiceDiscovery(int discoveryId) {
paulhu2b9ed952022-02-10 21:58:32 +08001637 return mMDnsManager.stopOperation(discoveryId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001638 }
1639
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001640 private boolean resolveService(int resolveId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001641 final String name = service.getServiceName();
1642 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001643 final int resolveInterface = getNetworkInterfaceIndex(service);
1644 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001645 Log.e(TAG, "Interface to resolve service on not found");
1646 return false;
1647 }
paulhu2b9ed952022-02-10 21:58:32 +08001648 return mMDnsManager.resolve(resolveId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001649 }
1650
1651 /**
1652 * Guess the interface to use to resolve or discover a service on a specific network.
1653 *
1654 * This is an imperfect guess, as for example the network may be gone or not yet fully
1655 * registered. This is fine as failing is correct if the network is gone, and a client
1656 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
1657 * this is to support the legacy mdnsresponder implementation, which historically resolved
1658 * services on an unspecified network.
1659 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001660 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
1661 final Network network = serviceInfo.getNetwork();
1662 if (network == null) {
1663 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
1664 // provided by NsdService from discovery results, and the service was found on an
1665 // interface that has no app-usable Network).
1666 if (serviceInfo.getInterfaceIndex() != 0) {
1667 return serviceInfo.getInterfaceIndex();
1668 }
1669 return IFACE_IDX_ANY;
1670 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001671
1672 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
1673 if (cm == null) {
1674 Log.wtf(TAG, "No ConnectivityManager for resolveService");
1675 return IFACE_IDX_ANY;
1676 }
1677 final LinkProperties lp = cm.getLinkProperties(network);
1678 if (lp == null) return IFACE_IDX_ANY;
1679
1680 // Only resolve on non-stacked interfaces
1681 final NetworkInterface iface;
1682 try {
1683 iface = NetworkInterface.getByName(lp.getInterfaceName());
1684 } catch (SocketException e) {
1685 Log.e(TAG, "Error querying interface", e);
1686 return IFACE_IDX_ANY;
1687 }
1688
1689 if (iface == null) {
1690 Log.e(TAG, "Interface not found: " + lp.getInterfaceName());
1691 return IFACE_IDX_ANY;
1692 }
1693
1694 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001695 }
1696
1697 private boolean stopResolveService(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001698 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001699 }
1700
paulhu2b9ed952022-02-10 21:58:32 +08001701 private boolean getAddrInfo(int resolveId, String hostname, int interfaceIdx) {
1702 return mMDnsManager.getServiceAddress(resolveId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001703 }
1704
1705 private boolean stopGetAddrInfo(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001706 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001707 }
1708
1709 @Override
Irfan Sheriff75006652012-04-17 23:15:29 -07001710 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
paulhu3ffffe72021-09-16 10:15:22 +08001711 if (!PermissionUtils.checkDumpPermission(mContext, TAG, pw)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001712
Irfan Sheriff75006652012-04-17 23:15:29 -07001713 for (ClientInfo client : mClients.values()) {
1714 pw.println("Client Info");
1715 pw.println(client);
1716 }
1717
1718 mNsdStateMachine.dump(fd, pw, args);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001719 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001720
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001721 private abstract static class ClientRequest {
1722 private final int mGlobalId;
1723
1724 private ClientRequest(int globalId) {
1725 mGlobalId = globalId;
1726 }
1727 }
1728
1729 private static class LegacyClientRequest extends ClientRequest {
1730 private final int mRequestCode;
1731
1732 private LegacyClientRequest(int globalId, int requestCode) {
1733 super(globalId);
1734 mRequestCode = requestCode;
1735 }
1736 }
1737
1738 private static class AdvertiserClientRequest extends ClientRequest {
1739 private AdvertiserClientRequest(int globalId) {
1740 super(globalId);
1741 }
1742 }
1743
1744 private static class DiscoveryManagerRequest extends ClientRequest {
1745 @NonNull
1746 private final MdnsListener mListener;
1747
1748 private DiscoveryManagerRequest(int globalId, @NonNull MdnsListener listener) {
1749 super(globalId);
1750 mListener = listener;
1751 }
1752 }
1753
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001754 /* Information tracked per client */
1755 private class ClientInfo {
1756
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001757 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001758 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001759 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001760 private NsdServiceInfo mResolvedService;
1761
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001762 /* A map from client-side ID (listenerKey) to the request */
1763 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08001764
Luke Huangf7277ed2021-07-12 21:15:10 +08001765 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001766 private boolean mIsPreSClient = false;
Luke Huangf7277ed2021-07-12 21:15:10 +08001767
Paul Hu18aeccc2022-12-27 08:48:48 +00001768 /*** The service that is registered to listen to its updates */
1769 private NsdServiceInfo mRegisteredService;
1770 /*** The client id that listen to updates */
1771 private int mClientIdForServiceUpdates;
1772
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001773 private ClientInfo(INsdManagerCallback cb) {
1774 mCb = cb;
paulhub2225702021-11-17 09:35:33 +08001775 if (DBG) Log.d(TAG, "New client");
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001776 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001777
1778 @Override
1779 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06001780 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07001781 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001782 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
1783 for (int i = 0; i < mClientRequests.size(); i++) {
1784 int clientID = mClientRequests.keyAt(i);
1785 sb.append("clientId ")
1786 .append(clientID)
1787 .append(" mDnsId ").append(mClientRequests.valueAt(i).mGlobalId)
1788 .append(" type ").append(
1789 mClientRequests.valueAt(i).getClass().getSimpleName())
1790 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07001791 }
1792 return sb.toString();
1793 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001794
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001795 private boolean isPreSClient() {
1796 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08001797 }
1798
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001799 private void setPreSClient() {
1800 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08001801 }
1802
Paul Hue4f5f252023-02-16 21:13:47 +08001803 private void unregisterMdnsListenerFromRequest(ClientRequest request) {
1804 final MdnsListener listener =
1805 ((DiscoveryManagerRequest) request).mListener;
1806 mMdnsDiscoveryManager.unregisterListener(
1807 listener.getListenedServiceType(), listener);
1808 }
1809
Dave Plattfeff2af2014-03-07 14:48:22 -08001810 // Remove any pending requests from the global map when we get rid of a client,
1811 // and send cancellations to the daemon.
1812 private void expungeAllRequests() {
Hugo Benichid2552ae2017-04-11 14:42:47 +09001813 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001814 for (int i = 0; i < mClientRequests.size(); i++) {
1815 final int clientId = mClientRequests.keyAt(i);
1816 final ClientRequest request = mClientRequests.valueAt(i);
1817 final int globalId = request.mGlobalId;
Dave Plattfeff2af2014-03-07 14:48:22 -08001818 mIdToClientInfoMap.remove(globalId);
paulhub2225702021-11-17 09:35:33 +08001819 if (DBG) {
1820 Log.d(TAG, "Terminating client-ID " + clientId
1821 + " global-ID " + globalId + " type " + mClientRequests.get(clientId));
1822 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001823
1824 if (request instanceof DiscoveryManagerRequest) {
Paul Hue4f5f252023-02-16 21:13:47 +08001825 unregisterMdnsListenerFromRequest(request);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001826 continue;
1827 }
1828
1829 if (request instanceof AdvertiserClientRequest) {
1830 mAdvertiser.removeService(globalId);
1831 continue;
1832 }
1833
1834 if (!(request instanceof LegacyClientRequest)) {
1835 throw new IllegalStateException("Unknown request type: " + request.getClass());
1836 }
1837
1838 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08001839 case NsdManager.DISCOVER_SERVICES:
1840 stopServiceDiscovery(globalId);
1841 break;
1842 case NsdManager.RESOLVE_SERVICE:
1843 stopResolveService(globalId);
1844 break;
1845 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001846 unregisterService(globalId);
Dave Plattfeff2af2014-03-07 14:48:22 -08001847 break;
1848 default:
1849 break;
1850 }
1851 }
Dave Plattfeff2af2014-03-07 14:48:22 -08001852 mClientRequests.clear();
1853 }
1854
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001855 // mClientRequests is a sparse array of listener id -> ClientRequest. For a given
1856 // mDnsClient id, return the corresponding listener id. mDnsClient id is also called a
1857 // global id.
Christopher Lane74411222014-04-25 18:39:07 -07001858 private int getClientId(final int globalId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001859 for (int i = 0; i < mClientRequests.size(); i++) {
1860 if (mClientRequests.valueAt(i).mGlobalId == globalId) {
1861 return mClientRequests.keyAt(i);
1862 }
Christopher Lane74411222014-04-25 18:39:07 -07001863 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001864 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07001865 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001866
Paul Hu18aeccc2022-12-27 08:48:48 +00001867 private void maybeNotifyRegisteredServiceLost(@NonNull NsdServiceInfo info) {
1868 if (mRegisteredService == null) return;
1869 if (!Objects.equals(mRegisteredService.getServiceName(), info.getServiceName())) return;
1870 // Resolved services have a leading dot appended at the beginning of their type, but in
1871 // discovered info it's at the end
1872 if (!Objects.equals(
1873 mRegisteredService.getServiceType() + ".", "." + info.getServiceType())) {
1874 return;
1875 }
1876 onServiceUpdatedLost(mClientIdForServiceUpdates);
1877 }
1878
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001879 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info) {
1880 try {
1881 mCb.onDiscoverServicesStarted(listenerKey, info);
1882 } catch (RemoteException e) {
1883 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
1884 }
1885 }
1886
1887 void onDiscoverServicesFailed(int listenerKey, int error) {
1888 try {
1889 mCb.onDiscoverServicesFailed(listenerKey, error);
1890 } catch (RemoteException e) {
1891 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
1892 }
1893 }
1894
1895 void onServiceFound(int listenerKey, NsdServiceInfo info) {
1896 try {
1897 mCb.onServiceFound(listenerKey, info);
1898 } catch (RemoteException e) {
1899 Log.e(TAG, "Error calling onServiceFound(", e);
1900 }
1901 }
1902
1903 void onServiceLost(int listenerKey, NsdServiceInfo info) {
1904 try {
1905 mCb.onServiceLost(listenerKey, info);
1906 } catch (RemoteException e) {
1907 Log.e(TAG, "Error calling onServiceLost(", e);
1908 }
1909 }
1910
1911 void onStopDiscoveryFailed(int listenerKey, int error) {
1912 try {
1913 mCb.onStopDiscoveryFailed(listenerKey, error);
1914 } catch (RemoteException e) {
1915 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
1916 }
1917 }
1918
1919 void onStopDiscoverySucceeded(int listenerKey) {
1920 try {
1921 mCb.onStopDiscoverySucceeded(listenerKey);
1922 } catch (RemoteException e) {
1923 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
1924 }
1925 }
1926
1927 void onRegisterServiceFailed(int listenerKey, int error) {
1928 try {
1929 mCb.onRegisterServiceFailed(listenerKey, error);
1930 } catch (RemoteException e) {
1931 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
1932 }
1933 }
1934
1935 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info) {
1936 try {
1937 mCb.onRegisterServiceSucceeded(listenerKey, info);
1938 } catch (RemoteException e) {
1939 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
1940 }
1941 }
1942
1943 void onUnregisterServiceFailed(int listenerKey, int error) {
1944 try {
1945 mCb.onUnregisterServiceFailed(listenerKey, error);
1946 } catch (RemoteException e) {
1947 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
1948 }
1949 }
1950
1951 void onUnregisterServiceSucceeded(int listenerKey) {
1952 try {
1953 mCb.onUnregisterServiceSucceeded(listenerKey);
1954 } catch (RemoteException e) {
1955 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
1956 }
1957 }
1958
1959 void onResolveServiceFailed(int listenerKey, int error) {
1960 try {
1961 mCb.onResolveServiceFailed(listenerKey, error);
1962 } catch (RemoteException e) {
1963 Log.e(TAG, "Error calling onResolveServiceFailed", e);
1964 }
1965 }
1966
1967 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info) {
1968 try {
1969 mCb.onResolveServiceSucceeded(listenerKey, info);
1970 } catch (RemoteException e) {
1971 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
1972 }
1973 }
Paul Hub58deb72022-12-26 09:24:42 +00001974
1975 void onStopResolutionFailed(int listenerKey, int error) {
1976 try {
1977 mCb.onStopResolutionFailed(listenerKey, error);
1978 } catch (RemoteException e) {
1979 Log.e(TAG, "Error calling onStopResolutionFailed", e);
1980 }
1981 }
1982
1983 void onStopResolutionSucceeded(int listenerKey) {
1984 try {
1985 mCb.onStopResolutionSucceeded(listenerKey);
1986 } catch (RemoteException e) {
1987 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
1988 }
1989 }
Paul Hu18aeccc2022-12-27 08:48:48 +00001990
1991 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
1992 try {
1993 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
1994 } catch (RemoteException e) {
1995 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
1996 }
1997 }
1998
1999 void onServiceUpdated(int listenerKey, NsdServiceInfo info) {
2000 try {
2001 mCb.onServiceUpdated(listenerKey, info);
2002 } catch (RemoteException e) {
2003 Log.e(TAG, "Error calling onServiceUpdated", e);
2004 }
2005 }
2006
2007 void onServiceUpdatedLost(int listenerKey) {
2008 try {
2009 mCb.onServiceUpdatedLost(listenerKey);
2010 } catch (RemoteException e) {
2011 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2012 }
2013 }
2014
2015 void onServiceInfoCallbackUnregistered(int listenerKey) {
2016 try {
2017 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2018 } catch (RemoteException e) {
2019 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2020 }
2021 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002022 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002023}