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