1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
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 
17 package com.android.server.connectivity;
18 
19 import static android.net.ConnectivityManager.NETID_UNSET;
20 
21 import android.annotation.NonNull;
22 import android.annotation.Nullable;
23 import android.app.PendingIntent;
24 import android.content.ComponentName;
25 import android.content.Context;
26 import android.content.Intent;
27 import android.content.res.Resources;
28 import android.net.NetworkCapabilities;
29 import android.os.SystemClock;
30 import android.os.UserHandle;
31 import android.text.TextUtils;
32 import android.text.format.DateUtils;
33 import android.util.Log;
34 import android.util.SparseArray;
35 import android.util.SparseBooleanArray;
36 import android.util.SparseIntArray;
37 
38 import com.android.connectivity.resources.R;
39 import com.android.internal.annotations.VisibleForTesting;
40 import com.android.internal.util.MessageUtils;
41 import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
42 
43 import java.util.Arrays;
44 import java.util.HashMap;
45 
46 /**
47  * Class that monitors default network linger events and possibly notifies the user of network
48  * switches.
49  *
50  * This class is not thread-safe and all its methods must be called on the ConnectivityService
51  * handler thread.
52  */
53 public class LingerMonitor {
54 
55     private static final boolean DBG = true;
56     private static final boolean VDBG = false;
57     private static final String TAG = LingerMonitor.class.getSimpleName();
58 
59     public static final int DEFAULT_NOTIFICATION_DAILY_LIMIT = 3;
60     public static final long DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS = DateUtils.MINUTE_IN_MILLIS;
61 
62     private static final HashMap<String, Integer> TRANSPORT_NAMES = makeTransportToNameMap();
63     @VisibleForTesting
64     public static final Intent CELLULAR_SETTINGS = new Intent().setComponent(new ComponentName(
65             "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
66 
67     @VisibleForTesting
68     public static final int NOTIFY_TYPE_NONE         = 0;
69     public static final int NOTIFY_TYPE_NOTIFICATION = 1;
70     public static final int NOTIFY_TYPE_TOAST        = 2;
71 
72     private static SparseArray<String> sNotifyTypeNames = MessageUtils.findMessageNames(
73             new Class[] { LingerMonitor.class }, new String[]{ "NOTIFY_TYPE_" });
74 
75     private final Context mContext;
76     final Resources mResources;
77     private final NetworkNotificationManager mNotifier;
78     private final int mDailyLimit;
79     private final long mRateLimitMillis;
80 
81     private long mFirstNotificationMillis;
82     private long mLastNotificationMillis;
83     private int mNotificationCounter;
84 
85     /** Current notifications. Maps the netId we switched away from to the netId we switched to. */
86     private final SparseIntArray mNotifications = new SparseIntArray();
87 
88     /** Whether we ever notified that we switched away from a particular network. */
89     private final SparseBooleanArray mEverNotified = new SparseBooleanArray();
90 
LingerMonitor(Context context, NetworkNotificationManager notifier, int dailyLimit, long rateLimitMillis)91     public LingerMonitor(Context context, NetworkNotificationManager notifier,
92             int dailyLimit, long rateLimitMillis) {
93         mContext = context;
94         mResources = new ConnectivityResources(mContext).get();
95         mNotifier = notifier;
96         mDailyLimit = dailyLimit;
97         mRateLimitMillis = rateLimitMillis;
98         // Ensure that (now - mLastNotificationMillis) >= rateLimitMillis at first
99         mLastNotificationMillis = -rateLimitMillis;
100     }
101 
makeTransportToNameMap()102     private static HashMap<String, Integer> makeTransportToNameMap() {
103         SparseArray<String> numberToName = MessageUtils.findMessageNames(
104             new Class[] { NetworkCapabilities.class }, new String[]{ "TRANSPORT_" });
105         HashMap<String, Integer> nameToNumber = new HashMap<>();
106         for (int i = 0; i < numberToName.size(); i++) {
107             // MessageUtils will fail to initialize if there are duplicate constant values, so there
108             // are no duplicates here.
109             nameToNumber.put(numberToName.valueAt(i), numberToName.keyAt(i));
110         }
111         return nameToNumber;
112     }
113 
hasTransport(NetworkAgentInfo nai, int transport)114     private static boolean hasTransport(NetworkAgentInfo nai, int transport) {
115         return nai.networkCapabilities.hasTransport(transport);
116     }
117 
getNotificationSource(NetworkAgentInfo toNai)118     private int getNotificationSource(NetworkAgentInfo toNai) {
119         for (int i = 0; i < mNotifications.size(); i++) {
120             if (mNotifications.valueAt(i) == toNai.network.getNetId()) {
121                 return mNotifications.keyAt(i);
122             }
123         }
124         return NETID_UNSET;
125     }
126 
everNotified(NetworkAgentInfo nai)127     private boolean everNotified(NetworkAgentInfo nai) {
128         return mEverNotified.get(nai.network.getNetId(), false);
129     }
130 
131     @VisibleForTesting
isNotificationEnabled(NetworkAgentInfo fromNai, NetworkAgentInfo toNai)132     public boolean isNotificationEnabled(NetworkAgentInfo fromNai, NetworkAgentInfo toNai) {
133         // TODO: Evaluate moving to CarrierConfigManager.
134         String[] notifySwitches = mResources.getStringArray(R.array.config_networkNotifySwitches);
135 
136         if (VDBG) {
137             Log.d(TAG, "Notify on network switches: " + Arrays.toString(notifySwitches));
138         }
139 
140         for (String notifySwitch : notifySwitches) {
141             if (TextUtils.isEmpty(notifySwitch)) continue;
142             String[] transports = notifySwitch.split("-", 2);
143             if (transports.length != 2) {
144                 Log.e(TAG, "Invalid network switch notification configuration: " + notifySwitch);
145                 continue;
146             }
147             int fromTransport = TRANSPORT_NAMES.get("TRANSPORT_" + transports[0]);
148             int toTransport = TRANSPORT_NAMES.get("TRANSPORT_" + transports[1]);
149             if (hasTransport(fromNai, fromTransport) && hasTransport(toNai, toTransport)) {
150                 return true;
151             }
152         }
153 
154         return false;
155     }
156 
showNotification(NetworkAgentInfo fromNai, NetworkAgentInfo toNai)157     private void showNotification(NetworkAgentInfo fromNai, NetworkAgentInfo toNai) {
158         mNotifier.showNotification(fromNai.network.getNetId(), NotificationType.NETWORK_SWITCH,
159                 fromNai, toNai, createNotificationIntent(), true);
160     }
161 
162     @VisibleForTesting
createNotificationIntent()163     protected PendingIntent createNotificationIntent() {
164         return PendingIntent.getActivity(
165                 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
166                 0 /* requestCode */,
167                 CELLULAR_SETTINGS,
168                 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
169     }
170 
171     // Removes any notification that was put up as a result of switching to nai.
maybeStopNotifying(NetworkAgentInfo nai)172     private void maybeStopNotifying(NetworkAgentInfo nai) {
173         int fromNetId = getNotificationSource(nai);
174         if (fromNetId != NETID_UNSET) {
175             mNotifications.delete(fromNetId);
176             mNotifier.clearNotification(fromNetId);
177             // Toasts can't be deleted.
178         }
179     }
180 
181     // Notify the user of a network switch using a notification or a toast.
notify(NetworkAgentInfo fromNai, NetworkAgentInfo toNai, boolean forceToast)182     private void notify(NetworkAgentInfo fromNai, NetworkAgentInfo toNai, boolean forceToast) {
183         int notifyType = mResources.getInteger(R.integer.config_networkNotifySwitchType);
184         if (notifyType == NOTIFY_TYPE_NOTIFICATION && forceToast) {
185             notifyType = NOTIFY_TYPE_TOAST;
186         }
187 
188         if (VDBG) {
189             Log.d(TAG, "Notify type: " + sNotifyTypeNames.get(notifyType, "" + notifyType));
190         }
191 
192         switch (notifyType) {
193             case NOTIFY_TYPE_NONE:
194                 return;
195             case NOTIFY_TYPE_NOTIFICATION:
196                 showNotification(fromNai, toNai);
197                 break;
198             case NOTIFY_TYPE_TOAST:
199                 mNotifier.showToast(fromNai, toNai);
200                 break;
201             default:
202                 Log.e(TAG, "Unknown notify type " + notifyType);
203                 return;
204         }
205 
206         if (DBG) {
207             Log.d(TAG, "Notifying switch from=" + fromNai.toShortString()
208                     + " to=" + toNai.toShortString()
209                     + " type=" + sNotifyTypeNames.get(notifyType, "unknown(" + notifyType + ")"));
210         }
211 
212         mNotifications.put(fromNai.network.getNetId(), toNai.network.getNetId());
213         mEverNotified.put(fromNai.network.getNetId(), true);
214     }
215 
216     /**
217      * Put up or dismiss a notification or toast for of a change in the default network if needed.
218      *
219      * Putting up a notification when switching from no network to some network is not supported
220      * and as such this method can't be called with a null |fromNai|. It can be called with a
221      * null |toNai| if there isn't a default network any more.
222      *
223      * @param fromNai switching from this NAI
224      * @param toNai switching to this NAI
225      */
226     // The default network changed from fromNai to toNai due to a change in score.
noteLingerDefaultNetwork(@onNull final NetworkAgentInfo fromNai, @Nullable final NetworkAgentInfo toNai)227     public void noteLingerDefaultNetwork(@NonNull final NetworkAgentInfo fromNai,
228             @Nullable final NetworkAgentInfo toNai) {
229         if (VDBG) {
230             Log.d(TAG, "noteLingerDefaultNetwork from=" + fromNai.toShortString()
231                     + " firstValidated=" + fromNai.getFirstValidationTime()
232                     + " lastValidated=" + fromNai.getCurrentValidationTime()
233                     + " to=" + toNai.toShortString());
234         }
235 
236         // If we are currently notifying the user because the device switched to fromNai, now that
237         // we are switching away from it we should remove the notification. This includes the case
238         // where we switch back to toNai because its score improved again (e.g., because it regained
239         // Internet access).
240         maybeStopNotifying(fromNai);
241 
242         // If the network was simply lost (either because it disconnected or because it stopped
243         // being the default with no replacement), then don't show a notification.
244         if (null == toNai) return;
245 
246         // If this network never validated, don't notify. Otherwise, we could do things like:
247         //
248         // 1. Unvalidated wifi connects.
249         // 2. Unvalidated mobile data connects.
250         // 3. Cell validates, and we show a notification.
251         // or:
252         // 1. User connects to wireless printer.
253         // 2. User turns on cellular data.
254         // 3. We show a notification.
255         if (!fromNai.everValidated()) return;
256 
257         // If this network is a captive portal, don't notify. This cannot happen on initial connect
258         // to a captive portal, because the everValidated check above will fail. However, it can
259         // happen if the captive portal reasserts itself (e.g., because its timeout fires). In that
260         // case, as soon as the captive portal reasserts itself, we'll show a sign-in notification.
261         // We don't want to overwrite that notification with this one; the user has already been
262         // notified, and of the two, the captive portal notification is the more useful one because
263         // it allows the user to sign in to the captive portal. In this case, display a toast
264         // in addition to the captive portal notification.
265         //
266         // Note that if the network we switch to is already up when the captive portal reappears,
267         // this won't work because NetworkMonitor tells ConnectivityService that the network is
268         // unvalidated (causing a switch) before asking it to show the sign in notification. In this
269         // case, the toast won't show and we'll only display the sign in notification. This is the
270         // best we can do at this time.
271         boolean forceToast = fromNai.networkCapabilities.hasCapability(
272                 NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL);
273 
274         // Only show the notification once, in order to avoid irritating the user every time.
275         // TODO: should we do this?
276         if (everNotified(fromNai)) {
277             if (VDBG) {
278                 Log.d(TAG, "Not notifying handover from " + fromNai.toShortString()
279                         + ", already notified");
280             }
281             return;
282         }
283 
284         // Only show the notification if we switched away because a network became unvalidated, not
285         // because its score changed.
286         // TODO: instead of just skipping notification, keep a note of it, and show it if it becomes
287         // unvalidated.
288         if (fromNai.isValidated()) return;
289 
290         if (!isNotificationEnabled(fromNai, toNai)) return;
291 
292         final long now = SystemClock.elapsedRealtime();
293         if (isRateLimited(now) || isAboveDailyLimit(now)) return;
294 
295         notify(fromNai, toNai, forceToast);
296     }
297 
noteDisconnect(NetworkAgentInfo nai)298     public void noteDisconnect(NetworkAgentInfo nai) {
299         mNotifications.delete(nai.network.getNetId());
300         mEverNotified.delete(nai.network.getNetId());
301         maybeStopNotifying(nai);
302         // No need to cancel notifications on nai: NetworkMonitor does that on disconnect.
303     }
304 
isRateLimited(long now)305     private boolean isRateLimited(long now) {
306         final long millisSinceLast = now - mLastNotificationMillis;
307         if (millisSinceLast < mRateLimitMillis) {
308             return true;
309         }
310         mLastNotificationMillis = now;
311         return false;
312     }
313 
isAboveDailyLimit(long now)314     private boolean isAboveDailyLimit(long now) {
315         if (mFirstNotificationMillis == 0) {
316             mFirstNotificationMillis = now;
317         }
318         final long millisSinceFirst = now - mFirstNotificationMillis;
319         if (millisSinceFirst > DateUtils.DAY_IN_MILLIS) {
320             mNotificationCounter = 0;
321             mFirstNotificationMillis = 0;
322         }
323         if (mNotificationCounter >= mDailyLimit) {
324             return true;
325         }
326         mNotificationCounter++;
327         return false;
328     }
329 }
330