blob: 25aa693d077f224a41399297d591c7b12cd8c2c8 [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;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090020import static android.net.NetworkCapabilities.TRANSPORT_VPN;
21import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
Paul Hu019621e2023-01-13 23:26:49 +080022import static android.net.nsd.NsdManager.MDNS_DISCOVERY_MANAGER_EVENT;
paulhu2b9ed952022-02-10 21:58:32 +080023import static android.net.nsd.NsdManager.MDNS_SERVICE_EVENT;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +090024import static android.net.nsd.NsdManager.RESOLVE_SERVICE_SUCCEEDED;
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +090025import static android.provider.DeviceConfig.NAMESPACE_TETHERING;
paulhu2b9ed952022-02-10 21:58:32 +080026
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090027import static com.android.modules.utils.build.SdkLevel.isAtLeastU;
Yuyang Huangde802c82023-05-02 17:14:22 +090028import static com.android.server.connectivity.mdns.MdnsRecord.MAX_LABEL_LENGTH;
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +090029
Paul Hu23fa2022023-01-13 22:57:24 +080030import android.annotation.NonNull;
Paul Hu4bd98ef2023-01-12 13:42:07 +080031import android.annotation.Nullable;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090032import android.app.ActivityManager;
paulhua262cc12019-08-12 16:25:11 +080033import android.content.Context;
Irfan Sheriff75006652012-04-17 23:15:29 -070034import android.content.Intent;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090035import android.net.ConnectivityManager;
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +090036import android.net.INetd;
Paul Hu75069ed2023-01-14 00:31:09 +080037import android.net.InetAddresses;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090038import android.net.LinkProperties;
39import android.net.Network;
paulhu2b9ed952022-02-10 21:58:32 +080040import android.net.mdns.aidl.DiscoveryInfo;
41import android.net.mdns.aidl.GetAddressInfo;
42import android.net.mdns.aidl.IMDnsEventListener;
43import android.net.mdns.aidl.RegistrationInfo;
44import android.net.mdns.aidl.ResolutionInfo;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070045import android.net.nsd.INsdManager;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090046import android.net.nsd.INsdManagerCallback;
47import android.net.nsd.INsdServiceConnector;
paulhu2b9ed952022-02-10 21:58:32 +080048import android.net.nsd.MDnsManager;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070049import android.net.nsd.NsdManager;
paulhua262cc12019-08-12 16:25:11 +080050import android.net.nsd.NsdServiceInfo;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090051import android.net.wifi.WifiManager;
Paul Hub2e67d32023-04-18 05:50:14 +000052import android.os.Binder;
Hugo Benichi803a2f02017-04-24 11:35:06 +090053import android.os.Handler;
paulhua262cc12019-08-12 16:25:11 +080054import android.os.HandlerThread;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090055import android.os.IBinder;
Paul Hu4bd98ef2023-01-12 13:42:07 +080056import android.os.Looper;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070057import android.os.Message;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090058import android.os.RemoteException;
Dianne Hackborn692107e2012-08-29 18:32:08 -070059import android.os.UserHandle;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090060import android.provider.DeviceConfig;
Paul Hu23fa2022023-01-13 22:57:24 +080061import android.text.TextUtils;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090062import android.util.ArraySet;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +090063import android.util.Log;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +090064import android.util.Pair;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -070065import android.util.SparseArray;
Irfan Sheriff77ec5582012-03-22 17:01:39 -070066
paulhua262cc12019-08-12 16:25:11 +080067import com.android.internal.annotations.VisibleForTesting;
Paul Hub2e67d32023-04-18 05:50:14 +000068import com.android.internal.util.IndentingPrintWriter;
paulhua262cc12019-08-12 16:25:11 +080069import com.android.internal.util.State;
70import com.android.internal.util.StateMachine;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090071import com.android.net.module.util.CollectionUtils;
Paul Hu4bd98ef2023-01-12 13:42:07 +080072import com.android.net.module.util.DeviceConfigUtils;
Yuyang Huanga6a6ff92023-04-24 13:33:34 +090073import com.android.net.module.util.InetAddressUtils;
paulhu3ffffe72021-09-16 10:15:22 +080074import com.android.net.module.util.PermissionUtils;
Paul Hub2e67d32023-04-18 05:50:14 +000075import com.android.net.module.util.SharedLog;
Paul Hu4bd98ef2023-01-12 13:42:07 +080076import com.android.server.connectivity.mdns.ExecutorProvider;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +090077import com.android.server.connectivity.mdns.MdnsAdvertiser;
Paul Hu4bd98ef2023-01-12 13:42:07 +080078import com.android.server.connectivity.mdns.MdnsDiscoveryManager;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +090079import com.android.server.connectivity.mdns.MdnsInterfaceSocket;
Paul Hu4bd98ef2023-01-12 13:42:07 +080080import com.android.server.connectivity.mdns.MdnsMultinetworkSocketClient;
Paul Hu23fa2022023-01-13 22:57:24 +080081import com.android.server.connectivity.mdns.MdnsSearchOptions;
82import com.android.server.connectivity.mdns.MdnsServiceBrowserListener;
83import com.android.server.connectivity.mdns.MdnsServiceInfo;
Paul Hu4bd98ef2023-01-12 13:42:07 +080084import com.android.server.connectivity.mdns.MdnsSocketProvider;
Yuyang Huangde802c82023-05-02 17:14:22 +090085import com.android.server.connectivity.mdns.util.MdnsUtils;
paulhua262cc12019-08-12 16:25:11 +080086
Irfan Sheriff77ec5582012-03-22 17:01:39 -070087import java.io.FileDescriptor;
88import java.io.PrintWriter;
Yuyang Huangaa0e9602023-03-17 12:43:09 +090089import java.net.Inet6Address;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070090import java.net.InetAddress;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +090091import java.net.NetworkInterface;
92import java.net.SocketException;
93import java.net.UnknownHostException;
Paul Hu2b865912023-03-06 14:27:53 +080094import java.util.ArrayList;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +090095import java.util.Arrays;
Irfan Sheriffe8de2462012-04-11 14:52:19 -070096import java.util.HashMap;
Paul Hu23fa2022023-01-13 22:57:24 +080097import java.util.List;
Paul Hu75069ed2023-01-14 00:31:09 +080098import java.util.Map;
Paul Hu23fa2022023-01-13 22:57:24 +080099import java.util.regex.Matcher;
100import java.util.regex.Pattern;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700101
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700102/**
103 * Network Service Discovery Service handles remote service discovery operation requests by
104 * implementing the INsdManager interface.
105 *
106 * @hide
107 */
108public class NsdService extends INsdManager.Stub {
109 private static final String TAG = "NsdService";
110 private static final String MDNS_TAG = "mDnsConnector";
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900111 /**
112 * Enable discovery using the Java DiscoveryManager, instead of the legacy mdnsresponder
113 * implementation.
114 */
Paul Hu4bd98ef2023-01-12 13:42:07 +0800115 private static final String MDNS_DISCOVERY_MANAGER_VERSION = "mdns_discovery_manager_version";
Paul Hu23fa2022023-01-13 22:57:24 +0800116 private static final String LOCAL_DOMAIN_NAME = "local";
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700117
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900118 /**
119 * Enable advertising using the Java MdnsAdvertiser, instead of the legacy mdnsresponder
120 * implementation.
121 */
122 private static final String MDNS_ADVERTISER_VERSION = "mdns_advertiser_version";
123
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900124 /**
125 * Comma-separated list of type:flag mappings indicating the flags to use to allowlist
126 * discovery/advertising using MdnsDiscoveryManager / MdnsAdvertiser for a given type.
127 *
128 * For example _mytype._tcp.local and _othertype._tcp.local would be configured with:
129 * _mytype._tcp:mytype,_othertype._tcp.local:othertype
130 *
131 * In which case the flags:
132 * "mdns_discovery_manager_allowlist_mytype_version",
133 * "mdns_advertiser_allowlist_mytype_version",
134 * "mdns_discovery_manager_allowlist_othertype_version",
135 * "mdns_advertiser_allowlist_othertype_version"
136 * would be used to toggle MdnsDiscoveryManager / MdnsAdvertiser for each type. The flags will
137 * be read with
138 * {@link DeviceConfigUtils#isFeatureEnabled(Context, String, String, String, boolean)}.
139 *
140 * @see #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX
141 * @see #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX
142 * @see #MDNS_ALLOWLIST_FLAG_SUFFIX
143 */
144 private static final String MDNS_TYPE_ALLOWLIST_FLAGS = "mdns_type_allowlist_flags";
145
146 private static final String MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX =
147 "mdns_discovery_manager_allowlist_";
148 private static final String MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX =
149 "mdns_advertiser_allowlist_";
150 private static final String MDNS_ALLOWLIST_FLAG_SUFFIX = "_version";
151
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900152 @VisibleForTesting
153 static final String MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
154 "mdns_config_running_app_active_importance_cutoff";
155 @VisibleForTesting
156 static final int DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF =
157 ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
158 private final int mRunningAppActiveImportanceCutoff;
159
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900160 public static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Luke Huang92860f92021-06-23 06:29:30 +0000161 private static final long CLEANUP_DELAY_MS = 10000;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +0900162 private static final int IFACE_IDX_ANY = 0;
Paul Hu14667de2023-04-17 22:42:47 +0800163 private static final SharedLog LOGGER = new SharedLog("serviceDiscovery");
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700164
Hugo Benichi32be63d2017-04-05 14:06:11 +0900165 private final Context mContext;
Hugo Benichi32be63d2017-04-05 14:06:11 +0900166 private final NsdStateMachine mNsdStateMachine;
paulhu2b9ed952022-02-10 21:58:32 +0800167 private final MDnsManager mMDnsManager;
168 private final MDnsEventCallback mMDnsEventCallback;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900169 @NonNull
170 private final Dependencies mDeps;
171 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800172 private final MdnsMultinetworkSocketClient mMdnsSocketClient;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900173 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800174 private final MdnsDiscoveryManager mMdnsDiscoveryManager;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900175 @NonNull
Paul Hu4bd98ef2023-01-12 13:42:07 +0800176 private final MdnsSocketProvider mMdnsSocketProvider;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900177 @NonNull
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900178 private final MdnsAdvertiser mAdvertiser;
Paul Hu14667de2023-04-17 22:42:47 +0800179 private final SharedLog mServiceLogs = LOGGER.forSubComponent(TAG);
Paul Hu23fa2022023-01-13 22:57:24 +0800180 // WARNING : Accessing these values in any thread is not safe, it must only be changed in the
paulhu2b9ed952022-02-10 21:58:32 +0800181 // state machine thread. If change this outside state machine, it will need to introduce
182 // synchronization.
183 private boolean mIsDaemonStarted = false;
Paul Hu23fa2022023-01-13 22:57:24 +0800184 private boolean mIsMonitoringSocketsStarted = false;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700185
186 /**
187 * Clients receiving asynchronous messages
188 */
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900189 private final HashMap<NsdServiceConnector, ClientInfo> mClients = new HashMap<>();
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700190
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700191 /* A map from unique id to client info */
Hugo Benichi32be63d2017-04-05 14:06:11 +0900192 private final SparseArray<ClientInfo> mIdToClientInfoMap= new SparseArray<>();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700193
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900194 // Note this is not final to avoid depending on the Wi-Fi service starting before NsdService
195 @Nullable
196 private WifiManager.MulticastLock mHeldMulticastLock;
197 // Fulfilled network requests that require the Wi-Fi lock: key is the obtained Network
198 // (non-null), value is the requested Network (nullable)
199 @NonNull
200 private final ArraySet<Network> mWifiLockRequiredNetworks = new ArraySet<>();
201 @NonNull
202 private final ArraySet<Integer> mRunningAppActiveUids = new ArraySet<>();
203
Luke Huang05298582021-06-13 16:52:05 +0000204 private final long mCleanupDelayMs;
Irfan Sheriff77ec5582012-03-22 17:01:39 -0700205
Hugo Benichi32be63d2017-04-05 14:06:11 +0900206 private static final int INVALID_ID = 0;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700207 private int mUniqueId = 1;
Luke Huangf7277ed2021-07-12 21:15:10 +0800208 // The count of the connected legacy clients.
209 private int mLegacyClientCount = 0;
Paul Hub2e67d32023-04-18 05:50:14 +0000210 // The number of client that ever connected.
211 private int mClientNumberId = 1;
Irfan Sheriffe8de2462012-04-11 14:52:19 -0700212
Paul Hu23fa2022023-01-13 22:57:24 +0800213 private static class MdnsListener implements MdnsServiceBrowserListener {
214 protected final int mClientId;
215 protected final int mTransactionId;
216 @NonNull
217 protected final NsdServiceInfo mReqServiceInfo;
218 @NonNull
219 protected final String mListenedServiceType;
220
221 MdnsListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
222 @NonNull String listenedServiceType) {
223 mClientId = clientId;
224 mTransactionId = transactionId;
225 mReqServiceInfo = reqServiceInfo;
226 mListenedServiceType = listenedServiceType;
227 }
228
229 @NonNull
230 public String getListenedServiceType() {
231 return mListenedServiceType;
232 }
233
234 @Override
235 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo) { }
236
237 @Override
238 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) { }
239
240 @Override
241 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
242
243 @Override
244 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) { }
245
246 @Override
247 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) { }
248
249 @Override
250 public void onSearchStoppedWithError(int error) { }
251
252 @Override
253 public void onSearchFailedToStart() { }
254
255 @Override
256 public void onDiscoveryQuerySent(@NonNull List<String> subtypes, int transactionId) { }
257
258 @Override
259 public void onFailedToParseMdnsResponse(int receivedPacketNumber, int errorCode) { }
260 }
261
262 private class DiscoveryListener extends MdnsListener {
263
264 DiscoveryListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
265 @NonNull String listenServiceType) {
266 super(clientId, transactionId, reqServiceInfo, listenServiceType);
267 }
268
269 @Override
270 public void onServiceNameDiscovered(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu019621e2023-01-13 23:26:49 +0800271 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
272 NsdManager.SERVICE_FOUND,
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900273 new MdnsEvent(mClientId, serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800274 }
275
276 @Override
277 public void onServiceNameRemoved(@NonNull MdnsServiceInfo serviceInfo) {
Paul Hu319751a2023-01-13 23:56:34 +0800278 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
279 NsdManager.SERVICE_LOST,
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900280 new MdnsEvent(mClientId, serviceInfo));
Paul Hu23fa2022023-01-13 22:57:24 +0800281 }
282 }
283
Paul Hu75069ed2023-01-14 00:31:09 +0800284 private class ResolutionListener extends MdnsListener {
285
286 ResolutionListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
287 @NonNull String listenServiceType) {
288 super(clientId, transactionId, reqServiceInfo, listenServiceType);
289 }
290
291 @Override
292 public void onServiceFound(MdnsServiceInfo serviceInfo) {
293 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
294 NsdManager.RESOLVE_SERVICE_SUCCEEDED,
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900295 new MdnsEvent(mClientId, serviceInfo));
Paul Hu75069ed2023-01-14 00:31:09 +0800296 }
297 }
298
Paul Hu30bd70d2023-02-07 13:20:56 +0000299 private class ServiceInfoListener extends MdnsListener {
300
301 ServiceInfoListener(int clientId, int transactionId, @NonNull NsdServiceInfo reqServiceInfo,
302 @NonNull String listenServiceType) {
303 super(clientId, transactionId, reqServiceInfo, listenServiceType);
304 }
305
306 @Override
307 public void onServiceFound(@NonNull MdnsServiceInfo serviceInfo) {
308 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
309 NsdManager.SERVICE_UPDATED,
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900310 new MdnsEvent(mClientId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000311 }
312
313 @Override
314 public void onServiceUpdated(@NonNull MdnsServiceInfo serviceInfo) {
315 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
316 NsdManager.SERVICE_UPDATED,
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900317 new MdnsEvent(mClientId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000318 }
319
320 @Override
321 public void onServiceRemoved(@NonNull MdnsServiceInfo serviceInfo) {
322 mNsdStateMachine.sendMessage(MDNS_DISCOVERY_MANAGER_EVENT, mTransactionId,
323 NsdManager.SERVICE_UPDATED_LOST,
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900324 new MdnsEvent(mClientId, serviceInfo));
Paul Hu30bd70d2023-02-07 13:20:56 +0000325 }
326 }
327
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900328 private class SocketRequestMonitor implements MdnsSocketProvider.SocketRequestMonitor {
329 @Override
330 public void onSocketRequestFulfilled(@Nullable Network socketNetwork,
331 @NonNull MdnsInterfaceSocket socket, @NonNull int[] transports) {
332 // The network may be null for Wi-Fi SoftAp interfaces (tethering), but there is no APF
333 // filtering on such interfaces, so taking the multicast lock is not necessary to
334 // disable APF filtering of multicast.
335 if (socketNetwork == null
336 || !CollectionUtils.contains(transports, TRANSPORT_WIFI)
337 || CollectionUtils.contains(transports, TRANSPORT_VPN)) {
338 return;
339 }
340
341 if (mWifiLockRequiredNetworks.add(socketNetwork)) {
342 updateMulticastLock();
343 }
344 }
345
346 @Override
347 public void onSocketDestroyed(@Nullable Network socketNetwork,
348 @NonNull MdnsInterfaceSocket socket) {
349 if (mWifiLockRequiredNetworks.remove(socketNetwork)) {
350 updateMulticastLock();
351 }
352 }
353 }
354
355 private class UidImportanceListener implements ActivityManager.OnUidImportanceListener {
356 private final Handler mHandler;
357
358 private UidImportanceListener(Handler handler) {
359 mHandler = handler;
360 }
361
362 @Override
363 public void onUidImportance(int uid, int importance) {
364 mHandler.post(() -> handleUidImportanceChanged(uid, importance));
365 }
366 }
367
368 private void handleUidImportanceChanged(int uid, int importance) {
369 // Lower importance values are more "important"
370 final boolean modified = importance <= mRunningAppActiveImportanceCutoff
371 ? mRunningAppActiveUids.add(uid)
372 : mRunningAppActiveUids.remove(uid);
373 if (modified) {
374 updateMulticastLock();
375 }
376 }
377
378 /**
379 * Take or release the lock based on updated internal state.
380 *
381 * This determines whether the lock needs to be held based on
382 * {@link #mWifiLockRequiredNetworks}, {@link #mRunningAppActiveUids} and
383 * {@link ClientInfo#mClientRequests}, so it must be called after any of the these have been
384 * updated.
385 */
386 private void updateMulticastLock() {
387 final int needsLockUid = getMulticastLockNeededUid();
388 if (needsLockUid >= 0 && mHeldMulticastLock == null) {
389 final WifiManager wm = mContext.getSystemService(WifiManager.class);
390 if (wm == null) {
391 Log.wtf(TAG, "Got a TRANSPORT_WIFI network without WifiManager");
392 return;
393 }
394 mHeldMulticastLock = wm.createMulticastLock(TAG);
395 mHeldMulticastLock.acquire();
396 mServiceLogs.log("Taking multicast lock for uid " + needsLockUid);
397 } else if (needsLockUid < 0 && mHeldMulticastLock != null) {
398 mHeldMulticastLock.release();
399 mHeldMulticastLock = null;
400 mServiceLogs.log("Released multicast lock");
401 }
402 }
403
404 /**
405 * @return The UID of an app requiring the multicast lock, or -1 if none.
406 */
407 private int getMulticastLockNeededUid() {
408 if (mWifiLockRequiredNetworks.size() == 0) {
409 // Return early if NSD is not active, or not on any relevant network
410 return -1;
411 }
412 for (int i = 0; i < mIdToClientInfoMap.size(); i++) {
413 final ClientInfo clientInfo = mIdToClientInfoMap.valueAt(i);
414 if (!mRunningAppActiveUids.contains(clientInfo.mUid)) {
415 // Ignore non-active UIDs
416 continue;
417 }
418
419 if (clientInfo.hasAnyJavaBackendRequestForNetworks(mWifiLockRequiredNetworks)) {
420 return clientInfo.mUid;
421 }
422 }
423 return -1;
424 }
425
Paul Hu019621e2023-01-13 23:26:49 +0800426 /**
427 * Data class of mdns service callback information.
428 */
429 private static class MdnsEvent {
430 final int mClientId;
431 @NonNull
Paul Hu019621e2023-01-13 23:26:49 +0800432 final MdnsServiceInfo mMdnsServiceInfo;
433
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +0900434 MdnsEvent(int clientId, @NonNull MdnsServiceInfo mdnsServiceInfo) {
Paul Hu019621e2023-01-13 23:26:49 +0800435 mClientId = clientId;
Paul Hu019621e2023-01-13 23:26:49 +0800436 mMdnsServiceInfo = mdnsServiceInfo;
437 }
438 }
439
Irfan Sheriff75006652012-04-17 23:15:29 -0700440 private class NsdStateMachine extends StateMachine {
441
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700442 private final DefaultState mDefaultState = new DefaultState();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700443 private final EnabledState mEnabledState = new EnabledState();
Irfan Sheriff75006652012-04-17 23:15:29 -0700444
445 @Override
Wink Saville358f5d42012-05-29 12:40:46 -0700446 protected String getWhatToString(int what) {
Hugo Benichi32be63d2017-04-05 14:06:11 +0900447 return NsdManager.nameOf(what);
Irfan Sheriff75006652012-04-17 23:15:29 -0700448 }
449
Luke Huang92860f92021-06-23 06:29:30 +0000450 private void maybeStartDaemon() {
paulhu2b9ed952022-02-10 21:58:32 +0800451 if (mIsDaemonStarted) {
452 if (DBG) Log.d(TAG, "Daemon is already started.");
453 return;
454 }
455 mMDnsManager.registerEventListener(mMDnsEventCallback);
456 mMDnsManager.startDaemon();
457 mIsDaemonStarted = true;
Luke Huang05298582021-06-13 16:52:05 +0000458 maybeScheduleStop();
Paul Hub2e67d32023-04-18 05:50:14 +0000459 mServiceLogs.log("Start mdns_responder daemon");
Luke Huang05298582021-06-13 16:52:05 +0000460 }
461
paulhu2b9ed952022-02-10 21:58:32 +0800462 private void maybeStopDaemon() {
463 if (!mIsDaemonStarted) {
464 if (DBG) Log.d(TAG, "Daemon has not been started.");
465 return;
466 }
467 mMDnsManager.unregisterEventListener(mMDnsEventCallback);
468 mMDnsManager.stopDaemon();
469 mIsDaemonStarted = false;
Paul Hub2e67d32023-04-18 05:50:14 +0000470 mServiceLogs.log("Stop mdns_responder daemon");
paulhu2b9ed952022-02-10 21:58:32 +0800471 }
472
Luke Huang92860f92021-06-23 06:29:30 +0000473 private boolean isAnyRequestActive() {
474 return mIdToClientInfoMap.size() != 0;
475 }
476
477 private void scheduleStop() {
478 sendMessageDelayed(NsdManager.DAEMON_CLEANUP, mCleanupDelayMs);
479 }
480 private void maybeScheduleStop() {
Luke Huangf7277ed2021-07-12 21:15:10 +0800481 // The native daemon should stay alive and can't be cleanup
482 // if any legacy client connected.
483 if (!isAnyRequestActive() && mLegacyClientCount == 0) {
Luke Huang92860f92021-06-23 06:29:30 +0000484 scheduleStop();
Luke Huang05298582021-06-13 16:52:05 +0000485 }
486 }
487
Luke Huang92860f92021-06-23 06:29:30 +0000488 private void cancelStop() {
Luke Huang05298582021-06-13 16:52:05 +0000489 this.removeMessages(NsdManager.DAEMON_CLEANUP);
490 }
491
Paul Hu23fa2022023-01-13 22:57:24 +0800492 private void maybeStartMonitoringSockets() {
493 if (mIsMonitoringSocketsStarted) {
494 if (DBG) Log.d(TAG, "Socket monitoring is already started.");
495 return;
496 }
497
498 mMdnsSocketProvider.startMonitoringSockets();
499 mIsMonitoringSocketsStarted = true;
500 }
501
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900502 private void maybeStopMonitoringSocketsIfNoActiveRequest() {
503 if (!mIsMonitoringSocketsStarted) return;
504 if (isAnyRequestActive()) return;
505
Paul Hu58f20602023-02-18 11:41:07 +0800506 mMdnsSocketProvider.requestStopWhenInactive();
Paul Hu23fa2022023-01-13 22:57:24 +0800507 mIsMonitoringSocketsStarted = false;
508 }
509
Hugo Benichi803a2f02017-04-24 11:35:06 +0900510 NsdStateMachine(String name, Handler handler) {
511 super(name, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -0700512 addState(mDefaultState);
Irfan Sheriff75006652012-04-17 23:15:29 -0700513 addState(mEnabledState, mDefaultState);
paulhu5568f452021-11-30 13:31:29 +0800514 State initialState = mEnabledState;
Hugo Benichi912db992017-04-24 16:41:03 +0900515 setInitialState(initialState);
Wink Saville358f5d42012-05-29 12:40:46 -0700516 setLogRecSize(25);
Irfan Sheriff75006652012-04-17 23:15:29 -0700517 }
518
519 class DefaultState extends State {
520 @Override
521 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900522 final ClientInfo cInfo;
523 final int clientId = msg.arg2;
Irfan Sheriff75006652012-04-17 23:15:29 -0700524 switch (msg.what) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900525 case NsdManager.REGISTER_CLIENT:
Paul Hu2e0a88c2023-03-09 16:05:01 +0800526 final ConnectorArgs arg = (ConnectorArgs) msg.obj;
527 final INsdManagerCallback cb = arg.callback;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900528 try {
Paul Hu2e0a88c2023-03-09 16:05:01 +0800529 cb.asBinder().linkToDeath(arg.connector, 0);
Paul Hub2e67d32023-04-18 05:50:14 +0000530 final String tag = "Client" + arg.uid + "-" + mClientNumberId++;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900531 cInfo = new ClientInfo(cb, arg.uid, arg.useJavaBackend,
Paul Hub2e67d32023-04-18 05:50:14 +0000532 mServiceLogs.forSubComponent(tag));
Paul Hu2e0a88c2023-03-09 16:05:01 +0800533 mClients.put(arg.connector, cInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900534 } catch (RemoteException e) {
535 Log.w(TAG, "Client " + clientId + " has already died");
Irfan Sheriff75006652012-04-17 23:15:29 -0700536 }
537 break;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900538 case NsdManager.UNREGISTER_CLIENT:
539 final NsdServiceConnector connector = (NsdServiceConnector) msg.obj;
540 cInfo = mClients.remove(connector);
Dave Plattfeff2af2014-03-07 14:48:22 -0800541 if (cInfo != null) {
542 cInfo.expungeAllRequests();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900543 if (cInfo.isPreSClient()) {
Luke Huangf7277ed2021-07-12 21:15:10 +0800544 mLegacyClientCount -= 1;
545 }
Dave Plattfeff2af2014-03-07 14:48:22 -0800546 }
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900547 maybeStopMonitoringSocketsIfNoActiveRequest();
Luke Huangf7277ed2021-07-12 21:15:10 +0800548 maybeScheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700549 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700550 case NsdManager.DISCOVER_SERVICES:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900551 cInfo = getClientInfoForReply(msg);
552 if (cInfo != null) {
553 cInfo.onDiscoverServicesFailed(
554 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
555 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700556 break;
557 case NsdManager.STOP_DISCOVERY:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900558 cInfo = getClientInfoForReply(msg);
559 if (cInfo != null) {
560 cInfo.onStopDiscoveryFailed(
561 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
562 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700563 break;
564 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900565 cInfo = getClientInfoForReply(msg);
566 if (cInfo != null) {
567 cInfo.onRegisterServiceFailed(
568 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
569 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700570 break;
571 case NsdManager.UNREGISTER_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900572 cInfo = getClientInfoForReply(msg);
573 if (cInfo != null) {
574 cInfo.onUnregisterServiceFailed(
575 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
576 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700577 break;
578 case NsdManager.RESOLVE_SERVICE:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900579 cInfo = getClientInfoForReply(msg);
580 if (cInfo != null) {
581 cInfo.onResolveServiceFailed(
582 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
583 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700584 break;
Paul Hub58deb72022-12-26 09:24:42 +0000585 case NsdManager.STOP_RESOLUTION:
586 cInfo = getClientInfoForReply(msg);
587 if (cInfo != null) {
588 cInfo.onStopResolutionFailed(
589 clientId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
590 }
591 break;
Paul Hu18aeccc2022-12-27 08:48:48 +0000592 case NsdManager.REGISTER_SERVICE_CALLBACK:
593 cInfo = getClientInfoForReply(msg);
594 if (cInfo != null) {
595 cInfo.onServiceInfoCallbackRegistrationFailed(
596 clientId, NsdManager.FAILURE_BAD_PARAMETERS);
597 }
598 break;
Luke Huang05298582021-06-13 16:52:05 +0000599 case NsdManager.DAEMON_CLEANUP:
paulhu2b9ed952022-02-10 21:58:32 +0800600 maybeStopDaemon();
Luke Huang05298582021-06-13 16:52:05 +0000601 break;
Luke Huangf7277ed2021-07-12 21:15:10 +0800602 // This event should be only sent by the legacy (target SDK < S) clients.
603 // Mark the sending client as legacy.
604 case NsdManager.DAEMON_STARTUP:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900605 cInfo = getClientInfoForReply(msg);
Luke Huangf7277ed2021-07-12 21:15:10 +0800606 if (cInfo != null) {
607 cancelStop();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900608 cInfo.setPreSClient();
Luke Huangf7277ed2021-07-12 21:15:10 +0800609 mLegacyClientCount += 1;
610 maybeStartDaemon();
611 }
612 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700613 default:
paulhub2225702021-11-17 09:35:33 +0800614 Log.e(TAG, "Unhandled " + msg);
Irfan Sheriff75006652012-04-17 23:15:29 -0700615 return NOT_HANDLED;
616 }
617 return HANDLED;
618 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900619
620 private ClientInfo getClientInfoForReply(Message msg) {
621 final ListenerArgs args = (ListenerArgs) msg.obj;
622 return mClients.get(args.connector);
623 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700624 }
625
Irfan Sheriff75006652012-04-17 23:15:29 -0700626 class EnabledState extends State {
627 @Override
628 public void enter() {
629 sendNsdStateChangeBroadcast(true);
Irfan Sheriff75006652012-04-17 23:15:29 -0700630 }
631
632 @Override
633 public void exit() {
Luke Huang05298582021-06-13 16:52:05 +0000634 // TODO: it is incorrect to stop the daemon without expunging all requests
635 // and sending error callbacks to clients.
Luke Huang92860f92021-06-23 06:29:30 +0000636 scheduleStop();
Irfan Sheriff75006652012-04-17 23:15:29 -0700637 }
638
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700639 private boolean requestLimitReached(ClientInfo clientInfo) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900640 if (clientInfo.mClientRequests.size() >= ClientInfo.MAX_LIMIT) {
paulhub2225702021-11-17 09:35:33 +0800641 if (DBG) Log.d(TAG, "Exceeded max outstanding requests " + clientInfo);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700642 return true;
643 }
644 return false;
645 }
646
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900647 private void storeLegacyRequestMap(int clientId, int globalId, ClientInfo clientInfo,
648 int what) {
649 clientInfo.mClientRequests.put(clientId, new LegacyClientRequest(globalId, what));
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700650 mIdToClientInfoMap.put(globalId, clientInfo);
Luke Huang05298582021-06-13 16:52:05 +0000651 // Remove the cleanup event because here comes a new request.
652 cancelStop();
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700653 }
654
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900655 private void storeAdvertiserRequestMap(int clientId, int globalId,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900656 ClientInfo clientInfo, @Nullable Network requestedNetwork) {
657 clientInfo.mClientRequests.put(clientId,
658 new AdvertiserClientRequest(globalId, requestedNetwork));
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900659 mIdToClientInfoMap.put(globalId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900660 updateMulticastLock();
Paul Hu23fa2022023-01-13 22:57:24 +0800661 }
662
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900663 private void removeRequestMap(int clientId, int globalId, ClientInfo clientInfo) {
664 final ClientRequest existing = clientInfo.mClientRequests.get(clientId);
665 if (existing == null) return;
666 clientInfo.mClientRequests.remove(clientId);
667 mIdToClientInfoMap.remove(globalId);
668
669 if (existing instanceof LegacyClientRequest) {
670 maybeScheduleStop();
671 } else {
672 maybeStopMonitoringSocketsIfNoActiveRequest();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900673 updateMulticastLock();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900674 }
675 }
676
677 private void storeDiscoveryManagerRequestMap(int clientId, int globalId,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900678 MdnsListener listener, ClientInfo clientInfo,
679 @Nullable Network requestedNetwork) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900680 clientInfo.mClientRequests.put(clientId,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900681 new DiscoveryManagerRequest(globalId, listener, requestedNetwork));
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900682 mIdToClientInfoMap.put(globalId, clientInfo);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900683 updateMulticastLock();
Paul Hu23fa2022023-01-13 22:57:24 +0800684 }
685
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900686 /**
687 * Truncate a service name to up to 63 UTF-8 bytes.
688 *
689 * See RFC6763 4.1.1: service instance names are UTF-8 and up to 63 bytes. Truncating
690 * names used in registerService follows historical behavior (see mdnsresponder
691 * handle_regservice_request).
692 */
693 @NonNull
694 private String truncateServiceName(@NonNull String originalName) {
Yuyang Huangde802c82023-05-02 17:14:22 +0900695 return MdnsUtils.truncateServiceName(originalName, MAX_LABEL_LENGTH);
Paul Hu23fa2022023-01-13 22:57:24 +0800696 }
697
Paul Hue4f5f252023-02-16 21:13:47 +0800698 private void stopDiscoveryManagerRequest(ClientRequest request, int clientId, int id,
699 ClientInfo clientInfo) {
700 clientInfo.unregisterMdnsListenerFromRequest(request);
701 removeRequestMap(clientId, id, clientInfo);
702 }
703
Irfan Sheriff75006652012-04-17 23:15:29 -0700704 @Override
705 public boolean processMessage(Message msg) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900706 final ClientInfo clientInfo;
707 final int id;
708 final int clientId = msg.arg2;
709 final ListenerArgs args;
Irfan Sheriff75006652012-04-17 23:15:29 -0700710 switch (msg.what) {
Paul Hu75069ed2023-01-14 00:31:09 +0800711 case NsdManager.DISCOVER_SERVICES: {
paulhub2225702021-11-17 09:35:33 +0800712 if (DBG) Log.d(TAG, "Discover services");
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.
718 if (clientInfo == null) {
719 Log.e(TAG, "Unknown connector in discovery");
720 break;
721 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700722
723 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900724 clientInfo.onDiscoverServicesFailed(
725 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriff75006652012-04-17 23:15:29 -0700726 break;
727 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700728
Paul Hu23fa2022023-01-13 22:57:24 +0800729 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700730 id = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900731 final Pair<String, String> typeAndSubtype =
732 parseTypeAndSubtype(info.getServiceType());
733 final String serviceType = typeAndSubtype == null
734 ? null : typeAndSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800735 if (clientInfo.mUseJavaBackend
736 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900737 || useDiscoveryManagerForType(serviceType)) {
Paul Hu23fa2022023-01-13 22:57:24 +0800738 if (serviceType == null) {
739 clientInfo.onDiscoverServicesFailed(clientId,
740 NsdManager.FAILURE_INTERNAL_ERROR);
741 break;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700742 }
Paul Hu23fa2022023-01-13 22:57:24 +0800743
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900744 final String listenServiceType = serviceType + ".local";
Paul Hu23fa2022023-01-13 22:57:24 +0800745 maybeStartMonitoringSockets();
746 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900747 new DiscoveryListener(clientId, id, info, listenServiceType);
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900748 final MdnsSearchOptions.Builder optionsBuilder =
749 MdnsSearchOptions.newBuilder()
750 .setNetwork(info.getNetwork())
Yuyang Huangff963222023-06-01 18:42:42 +0900751 .setRemoveExpiredService(true)
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900752 .setIsPassiveMode(true);
753 if (typeAndSubtype.second != null) {
754 // The parsing ensures subtype starts with an underscore.
755 // MdnsSearchOptions expects the underscore to not be present.
756 optionsBuilder.addSubtype(typeAndSubtype.second.substring(1));
757 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900758 mMdnsDiscoveryManager.registerListener(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900759 listenServiceType, listener, optionsBuilder.build());
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900760 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo,
761 info.getNetwork());
Paul Hu23fa2022023-01-13 22:57:24 +0800762 clientInfo.onDiscoverServicesStarted(clientId, info);
Paul Hub2e67d32023-04-18 05:50:14 +0000763 clientInfo.log("Register a DiscoveryListener " + id
764 + " for service type:" + listenServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700765 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800766 maybeStartDaemon();
767 if (discoverServices(id, info)) {
768 if (DBG) {
769 Log.d(TAG, "Discover " + msg.arg2 + " " + id
770 + info.getServiceType());
771 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900772 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu23fa2022023-01-13 22:57:24 +0800773 clientInfo.onDiscoverServicesStarted(clientId, info);
774 } else {
775 stopServiceDiscovery(id);
776 clientInfo.onDiscoverServicesFailed(clientId,
777 NsdManager.FAILURE_INTERNAL_ERROR);
778 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700779 }
780 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800781 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900782 case NsdManager.STOP_DISCOVERY: {
paulhub2225702021-11-17 09:35:33 +0800783 if (DBG) Log.d(TAG, "Stop service discovery");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900784 args = (ListenerArgs) msg.obj;
785 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000786 // If the binder death notification for a INsdManagerCallback was received
787 // before any calls are received by NsdService, the clientInfo would be
788 // cleared and cause NPE. Add a null check here to prevent this corner case.
789 if (clientInfo == null) {
790 Log.e(TAG, "Unknown connector in stop discovery");
791 break;
792 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700793
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900794 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
795 if (request == null) {
796 Log.e(TAG, "Unknown client request in STOP_DISCOVERY");
Irfan Sheriff75006652012-04-17 23:15:29 -0700797 break;
798 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900799 id = request.mGlobalId;
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900800 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
801 // point, so this needs to check the type of the original request to
802 // unregister instead of looking at the flag value.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900803 if (request instanceof DiscoveryManagerRequest) {
Paul Hue4f5f252023-02-16 21:13:47 +0800804 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900805 clientInfo.onStopDiscoverySucceeded(clientId);
Paul Hub2e67d32023-04-18 05:50:14 +0000806 clientInfo.log("Unregister the DiscoveryListener " + id);
Irfan Sheriff75006652012-04-17 23:15:29 -0700807 } else {
Paul Hu23fa2022023-01-13 22:57:24 +0800808 removeRequestMap(clientId, id, clientInfo);
809 if (stopServiceDiscovery(id)) {
810 clientInfo.onStopDiscoverySucceeded(clientId);
811 } else {
812 clientInfo.onStopDiscoveryFailed(
813 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
814 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700815 }
816 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900817 }
818 case NsdManager.REGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800819 if (DBG) Log.d(TAG, "Register service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900820 args = (ListenerArgs) msg.obj;
821 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000822 // If the binder death notification for a INsdManagerCallback was received
823 // before any calls are received by NsdService, the clientInfo would be
824 // cleared and cause NPE. Add a null check here to prevent this corner case.
825 if (clientInfo == null) {
826 Log.e(TAG, "Unknown connector in registration");
827 break;
828 }
829
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700830 if (requestLimitReached(clientInfo)) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900831 clientInfo.onRegisterServiceFailed(
832 clientId, NsdManager.FAILURE_MAX_LIMIT);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700833 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700834 }
835
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700836 id = getUniqueId();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900837 final NsdServiceInfo serviceInfo = args.serviceInfo;
838 final String serviceType = serviceInfo.getServiceType();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900839 final Pair<String, String> typeSubtype = parseTypeAndSubtype(serviceType);
840 final String registerServiceType = typeSubtype == null
841 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800842 if (clientInfo.mUseJavaBackend
843 || mDeps.isMdnsAdvertiserEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900844 || useAdvertiserForType(registerServiceType)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900845 if (registerServiceType == null) {
846 Log.e(TAG, "Invalid service type: " + serviceType);
847 clientInfo.onRegisterServiceFailed(clientId,
848 NsdManager.FAILURE_INTERNAL_ERROR);
849 break;
850 }
851 serviceInfo.setServiceType(registerServiceType);
852 serviceInfo.setServiceName(truncateServiceName(
853 serviceInfo.getServiceName()));
854
855 maybeStartMonitoringSockets();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900856 // TODO: pass in the subtype as well. Including the subtype in the
857 // service type would generate service instance names like
858 // Name._subtype._sub._type._tcp, which is incorrect
859 // (it should be Name._type._tcp).
Remi NGUYEN VANce44beb2023-05-11 20:42:26 +0900860 mAdvertiser.addService(id, serviceInfo, typeSubtype.second);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900861 storeAdvertiserRequestMap(clientId, id, clientInfo,
862 serviceInfo.getNetwork());
Irfan Sheriff75006652012-04-17 23:15:29 -0700863 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900864 maybeStartDaemon();
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900865 if (registerService(id, serviceInfo)) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900866 if (DBG) Log.d(TAG, "Register " + clientId + " " + id);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900867 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900868 // Return success after mDns reports success
869 } else {
870 unregisterService(id);
871 clientInfo.onRegisterServiceFailed(
872 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
873 }
874
Irfan Sheriff75006652012-04-17 23:15:29 -0700875 }
876 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900877 }
878 case NsdManager.UNREGISTER_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800879 if (DBG) Log.d(TAG, "unregister service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900880 args = (ListenerArgs) msg.obj;
881 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000882 // If the binder death notification for a INsdManagerCallback was received
883 // before any calls are received by NsdService, the clientInfo would be
884 // cleared and cause NPE. Add a null check here to prevent this corner case.
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900885 if (clientInfo == null) {
paulhub2225702021-11-17 09:35:33 +0800886 Log.e(TAG, "Unknown connector in unregistration");
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700887 break;
Irfan Sheriff75006652012-04-17 23:15:29 -0700888 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900889 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
890 if (request == null) {
891 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE");
892 break;
893 }
894 id = request.mGlobalId;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900895 removeRequestMap(clientId, id, clientInfo);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900896
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +0900897 // Note isMdnsAdvertiserEnabled may have changed to false at this point,
898 // so this needs to check the type of the original request to unregister
899 // instead of looking at the flag value.
900 if (request instanceof AdvertiserClientRequest) {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900901 mAdvertiser.removeService(id);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900902 clientInfo.onUnregisterServiceSucceeded(clientId);
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700903 } else {
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900904 if (unregisterService(id)) {
905 clientInfo.onUnregisterServiceSucceeded(clientId);
906 } else {
907 clientInfo.onUnregisterServiceFailed(
908 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
909 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700910 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700911 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900912 }
Paul Hu75069ed2023-01-14 00:31:09 +0800913 case NsdManager.RESOLVE_SERVICE: {
paulhub2225702021-11-17 09:35:33 +0800914 if (DBG) Log.d(TAG, "Resolve service");
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +0900915 args = (ListenerArgs) msg.obj;
916 clientInfo = mClients.get(args.connector);
Paul Hu116b4c02022-08-16 07:21:55 +0000917 // If the binder death notification for a INsdManagerCallback was received
918 // before any calls are received by NsdService, the clientInfo would be
919 // cleared and cause NPE. Add a null check here to prevent this corner case.
920 if (clientInfo == null) {
921 Log.e(TAG, "Unknown connector in resolution");
922 break;
923 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700924
Paul Hu75069ed2023-01-14 00:31:09 +0800925 final NsdServiceInfo info = args.serviceInfo;
Irfan Sheriffe4c42f42012-05-03 16:44:27 -0700926 id = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +0900927 final Pair<String, String> typeSubtype =
928 parseTypeAndSubtype(info.getServiceType());
929 final String serviceType = typeSubtype == null
930 ? null : typeSubtype.first;
Paul Hu2e0a88c2023-03-09 16:05:01 +0800931 if (clientInfo.mUseJavaBackend
932 || mDeps.isMdnsDiscoveryManagerEnabled(mContext)
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +0900933 || useDiscoveryManagerForType(serviceType)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800934 if (serviceType == null) {
935 clientInfo.onResolveServiceFailed(clientId,
936 NsdManager.FAILURE_INTERNAL_ERROR);
937 break;
938 }
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900939 final String resolveServiceType = serviceType + ".local";
Paul Hu75069ed2023-01-14 00:31:09 +0800940
941 maybeStartMonitoringSockets();
942 final MdnsListener listener =
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900943 new ResolutionListener(clientId, id, info, resolveServiceType);
Paul Hu75069ed2023-01-14 00:31:09 +0800944 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
945 .setNetwork(info.getNetwork())
946 .setIsPassiveMode(true)
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900947 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +0900948 .setRemoveExpiredService(true)
Paul Hu75069ed2023-01-14 00:31:09 +0800949 .build();
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +0900950 mMdnsDiscoveryManager.registerListener(
951 resolveServiceType, listener, options);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +0900952 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo,
953 info.getNetwork());
Paul Hub2e67d32023-04-18 05:50:14 +0000954 clientInfo.log("Register a ResolutionListener " + id
955 + " for service type:" + resolveServiceType);
Irfan Sheriff75006652012-04-17 23:15:29 -0700956 } else {
Paul Hu75069ed2023-01-14 00:31:09 +0800957 if (clientInfo.mResolvedService != null) {
958 clientInfo.onResolveServiceFailed(
959 clientId, NsdManager.FAILURE_ALREADY_ACTIVE);
960 break;
961 }
962
963 maybeStartDaemon();
Remi NGUYEN VANbb62b1d2023-02-27 12:18:27 +0900964 if (resolveService(id, info)) {
Paul Hu75069ed2023-01-14 00:31:09 +0800965 clientInfo.mResolvedService = new NsdServiceInfo();
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900966 storeLegacyRequestMap(clientId, id, clientInfo, msg.what);
Paul Hu75069ed2023-01-14 00:31:09 +0800967 } else {
968 clientInfo.onResolveServiceFailed(
969 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
970 }
Irfan Sheriff75006652012-04-17 23:15:29 -0700971 }
972 break;
Paul Hu75069ed2023-01-14 00:31:09 +0800973 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900974 case NsdManager.STOP_RESOLUTION: {
Paul Hub58deb72022-12-26 09:24:42 +0000975 if (DBG) Log.d(TAG, "Stop service resolution");
976 args = (ListenerArgs) msg.obj;
977 clientInfo = mClients.get(args.connector);
978 // If the binder death notification for a INsdManagerCallback was received
979 // before any calls are received by NsdService, the clientInfo would be
980 // cleared and cause NPE. Add a null check here to prevent this corner case.
981 if (clientInfo == null) {
982 Log.e(TAG, "Unknown connector in stop resolution");
983 break;
984 }
985
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +0900986 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
987 if (request == null) {
988 Log.e(TAG, "Unknown client request in STOP_RESOLUTION");
989 break;
990 }
991 id = request.mGlobalId;
Paul Hue4f5f252023-02-16 21:13:47 +0800992 // Note isMdnsDiscoveryManagerEnabled may have changed to false at this
993 // point, so this needs to check the type of the original request to
994 // unregister instead of looking at the flag value.
995 if (request instanceof DiscoveryManagerRequest) {
996 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Paul Hub58deb72022-12-26 09:24:42 +0000997 clientInfo.onStopResolutionSucceeded(clientId);
Paul Hub2e67d32023-04-18 05:50:14 +0000998 clientInfo.log("Unregister the ResolutionListener " + id);
Paul Hub58deb72022-12-26 09:24:42 +0000999 } else {
Paul Hue4f5f252023-02-16 21:13:47 +08001000 removeRequestMap(clientId, id, clientInfo);
1001 if (stopResolveService(id)) {
1002 clientInfo.onStopResolutionSucceeded(clientId);
1003 } else {
1004 clientInfo.onStopResolutionFailed(
1005 clientId, NsdManager.FAILURE_OPERATION_NOT_RUNNING);
1006 }
1007 clientInfo.mResolvedService = null;
Paul Hub58deb72022-12-26 09:24:42 +00001008 }
Paul Hub58deb72022-12-26 09:24:42 +00001009 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001010 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001011 case NsdManager.REGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001012 if (DBG) Log.d(TAG, "Register a service callback");
1013 args = (ListenerArgs) msg.obj;
1014 clientInfo = mClients.get(args.connector);
1015 // If the binder death notification for a INsdManagerCallback was received
1016 // before any calls are received by NsdService, the clientInfo would be
1017 // cleared and cause NPE. Add a null check here to prevent this corner case.
1018 if (clientInfo == null) {
1019 Log.e(TAG, "Unknown connector in callback registration");
1020 break;
1021 }
1022
Paul Hu30bd70d2023-02-07 13:20:56 +00001023 final NsdServiceInfo info = args.serviceInfo;
1024 id = getUniqueId();
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001025 final Pair<String, String> typeAndSubtype =
1026 parseTypeAndSubtype(info.getServiceType());
1027 final String serviceType = typeAndSubtype == null
1028 ? null : typeAndSubtype.first;
Paul Hu30bd70d2023-02-07 13:20:56 +00001029 if (serviceType == null) {
1030 clientInfo.onServiceInfoCallbackRegistrationFailed(clientId,
1031 NsdManager.FAILURE_BAD_PARAMETERS);
Paul Hu18aeccc2022-12-27 08:48:48 +00001032 break;
1033 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001034 final String resolveServiceType = serviceType + ".local";
Paul Hu18aeccc2022-12-27 08:48:48 +00001035
Paul Hu30bd70d2023-02-07 13:20:56 +00001036 maybeStartMonitoringSockets();
1037 final MdnsListener listener =
1038 new ServiceInfoListener(clientId, id, info, resolveServiceType);
1039 final MdnsSearchOptions options = MdnsSearchOptions.newBuilder()
1040 .setNetwork(info.getNetwork())
1041 .setIsPassiveMode(true)
1042 .setResolveInstanceName(info.getServiceName())
Yuyang Huangff963222023-06-01 18:42:42 +09001043 .setRemoveExpiredService(true)
Paul Hu30bd70d2023-02-07 13:20:56 +00001044 .build();
1045 mMdnsDiscoveryManager.registerListener(
1046 resolveServiceType, listener, options);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001047 storeDiscoveryManagerRequestMap(clientId, id, listener, clientInfo,
1048 info.getNetwork());
Paul Hub2e67d32023-04-18 05:50:14 +00001049 clientInfo.log("Register a ServiceInfoListener " + id
1050 + " for service type:" + resolveServiceType);
Paul Hu18aeccc2022-12-27 08:48:48 +00001051 break;
Paul Hu30bd70d2023-02-07 13:20:56 +00001052 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001053 case NsdManager.UNREGISTER_SERVICE_CALLBACK: {
Paul Hu18aeccc2022-12-27 08:48:48 +00001054 if (DBG) Log.d(TAG, "Unregister a service callback");
1055 args = (ListenerArgs) msg.obj;
1056 clientInfo = mClients.get(args.connector);
1057 // If the binder death notification for a INsdManagerCallback was received
1058 // before any calls are received by NsdService, the clientInfo would be
1059 // cleared and cause NPE. Add a null check here to prevent this corner case.
1060 if (clientInfo == null) {
1061 Log.e(TAG, "Unknown connector in callback unregistration");
1062 break;
1063 }
1064
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001065 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
1066 if (request == null) {
Paul Hu30bd70d2023-02-07 13:20:56 +00001067 Log.e(TAG, "Unknown client request in UNREGISTER_SERVICE_CALLBACK");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001068 break;
1069 }
1070 id = request.mGlobalId;
Paul Hu30bd70d2023-02-07 13:20:56 +00001071 if (request instanceof DiscoveryManagerRequest) {
1072 stopDiscoveryManagerRequest(request, clientId, id, clientInfo);
Paul Hu18aeccc2022-12-27 08:48:48 +00001073 clientInfo.onServiceInfoCallbackUnregistered(clientId);
Paul Hub2e67d32023-04-18 05:50:14 +00001074 clientInfo.log("Unregister the ServiceInfoListener " + id);
Paul Hu18aeccc2022-12-27 08:48:48 +00001075 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001076 loge("Unregister failed with non-DiscoveryManagerRequest.");
Paul Hu18aeccc2022-12-27 08:48:48 +00001077 }
Paul Hu18aeccc2022-12-27 08:48:48 +00001078 break;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001079 }
paulhu2b9ed952022-02-10 21:58:32 +08001080 case MDNS_SERVICE_EVENT:
1081 if (!handleMDnsServiceEvent(msg.arg1, msg.arg2, msg.obj)) {
Hugo Benichif0c84092017-04-05 14:43:29 +09001082 return NOT_HANDLED;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001083 }
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001084 break;
Paul Hu019621e2023-01-13 23:26:49 +08001085 case MDNS_DISCOVERY_MANAGER_EVENT:
1086 if (!handleMdnsDiscoveryManagerEvent(msg.arg1, msg.arg2, msg.obj)) {
1087 return NOT_HANDLED;
1088 }
1089 break;
Irfan Sheriff75006652012-04-17 23:15:29 -07001090 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001091 return NOT_HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001092 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001093 return HANDLED;
Irfan Sheriff75006652012-04-17 23:15:29 -07001094 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001095
paulhu2b9ed952022-02-10 21:58:32 +08001096 private boolean handleMDnsServiceEvent(int code, int id, Object obj) {
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001097 NsdServiceInfo servInfo;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001098 ClientInfo clientInfo = mIdToClientInfoMap.get(id);
1099 if (clientInfo == null) {
paulhu2b9ed952022-02-10 21:58:32 +08001100 Log.e(TAG, String.format("id %d for %d has no client mapping", id, code));
Hugo Benichif0c84092017-04-05 14:43:29 +09001101 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001102 }
1103
1104 /* This goes in response as msg.arg2 */
Christopher Lane74411222014-04-25 18:39:07 -07001105 int clientId = clientInfo.getClientId(id);
1106 if (clientId < 0) {
Vinit Deshapnde930a8512013-06-25 19:45:03 -07001107 // This can happen because of race conditions. For example,
1108 // SERVICE_FOUND may race with STOP_SERVICE_DISCOVERY,
1109 // and we may get in this situation.
paulhu2b9ed952022-02-10 21:58:32 +08001110 Log.d(TAG, String.format("%d for listener id %d that is no longer active",
1111 code, id));
Hugo Benichif0c84092017-04-05 14:43:29 +09001112 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001113 }
Hugo Benichi32be63d2017-04-05 14:06:11 +09001114 if (DBG) {
paulhu2b9ed952022-02-10 21:58:32 +08001115 Log.d(TAG, String.format("MDns service event code:%d id=%d", code, id));
Hugo Benichi32be63d2017-04-05 14:06:11 +09001116 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001117 switch (code) {
paulhu2b9ed952022-02-10 21:58:32 +08001118 case IMDnsEventListener.SERVICE_FOUND: {
1119 final DiscoveryInfo info = (DiscoveryInfo) obj;
1120 final String name = info.serviceName;
1121 final String type = info.registrationType;
1122 servInfo = new NsdServiceInfo(name, type);
1123 final int foundNetId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001124 if (foundNetId == 0L) {
1125 // Ignore services that do not have a Network: they are not usable
1126 // by apps, as they would need privileged permissions to use
1127 // interfaces that do not have an associated Network.
1128 break;
1129 }
Remi NGUYEN VAN643edb62023-01-23 19:14:57 +09001130 if (foundNetId == INetd.DUMMY_NET_ID) {
1131 // Ignore services on the dummy0 interface: they are only seen when
1132 // discovering locally advertised services, and are not reachable
1133 // through that interface.
1134 break;
1135 }
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001136 setServiceNetworkForCallback(servInfo, info.netId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001137 clientInfo.onServiceFound(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001138 break;
paulhu2b9ed952022-02-10 21:58:32 +08001139 }
1140 case IMDnsEventListener.SERVICE_LOST: {
1141 final DiscoveryInfo info = (DiscoveryInfo) obj;
1142 final String name = info.serviceName;
1143 final String type = info.registrationType;
1144 final int lostNetId = info.netId;
1145 servInfo = new NsdServiceInfo(name, type);
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001146 // The network could be set to null (netId 0) if it was torn down when the
1147 // service is lost
1148 // TODO: avoid returning null in that case, possibly by remembering
1149 // found services on the same interface index and their network at the time
1150 setServiceNetworkForCallback(servInfo, lostNetId, info.interfaceIdx);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001151 clientInfo.onServiceLost(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001152 break;
paulhu2b9ed952022-02-10 21:58:32 +08001153 }
1154 case IMDnsEventListener.SERVICE_DISCOVERY_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001155 clientInfo.onDiscoverServicesFailed(
1156 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001157 break;
paulhu2b9ed952022-02-10 21:58:32 +08001158 case IMDnsEventListener.SERVICE_REGISTERED: {
1159 final RegistrationInfo info = (RegistrationInfo) obj;
1160 final String name = info.serviceName;
1161 servInfo = new NsdServiceInfo(name, null /* serviceType */);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001162 clientInfo.onRegisterServiceSucceeded(clientId, servInfo);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001163 break;
paulhu2b9ed952022-02-10 21:58:32 +08001164 }
1165 case IMDnsEventListener.SERVICE_REGISTRATION_FAILED:
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001166 clientInfo.onRegisterServiceFailed(
1167 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001168 break;
paulhu2b9ed952022-02-10 21:58:32 +08001169 case IMDnsEventListener.SERVICE_RESOLVED: {
1170 final ResolutionInfo info = (ResolutionInfo) obj;
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001171 int index = 0;
paulhu2b9ed952022-02-10 21:58:32 +08001172 final String fullName = info.serviceFullName;
1173 while (index < fullName.length() && fullName.charAt(index) != '.') {
1174 if (fullName.charAt(index) == '\\') {
Sreeram Ramachandrana53dd7f2014-09-03 15:45:59 -07001175 ++index;
1176 }
1177 ++index;
1178 }
paulhu2b9ed952022-02-10 21:58:32 +08001179 if (index >= fullName.length()) {
1180 Log.e(TAG, "Invalid service found " + fullName);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001181 break;
1182 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001183
paulhube186602022-04-12 07:18:23 +00001184 String name = unescape(fullName.substring(0, index));
paulhu2b9ed952022-02-10 21:58:32 +08001185 String rest = fullName.substring(index);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001186 String type = rest.replace(".local.", "");
1187
Paul Hu30bd70d2023-02-07 13:20:56 +00001188 final NsdServiceInfo serviceInfo = clientInfo.mResolvedService;
Paul Hu18aeccc2022-12-27 08:48:48 +00001189 serviceInfo.setServiceName(name);
1190 serviceInfo.setServiceType(type);
1191 serviceInfo.setPort(info.port);
1192 serviceInfo.setTxtRecords(info.txtRecord);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001193 // Network will be added after SERVICE_GET_ADDR_SUCCESS
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001194
1195 stopResolveService(id);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001196 removeRequestMap(clientId, id, clientInfo);
1197
paulhu2b9ed952022-02-10 21:58:32 +08001198 final int id2 = getUniqueId();
1199 if (getAddrInfo(id2, info.hostname, info.interfaceIdx)) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001200 storeLegacyRequestMap(clientId, id2, clientInfo,
1201 NsdManager.RESOLVE_SERVICE);
Vinit Deshapnde4429e872013-11-12 15:36:37 -08001202 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001203 clientInfo.onResolveServiceFailed(
1204 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1205 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001206 }
1207 break;
paulhu2b9ed952022-02-10 21:58:32 +08001208 }
1209 case IMDnsEventListener.SERVICE_RESOLUTION_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001210 /* NNN resolveId errorCode */
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001211 stopResolveService(id);
1212 removeRequestMap(clientId, id, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001213 clientInfo.onResolveServiceFailed(
1214 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1215 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001216 break;
paulhu2b9ed952022-02-10 21:58:32 +08001217 case IMDnsEventListener.SERVICE_GET_ADDR_FAILED:
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001218 /* NNN resolveId errorCode */
1219 stopGetAddrInfo(id);
1220 removeRequestMap(clientId, id, clientInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001221 clientInfo.onResolveServiceFailed(
1222 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1223 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001224 break;
paulhu2b9ed952022-02-10 21:58:32 +08001225 case IMDnsEventListener.SERVICE_GET_ADDR_SUCCESS: {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001226 /* NNN resolveId hostname ttl addr interfaceIdx netId */
paulhu2b9ed952022-02-10 21:58:32 +08001227 final GetAddressInfo info = (GetAddressInfo) obj;
1228 final String address = info.address;
1229 final int netId = info.netId;
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001230 InetAddress serviceHost = null;
1231 try {
paulhu2b9ed952022-02-10 21:58:32 +08001232 serviceHost = InetAddress.getByName(address);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001233 } catch (UnknownHostException e) {
1234 Log.wtf(TAG, "Invalid host in GET_ADDR_SUCCESS", e);
1235 }
1236
1237 // If the resolved service is on an interface without a network, consider it
1238 // as a failure: it would not be usable by apps as they would need
1239 // privileged permissions.
Paul Hu30bd70d2023-02-07 13:20:56 +00001240 if (netId != NETID_UNSET && serviceHost != null) {
1241 clientInfo.mResolvedService.setHost(serviceHost);
1242 setServiceNetworkForCallback(clientInfo.mResolvedService,
1243 netId, info.interfaceIdx);
1244 clientInfo.onResolveServiceSucceeded(
1245 clientId, clientInfo.mResolvedService);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001246 } else {
Paul Hu30bd70d2023-02-07 13:20:56 +00001247 clientInfo.onResolveServiceFailed(
1248 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001249 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001250 stopGetAddrInfo(id);
1251 removeRequestMap(clientId, id, clientInfo);
1252 clientInfo.mResolvedService = null;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001253 break;
paulhu2b9ed952022-02-10 21:58:32 +08001254 }
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001255 default:
Hugo Benichif0c84092017-04-05 14:43:29 +09001256 return false;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001257 }
Hugo Benichif0c84092017-04-05 14:43:29 +09001258 return true;
Vairavan Srinivasan6ce48182012-08-05 13:14:12 -07001259 }
Paul Hu019621e2023-01-13 23:26:49 +08001260
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001261 @Nullable
1262 private NsdServiceInfo buildNsdServiceInfoFromMdnsEvent(
1263 final MdnsEvent event, int code) {
Paul Hu019621e2023-01-13 23:26:49 +08001264 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001265 final String[] typeArray = serviceInfo.getServiceType();
1266 final String joinedType;
1267 if (typeArray.length == 0
1268 || !typeArray[typeArray.length - 1].equals(LOCAL_DOMAIN_NAME)) {
1269 Log.wtf(TAG, "MdnsServiceInfo type does not end in .local: "
1270 + Arrays.toString(typeArray));
1271 return null;
1272 } else {
1273 joinedType = TextUtils.join(".",
1274 Arrays.copyOfRange(typeArray, 0, typeArray.length - 1));
1275 }
1276 final String serviceType;
1277 switch (code) {
1278 case NsdManager.SERVICE_FOUND:
1279 case NsdManager.SERVICE_LOST:
1280 // For consistency with historical behavior, discovered service types have
1281 // a dot at the end.
1282 serviceType = joinedType + ".";
1283 break;
1284 case RESOLVE_SERVICE_SUCCEEDED:
1285 // For consistency with historical behavior, resolved service types have
1286 // a dot at the beginning.
1287 serviceType = "." + joinedType;
1288 break;
1289 default:
1290 serviceType = joinedType;
1291 break;
1292 }
Paul Hu019621e2023-01-13 23:26:49 +08001293 final String serviceName = serviceInfo.getServiceInstanceName();
1294 final NsdServiceInfo servInfo = new NsdServiceInfo(serviceName, serviceType);
1295 final Network network = serviceInfo.getNetwork();
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001296 // In MdnsDiscoveryManagerEvent, the Network can be null which means it is a
1297 // network for Tethering interface. In other words, the network == null means the
1298 // network has netId = INetd.LOCAL_NET_ID.
Paul Hu019621e2023-01-13 23:26:49 +08001299 setServiceNetworkForCallback(
1300 servInfo,
Yuyang Huang3bee9d42023-04-04 13:00:54 +09001301 network == null ? INetd.LOCAL_NET_ID : network.netId,
Paul Hu019621e2023-01-13 23:26:49 +08001302 serviceInfo.getInterfaceIndex());
1303 return servInfo;
1304 }
1305
1306 private boolean handleMdnsDiscoveryManagerEvent(
1307 int transactionId, int code, Object obj) {
1308 final ClientInfo clientInfo = mIdToClientInfoMap.get(transactionId);
1309 if (clientInfo == null) {
1310 Log.e(TAG, String.format(
1311 "id %d for %d has no client mapping", transactionId, code));
1312 return false;
1313 }
1314
1315 final MdnsEvent event = (MdnsEvent) obj;
1316 final int clientId = event.mClientId;
Remi NGUYEN VAN2f82fcd2023-05-10 13:24:53 +09001317 final NsdServiceInfo info = buildNsdServiceInfoFromMdnsEvent(event, code);
1318 // Errors are already logged if null
1319 if (info == null) return false;
Paul Hu019621e2023-01-13 23:26:49 +08001320 if (DBG) {
1321 Log.d(TAG, String.format("MdnsDiscoveryManager event code=%s transactionId=%d",
1322 NsdManager.nameOf(code), transactionId));
1323 }
1324 switch (code) {
1325 case NsdManager.SERVICE_FOUND:
Paul Hu319751a2023-01-13 23:56:34 +08001326 clientInfo.onServiceFound(clientId, info);
1327 break;
1328 case NsdManager.SERVICE_LOST:
1329 clientInfo.onServiceLost(clientId, info);
Paul Hu019621e2023-01-13 23:26:49 +08001330 break;
Paul Hu75069ed2023-01-14 00:31:09 +08001331 case NsdManager.RESOLVE_SERVICE_SUCCEEDED: {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001332 final ClientRequest request = clientInfo.mClientRequests.get(clientId);
1333 if (request == null) {
1334 Log.e(TAG, "Unknown client request in RESOLVE_SERVICE_SUCCEEDED");
1335 break;
1336 }
Paul Hu75069ed2023-01-14 00:31:09 +08001337 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
Paul Hu75069ed2023-01-14 00:31:09 +08001338 info.setPort(serviceInfo.getPort());
1339
1340 Map<String, String> attrs = serviceInfo.getAttributes();
1341 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1342 final String key = kv.getKey();
1343 try {
1344 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1345 } catch (IllegalArgumentException e) {
1346 Log.e(TAG, "Invalid attribute", e);
1347 }
1348 }
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001349 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu2b865912023-03-06 14:27:53 +08001350 if (addresses.size() != 0) {
1351 info.setHostAddresses(addresses);
Paul Hu75069ed2023-01-14 00:31:09 +08001352 clientInfo.onResolveServiceSucceeded(clientId, info);
Paul Hu2b865912023-03-06 14:27:53 +08001353 } else {
1354 // No address. Notify resolution failure.
Paul Hu75069ed2023-01-14 00:31:09 +08001355 clientInfo.onResolveServiceFailed(
1356 clientId, NsdManager.FAILURE_INTERNAL_ERROR);
1357 }
1358
1359 // Unregister the listener immediately like IMDnsEventListener design
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09001360 if (!(request instanceof DiscoveryManagerRequest)) {
1361 Log.wtf(TAG, "non-DiscoveryManager request in DiscoveryManager event");
1362 break;
1363 }
Paul Hue4f5f252023-02-16 21:13:47 +08001364 stopDiscoveryManagerRequest(request, clientId, transactionId, clientInfo);
Paul Hu75069ed2023-01-14 00:31:09 +08001365 break;
1366 }
Paul Hu30bd70d2023-02-07 13:20:56 +00001367 case NsdManager.SERVICE_UPDATED: {
1368 final MdnsServiceInfo serviceInfo = event.mMdnsServiceInfo;
1369 info.setPort(serviceInfo.getPort());
1370
1371 Map<String, String> attrs = serviceInfo.getAttributes();
1372 for (Map.Entry<String, String> kv : attrs.entrySet()) {
1373 final String key = kv.getKey();
1374 try {
1375 info.setAttribute(key, serviceInfo.getAttributeAsBytes(key));
1376 } catch (IllegalArgumentException e) {
1377 Log.e(TAG, "Invalid attribute", e);
1378 }
1379 }
1380
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001381 final List<InetAddress> addresses = getInetAddresses(serviceInfo);
Paul Hu30bd70d2023-02-07 13:20:56 +00001382 info.setHostAddresses(addresses);
1383 clientInfo.onServiceUpdated(clientId, info);
1384 break;
1385 }
1386 case NsdManager.SERVICE_UPDATED_LOST:
1387 clientInfo.onServiceUpdatedLost(clientId);
1388 break;
Paul Hu019621e2023-01-13 23:26:49 +08001389 default:
1390 return false;
1391 }
1392 return true;
1393 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001394 }
1395 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001396
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001397 @NonNull
1398 private static List<InetAddress> getInetAddresses(@NonNull MdnsServiceInfo serviceInfo) {
1399 final List<String> v4Addrs = serviceInfo.getIpv4Addresses();
1400 final List<String> v6Addrs = serviceInfo.getIpv6Addresses();
1401 final List<InetAddress> addresses = new ArrayList<>(v4Addrs.size() + v6Addrs.size());
1402 for (String ipv4Address : v4Addrs) {
1403 try {
1404 addresses.add(InetAddresses.parseNumericAddress(ipv4Address));
1405 } catch (IllegalArgumentException e) {
1406 Log.wtf(TAG, "Invalid ipv4 address", e);
1407 }
1408 }
1409 for (String ipv6Address : v6Addrs) {
1410 try {
Yuyang Huanga6a6ff92023-04-24 13:33:34 +09001411 final Inet6Address addr = (Inet6Address) InetAddresses.parseNumericAddress(
1412 ipv6Address);
1413 addresses.add(InetAddressUtils.withScopeId(addr, serviceInfo.getInterfaceIndex()));
1414 } catch (IllegalArgumentException e) {
Yuyang Huangaa0e9602023-03-17 12:43:09 +09001415 Log.wtf(TAG, "Invalid ipv6 address", e);
1416 }
1417 }
1418 return addresses;
1419 }
1420
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001421 private static void setServiceNetworkForCallback(NsdServiceInfo info, int netId, int ifaceIdx) {
1422 switch (netId) {
1423 case NETID_UNSET:
1424 info.setNetwork(null);
1425 break;
1426 case INetd.LOCAL_NET_ID:
1427 // Special case for LOCAL_NET_ID: Networks on netId 99 are not generally
1428 // visible / usable for apps, so do not return it. Store the interface
1429 // index instead, so at least if the client tries to resolve the service
1430 // with that NsdServiceInfo, it will be done on the same interface.
1431 // If they recreate the NsdServiceInfo themselves, resolution would be
1432 // done on all interfaces as before T, which should also work.
1433 info.setNetwork(null);
1434 info.setInterfaceIndex(ifaceIdx);
1435 break;
1436 default:
1437 info.setNetwork(new Network(netId));
1438 }
1439 }
1440
paulhube186602022-04-12 07:18:23 +00001441 // The full service name is escaped from standard DNS rules on mdnsresponder, making it suitable
1442 // for passing to standard system DNS APIs such as res_query() . Thus, make the service name
1443 // unescape for getting right service address. See "Notes on DNS Name Escaping" on
1444 // external/mdnsresponder/mDNSShared/dns_sd.h for more details.
1445 private String unescape(String s) {
1446 StringBuilder sb = new StringBuilder(s.length());
1447 for (int i = 0; i < s.length(); ++i) {
1448 char c = s.charAt(i);
1449 if (c == '\\') {
1450 if (++i >= s.length()) {
1451 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1452 break;
1453 }
1454 c = s.charAt(i);
1455 if (c != '.' && c != '\\') {
1456 if (i + 2 >= s.length()) {
1457 Log.e(TAG, "Unexpected end of escape sequence in: " + s);
1458 break;
1459 }
1460 c = (char) ((c - '0') * 100 + (s.charAt(i + 1) - '0') * 10
1461 + (s.charAt(i + 2) - '0'));
1462 i += 2;
1463 }
1464 }
1465 sb.append(c);
1466 }
1467 return sb.toString();
1468 }
1469
Paul Hu7445e3d2023-03-03 15:14:00 +08001470 /**
1471 * Check the given service type is valid and construct it to a service type
1472 * which can use for discovery / resolution service.
1473 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001474 * <p>The valid service type should be 2 labels, or 3 labels if the query is for a
Paul Hu7445e3d2023-03-03 15:14:00 +08001475 * subtype (see RFC6763 7.1). Each label is up to 63 characters and must start with an
1476 * underscore; they are alphanumerical characters or dashes or underscore, except the
1477 * last one that is just alphanumerical. The last label must be _tcp or _udp.
1478 *
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001479 * <p>The subtype may also be specified with a comma after the service type, for example
1480 * _type._tcp,_subtype.
1481 *
Paul Hu7445e3d2023-03-03 15:14:00 +08001482 * @param serviceType the request service type for discovery / resolution service
1483 * @return constructed service type or null if the given service type is invalid.
1484 */
1485 @Nullable
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001486 public static Pair<String, String> parseTypeAndSubtype(String serviceType) {
Paul Hu7445e3d2023-03-03 15:14:00 +08001487 if (TextUtils.isEmpty(serviceType)) return null;
1488
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001489 final String typeOrSubtypePattern = "_[a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]";
Paul Hu7445e3d2023-03-03 15:14:00 +08001490 final Pattern serviceTypePattern = Pattern.compile(
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001491 // Optional leading subtype (_subtype._type._tcp)
1492 // (?: xxx) is a non-capturing parenthesis, don't capture the dot
1493 "^(?:(" + typeOrSubtypePattern + ")\\.)?"
1494 // Actual type (_type._tcp.local)
1495 + "(" + typeOrSubtypePattern + "\\._(?:tcp|udp))"
Paul Hu7445e3d2023-03-03 15:14:00 +08001496 // Drop '.' at the end of service type that is compatible with old backend.
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001497 // e.g. allow "_type._tcp.local."
1498 + "\\.?"
1499 // Optional subtype after comma, for "_type._tcp,_subtype" format
1500 + "(?:,(" + typeOrSubtypePattern + "))?"
1501 + "$");
Paul Hu7445e3d2023-03-03 15:14:00 +08001502 final Matcher matcher = serviceTypePattern.matcher(serviceType);
1503 if (!matcher.matches()) return null;
Remi NGUYEN VANf2d06412023-05-11 19:18:44 +09001504 // Use the subtype either at the beginning or after the comma
1505 final String subtype = matcher.group(1) != null ? matcher.group(1) : matcher.group(3);
1506 return new Pair<>(matcher.group(2), subtype);
Paul Hu7445e3d2023-03-03 15:14:00 +08001507 }
1508
Hugo Benichi803a2f02017-04-24 11:35:06 +09001509 @VisibleForTesting
paulhu2b9ed952022-02-10 21:58:32 +08001510 NsdService(Context ctx, Handler handler, long cleanupDelayMs) {
Paul Hu4bd98ef2023-01-12 13:42:07 +08001511 this(ctx, handler, cleanupDelayMs, new Dependencies());
1512 }
1513
1514 @VisibleForTesting
1515 NsdService(Context ctx, Handler handler, long cleanupDelayMs, Dependencies deps) {
Luke Huang05298582021-06-13 16:52:05 +00001516 mCleanupDelayMs = cleanupDelayMs;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001517 mContext = ctx;
Hugo Benichi803a2f02017-04-24 11:35:06 +09001518 mNsdStateMachine = new NsdStateMachine(TAG, handler);
Irfan Sheriff75006652012-04-17 23:15:29 -07001519 mNsdStateMachine.start();
paulhu2b9ed952022-02-10 21:58:32 +08001520 mMDnsManager = ctx.getSystemService(MDnsManager.class);
1521 mMDnsEventCallback = new MDnsEventCallback(mNsdStateMachine);
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001522 mDeps = deps;
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001523
Paul Hu14667de2023-04-17 22:42:47 +08001524 mMdnsSocketProvider = deps.makeMdnsSocketProvider(ctx, handler.getLooper(),
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001525 LOGGER.forSubComponent("MdnsSocketProvider"), new SocketRequestMonitor());
Yuyang Huang700778b2023-03-08 16:17:05 +09001526 // Netlink monitor starts on boot, and intentionally never stopped, to ensure that all
1527 // address events are received.
1528 handler.post(mMdnsSocketProvider::startNetLinkMonitor);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001529
1530 // NsdService is started after ActivityManager (startOtherServices in SystemServer, vs.
1531 // startBootstrapServices).
1532 mRunningAppActiveImportanceCutoff = mDeps.getDeviceConfigInt(
1533 MDNS_CONFIG_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF,
1534 DEFAULT_RUNNING_APP_ACTIVE_IMPORTANCE_CUTOFF);
1535 final ActivityManager am = ctx.getSystemService(ActivityManager.class);
1536 am.addOnUidImportanceListener(new UidImportanceListener(handler),
1537 mRunningAppActiveImportanceCutoff);
1538
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001539 mMdnsSocketClient =
1540 new MdnsMultinetworkSocketClient(handler.getLooper(), mMdnsSocketProvider);
Paul Hu14667de2023-04-17 22:42:47 +08001541 mMdnsDiscoveryManager = deps.makeMdnsDiscoveryManager(new ExecutorProvider(),
Yuyang Huang243d1a52023-05-23 17:26:52 +09001542 mMdnsSocketClient, LOGGER.forSubComponent("MdnsDiscoveryManager"));
Remi NGUYEN VANa8a777b2023-01-18 18:57:41 +09001543 handler.post(() -> mMdnsSocketClient.setCallback(mMdnsDiscoveryManager));
1544 mAdvertiser = deps.makeMdnsAdvertiser(handler.getLooper(), mMdnsSocketProvider,
Paul Hu14667de2023-04-17 22:42:47 +08001545 new AdvertiserCallback(), LOGGER.forSubComponent("MdnsAdvertiser"));
Paul Hu4bd98ef2023-01-12 13:42:07 +08001546 }
1547
1548 /**
1549 * Dependencies of NsdService, for injection in tests.
1550 */
1551 @VisibleForTesting
1552 public static class Dependencies {
1553 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001554 * Check whether the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001555 *
1556 * @param context The global context information about an app environment.
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001557 * @return true if the MdnsDiscoveryManager feature is enabled.
Paul Hu4bd98ef2023-01-12 13:42:07 +08001558 */
1559 public boolean isMdnsDiscoveryManagerEnabled(Context context) {
Motomu Utsumi278db582023-04-21 12:35:22 +09001560 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1561 MDNS_DISCOVERY_MANAGER_VERSION, DeviceConfigUtils.TETHERING_MODULE_NAME,
Remi NGUYEN VANbeb03f12023-03-08 19:03:27 +09001562 false /* defaultEnabled */);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001563 }
1564
1565 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001566 * Check whether the MdnsAdvertiser feature is enabled.
1567 *
1568 * @param context The global context information about an app environment.
1569 * @return true if the MdnsAdvertiser feature is enabled.
1570 */
1571 public boolean isMdnsAdvertiserEnabled(Context context) {
Motomu Utsumi278db582023-04-21 12:35:22 +09001572 return isAtLeastU() || DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1573 MDNS_ADVERTISER_VERSION, DeviceConfigUtils.TETHERING_MODULE_NAME,
1574 false /* defaultEnabled */);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001575 }
1576
1577 /**
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001578 * Get the type allowlist flag value.
1579 * @see #MDNS_TYPE_ALLOWLIST_FLAGS
1580 */
1581 @Nullable
1582 public String getTypeAllowlistFlags() {
1583 return DeviceConfigUtils.getDeviceConfigProperty(NAMESPACE_TETHERING,
1584 MDNS_TYPE_ALLOWLIST_FLAGS, null);
1585 }
1586
1587 /**
1588 * @see DeviceConfigUtils#isFeatureEnabled(Context, String, String, String, boolean)
1589 */
1590 public boolean isFeatureEnabled(Context context, String feature) {
1591 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING,
1592 feature, DeviceConfigUtils.TETHERING_MODULE_NAME, false /* defaultEnabled */);
1593 }
1594
1595 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001596 * @see MdnsDiscoveryManager
1597 */
1598 public MdnsDiscoveryManager makeMdnsDiscoveryManager(
Paul Hu14667de2023-04-17 22:42:47 +08001599 @NonNull ExecutorProvider executorProvider,
Yuyang Huang243d1a52023-05-23 17:26:52 +09001600 @NonNull MdnsMultinetworkSocketClient socketClient, @NonNull SharedLog sharedLog) {
1601 return new MdnsDiscoveryManager(executorProvider, socketClient, sharedLog);
Paul Hu4bd98ef2023-01-12 13:42:07 +08001602 }
1603
1604 /**
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001605 * @see MdnsAdvertiser
1606 */
1607 public MdnsAdvertiser makeMdnsAdvertiser(
1608 @NonNull Looper looper, @NonNull MdnsSocketProvider socketProvider,
Paul Hu14667de2023-04-17 22:42:47 +08001609 @NonNull MdnsAdvertiser.AdvertiserCallback cb, @NonNull SharedLog sharedLog) {
1610 return new MdnsAdvertiser(looper, socketProvider, cb, sharedLog);
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001611 }
1612
1613 /**
Paul Hu4bd98ef2023-01-12 13:42:07 +08001614 * @see MdnsSocketProvider
1615 */
Paul Hu14667de2023-04-17 22:42:47 +08001616 public MdnsSocketProvider makeMdnsSocketProvider(@NonNull Context context,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001617 @NonNull Looper looper, @NonNull SharedLog sharedLog,
1618 @NonNull MdnsSocketProvider.SocketRequestMonitor socketCreationCallback) {
1619 return new MdnsSocketProvider(context, looper, sharedLog, socketCreationCallback);
1620 }
1621
1622 /**
1623 * @see DeviceConfig#getInt(String, String, int)
1624 */
1625 public int getDeviceConfigInt(@NonNull String config, int defaultValue) {
1626 return DeviceConfig.getInt(NAMESPACE_TETHERING, config, defaultValue);
1627 }
1628
1629 /**
1630 * @see Binder#getCallingUid()
1631 */
1632 public int getCallingUid() {
1633 return Binder.getCallingUid();
Paul Hu4bd98ef2023-01-12 13:42:07 +08001634 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001635 }
1636
Remi NGUYEN VAN151d0a52023-03-03 17:50:50 +09001637 /**
1638 * Return whether a type is allowlisted to use the Java backend.
1639 * @param type The service type
1640 * @param flagPrefix One of {@link #MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX} or
1641 * {@link #MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX}.
1642 */
1643 private boolean isTypeAllowlistedForJavaBackend(@Nullable String type,
1644 @NonNull String flagPrefix) {
1645 if (type == null) return false;
1646 final String typesConfig = mDeps.getTypeAllowlistFlags();
1647 if (TextUtils.isEmpty(typesConfig)) return false;
1648
1649 final String mappingPrefix = type + ":";
1650 String mappedFlag = null;
1651 for (String mapping : TextUtils.split(typesConfig, ",")) {
1652 if (mapping.startsWith(mappingPrefix)) {
1653 mappedFlag = mapping.substring(mappingPrefix.length());
1654 break;
1655 }
1656 }
1657
1658 if (mappedFlag == null) return false;
1659
1660 return mDeps.isFeatureEnabled(mContext,
1661 flagPrefix + mappedFlag + MDNS_ALLOWLIST_FLAG_SUFFIX);
1662 }
1663
1664 private boolean useDiscoveryManagerForType(@Nullable String type) {
1665 return isTypeAllowlistedForJavaBackend(type, MDNS_DISCOVERY_MANAGER_ALLOWLIST_FLAG_PREFIX);
1666 }
1667
1668 private boolean useAdvertiserForType(@Nullable String type) {
1669 return isTypeAllowlistedForJavaBackend(type, MDNS_ADVERTISER_ALLOWLIST_FLAG_PREFIX);
1670 }
1671
paulhu1b35e822022-04-08 14:48:41 +08001672 public static NsdService create(Context context) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001673 HandlerThread thread = new HandlerThread(TAG);
1674 thread.start();
1675 Handler handler = new Handler(thread.getLooper());
paulhu2b9ed952022-02-10 21:58:32 +08001676 NsdService service = new NsdService(context, handler, CLEANUP_DELAY_MS);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001677 return service;
1678 }
1679
paulhu2b9ed952022-02-10 21:58:32 +08001680 private static class MDnsEventCallback extends IMDnsEventListener.Stub {
1681 private final StateMachine mStateMachine;
1682
1683 MDnsEventCallback(StateMachine sm) {
1684 mStateMachine = sm;
1685 }
1686
1687 @Override
1688 public void onServiceRegistrationStatus(final RegistrationInfo status) {
1689 mStateMachine.sendMessage(
1690 MDNS_SERVICE_EVENT, status.result, status.id, status);
1691 }
1692
1693 @Override
1694 public void onServiceDiscoveryStatus(final DiscoveryInfo status) {
1695 mStateMachine.sendMessage(
1696 MDNS_SERVICE_EVENT, status.result, status.id, status);
1697 }
1698
1699 @Override
1700 public void onServiceResolutionStatus(final ResolutionInfo status) {
1701 mStateMachine.sendMessage(
1702 MDNS_SERVICE_EVENT, status.result, status.id, status);
1703 }
1704
1705 @Override
1706 public void onGettingServiceAddressStatus(final GetAddressInfo status) {
1707 mStateMachine.sendMessage(
1708 MDNS_SERVICE_EVENT, status.result, status.id, status);
1709 }
1710
1711 @Override
1712 public int getInterfaceVersion() throws RemoteException {
1713 return this.VERSION;
1714 }
1715
1716 @Override
1717 public String getInterfaceHash() throws RemoteException {
1718 return this.HASH;
1719 }
1720 }
1721
Remi NGUYEN VAN5b9074c2023-01-18 15:58:03 +09001722 private class AdvertiserCallback implements MdnsAdvertiser.AdvertiserCallback {
1723 @Override
1724 public void onRegisterServiceSucceeded(int serviceId, NsdServiceInfo registeredInfo) {
1725 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1726 if (clientInfo == null) return;
1727
1728 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1729 if (clientId < 0) return;
1730
1731 // onRegisterServiceSucceeded only has the service name in its info. This aligns with
1732 // historical behavior.
1733 final NsdServiceInfo cbInfo = new NsdServiceInfo(registeredInfo.getServiceName(), null);
1734 clientInfo.onRegisterServiceSucceeded(clientId, cbInfo);
1735 }
1736
1737 @Override
1738 public void onRegisterServiceFailed(int serviceId, int errorCode) {
1739 final ClientInfo clientInfo = getClientInfoOrLog(serviceId);
1740 if (clientInfo == null) return;
1741
1742 final int clientId = getClientIdOrLog(clientInfo, serviceId);
1743 if (clientId < 0) return;
1744
1745 clientInfo.onRegisterServiceFailed(clientId, errorCode);
1746 }
1747
1748 private ClientInfo getClientInfoOrLog(int serviceId) {
1749 final ClientInfo clientInfo = mIdToClientInfoMap.get(serviceId);
1750 if (clientInfo == null) {
1751 Log.e(TAG, String.format("Callback for service %d has no client", serviceId));
1752 }
1753 return clientInfo;
1754 }
1755
1756 private int getClientIdOrLog(@NonNull ClientInfo info, int serviceId) {
1757 final int clientId = info.getClientId(serviceId);
1758 if (clientId < 0) {
1759 Log.e(TAG, String.format("Client ID not found for service %d", serviceId));
1760 }
1761 return clientId;
1762 }
1763 }
1764
Paul Hu2e0a88c2023-03-09 16:05:01 +08001765 private static class ConnectorArgs {
1766 @NonNull public final NsdServiceConnector connector;
1767 @NonNull public final INsdManagerCallback callback;
1768 public final boolean useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001769 public final int uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001770
1771 ConnectorArgs(@NonNull NsdServiceConnector connector, @NonNull INsdManagerCallback callback,
Paul Hub2e67d32023-04-18 05:50:14 +00001772 boolean useJavaBackend, int uid) {
Paul Hu2e0a88c2023-03-09 16:05:01 +08001773 this.connector = connector;
1774 this.callback = callback;
1775 this.useJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00001776 this.uid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08001777 }
1778 }
1779
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001780 @Override
Paul Hu2e0a88c2023-03-09 16:05:01 +08001781 public INsdServiceConnector connect(INsdManagerCallback cb, boolean useJavaBackend) {
Hugo Benichi803a2f02017-04-24 11:35:06 +09001782 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET, "NsdService");
Paul Hu2e0a88c2023-03-09 16:05:01 +08001783 if (DBG) Log.d(TAG, "New client connect. useJavaBackend=" + useJavaBackend);
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001784 final INsdServiceConnector connector = new NsdServiceConnector();
Paul Hub2e67d32023-04-18 05:50:14 +00001785 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(NsdManager.REGISTER_CLIENT,
1786 new ConnectorArgs((NsdServiceConnector) connector, cb, useJavaBackend,
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09001787 mDeps.getCallingUid())));
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001788 return connector;
Irfan Sheriff75006652012-04-17 23:15:29 -07001789 }
1790
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001791 private static class ListenerArgs {
1792 public final NsdServiceConnector connector;
1793 public final NsdServiceInfo serviceInfo;
1794 ListenerArgs(NsdServiceConnector connector, NsdServiceInfo serviceInfo) {
1795 this.connector = connector;
1796 this.serviceInfo = serviceInfo;
1797 }
1798 }
1799
1800 private class NsdServiceConnector extends INsdServiceConnector.Stub
1801 implements IBinder.DeathRecipient {
1802 @Override
1803 public void registerService(int listenerKey, NsdServiceInfo serviceInfo) {
1804 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1805 NsdManager.REGISTER_SERVICE, 0, listenerKey,
1806 new ListenerArgs(this, serviceInfo)));
1807 }
1808
1809 @Override
1810 public void unregisterService(int listenerKey) {
1811 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1812 NsdManager.UNREGISTER_SERVICE, 0, listenerKey,
1813 new ListenerArgs(this, null)));
1814 }
1815
1816 @Override
1817 public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
1818 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1819 NsdManager.DISCOVER_SERVICES, 0, listenerKey,
1820 new ListenerArgs(this, serviceInfo)));
1821 }
1822
1823 @Override
1824 public void stopDiscovery(int listenerKey) {
1825 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1826 NsdManager.STOP_DISCOVERY, 0, listenerKey, new ListenerArgs(this, null)));
1827 }
1828
1829 @Override
1830 public void resolveService(int listenerKey, NsdServiceInfo serviceInfo) {
1831 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1832 NsdManager.RESOLVE_SERVICE, 0, listenerKey,
1833 new ListenerArgs(this, serviceInfo)));
1834 }
1835
1836 @Override
Paul Hub58deb72022-12-26 09:24:42 +00001837 public void stopResolution(int listenerKey) {
1838 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1839 NsdManager.STOP_RESOLUTION, 0, listenerKey, new ListenerArgs(this, null)));
1840 }
1841
1842 @Override
Paul Hu18aeccc2022-12-27 08:48:48 +00001843 public void registerServiceInfoCallback(int listenerKey, NsdServiceInfo serviceInfo) {
1844 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1845 NsdManager.REGISTER_SERVICE_CALLBACK, 0, listenerKey,
1846 new ListenerArgs(this, serviceInfo)));
1847 }
1848
1849 @Override
1850 public void unregisterServiceInfoCallback(int listenerKey) {
1851 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1852 NsdManager.UNREGISTER_SERVICE_CALLBACK, 0, listenerKey,
1853 new ListenerArgs(this, null)));
1854 }
1855
1856 @Override
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09001857 public void startDaemon() {
1858 mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
1859 NsdManager.DAEMON_STARTUP, new ListenerArgs(this, null)));
1860 }
1861
1862 @Override
1863 public void binderDied() {
1864 mNsdStateMachine.sendMessage(
1865 mNsdStateMachine.obtainMessage(NsdManager.UNREGISTER_CLIENT, this));
1866 }
Irfan Sheriff75006652012-04-17 23:15:29 -07001867 }
1868
Hugo Benichi912db992017-04-24 16:41:03 +09001869 private void sendNsdStateChangeBroadcast(boolean isEnabled) {
Irfan Sheriff52fc83a2012-04-19 10:26:34 -07001870 final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
Irfan Sheriff75006652012-04-17 23:15:29 -07001871 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Hugo Benichi912db992017-04-24 16:41:03 +09001872 int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
1873 intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
Dianne Hackborn692107e2012-08-29 18:32:08 -07001874 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
Irfan Sheriff75006652012-04-17 23:15:29 -07001875 }
1876
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001877 private int getUniqueId() {
1878 if (++mUniqueId == INVALID_ID) return ++mUniqueId;
1879 return mUniqueId;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001880 }
1881
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001882 private boolean registerService(int regId, NsdServiceInfo service) {
Hugo Benichi6d706442017-04-24 16:19:58 +09001883 if (DBG) {
paulhub2225702021-11-17 09:35:33 +08001884 Log.d(TAG, "registerService: " + regId + " " + service);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001885 }
Hugo Benichi6d706442017-04-24 16:19:58 +09001886 String name = service.getServiceName();
1887 String type = service.getServiceType();
1888 int port = service.getPort();
1889 byte[] textRecord = service.getTxtRecord();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001890 final int registerInterface = getNetworkInterfaceIndex(service);
1891 if (service.getNetwork() != null && registerInterface == IFACE_IDX_ANY) {
Paul Hu360a8e92022-04-26 11:14:14 +08001892 Log.e(TAG, "Interface to register service on not found");
1893 return false;
1894 }
1895 return mMDnsManager.registerService(regId, name, type, port, textRecord, registerInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001896 }
1897
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001898 private boolean unregisterService(int regId) {
paulhu2b9ed952022-02-10 21:58:32 +08001899 return mMDnsManager.stopOperation(regId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001900 }
1901
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001902 private boolean discoverServices(int discoveryId, NsdServiceInfo serviceInfo) {
paulhu2b9ed952022-02-10 21:58:32 +08001903 final String type = serviceInfo.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001904 final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
1905 if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001906 Log.e(TAG, "Interface to discover service on not found");
1907 return false;
1908 }
paulhu2b9ed952022-02-10 21:58:32 +08001909 return mMDnsManager.discover(discoveryId, type, discoverInterface);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001910 }
1911
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001912 private boolean stopServiceDiscovery(int discoveryId) {
paulhu2b9ed952022-02-10 21:58:32 +08001913 return mMDnsManager.stopOperation(discoveryId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001914 }
1915
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07001916 private boolean resolveService(int resolveId, NsdServiceInfo service) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001917 final String name = service.getServiceName();
1918 final String type = service.getServiceType();
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001919 final int resolveInterface = getNetworkInterfaceIndex(service);
1920 if (service.getNetwork() != null && resolveInterface == IFACE_IDX_ANY) {
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001921 Log.e(TAG, "Interface to resolve service on not found");
1922 return false;
1923 }
paulhu2b9ed952022-02-10 21:58:32 +08001924 return mMDnsManager.resolve(resolveId, name, type, "local.", resolveInterface);
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001925 }
1926
1927 /**
1928 * Guess the interface to use to resolve or discover a service on a specific network.
1929 *
1930 * This is an imperfect guess, as for example the network may be gone or not yet fully
1931 * registered. This is fine as failing is correct if the network is gone, and a client
1932 * attempting to resolve/discover on a network not yet setup would have a bad time anyway; also
1933 * this is to support the legacy mdnsresponder implementation, which historically resolved
1934 * services on an unspecified network.
1935 */
Remi NGUYEN VAN1a8ee102022-05-30 12:42:24 +09001936 private int getNetworkInterfaceIndex(NsdServiceInfo serviceInfo) {
1937 final Network network = serviceInfo.getNetwork();
1938 if (network == null) {
1939 // Fallback to getInterfaceIndex if present (typically if the NsdServiceInfo was
1940 // provided by NsdService from discovery results, and the service was found on an
1941 // interface that has no app-usable Network).
1942 if (serviceInfo.getInterfaceIndex() != 0) {
1943 return serviceInfo.getInterfaceIndex();
1944 }
1945 return IFACE_IDX_ANY;
1946 }
Remi NGUYEN VAN23651302021-12-16 15:31:16 +09001947
1948 final ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
1949 if (cm == null) {
1950 Log.wtf(TAG, "No ConnectivityManager for resolveService");
1951 return IFACE_IDX_ANY;
1952 }
1953 final LinkProperties lp = cm.getLinkProperties(network);
1954 if (lp == null) return IFACE_IDX_ANY;
1955
1956 // Only resolve on non-stacked interfaces
1957 final NetworkInterface iface;
1958 try {
1959 iface = NetworkInterface.getByName(lp.getInterfaceName());
1960 } catch (SocketException e) {
1961 Log.e(TAG, "Error querying interface", e);
1962 return IFACE_IDX_ANY;
1963 }
1964
1965 if (iface == null) {
1966 Log.e(TAG, "Interface not found: " + lp.getInterfaceName());
1967 return IFACE_IDX_ANY;
1968 }
1969
1970 return iface.getIndex();
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001971 }
1972
1973 private boolean stopResolveService(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001974 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001975 }
1976
paulhu2b9ed952022-02-10 21:58:32 +08001977 private boolean getAddrInfo(int resolveId, String hostname, int interfaceIdx) {
1978 return mMDnsManager.getServiceAddress(resolveId, hostname, interfaceIdx);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07001979 }
1980
1981 private boolean stopGetAddrInfo(int resolveId) {
paulhu2b9ed952022-02-10 21:58:32 +08001982 return mMDnsManager.stopOperation(resolveId);
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001983 }
1984
1985 @Override
Paul Hub2e67d32023-04-18 05:50:14 +00001986 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1987 if (!PermissionUtils.checkDumpPermission(mContext, TAG, writer)) return;
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001988
Paul Hub2e67d32023-04-18 05:50:14 +00001989 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
1990 // Dump state machine logs
Irfan Sheriff75006652012-04-17 23:15:29 -07001991 mNsdStateMachine.dump(fd, pw, args);
Paul Hub2e67d32023-04-18 05:50:14 +00001992
1993 // Dump service and clients logs
1994 pw.println();
Paul Hu14667de2023-04-17 22:42:47 +08001995 pw.println("Logs:");
Paul Hub2e67d32023-04-18 05:50:14 +00001996 pw.increaseIndent();
1997 mServiceLogs.reverseDump(pw);
1998 pw.decreaseIndent();
Irfan Sheriff77ec5582012-03-22 17:01:39 -07001999 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002000
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002001 private abstract static class ClientRequest {
2002 private final int mGlobalId;
2003
2004 private ClientRequest(int globalId) {
2005 mGlobalId = globalId;
2006 }
2007 }
2008
2009 private static class LegacyClientRequest extends ClientRequest {
2010 private final int mRequestCode;
2011
2012 private LegacyClientRequest(int globalId, int requestCode) {
2013 super(globalId);
2014 mRequestCode = requestCode;
2015 }
2016 }
2017
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002018 private abstract static class JavaBackendClientRequest extends ClientRequest {
2019 @Nullable
2020 private final Network mRequestedNetwork;
2021
2022 private JavaBackendClientRequest(int globalId, @Nullable Network requestedNetwork) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002023 super(globalId);
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002024 mRequestedNetwork = requestedNetwork;
2025 }
2026
2027 @Nullable
2028 public Network getRequestedNetwork() {
2029 return mRequestedNetwork;
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002030 }
2031 }
2032
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002033 private static class AdvertiserClientRequest extends JavaBackendClientRequest {
2034 private AdvertiserClientRequest(int globalId, @Nullable Network requestedNetwork) {
2035 super(globalId, requestedNetwork);
2036 }
2037 }
2038
2039 private static class DiscoveryManagerRequest extends JavaBackendClientRequest {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002040 @NonNull
2041 private final MdnsListener mListener;
2042
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002043 private DiscoveryManagerRequest(int globalId, @NonNull MdnsListener listener,
2044 @Nullable Network requestedNetwork) {
2045 super(globalId, requestedNetwork);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002046 mListener = listener;
2047 }
2048 }
2049
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002050 /* Information tracked per client */
2051 private class ClientInfo {
2052
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002053 private static final int MAX_LIMIT = 10;
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002054 private final INsdManagerCallback mCb;
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002055 /* Remembers a resolved service until getaddrinfo completes */
Irfan Sheriffe4c42f42012-05-03 16:44:27 -07002056 private NsdServiceInfo mResolvedService;
2057
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002058 /* A map from client-side ID (listenerKey) to the request */
2059 private final SparseArray<ClientRequest> mClientRequests = new SparseArray<>();
Paul Hu23fa2022023-01-13 22:57:24 +08002060
Luke Huangf7277ed2021-07-12 21:15:10 +08002061 // The target SDK of this client < Build.VERSION_CODES.S
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002062 private boolean mIsPreSClient = false;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002063 private final int mUid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002064 // The flag of using java backend if the client's target SDK >= U
2065 private final boolean mUseJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002066 // Store client logs
2067 private final SharedLog mClientLogs;
Luke Huangf7277ed2021-07-12 21:15:10 +08002068
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002069 private ClientInfo(INsdManagerCallback cb, int uid, boolean useJavaBackend,
2070 SharedLog sharedLog) {
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002071 mCb = cb;
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002072 mUid = uid;
Paul Hu2e0a88c2023-03-09 16:05:01 +08002073 mUseJavaBackend = useJavaBackend;
Paul Hub2e67d32023-04-18 05:50:14 +00002074 mClientLogs = sharedLog;
2075 mClientLogs.log("New client. useJavaBackend=" + useJavaBackend);
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002076 }
Irfan Sheriff75006652012-04-17 23:15:29 -07002077
2078 @Override
2079 public String toString() {
Jeff Sharkey63465382020-10-17 21:20:13 -06002080 StringBuilder sb = new StringBuilder();
Irfan Sheriff75006652012-04-17 23:15:29 -07002081 sb.append("mResolvedService ").append(mResolvedService).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002082 sb.append("mIsLegacy ").append(mIsPreSClient).append("\n");
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002083 sb.append("mUseJavaBackend ").append(mUseJavaBackend).append("\n");
2084 sb.append("mUid ").append(mUid).append("\n");
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002085 for (int i = 0; i < mClientRequests.size(); i++) {
2086 int clientID = mClientRequests.keyAt(i);
2087 sb.append("clientId ")
2088 .append(clientID)
2089 .append(" mDnsId ").append(mClientRequests.valueAt(i).mGlobalId)
2090 .append(" type ").append(
2091 mClientRequests.valueAt(i).getClass().getSimpleName())
2092 .append("\n");
Irfan Sheriff75006652012-04-17 23:15:29 -07002093 }
2094 return sb.toString();
2095 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002096
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002097 private boolean isPreSClient() {
2098 return mIsPreSClient;
Luke Huangf7277ed2021-07-12 21:15:10 +08002099 }
2100
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002101 private void setPreSClient() {
2102 mIsPreSClient = true;
Luke Huangf7277ed2021-07-12 21:15:10 +08002103 }
2104
Paul Hue4f5f252023-02-16 21:13:47 +08002105 private void unregisterMdnsListenerFromRequest(ClientRequest request) {
2106 final MdnsListener listener =
2107 ((DiscoveryManagerRequest) request).mListener;
2108 mMdnsDiscoveryManager.unregisterListener(
2109 listener.getListenedServiceType(), listener);
2110 }
2111
Dave Plattfeff2af2014-03-07 14:48:22 -08002112 // Remove any pending requests from the global map when we get rid of a client,
2113 // and send cancellations to the daemon.
2114 private void expungeAllRequests() {
Paul Hub2e67d32023-04-18 05:50:14 +00002115 mClientLogs.log("Client unregistered. expungeAllRequests!");
Hugo Benichid2552ae2017-04-11 14:42:47 +09002116 // TODO: to keep handler responsive, do not clean all requests for that client at once.
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002117 for (int i = 0; i < mClientRequests.size(); i++) {
2118 final int clientId = mClientRequests.keyAt(i);
2119 final ClientRequest request = mClientRequests.valueAt(i);
2120 final int globalId = request.mGlobalId;
Dave Plattfeff2af2014-03-07 14:48:22 -08002121 mIdToClientInfoMap.remove(globalId);
paulhub2225702021-11-17 09:35:33 +08002122 if (DBG) {
2123 Log.d(TAG, "Terminating client-ID " + clientId
2124 + " global-ID " + globalId + " type " + mClientRequests.get(clientId));
2125 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002126
2127 if (request instanceof DiscoveryManagerRequest) {
Paul Hue4f5f252023-02-16 21:13:47 +08002128 unregisterMdnsListenerFromRequest(request);
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002129 continue;
2130 }
2131
2132 if (request instanceof AdvertiserClientRequest) {
2133 mAdvertiser.removeService(globalId);
2134 continue;
2135 }
2136
2137 if (!(request instanceof LegacyClientRequest)) {
2138 throw new IllegalStateException("Unknown request type: " + request.getClass());
2139 }
2140
2141 switch (((LegacyClientRequest) request).mRequestCode) {
Dave Plattfeff2af2014-03-07 14:48:22 -08002142 case NsdManager.DISCOVER_SERVICES:
2143 stopServiceDiscovery(globalId);
2144 break;
2145 case NsdManager.RESOLVE_SERVICE:
2146 stopResolveService(globalId);
2147 break;
2148 case NsdManager.REGISTER_SERVICE:
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002149 unregisterService(globalId);
Dave Plattfeff2af2014-03-07 14:48:22 -08002150 break;
2151 default:
2152 break;
2153 }
2154 }
Dave Plattfeff2af2014-03-07 14:48:22 -08002155 mClientRequests.clear();
Remi NGUYEN VANa8efbe02023-05-26 11:43:20 +09002156 updateMulticastLock();
2157 }
2158
2159 /**
2160 * Returns true if this client has any Java backend request that requests one of the given
2161 * networks.
2162 */
2163 boolean hasAnyJavaBackendRequestForNetworks(@NonNull ArraySet<Network> networks) {
2164 for (int i = 0; i < mClientRequests.size(); i++) {
2165 final ClientRequest req = mClientRequests.valueAt(i);
2166 if (!(req instanceof JavaBackendClientRequest)) {
2167 continue;
2168 }
2169 final Network reqNetwork = ((JavaBackendClientRequest) mClientRequests.valueAt(i))
2170 .getRequestedNetwork();
2171 if (MdnsUtils.isAnyNetworkMatched(reqNetwork, networks)) {
2172 return true;
2173 }
2174 }
2175 return false;
Dave Plattfeff2af2014-03-07 14:48:22 -08002176 }
2177
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002178 // mClientRequests is a sparse array of listener id -> ClientRequest. For a given
2179 // mDnsClient id, return the corresponding listener id. mDnsClient id is also called a
2180 // global id.
Christopher Lane74411222014-04-25 18:39:07 -07002181 private int getClientId(final int globalId) {
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002182 for (int i = 0; i < mClientRequests.size(); i++) {
2183 if (mClientRequests.valueAt(i).mGlobalId == globalId) {
2184 return mClientRequests.keyAt(i);
2185 }
Christopher Lane74411222014-04-25 18:39:07 -07002186 }
Remi NGUYEN VAN8f453b92023-01-18 17:44:36 +09002187 return -1;
Christopher Lane74411222014-04-25 18:39:07 -07002188 }
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002189
Paul Hub2e67d32023-04-18 05:50:14 +00002190 private void log(String message) {
2191 mClientLogs.log(message);
2192 }
2193
Remi NGUYEN VAN62eb76e2021-09-09 17:39:05 +09002194 void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info) {
2195 try {
2196 mCb.onDiscoverServicesStarted(listenerKey, info);
2197 } catch (RemoteException e) {
2198 Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
2199 }
2200 }
2201
2202 void onDiscoverServicesFailed(int listenerKey, int error) {
2203 try {
2204 mCb.onDiscoverServicesFailed(listenerKey, error);
2205 } catch (RemoteException e) {
2206 Log.e(TAG, "Error calling onDiscoverServicesFailed", e);
2207 }
2208 }
2209
2210 void onServiceFound(int listenerKey, NsdServiceInfo info) {
2211 try {
2212 mCb.onServiceFound(listenerKey, info);
2213 } catch (RemoteException e) {
2214 Log.e(TAG, "Error calling onServiceFound(", e);
2215 }
2216 }
2217
2218 void onServiceLost(int listenerKey, NsdServiceInfo info) {
2219 try {
2220 mCb.onServiceLost(listenerKey, info);
2221 } catch (RemoteException e) {
2222 Log.e(TAG, "Error calling onServiceLost(", e);
2223 }
2224 }
2225
2226 void onStopDiscoveryFailed(int listenerKey, int error) {
2227 try {
2228 mCb.onStopDiscoveryFailed(listenerKey, error);
2229 } catch (RemoteException e) {
2230 Log.e(TAG, "Error calling onStopDiscoveryFailed", e);
2231 }
2232 }
2233
2234 void onStopDiscoverySucceeded(int listenerKey) {
2235 try {
2236 mCb.onStopDiscoverySucceeded(listenerKey);
2237 } catch (RemoteException e) {
2238 Log.e(TAG, "Error calling onStopDiscoverySucceeded", e);
2239 }
2240 }
2241
2242 void onRegisterServiceFailed(int listenerKey, int error) {
2243 try {
2244 mCb.onRegisterServiceFailed(listenerKey, error);
2245 } catch (RemoteException e) {
2246 Log.e(TAG, "Error calling onRegisterServiceFailed", e);
2247 }
2248 }
2249
2250 void onRegisterServiceSucceeded(int listenerKey, NsdServiceInfo info) {
2251 try {
2252 mCb.onRegisterServiceSucceeded(listenerKey, info);
2253 } catch (RemoteException e) {
2254 Log.e(TAG, "Error calling onRegisterServiceSucceeded", e);
2255 }
2256 }
2257
2258 void onUnregisterServiceFailed(int listenerKey, int error) {
2259 try {
2260 mCb.onUnregisterServiceFailed(listenerKey, error);
2261 } catch (RemoteException e) {
2262 Log.e(TAG, "Error calling onUnregisterServiceFailed", e);
2263 }
2264 }
2265
2266 void onUnregisterServiceSucceeded(int listenerKey) {
2267 try {
2268 mCb.onUnregisterServiceSucceeded(listenerKey);
2269 } catch (RemoteException e) {
2270 Log.e(TAG, "Error calling onUnregisterServiceSucceeded", e);
2271 }
2272 }
2273
2274 void onResolveServiceFailed(int listenerKey, int error) {
2275 try {
2276 mCb.onResolveServiceFailed(listenerKey, error);
2277 } catch (RemoteException e) {
2278 Log.e(TAG, "Error calling onResolveServiceFailed", e);
2279 }
2280 }
2281
2282 void onResolveServiceSucceeded(int listenerKey, NsdServiceInfo info) {
2283 try {
2284 mCb.onResolveServiceSucceeded(listenerKey, info);
2285 } catch (RemoteException e) {
2286 Log.e(TAG, "Error calling onResolveServiceSucceeded", e);
2287 }
2288 }
Paul Hub58deb72022-12-26 09:24:42 +00002289
2290 void onStopResolutionFailed(int listenerKey, int error) {
2291 try {
2292 mCb.onStopResolutionFailed(listenerKey, error);
2293 } catch (RemoteException e) {
2294 Log.e(TAG, "Error calling onStopResolutionFailed", e);
2295 }
2296 }
2297
2298 void onStopResolutionSucceeded(int listenerKey) {
2299 try {
2300 mCb.onStopResolutionSucceeded(listenerKey);
2301 } catch (RemoteException e) {
2302 Log.e(TAG, "Error calling onStopResolutionSucceeded", e);
2303 }
2304 }
Paul Hu18aeccc2022-12-27 08:48:48 +00002305
2306 void onServiceInfoCallbackRegistrationFailed(int listenerKey, int error) {
2307 try {
2308 mCb.onServiceInfoCallbackRegistrationFailed(listenerKey, error);
2309 } catch (RemoteException e) {
2310 Log.e(TAG, "Error calling onServiceInfoCallbackRegistrationFailed", e);
2311 }
2312 }
2313
2314 void onServiceUpdated(int listenerKey, NsdServiceInfo info) {
2315 try {
2316 mCb.onServiceUpdated(listenerKey, info);
2317 } catch (RemoteException e) {
2318 Log.e(TAG, "Error calling onServiceUpdated", e);
2319 }
2320 }
2321
2322 void onServiceUpdatedLost(int listenerKey) {
2323 try {
2324 mCb.onServiceUpdatedLost(listenerKey);
2325 } catch (RemoteException e) {
2326 Log.e(TAG, "Error calling onServiceUpdatedLost", e);
2327 }
2328 }
2329
2330 void onServiceInfoCallbackUnregistered(int listenerKey) {
2331 try {
2332 mCb.onServiceInfoCallbackUnregistered(listenerKey);
2333 } catch (RemoteException e) {
2334 Log.e(TAG, "Error calling onServiceInfoCallbackUnregistered", e);
2335 }
2336 }
Irfan Sheriffe8de2462012-04-11 14:52:19 -07002337 }
Irfan Sheriff77ec5582012-03-22 17:01:39 -07002338}