blob: 0cffb15b3758036a4cc427b50bacaf8c252684b6 [file] [log] [blame]
San Mehat873f2142010-01-14 10:25:07 -08001/*
2 * Copyright (C) 2007 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
17package com.android.server;
18
Jeff Sharkey47eb1022011-08-25 17:48:52 -070019import static android.Manifest.permission.DUMP;
Jeff Sharkey350083e2011-06-29 10:45:16 -070020import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070021import static android.net.NetworkStats.IFACE_ALL;
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -070022import static android.net.NetworkStats.SET_DEFAULT;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070023import static android.net.NetworkStats.TAG_NONE;
24import static android.net.NetworkStats.UID_ALL;
Jeff Sharkey350083e2011-06-29 10:45:16 -070025import static android.provider.Settings.Secure.NETSTATS_ENABLED;
Jeff Sharkeya63ba592011-07-19 23:47:12 -070026import static com.android.server.NetworkManagementSocketTagger.PROP_QTAGUID_ENABLED;
27import static com.android.server.NetworkManagementSocketTagger.kernelToTag;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070028
San Mehat873f2142010-01-14 10:25:07 -080029import android.content.Context;
San Mehat873f2142010-01-14 10:25:07 -080030import android.content.pm.PackageManager;
San Mehat4d02d002010-01-22 16:07:46 -080031import android.net.INetworkManagementEventObserver;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -070032import android.net.InterfaceConfiguration;
Robert Greenwalted126402011-01-28 15:34:55 -080033import android.net.LinkAddress;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -070034import android.net.NetworkStats;
Robert Greenwalted126402011-01-28 15:34:55 -080035import android.net.NetworkUtils;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -070036import android.net.RouteInfo;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080037import android.net.wifi.WifiConfiguration;
38import android.net.wifi.WifiConfiguration.KeyMgmt;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -070039import android.os.Binder;
San Mehat873f2142010-01-14 10:25:07 -080040import android.os.INetworkManagementService;
Jeff Sharkey9a13f362011-04-26 16:25:36 -070041import android.os.SystemClock;
Marco Nelissen62dbb222010-02-18 10:56:30 -080042import android.os.SystemProperties;
Jeff Sharkey350083e2011-06-29 10:45:16 -070043import android.provider.Settings;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080044import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080045import android.util.Slog;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -070046import android.util.SparseBooleanArray;
San Mehat873f2142010-01-14 10:25:07 -080047
Jeff Sharkey4414cea2011-06-24 17:05:24 -070048import com.google.android.collect.Lists;
49import com.google.android.collect.Maps;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -070050import com.google.android.collect.Sets;
Jeff Sharkey4414cea2011-06-24 17:05:24 -070051
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -070052import java.io.BufferedReader;
53import java.io.DataInputStream;
San Mehat873f2142010-01-14 10:25:07 -080054import java.io.File;
Jeff Sharkey47eb1022011-08-25 17:48:52 -070055import java.io.FileDescriptor;
Jeff Sharkey9a13f362011-04-26 16:25:36 -070056import java.io.FileInputStream;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070057import java.io.FileReader;
Jeff Sharkey9a13f362011-04-26 16:25:36 -070058import java.io.IOException;
Jeff Sharkey9a13f362011-04-26 16:25:36 -070059import java.io.InputStreamReader;
Jeff Sharkey47eb1022011-08-25 17:48:52 -070060import java.io.PrintWriter;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -070061import java.net.Inet4Address;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -070062import java.net.InetAddress;
63import java.util.ArrayList;
Jeff Sharkey4414cea2011-06-24 17:05:24 -070064import java.util.HashMap;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -070065import java.util.HashSet;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -070066import java.util.NoSuchElementException;
67import java.util.StringTokenizer;
Robert Greenwalte5c3afb2010-09-22 14:32:35 -070068import java.util.concurrent.CountDownLatch;
San Mehat873f2142010-01-14 10:25:07 -080069
Jeff Sharkey9a13f362011-04-26 16:25:36 -070070import libcore.io.IoUtils;
71
San Mehat873f2142010-01-14 10:25:07 -080072/**
73 * @hide
74 */
Jeff Sharkey8e9992a2011-08-23 18:37:23 -070075public class NetworkManagementService extends INetworkManagementService.Stub
76 implements Watchdog.Monitor {
Jeff Sharkeyeedcb952011-05-17 14:55:15 -070077 private static final String TAG = "NetworkManagementService";
Dianne Hackborncef65ee2010-09-30 18:27:22 -070078 private static final boolean DBG = false;
Kenny Root305bcbf2010-09-03 07:56:38 -070079 private static final String NETD_TAG = "NetdConnector";
80
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -070081 private static final int ADD = 1;
82 private static final int REMOVE = 2;
83
Jeff Sharkey4414cea2011-06-24 17:05:24 -070084 /** Path to {@code /proc/uid_stat}. */
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070085 @Deprecated
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -070086 private final File mStatsUid;
87 /** Path to {@code /proc/net/dev}. */
88 private final File mStatsIface;
Jeff Sharkey4414cea2011-06-24 17:05:24 -070089 /** Path to {@code /proc/net/xt_qtaguid/stats}. */
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -070090 private final File mStatsXtUid;
91 /** Path to {@code /proc/net/xt_qtaguid/iface_stat}. */
92 private final File mStatsXtIface;
Jeff Sharkey4414cea2011-06-24 17:05:24 -070093
Jeff Sharkey8e9992a2011-08-23 18:37:23 -070094 /**
95 * Name representing {@link #setGlobalAlert(long)} limit when delivered to
96 * {@link INetworkManagementEventObserver#limitReached(String, String)}.
97 */
98 public static final String LIMIT_GLOBAL_ALERT = "globalAlert";
99
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -0700100 /** {@link #mStatsXtUid} headers. */
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700101 private static final String KEY_IDX = "idx";
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700102 private static final String KEY_IFACE = "iface";
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700103 private static final String KEY_UID = "uid_tag_int";
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700104 private static final String KEY_COUNTER_SET = "cnt_set";
105 private static final String KEY_TAG_HEX = "acct_tag_hex";
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700106 private static final String KEY_RX_BYTES = "rx_bytes";
107 private static final String KEY_RX_PACKETS = "rx_packets";
108 private static final String KEY_TX_BYTES = "tx_bytes";
109 private static final String KEY_TX_PACKETS = "tx_packets";
Jeff Sharkeyeedcb952011-05-17 14:55:15 -0700110
San Mehat873f2142010-01-14 10:25:07 -0800111 class NetdResponseCode {
JP Abgrall12b933d2011-07-14 18:09:22 -0700112 /* Keep in sync with system/netd/ResponseCode.h */
San Mehat873f2142010-01-14 10:25:07 -0800113 public static final int InterfaceListResult = 110;
114 public static final int TetherInterfaceListResult = 111;
115 public static final int TetherDnsFwdTgtListResult = 112;
San Mehat72759df2010-01-19 13:50:37 -0800116 public static final int TtyListResult = 113;
San Mehat873f2142010-01-14 10:25:07 -0800117
118 public static final int TetherStatusResult = 210;
119 public static final int IpFwdStatusResult = 211;
San Mehated4fc8a2010-01-22 12:28:36 -0800120 public static final int InterfaceGetCfgResult = 213;
Robert Greenwalte3253922010-02-18 09:23:25 -0800121 public static final int SoftapStatusResult = 214;
San Mehat91cac642010-03-31 14:31:36 -0700122 public static final int InterfaceRxCounterResult = 216;
123 public static final int InterfaceTxCounterResult = 217;
124 public static final int InterfaceRxThrottleResult = 218;
125 public static final int InterfaceTxThrottleResult = 219;
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -0700126 public static final int QuotaCounterResult = 220;
127 public static final int TetheringStatsResult = 221;
Robert Greenwalte3253922010-02-18 09:23:25 -0800128
129 public static final int InterfaceChange = 600;
JP Abgrall12b933d2011-07-14 18:09:22 -0700130 public static final int BandwidthControl = 601;
San Mehat873f2142010-01-14 10:25:07 -0800131 }
132
133 /**
134 * Binder context for this service
135 */
136 private Context mContext;
137
138 /**
139 * connector object for communicating with netd
140 */
141 private NativeDaemonConnector mConnector;
142
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700143 private Thread mThread;
144 private final CountDownLatch mConnectedSignal = new CountDownLatch(1);
145
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700146 // TODO: replace with RemoteCallbackList
San Mehat4d02d002010-01-22 16:07:46 -0800147 private ArrayList<INetworkManagementEventObserver> mObservers;
148
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700149 private Object mQuotaLock = new Object();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700150 /** Set of interfaces with active quotas. */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700151 private HashSet<String> mActiveQuotaIfaces = Sets.newHashSet();
152 /** Set of interfaces with active alerts. */
153 private HashSet<String> mActiveAlertIfaces = Sets.newHashSet();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700154 /** Set of UIDs with active reject rules. */
155 private SparseBooleanArray mUidRejectOnQuota = new SparseBooleanArray();
156
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700157 private volatile boolean mBandwidthControlEnabled;
Jeff Sharkey350083e2011-06-29 10:45:16 -0700158
San Mehat873f2142010-01-14 10:25:07 -0800159 /**
160 * Constructs a new NetworkManagementService instance
161 *
162 * @param context Binder context for this service
163 */
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700164 private NetworkManagementService(Context context, File procRoot) {
San Mehat873f2142010-01-14 10:25:07 -0800165 mContext = context;
San Mehat4d02d002010-01-22 16:07:46 -0800166 mObservers = new ArrayList<INetworkManagementEventObserver>();
167
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -0700168 mStatsUid = new File(procRoot, "uid_stat");
169 mStatsIface = new File(procRoot, "net/dev");
170 mStatsXtUid = new File(procRoot, "net/xt_qtaguid/stats");
171 mStatsXtIface = new File(procRoot, "net/xt_qtaguid/iface_stat");
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700172
Marco Nelissen62dbb222010-02-18 10:56:30 -0800173 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
174 return;
175 }
176
San Mehat873f2142010-01-14 10:25:07 -0800177 mConnector = new NativeDaemonConnector(
Kenny Root305bcbf2010-09-03 07:56:38 -0700178 new NetdCallbackReceiver(), "netd", 10, NETD_TAG);
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700179 mThread = new Thread(mConnector, NETD_TAG);
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700180
181 // Add ourself to the Watchdog monitors.
182 Watchdog.getInstance().addMonitor(this);
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700183 }
184
185 public static NetworkManagementService create(Context context) throws InterruptedException {
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700186 NetworkManagementService service = new NetworkManagementService(
187 context, new File("/proc/"));
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700188 if (DBG) Slog.d(TAG, "Creating NetworkManagementService");
189 service.mThread.start();
190 if (DBG) Slog.d(TAG, "Awaiting socket connection");
191 service.mConnectedSignal.await();
192 if (DBG) Slog.d(TAG, "Connected");
193 return service;
San Mehat873f2142010-01-14 10:25:07 -0800194 }
195
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700196 // @VisibleForTesting
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -0700197 public static NetworkManagementService createForTest(
198 Context context, File procRoot, boolean bandwidthControlEnabled) {
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700199 // TODO: eventually connect with mock netd
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -0700200 final NetworkManagementService service = new NetworkManagementService(context, procRoot);
201 service.mBandwidthControlEnabled = bandwidthControlEnabled;
202 return service;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700203 }
204
Jeff Sharkey350083e2011-06-29 10:45:16 -0700205 public void systemReady() {
Jeff Sharkey350083e2011-06-29 10:45:16 -0700206 // only enable bandwidth control when support exists, and requested by
207 // system setting.
Jeff Sharkey350083e2011-06-29 10:45:16 -0700208 final boolean hasKernelSupport = new File("/proc/net/xt_qtaguid/ctrl").exists();
209 final boolean shouldEnable =
Jeff Sharkey05355c32011-08-09 14:44:19 -0700210 Settings.Secure.getInt(mContext.getContentResolver(), NETSTATS_ENABLED, 1) != 0;
Jeff Sharkey350083e2011-06-29 10:45:16 -0700211
Jeff Sharkey350083e2011-06-29 10:45:16 -0700212 if (hasKernelSupport && shouldEnable) {
213 Slog.d(TAG, "enabling bandwidth control");
214 try {
215 mConnector.doCommand("bandwidth enable");
216 mBandwidthControlEnabled = true;
217 } catch (NativeDaemonConnectorException e) {
218 Slog.e(TAG, "problem enabling bandwidth controls", e);
219 }
220 } else {
221 Slog.d(TAG, "not enabling bandwidth control");
222 }
Jeff Sharkey62a2c8f2011-07-13 15:24:02 -0700223
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700224 SystemProperties.set(PROP_QTAGUID_ENABLED, mBandwidthControlEnabled ? "1" : "0");
Jeff Sharkey350083e2011-06-29 10:45:16 -0700225 }
226
San Mehat4d02d002010-01-22 16:07:46 -0800227 public void registerObserver(INetworkManagementEventObserver obs) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800228 Slog.d(TAG, "Registering observer");
San Mehat4d02d002010-01-22 16:07:46 -0800229 mObservers.add(obs);
230 }
231
232 public void unregisterObserver(INetworkManagementEventObserver obs) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800233 Slog.d(TAG, "Unregistering observer");
San Mehat4d02d002010-01-22 16:07:46 -0800234 mObservers.remove(mObservers.indexOf(obs));
235 }
236
237 /**
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700238 * Notify our observers of an interface status change
San Mehat4d02d002010-01-22 16:07:46 -0800239 */
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700240 private void notifyInterfaceStatusChanged(String iface, boolean up) {
San Mehat4d02d002010-01-22 16:07:46 -0800241 for (INetworkManagementEventObserver obs : mObservers) {
242 try {
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700243 obs.interfaceStatusChanged(iface, up);
244 } catch (Exception ex) {
245 Slog.w(TAG, "Observer notifier failed", ex);
246 }
247 }
248 }
249
250 /**
Mike J. Chenf59c7d02011-06-23 15:33:15 -0700251 * Notify our observers of an interface link state change
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700252 * (typically, an Ethernet cable has been plugged-in or unplugged).
253 */
254 private void notifyInterfaceLinkStateChanged(String iface, boolean up) {
255 for (INetworkManagementEventObserver obs : mObservers) {
256 try {
257 obs.interfaceLinkStateChanged(iface, up);
San Mehat4d02d002010-01-22 16:07:46 -0800258 } catch (Exception ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800259 Slog.w(TAG, "Observer notifier failed", ex);
San Mehat4d02d002010-01-22 16:07:46 -0800260 }
261 }
262 }
263
264 /**
265 * Notify our observers of an interface addition.
266 */
267 private void notifyInterfaceAdded(String iface) {
268 for (INetworkManagementEventObserver obs : mObservers) {
269 try {
270 obs.interfaceAdded(iface);
271 } catch (Exception ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800272 Slog.w(TAG, "Observer notifier failed", ex);
San Mehat4d02d002010-01-22 16:07:46 -0800273 }
274 }
275 }
276
277 /**
278 * Notify our observers of an interface removal.
279 */
280 private void notifyInterfaceRemoved(String iface) {
281 for (INetworkManagementEventObserver obs : mObservers) {
282 try {
283 obs.interfaceRemoved(iface);
284 } catch (Exception ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800285 Slog.w(TAG, "Observer notifier failed", ex);
San Mehat4d02d002010-01-22 16:07:46 -0800286 }
287 }
288 }
289
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700290 /**
JP Abgrall12b933d2011-07-14 18:09:22 -0700291 * Notify our observers of a limit reached.
292 */
293 private void notifyLimitReached(String limitName, String iface) {
294 for (INetworkManagementEventObserver obs : mObservers) {
295 try {
296 obs.limitReached(limitName, iface);
JP Abgrall12b933d2011-07-14 18:09:22 -0700297 } catch (Exception ex) {
298 Slog.w(TAG, "Observer notifier failed", ex);
299 }
300 }
301 }
302
303 /**
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700304 * Let us know the daemon is connected
305 */
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700306 protected void onDaemonConnected() {
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700307 if (DBG) Slog.d(TAG, "onConnected");
308 mConnectedSignal.countDown();
309 }
310
San Mehat4d02d002010-01-22 16:07:46 -0800311
San Mehat873f2142010-01-14 10:25:07 -0800312 //
313 // Netd Callback handling
314 //
315
316 class NetdCallbackReceiver implements INativeDaemonConnectorCallbacks {
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700317 /** {@inheritDoc} */
San Mehat873f2142010-01-14 10:25:07 -0800318 public void onDaemonConnected() {
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700319 NetworkManagementService.this.onDaemonConnected();
San Mehat873f2142010-01-14 10:25:07 -0800320 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700321
322 /** {@inheritDoc} */
San Mehat873f2142010-01-14 10:25:07 -0800323 public boolean onEvent(int code, String raw, String[] cooked) {
JP Abgrall12b933d2011-07-14 18:09:22 -0700324 switch (code) {
325 case NetdResponseCode.InterfaceChange:
326 /*
327 * a network interface change occured
328 * Format: "NNN Iface added <name>"
329 * "NNN Iface removed <name>"
330 * "NNN Iface changed <name> <up/down>"
331 * "NNN Iface linkstatus <name> <up/down>"
332 */
333 if (cooked.length < 4 || !cooked[1].equals("Iface")) {
334 throw new IllegalStateException(
335 String.format("Invalid event from daemon (%s)", raw));
336 }
337 if (cooked[2].equals("added")) {
338 notifyInterfaceAdded(cooked[3]);
339 return true;
340 } else if (cooked[2].equals("removed")) {
341 notifyInterfaceRemoved(cooked[3]);
342 return true;
343 } else if (cooked[2].equals("changed") && cooked.length == 5) {
344 notifyInterfaceStatusChanged(cooked[3], cooked[4].equals("up"));
345 return true;
346 } else if (cooked[2].equals("linkstate") && cooked.length == 5) {
347 notifyInterfaceLinkStateChanged(cooked[3], cooked[4].equals("up"));
348 return true;
349 }
Robert Greenwalte3253922010-02-18 09:23:25 -0800350 throw new IllegalStateException(
351 String.format("Invalid event from daemon (%s)", raw));
JP Abgrall12b933d2011-07-14 18:09:22 -0700352 // break;
353 case NetdResponseCode.BandwidthControl:
354 /*
355 * Bandwidth control needs some attention
356 * Format: "NNN limit alert <alertName> <ifaceName>"
357 */
358 if (cooked.length < 5 || !cooked[1].equals("limit")) {
359 throw new IllegalStateException(
360 String.format("Invalid event from daemon (%s)", raw));
361 }
362 if (cooked[2].equals("alert")) {
363 notifyLimitReached(cooked[3], cooked[4]);
364 return true;
365 }
366 throw new IllegalStateException(
367 String.format("Invalid event from daemon (%s)", raw));
368 // break;
369 default: break;
Robert Greenwalte3253922010-02-18 09:23:25 -0800370 }
371 return false;
San Mehat873f2142010-01-14 10:25:07 -0800372 }
373 }
374
San Mehated4fc8a2010-01-22 12:28:36 -0800375
San Mehat873f2142010-01-14 10:25:07 -0800376 //
377 // INetworkManagementService members
378 //
379
380 public String[] listInterfaces() throws IllegalStateException {
381 mContext.enforceCallingOrSelfPermission(
382 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
383
Kenny Roota80ce062010-06-01 13:23:53 -0700384 try {
385 return mConnector.doListCommand("interface list", NetdResponseCode.InterfaceListResult);
386 } catch (NativeDaemonConnectorException e) {
387 throw new IllegalStateException(
388 "Cannot communicate with native daemon to list interfaces");
389 }
San Mehated4fc8a2010-01-22 12:28:36 -0800390 }
391
392 public InterfaceConfiguration getInterfaceConfig(String iface) throws IllegalStateException {
Kenny Roota80ce062010-06-01 13:23:53 -0700393 String rsp;
394 try {
395 rsp = mConnector.doCommand("interface getcfg " + iface).get(0);
396 } catch (NativeDaemonConnectorException e) {
397 throw new IllegalStateException(
398 "Cannot communicate with native daemon to get interface config");
399 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800400 Slog.d(TAG, String.format("rsp <%s>", rsp));
San Mehated4fc8a2010-01-22 12:28:36 -0800401
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800402 // Rsp: 213 xx:xx:xx:xx:xx:xx yyy.yyy.yyy.yyy zzz [flag1 flag2 flag3]
San Mehated4fc8a2010-01-22 12:28:36 -0800403 StringTokenizer st = new StringTokenizer(rsp);
404
Kenny Roota80ce062010-06-01 13:23:53 -0700405 InterfaceConfiguration cfg;
San Mehated4fc8a2010-01-22 12:28:36 -0800406 try {
Kenny Roota80ce062010-06-01 13:23:53 -0700407 try {
408 int code = Integer.parseInt(st.nextToken(" "));
409 if (code != NetdResponseCode.InterfaceGetCfgResult) {
410 throw new IllegalStateException(
411 String.format("Expected code %d, but got %d",
412 NetdResponseCode.InterfaceGetCfgResult, code));
413 }
414 } catch (NumberFormatException nfe) {
San Mehated4fc8a2010-01-22 12:28:36 -0800415 throw new IllegalStateException(
Kenny Roota80ce062010-06-01 13:23:53 -0700416 String.format("Invalid response from daemon (%s)", rsp));
San Mehated4fc8a2010-01-22 12:28:36 -0800417 }
Kenny Roota80ce062010-06-01 13:23:53 -0700418
419 cfg = new InterfaceConfiguration();
420 cfg.hwAddr = st.nextToken(" ");
Robert Greenwalted126402011-01-28 15:34:55 -0800421 InetAddress addr = null;
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800422 int prefixLength = 0;
Kenny Roota80ce062010-06-01 13:23:53 -0700423 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800424 addr = NetworkUtils.numericToInetAddress(st.nextToken(" "));
425 } catch (IllegalArgumentException iae) {
426 Slog.e(TAG, "Failed to parse ipaddr", iae);
Kenny Roota80ce062010-06-01 13:23:53 -0700427 }
428
429 try {
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800430 prefixLength = Integer.parseInt(st.nextToken(" "));
431 } catch (NumberFormatException nfe) {
432 Slog.e(TAG, "Failed to parse prefixLength", nfe);
Kenny Roota80ce062010-06-01 13:23:53 -0700433 }
Robert Greenwalt04808c22010-12-13 17:01:41 -0800434
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800435 cfg.addr = new LinkAddress(addr, prefixLength);
Kenny Roota80ce062010-06-01 13:23:53 -0700436 cfg.interfaceFlags = st.nextToken("]").trim() +"]";
437 } catch (NoSuchElementException nsee) {
San Mehated4fc8a2010-01-22 12:28:36 -0800438 throw new IllegalStateException(
439 String.format("Invalid response from daemon (%s)", rsp));
440 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800441 Slog.d(TAG, String.format("flags <%s>", cfg.interfaceFlags));
San Mehated4fc8a2010-01-22 12:28:36 -0800442 return cfg;
443 }
444
445 public void setInterfaceConfig(
446 String iface, InterfaceConfiguration cfg) throws IllegalStateException {
Robert Greenwalted126402011-01-28 15:34:55 -0800447 LinkAddress linkAddr = cfg.addr;
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800448 if (linkAddr == null || linkAddr.getAddress() == null) {
449 throw new IllegalStateException("Null LinkAddress given");
Robert Greenwalted126402011-01-28 15:34:55 -0800450 }
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800451 String cmd = String.format("interface setcfg %s %s %d %s", iface,
452 linkAddr.getAddress().getHostAddress(),
453 linkAddr.getNetworkPrefixLength(),
454 cfg.interfaceFlags);
Kenny Roota80ce062010-06-01 13:23:53 -0700455 try {
456 mConnector.doCommand(cmd);
457 } catch (NativeDaemonConnectorException e) {
458 throw new IllegalStateException(
Robert Greenwalt81d5ad52010-12-16 11:27:38 -0800459 "Unable to communicate with native daemon to interface setcfg - " + e);
Kenny Roota80ce062010-06-01 13:23:53 -0700460 }
San Mehat873f2142010-01-14 10:25:07 -0800461 }
462
Irfan Sheriff7244c972011-08-05 20:40:45 -0700463 public void setInterfaceDown(String iface) throws IllegalStateException {
464 try {
465 InterfaceConfiguration ifcg = getInterfaceConfig(iface);
466 ifcg.interfaceFlags = ifcg.interfaceFlags.replace("up", "down");
467 setInterfaceConfig(iface, ifcg);
468 } catch (NativeDaemonConnectorException e) {
469 throw new IllegalStateException(
470 "Unable to communicate with native daemon for interface down - " + e);
471 }
472 }
473
474 public void setInterfaceUp(String iface) throws IllegalStateException {
475 try {
476 InterfaceConfiguration ifcg = getInterfaceConfig(iface);
477 ifcg.interfaceFlags = ifcg.interfaceFlags.replace("down", "up");
478 setInterfaceConfig(iface, ifcg);
479 } catch (NativeDaemonConnectorException e) {
480 throw new IllegalStateException(
481 "Unable to communicate with native daemon for interface up - " + e);
482 }
483 }
484
Irfan Sheriff73293612011-09-14 12:31:56 -0700485 public void setInterfaceIpv6PrivacyExtensions(String iface, boolean enable)
486 throws IllegalStateException {
487 String cmd = String.format("interface ipv6privacyextensions %s %s", iface,
488 enable ? "enable" : "disable");
489 try {
490 mConnector.doCommand(cmd);
491 } catch (NativeDaemonConnectorException e) {
492 throw new IllegalStateException(
493 "Unable to communicate with native daemon to set ipv6privacyextensions - " + e);
494 }
495 }
496
497
498
Irfan Sherifff5600612011-06-16 10:26:28 -0700499 /* TODO: This is right now a IPv4 only function. Works for wifi which loses its
500 IPv6 addresses on interface down, but we need to do full clean up here */
501 public void clearInterfaceAddresses(String iface) throws IllegalStateException {
502 String cmd = String.format("interface clearaddrs %s", iface);
503 try {
504 mConnector.doCommand(cmd);
505 } catch (NativeDaemonConnectorException e) {
506 throw new IllegalStateException(
507 "Unable to communicate with native daemon to interface clearallips - " + e);
508 }
509 }
510
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700511 public void addRoute(String interfaceName, RouteInfo route) {
512 modifyRoute(interfaceName, ADD, route);
513 }
514
515 public void removeRoute(String interfaceName, RouteInfo route) {
516 modifyRoute(interfaceName, REMOVE, route);
517 }
518
519 private void modifyRoute(String interfaceName, int action, RouteInfo route) {
520 ArrayList<String> rsp;
521
522 StringBuilder cmd;
523
524 switch (action) {
525 case ADD:
526 {
527 cmd = new StringBuilder("interface route add " + interfaceName);
528 break;
529 }
530 case REMOVE:
531 {
532 cmd = new StringBuilder("interface route remove " + interfaceName);
533 break;
534 }
535 default:
536 throw new IllegalStateException("Unknown action type " + action);
537 }
538
539 // create triplet: dest-ip-addr prefixlength gateway-ip-addr
540 LinkAddress la = route.getDestination();
541 cmd.append(' ');
542 cmd.append(la.getAddress().getHostAddress());
543 cmd.append(' ');
544 cmd.append(la.getNetworkPrefixLength());
545 cmd.append(' ');
546 if (route.getGateway() == null) {
547 if (la.getAddress() instanceof Inet4Address) {
548 cmd.append("0.0.0.0");
549 } else {
550 cmd.append ("::0");
551 }
552 } else {
553 cmd.append(route.getGateway().getHostAddress());
554 }
555 try {
556 rsp = mConnector.doCommand(cmd.toString());
557 } catch (NativeDaemonConnectorException e) {
558 throw new IllegalStateException(
559 "Unable to communicate with native dameon to add routes - "
560 + e);
561 }
562
563 for (String line : rsp) {
564 Log.v(TAG, "add route response is " + line);
565 }
566 }
567
568 private ArrayList<String> readRouteList(String filename) {
569 FileInputStream fstream = null;
570 ArrayList<String> list = new ArrayList<String>();
571
572 try {
573 fstream = new FileInputStream(filename);
574 DataInputStream in = new DataInputStream(fstream);
575 BufferedReader br = new BufferedReader(new InputStreamReader(in));
576 String s;
577
578 // throw away the title line
579
580 while (((s = br.readLine()) != null) && (s.length() != 0)) {
581 list.add(s);
582 }
583 } catch (IOException ex) {
584 // return current list, possibly empty
585 } finally {
586 if (fstream != null) {
587 try {
588 fstream.close();
589 } catch (IOException ex) {}
590 }
591 }
592
593 return list;
594 }
595
596 public RouteInfo[] getRoutes(String interfaceName) {
597 ArrayList<RouteInfo> routes = new ArrayList<RouteInfo>();
598
599 // v4 routes listed as:
600 // iface dest-addr gateway-addr flags refcnt use metric netmask mtu window IRTT
601 for (String s : readRouteList("/proc/net/route")) {
602 String[] fields = s.split("\t");
603
604 if (fields.length > 7) {
605 String iface = fields[0];
606
607 if (interfaceName.equals(iface)) {
608 String dest = fields[1];
609 String gate = fields[2];
610 String flags = fields[3]; // future use?
611 String mask = fields[7];
612 try {
613 // address stored as a hex string, ex: 0014A8C0
614 InetAddress destAddr =
615 NetworkUtils.intToInetAddress((int)Long.parseLong(dest, 16));
616 int prefixLength =
617 NetworkUtils.netmaskIntToPrefixLength(
618 (int)Long.parseLong(mask, 16));
619 LinkAddress linkAddress = new LinkAddress(destAddr, prefixLength);
620
621 // address stored as a hex string, ex 0014A8C0
622 InetAddress gatewayAddr =
623 NetworkUtils.intToInetAddress((int)Long.parseLong(gate, 16));
624
625 RouteInfo route = new RouteInfo(linkAddress, gatewayAddr);
626 routes.add(route);
627 } catch (Exception e) {
628 Log.e(TAG, "Error parsing route " + s + " : " + e);
629 continue;
630 }
631 }
632 }
633 }
634
635 // v6 routes listed as:
636 // dest-addr prefixlength ?? ?? gateway-addr ?? ?? ?? ?? iface
637 for (String s : readRouteList("/proc/net/ipv6_route")) {
638 String[]fields = s.split("\\s+");
639 if (fields.length > 9) {
640 String iface = fields[9].trim();
641 if (interfaceName.equals(iface)) {
642 String dest = fields[0];
643 String prefix = fields[1];
644 String gate = fields[4];
645
646 try {
647 // prefix length stored as a hex string, ex 40
648 int prefixLength = Integer.parseInt(prefix, 16);
649
650 // address stored as a 32 char hex string
651 // ex fe800000000000000000000000000000
652 InetAddress destAddr = NetworkUtils.hexToInet6Address(dest);
653 LinkAddress linkAddress = new LinkAddress(destAddr, prefixLength);
654
655 InetAddress gateAddr = NetworkUtils.hexToInet6Address(gate);
656
657 RouteInfo route = new RouteInfo(linkAddress, gateAddr);
658 routes.add(route);
659 } catch (Exception e) {
660 Log.e(TAG, "Error parsing route " + s + " : " + e);
661 continue;
662 }
663 }
664 }
665 }
666 return (RouteInfo[]) routes.toArray(new RouteInfo[0]);
667 }
668
San Mehat873f2142010-01-14 10:25:07 -0800669 public void shutdown() {
670 if (mContext.checkCallingOrSelfPermission(
671 android.Manifest.permission.SHUTDOWN)
672 != PackageManager.PERMISSION_GRANTED) {
673 throw new SecurityException("Requires SHUTDOWN permission");
674 }
675
Joe Onorato8a9b2202010-02-26 18:56:32 -0800676 Slog.d(TAG, "Shutting down");
San Mehat873f2142010-01-14 10:25:07 -0800677 }
678
679 public boolean getIpForwardingEnabled() throws IllegalStateException{
680 mContext.enforceCallingOrSelfPermission(
681 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
682
Kenny Roota80ce062010-06-01 13:23:53 -0700683 ArrayList<String> rsp;
684 try {
685 rsp = mConnector.doCommand("ipfwd status");
686 } catch (NativeDaemonConnectorException e) {
687 throw new IllegalStateException(
688 "Unable to communicate with native daemon to ipfwd status");
689 }
San Mehat873f2142010-01-14 10:25:07 -0800690
691 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700692 String[] tok = line.split(" ");
693 if (tok.length < 3) {
694 Slog.e(TAG, "Malformed response from native daemon: " + line);
695 return false;
696 }
697
San Mehat873f2142010-01-14 10:25:07 -0800698 int code = Integer.parseInt(tok[0]);
699 if (code == NetdResponseCode.IpFwdStatusResult) {
700 // 211 Forwarding <enabled/disabled>
Kenny Roota80ce062010-06-01 13:23:53 -0700701 return "enabled".equals(tok[2]);
San Mehat873f2142010-01-14 10:25:07 -0800702 } else {
703 throw new IllegalStateException(String.format("Unexpected response code %d", code));
704 }
705 }
706 throw new IllegalStateException("Got an empty response");
707 }
708
709 public void setIpForwardingEnabled(boolean enable) throws IllegalStateException {
710 mContext.enforceCallingOrSelfPermission(
711 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
712 mConnector.doCommand(String.format("ipfwd %sable", (enable ? "en" : "dis")));
713 }
714
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -0700715 public void startTethering(String[] dhcpRange)
San Mehat873f2142010-01-14 10:25:07 -0800716 throws IllegalStateException {
717 mContext.enforceCallingOrSelfPermission(
718 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -0700719 // cmd is "tether start first_start first_stop second_start second_stop ..."
720 // an odd number of addrs will fail
721 String cmd = "tether start";
722 for (String d : dhcpRange) {
723 cmd += " " + d;
724 }
Kenny Roota80ce062010-06-01 13:23:53 -0700725
726 try {
727 mConnector.doCommand(cmd);
728 } catch (NativeDaemonConnectorException e) {
729 throw new IllegalStateException("Unable to communicate to native daemon");
730 }
San Mehat873f2142010-01-14 10:25:07 -0800731 }
732
733 public void stopTethering() throws IllegalStateException {
734 mContext.enforceCallingOrSelfPermission(
735 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700736 try {
737 mConnector.doCommand("tether stop");
738 } catch (NativeDaemonConnectorException e) {
739 throw new IllegalStateException("Unable to communicate to native daemon to stop tether");
740 }
San Mehat873f2142010-01-14 10:25:07 -0800741 }
742
743 public boolean isTetheringStarted() throws IllegalStateException {
744 mContext.enforceCallingOrSelfPermission(
745 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
746
Kenny Roota80ce062010-06-01 13:23:53 -0700747 ArrayList<String> rsp;
748 try {
749 rsp = mConnector.doCommand("tether status");
750 } catch (NativeDaemonConnectorException e) {
751 throw new IllegalStateException(
752 "Unable to communicate to native daemon to get tether status");
753 }
San Mehat873f2142010-01-14 10:25:07 -0800754
755 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700756 String[] tok = line.split(" ");
757 if (tok.length < 3) {
758 throw new IllegalStateException("Malformed response for tether status: " + line);
759 }
San Mehat873f2142010-01-14 10:25:07 -0800760 int code = Integer.parseInt(tok[0]);
761 if (code == NetdResponseCode.TetherStatusResult) {
762 // XXX: Tethering services <started/stopped> <TBD>...
Kenny Roota80ce062010-06-01 13:23:53 -0700763 return "started".equals(tok[2]);
San Mehat873f2142010-01-14 10:25:07 -0800764 } else {
765 throw new IllegalStateException(String.format("Unexpected response code %d", code));
766 }
767 }
768 throw new IllegalStateException("Got an empty response");
769 }
770
771 public void tetherInterface(String iface) throws IllegalStateException {
772 mContext.enforceCallingOrSelfPermission(
773 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700774 try {
775 mConnector.doCommand("tether interface add " + iface);
776 } catch (NativeDaemonConnectorException e) {
777 throw new IllegalStateException(
778 "Unable to communicate to native daemon for adding tether interface");
779 }
San Mehat873f2142010-01-14 10:25:07 -0800780 }
781
782 public void untetherInterface(String iface) {
783 mContext.enforceCallingOrSelfPermission(
784 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700785 try {
786 mConnector.doCommand("tether interface remove " + iface);
787 } catch (NativeDaemonConnectorException e) {
788 throw new IllegalStateException(
789 "Unable to communicate to native daemon for removing tether interface");
790 }
San Mehat873f2142010-01-14 10:25:07 -0800791 }
792
793 public String[] listTetheredInterfaces() throws IllegalStateException {
794 mContext.enforceCallingOrSelfPermission(
795 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700796 try {
797 return mConnector.doListCommand(
798 "tether interface list", NetdResponseCode.TetherInterfaceListResult);
799 } catch (NativeDaemonConnectorException e) {
800 throw new IllegalStateException(
801 "Unable to communicate to native daemon for listing tether interfaces");
802 }
San Mehat873f2142010-01-14 10:25:07 -0800803 }
804
805 public void setDnsForwarders(String[] dns) throws IllegalStateException {
806 mContext.enforceCallingOrSelfPermission(
807 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
808 try {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800809 String cmd = "tether dns set";
San Mehat873f2142010-01-14 10:25:07 -0800810 for (String s : dns) {
Robert Greenwalte5903732011-02-22 16:00:42 -0800811 cmd += " " + NetworkUtils.numericToInetAddress(s).getHostAddress();
San Mehat873f2142010-01-14 10:25:07 -0800812 }
Kenny Roota80ce062010-06-01 13:23:53 -0700813 try {
814 mConnector.doCommand(cmd);
815 } catch (NativeDaemonConnectorException e) {
816 throw new IllegalStateException(
817 "Unable to communicate to native daemon for setting tether dns");
818 }
Robert Greenwalte5903732011-02-22 16:00:42 -0800819 } catch (IllegalArgumentException e) {
San Mehat873f2142010-01-14 10:25:07 -0800820 throw new IllegalStateException("Error resolving dns name", e);
821 }
822 }
823
824 public String[] getDnsForwarders() throws IllegalStateException {
825 mContext.enforceCallingOrSelfPermission(
826 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700827 try {
828 return mConnector.doListCommand(
829 "tether dns list", NetdResponseCode.TetherDnsFwdTgtListResult);
830 } catch (NativeDaemonConnectorException e) {
831 throw new IllegalStateException(
832 "Unable to communicate to native daemon for listing tether dns");
833 }
San Mehat873f2142010-01-14 10:25:07 -0800834 }
835
836 public void enableNat(String internalInterface, String externalInterface)
837 throws IllegalStateException {
838 mContext.enforceCallingOrSelfPermission(
839 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700840 try {
841 mConnector.doCommand(
842 String.format("nat enable %s %s", internalInterface, externalInterface));
843 } catch (NativeDaemonConnectorException e) {
844 throw new IllegalStateException(
845 "Unable to communicate to native daemon for enabling NAT interface");
846 }
San Mehat873f2142010-01-14 10:25:07 -0800847 }
848
849 public void disableNat(String internalInterface, String externalInterface)
850 throws IllegalStateException {
851 mContext.enforceCallingOrSelfPermission(
852 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700853 try {
854 mConnector.doCommand(
855 String.format("nat disable %s %s", internalInterface, externalInterface));
856 } catch (NativeDaemonConnectorException e) {
857 throw new IllegalStateException(
858 "Unable to communicate to native daemon for disabling NAT interface");
859 }
San Mehat873f2142010-01-14 10:25:07 -0800860 }
San Mehat72759df2010-01-19 13:50:37 -0800861
862 public String[] listTtys() throws IllegalStateException {
863 mContext.enforceCallingOrSelfPermission(
864 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700865 try {
866 return mConnector.doListCommand("list_ttys", NetdResponseCode.TtyListResult);
867 } catch (NativeDaemonConnectorException e) {
868 throw new IllegalStateException(
869 "Unable to communicate to native daemon for listing TTYs");
870 }
San Mehat72759df2010-01-19 13:50:37 -0800871 }
872
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800873 public void attachPppd(String tty, String localAddr, String remoteAddr, String dns1Addr,
874 String dns2Addr) throws IllegalStateException {
San Mehat72759df2010-01-19 13:50:37 -0800875 try {
876 mContext.enforceCallingOrSelfPermission(
877 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800878 mConnector.doCommand(String.format("pppd attach %s %s %s %s %s", tty,
Robert Greenwalte5903732011-02-22 16:00:42 -0800879 NetworkUtils.numericToInetAddress(localAddr).getHostAddress(),
880 NetworkUtils.numericToInetAddress(remoteAddr).getHostAddress(),
881 NetworkUtils.numericToInetAddress(dns1Addr).getHostAddress(),
882 NetworkUtils.numericToInetAddress(dns2Addr).getHostAddress()));
883 } catch (IllegalArgumentException e) {
San Mehat72759df2010-01-19 13:50:37 -0800884 throw new IllegalStateException("Error resolving addr", e);
Kenny Roota80ce062010-06-01 13:23:53 -0700885 } catch (NativeDaemonConnectorException e) {
886 throw new IllegalStateException("Error communicating to native daemon to attach pppd", e);
San Mehat72759df2010-01-19 13:50:37 -0800887 }
888 }
889
890 public void detachPppd(String tty) throws IllegalStateException {
891 mContext.enforceCallingOrSelfPermission(
892 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700893 try {
894 mConnector.doCommand(String.format("pppd detach %s", tty));
895 } catch (NativeDaemonConnectorException e) {
896 throw new IllegalStateException("Error communicating to native daemon to detach pppd", e);
897 }
San Mehat72759df2010-01-19 13:50:37 -0800898 }
Robert Greenwaltce1200d2010-02-18 11:25:54 -0800899
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700900 public void startAccessPoint(WifiConfiguration wifiConfig, String wlanIface, String softapIface)
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800901 throws IllegalStateException {
902 mContext.enforceCallingOrSelfPermission(
903 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
904 mContext.enforceCallingOrSelfPermission(
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700905 android.Manifest.permission.CHANGE_WIFI_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700906 try {
Irfan Sheriffcb30b222011-07-29 20:54:52 -0700907 wifiFirmwareReload(wlanIface, "AP");
Kenny Roota80ce062010-06-01 13:23:53 -0700908 mConnector.doCommand(String.format("softap start " + wlanIface));
909 if (wifiConfig == null) {
910 mConnector.doCommand(String.format("softap set " + wlanIface + " " + softapIface));
911 } else {
912 /**
913 * softap set arg1 arg2 arg3 [arg4 arg5 arg6 arg7 arg8]
914 * argv1 - wlan interface
915 * argv2 - softap interface
916 * argv3 - SSID
917 * argv4 - Security
918 * argv5 - Key
919 * argv6 - Channel
920 * argv7 - Preamble
921 * argv8 - Max SCB
922 */
Irfan Sheriffec8d23a2011-02-16 17:00:33 -0800923 String str = String.format("softap set " + wlanIface + " " + softapIface +
924 " %s %s %s", convertQuotedString(wifiConfig.SSID),
925 getSecurityType(wifiConfig),
926 convertQuotedString(wifiConfig.preSharedKey));
Kenny Roota80ce062010-06-01 13:23:53 -0700927 mConnector.doCommand(str);
928 }
929 mConnector.doCommand(String.format("softap startap"));
930 } catch (NativeDaemonConnectorException e) {
931 throw new IllegalStateException("Error communicating to native daemon to start softap", e);
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800932 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800933 }
934
Irfan Sheriffa6e559e2010-05-24 14:55:42 -0700935 private String convertQuotedString(String s) {
Irfan Sheriff7baec0f2010-05-26 17:16:47 -0700936 if (s == null) {
937 return s;
938 }
939 /* Replace \ with \\, then " with \" and add quotes at end */
940 return '"' + s.replaceAll("\\\\","\\\\\\\\").replaceAll("\"","\\\\\"") + '"';
Irfan Sheriffa6e559e2010-05-24 14:55:42 -0700941 }
942
Irfan Sheriffec8d23a2011-02-16 17:00:33 -0800943 private String getSecurityType(WifiConfiguration wifiConfig) {
944 switch (wifiConfig.getAuthType()) {
945 case KeyMgmt.WPA_PSK:
946 return "wpa-psk";
947 case KeyMgmt.WPA2_PSK:
948 return "wpa2-psk";
949 default:
950 return "open";
951 }
952 }
953
Irfan Sheriffcb30b222011-07-29 20:54:52 -0700954 /* @param mode can be "AP", "STA" or "P2P" */
955 public void wifiFirmwareReload(String wlanIface, String mode) throws IllegalStateException {
956 mContext.enforceCallingOrSelfPermission(
957 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
958 mContext.enforceCallingOrSelfPermission(
959 android.Manifest.permission.CHANGE_WIFI_STATE, "NetworkManagementService");
960
961 try {
962 mConnector.doCommand(String.format("softap fwreload " + wlanIface + " " + mode));
963 } catch (NativeDaemonConnectorException e) {
964 throw new IllegalStateException("Error communicating to native daemon ", e);
965 }
966 }
967
Irfan Sheriff23eb2972011-07-22 15:21:10 -0700968 public void stopAccessPoint(String wlanIface) throws IllegalStateException {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800969 mContext.enforceCallingOrSelfPermission(
970 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
971 mContext.enforceCallingOrSelfPermission(
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700972 android.Manifest.permission.CHANGE_WIFI_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700973 try {
974 mConnector.doCommand("softap stopap");
Irfan Sheriff23eb2972011-07-22 15:21:10 -0700975 mConnector.doCommand("softap stop " + wlanIface);
Irfan Sheriffcb30b222011-07-29 20:54:52 -0700976 wifiFirmwareReload(wlanIface, "STA");
Kenny Roota80ce062010-06-01 13:23:53 -0700977 } catch (NativeDaemonConnectorException e) {
978 throw new IllegalStateException("Error communicating to native daemon to stop soft AP",
979 e);
980 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800981 }
982
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700983 public void setAccessPoint(WifiConfiguration wifiConfig, String wlanIface, String softapIface)
984 throws IllegalStateException {
985 mContext.enforceCallingOrSelfPermission(
986 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
987 mContext.enforceCallingOrSelfPermission(
988 android.Manifest.permission.CHANGE_WIFI_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700989 try {
990 if (wifiConfig == null) {
991 mConnector.doCommand(String.format("softap set " + wlanIface + " " + softapIface));
992 } else {
993 String str = String.format("softap set " + wlanIface + " " + softapIface
994 + " %s %s %s", convertQuotedString(wifiConfig.SSID),
Irfan Sheriffec8d23a2011-02-16 17:00:33 -0800995 getSecurityType(wifiConfig),
Kenny Roota80ce062010-06-01 13:23:53 -0700996 convertQuotedString(wifiConfig.preSharedKey));
997 mConnector.doCommand(str);
998 }
999 } catch (NativeDaemonConnectorException e) {
1000 throw new IllegalStateException("Error communicating to native daemon to set soft AP",
1001 e);
Irfan Sheriffc2f54c22010-03-18 14:02:22 -07001002 }
1003 }
San Mehat91cac642010-03-31 14:31:36 -07001004
1005 private long getInterfaceCounter(String iface, boolean rx) {
1006 mContext.enforceCallingOrSelfPermission(
1007 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
1008 try {
Kenny Roota80ce062010-06-01 13:23:53 -07001009 String rsp;
1010 try {
1011 rsp = mConnector.doCommand(
1012 String.format("interface read%scounter %s", (rx ? "rx" : "tx"), iface)).get(0);
1013 } catch (NativeDaemonConnectorException e1) {
1014 Slog.e(TAG, "Error communicating with native daemon", e1);
1015 return -1;
1016 }
1017
1018 String[] tok = rsp.split(" ");
1019 if (tok.length < 2) {
1020 Slog.e(TAG, String.format("Malformed response for reading %s interface",
1021 (rx ? "rx" : "tx")));
1022 return -1;
1023 }
1024
San Mehat91cac642010-03-31 14:31:36 -07001025 int code;
1026 try {
1027 code = Integer.parseInt(tok[0]);
1028 } catch (NumberFormatException nfe) {
1029 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
1030 return -1;
1031 }
1032 if ((rx && code != NetdResponseCode.InterfaceRxCounterResult) || (
1033 !rx && code != NetdResponseCode.InterfaceTxCounterResult)) {
1034 Slog.e(TAG, String.format("Unexpected response code %d", code));
1035 return -1;
1036 }
1037 return Long.parseLong(tok[1]);
1038 } catch (Exception e) {
1039 Slog.e(TAG, String.format(
1040 "Failed to read interface %s counters", (rx ? "rx" : "tx")), e);
1041 }
1042 return -1;
1043 }
1044
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001045 @Override
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001046 public NetworkStats getNetworkStatsSummary() {
1047 mContext.enforceCallingOrSelfPermission(
1048 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
1049
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001050 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 6);
1051 final NetworkStats.Entry entry = new NetworkStats.Entry();
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001052
Jeff Sharkey0fea8232011-09-01 01:07:31 -07001053 final HashSet<String> knownIfaces = Sets.newHashSet();
1054 final HashSet<String> activeIfaces = Sets.newHashSet();
1055
1056 // collect any historical stats and active state
1057 // TODO: migrate to reading from single file
1058 if (mBandwidthControlEnabled) {
1059 for (String iface : fileListWithoutNull(mStatsXtIface)) {
1060 final File ifacePath = new File(mStatsXtIface, iface);
1061
1062 final long active = readSingleLongFromFile(new File(ifacePath, "active"));
1063 if (active == 1) {
1064 knownIfaces.add(iface);
1065 activeIfaces.add(iface);
1066 } else if (active == 0) {
1067 knownIfaces.add(iface);
1068 } else {
1069 continue;
1070 }
1071
1072 entry.iface = iface;
1073 entry.uid = UID_ALL;
1074 entry.set = SET_DEFAULT;
1075 entry.tag = TAG_NONE;
1076 entry.rxBytes = readSingleLongFromFile(new File(ifacePath, "rx_bytes"));
1077 entry.rxPackets = readSingleLongFromFile(new File(ifacePath, "rx_packets"));
1078 entry.txBytes = readSingleLongFromFile(new File(ifacePath, "tx_bytes"));
1079 entry.txPackets = readSingleLongFromFile(new File(ifacePath, "tx_packets"));
1080
1081 stats.addValues(entry);
1082 }
1083 }
1084
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001085 final ArrayList<String> values = Lists.newArrayList();
1086
1087 BufferedReader reader = null;
1088 try {
1089 reader = new BufferedReader(new FileReader(mStatsIface));
1090
1091 // skip first two header lines
1092 reader.readLine();
1093 reader.readLine();
1094
1095 // parse remaining lines
1096 String line;
1097 while ((line = reader.readLine()) != null) {
1098 splitLine(line, values);
1099
1100 try {
1101 entry.iface = values.get(0);
1102 entry.uid = UID_ALL;
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001103 entry.set = SET_DEFAULT;
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001104 entry.tag = TAG_NONE;
1105 entry.rxBytes = Long.parseLong(values.get(1));
1106 entry.rxPackets = Long.parseLong(values.get(2));
1107 entry.txBytes = Long.parseLong(values.get(9));
1108 entry.txPackets = Long.parseLong(values.get(10));
1109
Jeff Sharkey0fea8232011-09-01 01:07:31 -07001110 if (activeIfaces.contains(entry.iface)) {
1111 // combine stats when iface is active
1112 stats.combineValues(entry);
1113 } else if (!knownIfaces.contains(entry.iface)) {
1114 // add stats when iface is unknown
1115 stats.addValues(entry);
1116 }
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001117 } catch (NumberFormatException e) {
1118 Slog.w(TAG, "problem parsing stats row '" + line + "': " + e);
1119 }
1120 }
Jeff Sharkey558a2322011-08-24 15:42:09 -07001121 } catch (NullPointerException e) {
1122 throw new IllegalStateException("problem parsing stats: " + e);
1123 } catch (NumberFormatException e) {
1124 throw new IllegalStateException("problem parsing stats: " + e);
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001125 } catch (IOException e) {
Jeff Sharkey558a2322011-08-24 15:42:09 -07001126 throw new IllegalStateException("problem parsing stats: " + e);
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001127 } finally {
1128 IoUtils.closeQuietly(reader);
1129 }
1130
Jeff Sharkey4a971222011-06-11 22:16:55 -07001131 return stats;
San Mehat91cac642010-03-31 14:31:36 -07001132 }
1133
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001134 @Override
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001135 public NetworkStats getNetworkStatsDetail() {
1136 mContext.enforceCallingOrSelfPermission(
1137 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
1138
Jeff Sharkey350083e2011-06-29 10:45:16 -07001139 if (mBandwidthControlEnabled) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001140 return getNetworkStatsDetailNetfilter(UID_ALL);
1141 } else {
1142 return getNetworkStatsDetailUidstat(UID_ALL);
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001143 }
San Mehat91cac642010-03-31 14:31:36 -07001144 }
1145
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001146 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001147 public void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001148 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1149
Jeff Sharkey350083e2011-06-29 10:45:16 -07001150 // silently discard when control disabled
1151 // TODO: eventually migrate to be always enabled
1152 if (!mBandwidthControlEnabled) return;
1153
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001154 synchronized (mQuotaLock) {
1155 if (mActiveQuotaIfaces.contains(iface)) {
1156 throw new IllegalStateException("iface " + iface + " already has quota");
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001157 }
1158
1159 final StringBuilder command = new StringBuilder();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001160 command.append("bandwidth setiquota ").append(iface).append(" ").append(quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001161
1162 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001163 // TODO: support quota shared across interfaces
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001164 mConnector.doCommand(command.toString());
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001165 mActiveQuotaIfaces.add(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001166 } catch (NativeDaemonConnectorException e) {
1167 throw new IllegalStateException("Error communicating to native daemon", e);
1168 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001169 }
1170 }
1171
1172 @Override
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001173 public void removeInterfaceQuota(String iface) {
1174 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1175
Jeff Sharkey350083e2011-06-29 10:45:16 -07001176 // silently discard when control disabled
1177 // TODO: eventually migrate to be always enabled
1178 if (!mBandwidthControlEnabled) return;
1179
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001180 synchronized (mQuotaLock) {
1181 if (!mActiveQuotaIfaces.contains(iface)) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001182 // TODO: eventually consider throwing
1183 return;
1184 }
1185
1186 final StringBuilder command = new StringBuilder();
1187 command.append("bandwidth removeiquota ").append(iface);
1188
1189 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001190 // TODO: support quota shared across interfaces
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001191 mConnector.doCommand(command.toString());
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001192 mActiveQuotaIfaces.remove(iface);
1193 mActiveAlertIfaces.remove(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001194 } catch (NativeDaemonConnectorException e) {
1195 throw new IllegalStateException("Error communicating to native daemon", e);
1196 }
1197 }
1198 }
1199
1200 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001201 public void setInterfaceAlert(String iface, long alertBytes) {
1202 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1203
1204 // silently discard when control disabled
1205 // TODO: eventually migrate to be always enabled
1206 if (!mBandwidthControlEnabled) return;
1207
1208 // quick sanity check
1209 if (!mActiveQuotaIfaces.contains(iface)) {
1210 throw new IllegalStateException("setting alert requires existing quota on iface");
1211 }
1212
1213 synchronized (mQuotaLock) {
1214 if (mActiveAlertIfaces.contains(iface)) {
1215 throw new IllegalStateException("iface " + iface + " already has alert");
1216 }
1217
1218 final StringBuilder command = new StringBuilder();
1219 command.append("bandwidth setinterfacealert ").append(iface).append(" ").append(
1220 alertBytes);
1221
1222 try {
1223 // TODO: support alert shared across interfaces
1224 mConnector.doCommand(command.toString());
1225 mActiveAlertIfaces.add(iface);
1226 } catch (NativeDaemonConnectorException e) {
1227 throw new IllegalStateException("Error communicating to native daemon", e);
1228 }
1229 }
1230 }
1231
1232 @Override
1233 public void removeInterfaceAlert(String iface) {
1234 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1235
1236 // silently discard when control disabled
1237 // TODO: eventually migrate to be always enabled
1238 if (!mBandwidthControlEnabled) return;
1239
1240 synchronized (mQuotaLock) {
1241 if (!mActiveAlertIfaces.contains(iface)) {
1242 // TODO: eventually consider throwing
1243 return;
1244 }
1245
1246 final StringBuilder command = new StringBuilder();
1247 command.append("bandwidth removeinterfacealert ").append(iface);
1248
1249 try {
1250 // TODO: support alert shared across interfaces
1251 mConnector.doCommand(command.toString());
1252 mActiveAlertIfaces.remove(iface);
1253 } catch (NativeDaemonConnectorException e) {
1254 throw new IllegalStateException("Error communicating to native daemon", e);
1255 }
1256 }
1257 }
1258
1259 @Override
1260 public void setGlobalAlert(long alertBytes) {
1261 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1262
1263 // silently discard when control disabled
1264 // TODO: eventually migrate to be always enabled
1265 if (!mBandwidthControlEnabled) return;
1266
1267 final StringBuilder command = new StringBuilder();
1268 command.append("bandwidth setglobalalert ").append(alertBytes);
1269
1270 try {
1271 mConnector.doCommand(command.toString());
1272 } catch (NativeDaemonConnectorException e) {
1273 throw new IllegalStateException("Error communicating to native daemon", e);
1274 }
1275 }
1276
1277 @Override
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001278 public void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
1279 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1280
Jeff Sharkey350083e2011-06-29 10:45:16 -07001281 // silently discard when control disabled
1282 // TODO: eventually migrate to be always enabled
1283 if (!mBandwidthControlEnabled) return;
1284
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001285 synchronized (mUidRejectOnQuota) {
1286 final boolean oldRejectOnQuota = mUidRejectOnQuota.get(uid, false);
1287 if (oldRejectOnQuota == rejectOnQuotaInterfaces) {
1288 // TODO: eventually consider throwing
1289 return;
1290 }
1291
1292 final StringBuilder command = new StringBuilder();
1293 command.append("bandwidth");
1294 if (rejectOnQuotaInterfaces) {
1295 command.append(" addnaughtyapps");
1296 } else {
1297 command.append(" removenaughtyapps");
1298 }
1299 command.append(" ").append(uid);
1300
1301 try {
1302 mConnector.doCommand(command.toString());
1303 if (rejectOnQuotaInterfaces) {
1304 mUidRejectOnQuota.put(uid, true);
1305 } else {
1306 mUidRejectOnQuota.delete(uid);
1307 }
1308 } catch (NativeDaemonConnectorException e) {
1309 throw new IllegalStateException("Error communicating to native daemon", e);
1310 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001311 }
1312 }
1313
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001314 @Override
1315 public boolean isBandwidthControlEnabled() {
1316 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1317 return mBandwidthControlEnabled;
1318 }
1319
1320 @Override
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001321 public NetworkStats getNetworkStatsUidDetail(int uid) {
1322 if (Binder.getCallingUid() != uid) {
1323 mContext.enforceCallingOrSelfPermission(
1324 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
1325 }
1326
Jeff Sharkey350083e2011-06-29 10:45:16 -07001327 if (mBandwidthControlEnabled) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001328 return getNetworkStatsDetailNetfilter(uid);
1329 } else {
1330 return getNetworkStatsDetailUidstat(uid);
1331 }
1332 }
1333
1334 /**
1335 * Build {@link NetworkStats} with detailed UID statistics.
1336 */
1337 private NetworkStats getNetworkStatsDetailNetfilter(int limitUid) {
1338 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 24);
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001339 final NetworkStats.Entry entry = new NetworkStats.Entry();
1340
Jeff Sharkeya63ba592011-07-19 23:47:12 -07001341 // TODO: remove knownLines check once 5087722 verified
1342 final HashSet<String> knownLines = Sets.newHashSet();
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001343 // TODO: remove lastIdx check once 5270106 verified
JP Abgrall6acf39b2011-09-08 15:13:26 -07001344 int lastIdx;
Jeff Sharkeya63ba592011-07-19 23:47:12 -07001345
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001346 final ArrayList<String> keys = Lists.newArrayList();
1347 final ArrayList<String> values = Lists.newArrayList();
1348 final HashMap<String, String> parsed = Maps.newHashMap();
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001349
1350 BufferedReader reader = null;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001351 String line = null;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001352 try {
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001353 reader = new BufferedReader(new FileReader(mStatsXtUid));
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001354
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001355 // parse first line as header
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001356 line = reader.readLine();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001357 splitLine(line, keys);
JP Abgrall6acf39b2011-09-08 15:13:26 -07001358 lastIdx = 1;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001359
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001360 // parse remaining lines
1361 while ((line = reader.readLine()) != null) {
1362 splitLine(line, values);
1363 parseLine(keys, values, parsed);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001364
Jeff Sharkeya63ba592011-07-19 23:47:12 -07001365 if (!knownLines.add(line)) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001366 throw new IllegalStateException("duplicate proc entry: " + line);
Jeff Sharkeya63ba592011-07-19 23:47:12 -07001367 }
1368
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001369 final int idx = getParsedInt(parsed, KEY_IDX);
JP Abgrall6acf39b2011-09-08 15:13:26 -07001370 if (idx != lastIdx + 1) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001371 throw new IllegalStateException(
1372 "inconsistent idx=" + idx + " after lastIdx=" + lastIdx);
1373 }
1374 lastIdx = idx;
Jeff Sharkeyd03fd3f2011-06-19 20:55:09 -07001375
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001376 entry.iface = parsed.get(KEY_IFACE);
1377 entry.uid = getParsedInt(parsed, KEY_UID);
1378 entry.set = getParsedInt(parsed, KEY_COUNTER_SET);
1379 entry.tag = kernelToTag(parsed.get(KEY_TAG_HEX));
1380 entry.rxBytes = getParsedLong(parsed, KEY_RX_BYTES);
1381 entry.rxPackets = getParsedLong(parsed, KEY_RX_PACKETS);
1382 entry.txBytes = getParsedLong(parsed, KEY_TX_BYTES);
1383 entry.txPackets = getParsedLong(parsed, KEY_TX_PACKETS);
1384
1385 if (limitUid == UID_ALL || limitUid == entry.uid) {
1386 stats.addValues(entry);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001387 }
1388 }
Jeff Sharkey558a2322011-08-24 15:42:09 -07001389 } catch (NullPointerException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001390 throw new IllegalStateException("problem parsing line: " + line, e);
Jeff Sharkey558a2322011-08-24 15:42:09 -07001391 } catch (NumberFormatException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001392 throw new IllegalStateException("problem parsing line: " + line, e);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001393 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001394 throw new IllegalStateException("problem parsing line: " + line, e);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001395 } finally {
1396 IoUtils.closeQuietly(reader);
1397 }
1398
Jeff Sharkey4a971222011-06-11 22:16:55 -07001399 return stats;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001400 }
1401
Jeff Sharkeya63ba592011-07-19 23:47:12 -07001402 private static int getParsedInt(HashMap<String, String> parsed, String key) {
1403 final String value = parsed.get(key);
1404 return value != null ? Integer.parseInt(value) : 0;
1405 }
1406
1407 private static long getParsedLong(HashMap<String, String> parsed, String key) {
1408 final String value = parsed.get(key);
1409 return value != null ? Long.parseLong(value) : 0;
1410 }
1411
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001412 /**
1413 * Build {@link NetworkStats} with detailed UID statistics.
1414 *
1415 * @deprecated since this uses older "uid_stat" data, and doesn't provide
1416 * tag-level granularity or additional variables.
1417 */
1418 @Deprecated
1419 private NetworkStats getNetworkStatsDetailUidstat(int limitUid) {
1420 final String[] knownUids;
1421 if (limitUid == UID_ALL) {
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001422 knownUids = fileListWithoutNull(mStatsUid);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001423 } else {
1424 knownUids = new String[] { String.valueOf(limitUid) };
1425 }
1426
1427 final NetworkStats stats = new NetworkStats(
1428 SystemClock.elapsedRealtime(), knownUids.length);
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001429 final NetworkStats.Entry entry = new NetworkStats.Entry();
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001430 for (String uid : knownUids) {
1431 final int uidInt = Integer.parseInt(uid);
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001432 final File uidPath = new File(mStatsUid, uid);
1433
1434 entry.iface = IFACE_ALL;
1435 entry.uid = uidInt;
1436 entry.tag = TAG_NONE;
1437 entry.rxBytes = readSingleLongFromFile(new File(uidPath, "tcp_rcv"));
1438 entry.rxPackets = readSingleLongFromFile(new File(uidPath, "tcp_rcv_pkt"));
1439 entry.txBytes = readSingleLongFromFile(new File(uidPath, "tcp_snd"));
1440 entry.txPackets = readSingleLongFromFile(new File(uidPath, "tcp_snd_pkt"));
1441
1442 stats.addValues(entry);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001443 }
1444
1445 return stats;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001446 }
1447
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001448 @Override
1449 public NetworkStats getNetworkStatsTethering(String[] ifacePairs) {
1450 mContext.enforceCallingOrSelfPermission(
1451 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
1452
1453 if (ifacePairs.length % 2 != 0) {
1454 throw new IllegalArgumentException(
1455 "unexpected ifacePairs; length=" + ifacePairs.length);
1456 }
1457
1458 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 1);
1459 for (int i = 0; i < ifacePairs.length; i += 2) {
1460 final String ifaceIn = ifacePairs[i];
1461 final String ifaceOut = ifacePairs[i + 1];
1462 if (ifaceIn != null && ifaceOut != null) {
1463 stats.combineValues(getNetworkStatsTethering(ifaceIn, ifaceOut));
1464 }
1465 }
1466 return stats;
1467 }
1468
1469 private NetworkStats.Entry getNetworkStatsTethering(String ifaceIn, String ifaceOut) {
1470 final StringBuilder command = new StringBuilder();
1471 command.append("bandwidth gettetherstats ").append(ifaceIn).append(" ").append(ifaceOut);
1472
1473 final String rsp;
1474 try {
1475 rsp = mConnector.doCommand(command.toString()).get(0);
1476 } catch (NativeDaemonConnectorException e) {
1477 throw new IllegalStateException("Error communicating to native daemon", e);
1478 }
1479
1480 final String[] tok = rsp.split(" ");
1481 /* Expecting: "code ifaceIn ifaceOut rx_bytes rx_packets tx_bytes tx_packets" */
1482 if (tok.length != 7) {
1483 throw new IllegalStateException("Native daemon returned unexpected result: " + rsp);
1484 }
1485
1486 final int code;
1487 try {
1488 code = Integer.parseInt(tok[0]);
1489 } catch (NumberFormatException e) {
1490 throw new IllegalStateException(
1491 "Failed to parse native daemon return code for " + ifaceIn + " " + ifaceOut);
1492 }
1493 if (code != NetdResponseCode.TetheringStatsResult) {
1494 throw new IllegalStateException(
1495 "Unexpected return code from native daemon for " + ifaceIn + " " + ifaceOut);
1496 }
1497
1498 try {
1499 final NetworkStats.Entry entry = new NetworkStats.Entry();
1500 entry.iface = ifaceIn;
1501 entry.uid = UID_ALL;
1502 entry.set = SET_DEFAULT;
1503 entry.tag = TAG_NONE;
1504 entry.rxBytes = Long.parseLong(tok[3]);
1505 entry.rxPackets = Long.parseLong(tok[4]);
1506 entry.txBytes = Long.parseLong(tok[5]);
1507 entry.txPackets = Long.parseLong(tok[6]);
1508 return entry;
1509 } catch (NumberFormatException e) {
1510 throw new IllegalStateException(
1511 "problem parsing tethering stats for " + ifaceIn + " " + ifaceOut + ": " + e);
1512 }
1513 }
1514
San Mehatf0db6e12010-04-07 15:22:10 -07001515 public void setInterfaceThrottle(String iface, int rxKbps, int txKbps) {
San Mehat91cac642010-03-31 14:31:36 -07001516 mContext.enforceCallingOrSelfPermission(
1517 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -07001518 try {
1519 mConnector.doCommand(String.format(
1520 "interface setthrottle %s %d %d", iface, rxKbps, txKbps));
1521 } catch (NativeDaemonConnectorException e) {
1522 Slog.e(TAG, "Error communicating with native daemon to set throttle", e);
1523 }
San Mehat91cac642010-03-31 14:31:36 -07001524 }
1525
1526 private int getInterfaceThrottle(String iface, boolean rx) {
1527 mContext.enforceCallingOrSelfPermission(
1528 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
1529 try {
Kenny Roota80ce062010-06-01 13:23:53 -07001530 String rsp;
1531 try {
1532 rsp = mConnector.doCommand(
1533 String.format("interface getthrottle %s %s", iface,
1534 (rx ? "rx" : "tx"))).get(0);
1535 } catch (NativeDaemonConnectorException e) {
1536 Slog.e(TAG, "Error communicating with native daemon to getthrottle", e);
1537 return -1;
1538 }
1539
1540 String[] tok = rsp.split(" ");
1541 if (tok.length < 2) {
1542 Slog.e(TAG, "Malformed response to getthrottle command");
1543 return -1;
1544 }
1545
San Mehat91cac642010-03-31 14:31:36 -07001546 int code;
1547 try {
1548 code = Integer.parseInt(tok[0]);
1549 } catch (NumberFormatException nfe) {
1550 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
1551 return -1;
1552 }
1553 if ((rx && code != NetdResponseCode.InterfaceRxThrottleResult) || (
1554 !rx && code != NetdResponseCode.InterfaceTxThrottleResult)) {
1555 Slog.e(TAG, String.format("Unexpected response code %d", code));
1556 return -1;
1557 }
1558 return Integer.parseInt(tok[1]);
1559 } catch (Exception e) {
1560 Slog.e(TAG, String.format(
1561 "Failed to read interface %s throttle value", (rx ? "rx" : "tx")), e);
1562 }
1563 return -1;
1564 }
1565
1566 public int getInterfaceRxThrottle(String iface) {
1567 return getInterfaceThrottle(iface, true);
1568 }
1569
1570 public int getInterfaceTxThrottle(String iface) {
1571 return getInterfaceThrottle(iface, false);
1572 }
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001573
1574 /**
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001575 * Split given line into {@link ArrayList}.
1576 */
1577 private static void splitLine(String line, ArrayList<String> outSplit) {
1578 outSplit.clear();
1579
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001580 final StringTokenizer t = new StringTokenizer(line, " \t\n\r\f:");
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001581 while (t.hasMoreTokens()) {
1582 outSplit.add(t.nextToken());
1583 }
1584 }
1585
1586 /**
1587 * Zip the two given {@link ArrayList} as key and value pairs into
1588 * {@link HashMap}.
1589 */
1590 private static void parseLine(
1591 ArrayList<String> keys, ArrayList<String> values, HashMap<String, String> outParsed) {
1592 outParsed.clear();
1593
1594 final int size = Math.min(keys.size(), values.size());
1595 for (int i = 0; i < size; i++) {
1596 outParsed.put(keys.get(i), values.get(i));
1597 }
1598 }
1599
1600 /**
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001601 * Utility method to read a single plain-text {@link Long} from the given
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001602 * {@link File}, usually from a {@code /proc/} filesystem.
1603 */
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001604 private static long readSingleLongFromFile(File file) {
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001605 try {
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001606 final byte[] buffer = IoUtils.readFileAsByteArray(file.toString());
1607 return Long.parseLong(new String(buffer).trim());
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001608 } catch (NumberFormatException e) {
1609 return -1;
1610 } catch (IOException e) {
1611 return -1;
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001612 }
1613 }
Jean-Baptiste Querud5299ff2011-07-07 08:46:09 -07001614
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001615 /**
1616 * Wrapper for {@link File#list()} that returns empty array instead of
1617 * {@code null}.
1618 */
1619 private static String[] fileListWithoutNull(File file) {
1620 final String[] list = file.list();
1621 return list != null ? list : new String[0];
1622 }
1623
Mattias Falk7475c0c2011-04-04 16:10:36 +02001624 public void setDefaultInterfaceForDns(String iface) throws IllegalStateException {
1625 mContext.enforceCallingOrSelfPermission(
1626 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
1627 try {
1628 String cmd = "resolver setdefaultif " + iface;
1629
1630 mConnector.doCommand(cmd);
1631 } catch (NativeDaemonConnectorException e) {
1632 throw new IllegalStateException(
1633 "Error communicating with native daemon to set default interface", e);
1634 }
1635 }
1636
1637 public void setDnsServersForInterface(String iface, String[] servers)
1638 throws IllegalStateException {
1639 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE,
1640 "NetworkManagementService");
1641 try {
1642 String cmd = "resolver setifdns " + iface;
1643 for (String s : servers) {
Robert Greenwalt572b7042011-07-25 17:00:13 -07001644 InetAddress a = NetworkUtils.numericToInetAddress(s);
1645 if (a.isAnyLocalAddress() == false) {
1646 cmd += " " + a.getHostAddress();
Mattias Falk7475c0c2011-04-04 16:10:36 +02001647 }
1648 }
Mattias Falk7475c0c2011-04-04 16:10:36 +02001649 mConnector.doCommand(cmd);
Robert Greenwalt572b7042011-07-25 17:00:13 -07001650 } catch (IllegalArgumentException e) {
1651 throw new IllegalStateException("Error setting dnsn for interface", e);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001652 } catch (NativeDaemonConnectorException e) {
1653 throw new IllegalStateException(
Robert Greenwalt572b7042011-07-25 17:00:13 -07001654 "Error communicating with native daemon to set dns for interface", e);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001655 }
1656 }
1657
1658 public void flushDefaultDnsCache() throws IllegalStateException {
1659 mContext.enforceCallingOrSelfPermission(
1660 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
1661 try {
1662 String cmd = "resolver flushdefaultif";
1663
1664 mConnector.doCommand(cmd);
1665 } catch (NativeDaemonConnectorException e) {
1666 throw new IllegalStateException(
1667 "Error communicating with native deamon to flush default interface", e);
1668 }
1669 }
1670
1671 public void flushInterfaceDnsCache(String iface) throws IllegalStateException {
1672 mContext.enforceCallingOrSelfPermission(
1673 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
1674 try {
1675 String cmd = "resolver flushif " + iface;
1676
1677 mConnector.doCommand(cmd);
1678 } catch (NativeDaemonConnectorException e) {
1679 throw new IllegalStateException(
Robert Greenwalt572b7042011-07-25 17:00:13 -07001680 "Error communicating with native daemon to flush interface " + iface, e);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001681 }
1682 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07001683
1684 /** {@inheritDoc} */
1685 public void monitor() {
1686 if (mConnector != null) {
1687 mConnector.monitor();
1688 }
1689 }
Jeff Sharkey47eb1022011-08-25 17:48:52 -07001690
1691 @Override
1692 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1693 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
1694
1695 pw.print("Bandwidth control enabled: "); pw.println(mBandwidthControlEnabled);
1696
1697 synchronized (mQuotaLock) {
1698 pw.print("Active quota ifaces: "); pw.println(mActiveQuotaIfaces.toString());
1699 pw.print("Active alert ifaces: "); pw.println(mActiveAlertIfaces.toString());
1700 }
1701
1702 synchronized (mUidRejectOnQuota) {
1703 pw.print("UID reject on quota ifaces: [");
1704 final int size = mUidRejectOnQuota.size();
1705 for (int i = 0; i < size; i++) {
1706 pw.print(mUidRejectOnQuota.keyAt(i));
1707 if (i < size - 1) pw.print(",");
1708 }
1709 pw.println("]");
1710 }
1711 }
San Mehat873f2142010-01-14 10:25:07 -08001712}