blob: 85d8cece5401a56100f05adb863476fba58bbe0a [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 Sharkey4414cea2011-06-24 17:05:24 -0700101 private static final String KEY_IFACE = "iface";
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700102 private static final String KEY_UID = "uid_tag_int";
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700103 private static final String KEY_COUNTER_SET = "cnt_set";
104 private static final String KEY_TAG_HEX = "acct_tag_hex";
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700105 private static final String KEY_RX_BYTES = "rx_bytes";
106 private static final String KEY_RX_PACKETS = "rx_packets";
107 private static final String KEY_TX_BYTES = "tx_bytes";
108 private static final String KEY_TX_PACKETS = "tx_packets";
Jeff Sharkeyeedcb952011-05-17 14:55:15 -0700109
San Mehat873f2142010-01-14 10:25:07 -0800110 class NetdResponseCode {
JP Abgrall12b933d2011-07-14 18:09:22 -0700111 /* Keep in sync with system/netd/ResponseCode.h */
San Mehat873f2142010-01-14 10:25:07 -0800112 public static final int InterfaceListResult = 110;
113 public static final int TetherInterfaceListResult = 111;
114 public static final int TetherDnsFwdTgtListResult = 112;
San Mehat72759df2010-01-19 13:50:37 -0800115 public static final int TtyListResult = 113;
San Mehat873f2142010-01-14 10:25:07 -0800116
117 public static final int TetherStatusResult = 210;
118 public static final int IpFwdStatusResult = 211;
San Mehated4fc8a2010-01-22 12:28:36 -0800119 public static final int InterfaceGetCfgResult = 213;
Robert Greenwalte3253922010-02-18 09:23:25 -0800120 public static final int SoftapStatusResult = 214;
San Mehat91cac642010-03-31 14:31:36 -0700121 public static final int InterfaceRxCounterResult = 216;
122 public static final int InterfaceTxCounterResult = 217;
123 public static final int InterfaceRxThrottleResult = 218;
124 public static final int InterfaceTxThrottleResult = 219;
Robert Greenwalte3253922010-02-18 09:23:25 -0800125
126 public static final int InterfaceChange = 600;
JP Abgrall12b933d2011-07-14 18:09:22 -0700127 public static final int BandwidthControl = 601;
San Mehat873f2142010-01-14 10:25:07 -0800128 }
129
130 /**
131 * Binder context for this service
132 */
133 private Context mContext;
134
135 /**
136 * connector object for communicating with netd
137 */
138 private NativeDaemonConnector mConnector;
139
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700140 private Thread mThread;
141 private final CountDownLatch mConnectedSignal = new CountDownLatch(1);
142
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700143 // TODO: replace with RemoteCallbackList
San Mehat4d02d002010-01-22 16:07:46 -0800144 private ArrayList<INetworkManagementEventObserver> mObservers;
145
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700146 private Object mQuotaLock = new Object();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700147 /** Set of interfaces with active quotas. */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700148 private HashSet<String> mActiveQuotaIfaces = Sets.newHashSet();
149 /** Set of interfaces with active alerts. */
150 private HashSet<String> mActiveAlertIfaces = Sets.newHashSet();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700151 /** Set of UIDs with active reject rules. */
152 private SparseBooleanArray mUidRejectOnQuota = new SparseBooleanArray();
153
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700154 private volatile boolean mBandwidthControlEnabled;
Jeff Sharkey350083e2011-06-29 10:45:16 -0700155
San Mehat873f2142010-01-14 10:25:07 -0800156 /**
157 * Constructs a new NetworkManagementService instance
158 *
159 * @param context Binder context for this service
160 */
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700161 private NetworkManagementService(Context context, File procRoot) {
San Mehat873f2142010-01-14 10:25:07 -0800162 mContext = context;
San Mehat4d02d002010-01-22 16:07:46 -0800163 mObservers = new ArrayList<INetworkManagementEventObserver>();
164
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -0700165 mStatsUid = new File(procRoot, "uid_stat");
166 mStatsIface = new File(procRoot, "net/dev");
167 mStatsXtUid = new File(procRoot, "net/xt_qtaguid/stats");
168 mStatsXtIface = new File(procRoot, "net/xt_qtaguid/iface_stat");
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700169
Marco Nelissen62dbb222010-02-18 10:56:30 -0800170 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
171 return;
172 }
173
San Mehat873f2142010-01-14 10:25:07 -0800174 mConnector = new NativeDaemonConnector(
Kenny Root305bcbf2010-09-03 07:56:38 -0700175 new NetdCallbackReceiver(), "netd", 10, NETD_TAG);
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700176 mThread = new Thread(mConnector, NETD_TAG);
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700177
178 // Add ourself to the Watchdog monitors.
179 Watchdog.getInstance().addMonitor(this);
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700180 }
181
182 public static NetworkManagementService create(Context context) throws InterruptedException {
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700183 NetworkManagementService service = new NetworkManagementService(
184 context, new File("/proc/"));
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700185 if (DBG) Slog.d(TAG, "Creating NetworkManagementService");
186 service.mThread.start();
187 if (DBG) Slog.d(TAG, "Awaiting socket connection");
188 service.mConnectedSignal.await();
189 if (DBG) Slog.d(TAG, "Connected");
190 return service;
San Mehat873f2142010-01-14 10:25:07 -0800191 }
192
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700193 // @VisibleForTesting
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -0700194 public static NetworkManagementService createForTest(
195 Context context, File procRoot, boolean bandwidthControlEnabled) {
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700196 // TODO: eventually connect with mock netd
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -0700197 final NetworkManagementService service = new NetworkManagementService(context, procRoot);
198 service.mBandwidthControlEnabled = bandwidthControlEnabled;
199 return service;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700200 }
201
Jeff Sharkey350083e2011-06-29 10:45:16 -0700202 public void systemReady() {
Jeff Sharkey350083e2011-06-29 10:45:16 -0700203 // only enable bandwidth control when support exists, and requested by
204 // system setting.
Jeff Sharkey350083e2011-06-29 10:45:16 -0700205 final boolean hasKernelSupport = new File("/proc/net/xt_qtaguid/ctrl").exists();
206 final boolean shouldEnable =
Jeff Sharkey05355c32011-08-09 14:44:19 -0700207 Settings.Secure.getInt(mContext.getContentResolver(), NETSTATS_ENABLED, 1) != 0;
Jeff Sharkey350083e2011-06-29 10:45:16 -0700208
Jeff Sharkey350083e2011-06-29 10:45:16 -0700209 if (hasKernelSupport && shouldEnable) {
210 Slog.d(TAG, "enabling bandwidth control");
211 try {
212 mConnector.doCommand("bandwidth enable");
213 mBandwidthControlEnabled = true;
214 } catch (NativeDaemonConnectorException e) {
215 Slog.e(TAG, "problem enabling bandwidth controls", e);
216 }
217 } else {
218 Slog.d(TAG, "not enabling bandwidth control");
219 }
Jeff Sharkey62a2c8f2011-07-13 15:24:02 -0700220
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700221 SystemProperties.set(PROP_QTAGUID_ENABLED, mBandwidthControlEnabled ? "1" : "0");
Jeff Sharkey350083e2011-06-29 10:45:16 -0700222 }
223
San Mehat4d02d002010-01-22 16:07:46 -0800224 public void registerObserver(INetworkManagementEventObserver obs) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800225 Slog.d(TAG, "Registering observer");
San Mehat4d02d002010-01-22 16:07:46 -0800226 mObservers.add(obs);
227 }
228
229 public void unregisterObserver(INetworkManagementEventObserver obs) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800230 Slog.d(TAG, "Unregistering observer");
San Mehat4d02d002010-01-22 16:07:46 -0800231 mObservers.remove(mObservers.indexOf(obs));
232 }
233
234 /**
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700235 * Notify our observers of an interface status change
San Mehat4d02d002010-01-22 16:07:46 -0800236 */
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700237 private void notifyInterfaceStatusChanged(String iface, boolean up) {
San Mehat4d02d002010-01-22 16:07:46 -0800238 for (INetworkManagementEventObserver obs : mObservers) {
239 try {
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700240 obs.interfaceStatusChanged(iface, up);
241 } catch (Exception ex) {
242 Slog.w(TAG, "Observer notifier failed", ex);
243 }
244 }
245 }
246
247 /**
Mike J. Chenf59c7d02011-06-23 15:33:15 -0700248 * Notify our observers of an interface link state change
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700249 * (typically, an Ethernet cable has been plugged-in or unplugged).
250 */
251 private void notifyInterfaceLinkStateChanged(String iface, boolean up) {
252 for (INetworkManagementEventObserver obs : mObservers) {
253 try {
254 obs.interfaceLinkStateChanged(iface, up);
San Mehat4d02d002010-01-22 16:07:46 -0800255 } catch (Exception ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800256 Slog.w(TAG, "Observer notifier failed", ex);
San Mehat4d02d002010-01-22 16:07:46 -0800257 }
258 }
259 }
260
261 /**
262 * Notify our observers of an interface addition.
263 */
264 private void notifyInterfaceAdded(String iface) {
265 for (INetworkManagementEventObserver obs : mObservers) {
266 try {
267 obs.interfaceAdded(iface);
268 } catch (Exception ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800269 Slog.w(TAG, "Observer notifier failed", ex);
San Mehat4d02d002010-01-22 16:07:46 -0800270 }
271 }
272 }
273
274 /**
275 * Notify our observers of an interface removal.
276 */
277 private void notifyInterfaceRemoved(String iface) {
278 for (INetworkManagementEventObserver obs : mObservers) {
279 try {
280 obs.interfaceRemoved(iface);
281 } catch (Exception ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800282 Slog.w(TAG, "Observer notifier failed", ex);
San Mehat4d02d002010-01-22 16:07:46 -0800283 }
284 }
285 }
286
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700287 /**
JP Abgrall12b933d2011-07-14 18:09:22 -0700288 * Notify our observers of a limit reached.
289 */
290 private void notifyLimitReached(String limitName, String iface) {
291 for (INetworkManagementEventObserver obs : mObservers) {
292 try {
293 obs.limitReached(limitName, iface);
JP Abgrall12b933d2011-07-14 18:09:22 -0700294 } catch (Exception ex) {
295 Slog.w(TAG, "Observer notifier failed", ex);
296 }
297 }
298 }
299
300 /**
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700301 * Let us know the daemon is connected
302 */
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700303 protected void onDaemonConnected() {
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700304 if (DBG) Slog.d(TAG, "onConnected");
305 mConnectedSignal.countDown();
306 }
307
San Mehat4d02d002010-01-22 16:07:46 -0800308
San Mehat873f2142010-01-14 10:25:07 -0800309 //
310 // Netd Callback handling
311 //
312
313 class NetdCallbackReceiver implements INativeDaemonConnectorCallbacks {
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700314 /** {@inheritDoc} */
San Mehat873f2142010-01-14 10:25:07 -0800315 public void onDaemonConnected() {
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700316 NetworkManagementService.this.onDaemonConnected();
San Mehat873f2142010-01-14 10:25:07 -0800317 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700318
319 /** {@inheritDoc} */
San Mehat873f2142010-01-14 10:25:07 -0800320 public boolean onEvent(int code, String raw, String[] cooked) {
JP Abgrall12b933d2011-07-14 18:09:22 -0700321 switch (code) {
322 case NetdResponseCode.InterfaceChange:
323 /*
324 * a network interface change occured
325 * Format: "NNN Iface added <name>"
326 * "NNN Iface removed <name>"
327 * "NNN Iface changed <name> <up/down>"
328 * "NNN Iface linkstatus <name> <up/down>"
329 */
330 if (cooked.length < 4 || !cooked[1].equals("Iface")) {
331 throw new IllegalStateException(
332 String.format("Invalid event from daemon (%s)", raw));
333 }
334 if (cooked[2].equals("added")) {
335 notifyInterfaceAdded(cooked[3]);
336 return true;
337 } else if (cooked[2].equals("removed")) {
338 notifyInterfaceRemoved(cooked[3]);
339 return true;
340 } else if (cooked[2].equals("changed") && cooked.length == 5) {
341 notifyInterfaceStatusChanged(cooked[3], cooked[4].equals("up"));
342 return true;
343 } else if (cooked[2].equals("linkstate") && cooked.length == 5) {
344 notifyInterfaceLinkStateChanged(cooked[3], cooked[4].equals("up"));
345 return true;
346 }
Robert Greenwalte3253922010-02-18 09:23:25 -0800347 throw new IllegalStateException(
348 String.format("Invalid event from daemon (%s)", raw));
JP Abgrall12b933d2011-07-14 18:09:22 -0700349 // break;
350 case NetdResponseCode.BandwidthControl:
351 /*
352 * Bandwidth control needs some attention
353 * Format: "NNN limit alert <alertName> <ifaceName>"
354 */
355 if (cooked.length < 5 || !cooked[1].equals("limit")) {
356 throw new IllegalStateException(
357 String.format("Invalid event from daemon (%s)", raw));
358 }
359 if (cooked[2].equals("alert")) {
360 notifyLimitReached(cooked[3], cooked[4]);
361 return true;
362 }
363 throw new IllegalStateException(
364 String.format("Invalid event from daemon (%s)", raw));
365 // break;
366 default: break;
Robert Greenwalte3253922010-02-18 09:23:25 -0800367 }
368 return false;
San Mehat873f2142010-01-14 10:25:07 -0800369 }
370 }
371
San Mehated4fc8a2010-01-22 12:28:36 -0800372
San Mehat873f2142010-01-14 10:25:07 -0800373 //
374 // INetworkManagementService members
375 //
376
377 public String[] listInterfaces() throws IllegalStateException {
378 mContext.enforceCallingOrSelfPermission(
379 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
380
Kenny Roota80ce062010-06-01 13:23:53 -0700381 try {
382 return mConnector.doListCommand("interface list", NetdResponseCode.InterfaceListResult);
383 } catch (NativeDaemonConnectorException e) {
384 throw new IllegalStateException(
385 "Cannot communicate with native daemon to list interfaces");
386 }
San Mehated4fc8a2010-01-22 12:28:36 -0800387 }
388
389 public InterfaceConfiguration getInterfaceConfig(String iface) throws IllegalStateException {
Kenny Roota80ce062010-06-01 13:23:53 -0700390 String rsp;
391 try {
392 rsp = mConnector.doCommand("interface getcfg " + iface).get(0);
393 } catch (NativeDaemonConnectorException e) {
394 throw new IllegalStateException(
395 "Cannot communicate with native daemon to get interface config");
396 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800397 Slog.d(TAG, String.format("rsp <%s>", rsp));
San Mehated4fc8a2010-01-22 12:28:36 -0800398
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800399 // Rsp: 213 xx:xx:xx:xx:xx:xx yyy.yyy.yyy.yyy zzz [flag1 flag2 flag3]
San Mehated4fc8a2010-01-22 12:28:36 -0800400 StringTokenizer st = new StringTokenizer(rsp);
401
Kenny Roota80ce062010-06-01 13:23:53 -0700402 InterfaceConfiguration cfg;
San Mehated4fc8a2010-01-22 12:28:36 -0800403 try {
Kenny Roota80ce062010-06-01 13:23:53 -0700404 try {
405 int code = Integer.parseInt(st.nextToken(" "));
406 if (code != NetdResponseCode.InterfaceGetCfgResult) {
407 throw new IllegalStateException(
408 String.format("Expected code %d, but got %d",
409 NetdResponseCode.InterfaceGetCfgResult, code));
410 }
411 } catch (NumberFormatException nfe) {
San Mehated4fc8a2010-01-22 12:28:36 -0800412 throw new IllegalStateException(
Kenny Roota80ce062010-06-01 13:23:53 -0700413 String.format("Invalid response from daemon (%s)", rsp));
San Mehated4fc8a2010-01-22 12:28:36 -0800414 }
Kenny Roota80ce062010-06-01 13:23:53 -0700415
416 cfg = new InterfaceConfiguration();
417 cfg.hwAddr = st.nextToken(" ");
Robert Greenwalted126402011-01-28 15:34:55 -0800418 InetAddress addr = null;
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800419 int prefixLength = 0;
Kenny Roota80ce062010-06-01 13:23:53 -0700420 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800421 addr = NetworkUtils.numericToInetAddress(st.nextToken(" "));
422 } catch (IllegalArgumentException iae) {
423 Slog.e(TAG, "Failed to parse ipaddr", iae);
Kenny Roota80ce062010-06-01 13:23:53 -0700424 }
425
426 try {
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800427 prefixLength = Integer.parseInt(st.nextToken(" "));
428 } catch (NumberFormatException nfe) {
429 Slog.e(TAG, "Failed to parse prefixLength", nfe);
Kenny Roota80ce062010-06-01 13:23:53 -0700430 }
Robert Greenwalt04808c22010-12-13 17:01:41 -0800431
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800432 cfg.addr = new LinkAddress(addr, prefixLength);
Kenny Roota80ce062010-06-01 13:23:53 -0700433 cfg.interfaceFlags = st.nextToken("]").trim() +"]";
434 } catch (NoSuchElementException nsee) {
San Mehated4fc8a2010-01-22 12:28:36 -0800435 throw new IllegalStateException(
436 String.format("Invalid response from daemon (%s)", rsp));
437 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800438 Slog.d(TAG, String.format("flags <%s>", cfg.interfaceFlags));
San Mehated4fc8a2010-01-22 12:28:36 -0800439 return cfg;
440 }
441
442 public void setInterfaceConfig(
443 String iface, InterfaceConfiguration cfg) throws IllegalStateException {
Robert Greenwalted126402011-01-28 15:34:55 -0800444 LinkAddress linkAddr = cfg.addr;
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800445 if (linkAddr == null || linkAddr.getAddress() == null) {
446 throw new IllegalStateException("Null LinkAddress given");
Robert Greenwalted126402011-01-28 15:34:55 -0800447 }
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800448 String cmd = String.format("interface setcfg %s %s %d %s", iface,
449 linkAddr.getAddress().getHostAddress(),
450 linkAddr.getNetworkPrefixLength(),
451 cfg.interfaceFlags);
Kenny Roota80ce062010-06-01 13:23:53 -0700452 try {
453 mConnector.doCommand(cmd);
454 } catch (NativeDaemonConnectorException e) {
455 throw new IllegalStateException(
Robert Greenwalt81d5ad52010-12-16 11:27:38 -0800456 "Unable to communicate with native daemon to interface setcfg - " + e);
Kenny Roota80ce062010-06-01 13:23:53 -0700457 }
San Mehat873f2142010-01-14 10:25:07 -0800458 }
459
Irfan Sheriff7244c972011-08-05 20:40:45 -0700460 public void setInterfaceDown(String iface) throws IllegalStateException {
461 try {
462 InterfaceConfiguration ifcg = getInterfaceConfig(iface);
463 ifcg.interfaceFlags = ifcg.interfaceFlags.replace("up", "down");
464 setInterfaceConfig(iface, ifcg);
465 } catch (NativeDaemonConnectorException e) {
466 throw new IllegalStateException(
467 "Unable to communicate with native daemon for interface down - " + e);
468 }
469 }
470
471 public void setInterfaceUp(String iface) throws IllegalStateException {
472 try {
473 InterfaceConfiguration ifcg = getInterfaceConfig(iface);
474 ifcg.interfaceFlags = ifcg.interfaceFlags.replace("down", "up");
475 setInterfaceConfig(iface, ifcg);
476 } catch (NativeDaemonConnectorException e) {
477 throw new IllegalStateException(
478 "Unable to communicate with native daemon for interface up - " + e);
479 }
480 }
481
Irfan Sherifff5600612011-06-16 10:26:28 -0700482 /* TODO: This is right now a IPv4 only function. Works for wifi which loses its
483 IPv6 addresses on interface down, but we need to do full clean up here */
484 public void clearInterfaceAddresses(String iface) throws IllegalStateException {
485 String cmd = String.format("interface clearaddrs %s", iface);
486 try {
487 mConnector.doCommand(cmd);
488 } catch (NativeDaemonConnectorException e) {
489 throw new IllegalStateException(
490 "Unable to communicate with native daemon to interface clearallips - " + e);
491 }
492 }
493
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700494 public void addRoute(String interfaceName, RouteInfo route) {
495 modifyRoute(interfaceName, ADD, route);
496 }
497
498 public void removeRoute(String interfaceName, RouteInfo route) {
499 modifyRoute(interfaceName, REMOVE, route);
500 }
501
502 private void modifyRoute(String interfaceName, int action, RouteInfo route) {
503 ArrayList<String> rsp;
504
505 StringBuilder cmd;
506
507 switch (action) {
508 case ADD:
509 {
510 cmd = new StringBuilder("interface route add " + interfaceName);
511 break;
512 }
513 case REMOVE:
514 {
515 cmd = new StringBuilder("interface route remove " + interfaceName);
516 break;
517 }
518 default:
519 throw new IllegalStateException("Unknown action type " + action);
520 }
521
522 // create triplet: dest-ip-addr prefixlength gateway-ip-addr
523 LinkAddress la = route.getDestination();
524 cmd.append(' ');
525 cmd.append(la.getAddress().getHostAddress());
526 cmd.append(' ');
527 cmd.append(la.getNetworkPrefixLength());
528 cmd.append(' ');
529 if (route.getGateway() == null) {
530 if (la.getAddress() instanceof Inet4Address) {
531 cmd.append("0.0.0.0");
532 } else {
533 cmd.append ("::0");
534 }
535 } else {
536 cmd.append(route.getGateway().getHostAddress());
537 }
538 try {
539 rsp = mConnector.doCommand(cmd.toString());
540 } catch (NativeDaemonConnectorException e) {
541 throw new IllegalStateException(
542 "Unable to communicate with native dameon to add routes - "
543 + e);
544 }
545
546 for (String line : rsp) {
547 Log.v(TAG, "add route response is " + line);
548 }
549 }
550
551 private ArrayList<String> readRouteList(String filename) {
552 FileInputStream fstream = null;
553 ArrayList<String> list = new ArrayList<String>();
554
555 try {
556 fstream = new FileInputStream(filename);
557 DataInputStream in = new DataInputStream(fstream);
558 BufferedReader br = new BufferedReader(new InputStreamReader(in));
559 String s;
560
561 // throw away the title line
562
563 while (((s = br.readLine()) != null) && (s.length() != 0)) {
564 list.add(s);
565 }
566 } catch (IOException ex) {
567 // return current list, possibly empty
568 } finally {
569 if (fstream != null) {
570 try {
571 fstream.close();
572 } catch (IOException ex) {}
573 }
574 }
575
576 return list;
577 }
578
579 public RouteInfo[] getRoutes(String interfaceName) {
580 ArrayList<RouteInfo> routes = new ArrayList<RouteInfo>();
581
582 // v4 routes listed as:
583 // iface dest-addr gateway-addr flags refcnt use metric netmask mtu window IRTT
584 for (String s : readRouteList("/proc/net/route")) {
585 String[] fields = s.split("\t");
586
587 if (fields.length > 7) {
588 String iface = fields[0];
589
590 if (interfaceName.equals(iface)) {
591 String dest = fields[1];
592 String gate = fields[2];
593 String flags = fields[3]; // future use?
594 String mask = fields[7];
595 try {
596 // address stored as a hex string, ex: 0014A8C0
597 InetAddress destAddr =
598 NetworkUtils.intToInetAddress((int)Long.parseLong(dest, 16));
599 int prefixLength =
600 NetworkUtils.netmaskIntToPrefixLength(
601 (int)Long.parseLong(mask, 16));
602 LinkAddress linkAddress = new LinkAddress(destAddr, prefixLength);
603
604 // address stored as a hex string, ex 0014A8C0
605 InetAddress gatewayAddr =
606 NetworkUtils.intToInetAddress((int)Long.parseLong(gate, 16));
607
608 RouteInfo route = new RouteInfo(linkAddress, gatewayAddr);
609 routes.add(route);
610 } catch (Exception e) {
611 Log.e(TAG, "Error parsing route " + s + " : " + e);
612 continue;
613 }
614 }
615 }
616 }
617
618 // v6 routes listed as:
619 // dest-addr prefixlength ?? ?? gateway-addr ?? ?? ?? ?? iface
620 for (String s : readRouteList("/proc/net/ipv6_route")) {
621 String[]fields = s.split("\\s+");
622 if (fields.length > 9) {
623 String iface = fields[9].trim();
624 if (interfaceName.equals(iface)) {
625 String dest = fields[0];
626 String prefix = fields[1];
627 String gate = fields[4];
628
629 try {
630 // prefix length stored as a hex string, ex 40
631 int prefixLength = Integer.parseInt(prefix, 16);
632
633 // address stored as a 32 char hex string
634 // ex fe800000000000000000000000000000
635 InetAddress destAddr = NetworkUtils.hexToInet6Address(dest);
636 LinkAddress linkAddress = new LinkAddress(destAddr, prefixLength);
637
638 InetAddress gateAddr = NetworkUtils.hexToInet6Address(gate);
639
640 RouteInfo route = new RouteInfo(linkAddress, gateAddr);
641 routes.add(route);
642 } catch (Exception e) {
643 Log.e(TAG, "Error parsing route " + s + " : " + e);
644 continue;
645 }
646 }
647 }
648 }
649 return (RouteInfo[]) routes.toArray(new RouteInfo[0]);
650 }
651
San Mehat873f2142010-01-14 10:25:07 -0800652 public void shutdown() {
653 if (mContext.checkCallingOrSelfPermission(
654 android.Manifest.permission.SHUTDOWN)
655 != PackageManager.PERMISSION_GRANTED) {
656 throw new SecurityException("Requires SHUTDOWN permission");
657 }
658
Joe Onorato8a9b2202010-02-26 18:56:32 -0800659 Slog.d(TAG, "Shutting down");
San Mehat873f2142010-01-14 10:25:07 -0800660 }
661
662 public boolean getIpForwardingEnabled() throws IllegalStateException{
663 mContext.enforceCallingOrSelfPermission(
664 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
665
Kenny Roota80ce062010-06-01 13:23:53 -0700666 ArrayList<String> rsp;
667 try {
668 rsp = mConnector.doCommand("ipfwd status");
669 } catch (NativeDaemonConnectorException e) {
670 throw new IllegalStateException(
671 "Unable to communicate with native daemon to ipfwd status");
672 }
San Mehat873f2142010-01-14 10:25:07 -0800673
674 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700675 String[] tok = line.split(" ");
676 if (tok.length < 3) {
677 Slog.e(TAG, "Malformed response from native daemon: " + line);
678 return false;
679 }
680
San Mehat873f2142010-01-14 10:25:07 -0800681 int code = Integer.parseInt(tok[0]);
682 if (code == NetdResponseCode.IpFwdStatusResult) {
683 // 211 Forwarding <enabled/disabled>
Kenny Roota80ce062010-06-01 13:23:53 -0700684 return "enabled".equals(tok[2]);
San Mehat873f2142010-01-14 10:25:07 -0800685 } else {
686 throw new IllegalStateException(String.format("Unexpected response code %d", code));
687 }
688 }
689 throw new IllegalStateException("Got an empty response");
690 }
691
692 public void setIpForwardingEnabled(boolean enable) throws IllegalStateException {
693 mContext.enforceCallingOrSelfPermission(
694 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
695 mConnector.doCommand(String.format("ipfwd %sable", (enable ? "en" : "dis")));
696 }
697
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -0700698 public void startTethering(String[] dhcpRange)
San Mehat873f2142010-01-14 10:25:07 -0800699 throws IllegalStateException {
700 mContext.enforceCallingOrSelfPermission(
701 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -0700702 // cmd is "tether start first_start first_stop second_start second_stop ..."
703 // an odd number of addrs will fail
704 String cmd = "tether start";
705 for (String d : dhcpRange) {
706 cmd += " " + d;
707 }
Kenny Roota80ce062010-06-01 13:23:53 -0700708
709 try {
710 mConnector.doCommand(cmd);
711 } catch (NativeDaemonConnectorException e) {
712 throw new IllegalStateException("Unable to communicate to native daemon");
713 }
San Mehat873f2142010-01-14 10:25:07 -0800714 }
715
716 public void stopTethering() throws IllegalStateException {
717 mContext.enforceCallingOrSelfPermission(
718 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700719 try {
720 mConnector.doCommand("tether stop");
721 } catch (NativeDaemonConnectorException e) {
722 throw new IllegalStateException("Unable to communicate to native daemon to stop tether");
723 }
San Mehat873f2142010-01-14 10:25:07 -0800724 }
725
726 public boolean isTetheringStarted() throws IllegalStateException {
727 mContext.enforceCallingOrSelfPermission(
728 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
729
Kenny Roota80ce062010-06-01 13:23:53 -0700730 ArrayList<String> rsp;
731 try {
732 rsp = mConnector.doCommand("tether status");
733 } catch (NativeDaemonConnectorException e) {
734 throw new IllegalStateException(
735 "Unable to communicate to native daemon to get tether status");
736 }
San Mehat873f2142010-01-14 10:25:07 -0800737
738 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700739 String[] tok = line.split(" ");
740 if (tok.length < 3) {
741 throw new IllegalStateException("Malformed response for tether status: " + line);
742 }
San Mehat873f2142010-01-14 10:25:07 -0800743 int code = Integer.parseInt(tok[0]);
744 if (code == NetdResponseCode.TetherStatusResult) {
745 // XXX: Tethering services <started/stopped> <TBD>...
Kenny Roota80ce062010-06-01 13:23:53 -0700746 return "started".equals(tok[2]);
San Mehat873f2142010-01-14 10:25:07 -0800747 } else {
748 throw new IllegalStateException(String.format("Unexpected response code %d", code));
749 }
750 }
751 throw new IllegalStateException("Got an empty response");
752 }
753
754 public void tetherInterface(String iface) throws IllegalStateException {
755 mContext.enforceCallingOrSelfPermission(
756 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700757 try {
758 mConnector.doCommand("tether interface add " + iface);
759 } catch (NativeDaemonConnectorException e) {
760 throw new IllegalStateException(
761 "Unable to communicate to native daemon for adding tether interface");
762 }
San Mehat873f2142010-01-14 10:25:07 -0800763 }
764
765 public void untetherInterface(String iface) {
766 mContext.enforceCallingOrSelfPermission(
767 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700768 try {
769 mConnector.doCommand("tether interface remove " + iface);
770 } catch (NativeDaemonConnectorException e) {
771 throw new IllegalStateException(
772 "Unable to communicate to native daemon for removing tether interface");
773 }
San Mehat873f2142010-01-14 10:25:07 -0800774 }
775
776 public String[] listTetheredInterfaces() throws IllegalStateException {
777 mContext.enforceCallingOrSelfPermission(
778 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700779 try {
780 return mConnector.doListCommand(
781 "tether interface list", NetdResponseCode.TetherInterfaceListResult);
782 } catch (NativeDaemonConnectorException e) {
783 throw new IllegalStateException(
784 "Unable to communicate to native daemon for listing tether interfaces");
785 }
San Mehat873f2142010-01-14 10:25:07 -0800786 }
787
788 public void setDnsForwarders(String[] dns) throws IllegalStateException {
789 mContext.enforceCallingOrSelfPermission(
790 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
791 try {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800792 String cmd = "tether dns set";
San Mehat873f2142010-01-14 10:25:07 -0800793 for (String s : dns) {
Robert Greenwalte5903732011-02-22 16:00:42 -0800794 cmd += " " + NetworkUtils.numericToInetAddress(s).getHostAddress();
San Mehat873f2142010-01-14 10:25:07 -0800795 }
Kenny Roota80ce062010-06-01 13:23:53 -0700796 try {
797 mConnector.doCommand(cmd);
798 } catch (NativeDaemonConnectorException e) {
799 throw new IllegalStateException(
800 "Unable to communicate to native daemon for setting tether dns");
801 }
Robert Greenwalte5903732011-02-22 16:00:42 -0800802 } catch (IllegalArgumentException e) {
San Mehat873f2142010-01-14 10:25:07 -0800803 throw new IllegalStateException("Error resolving dns name", e);
804 }
805 }
806
807 public String[] getDnsForwarders() throws IllegalStateException {
808 mContext.enforceCallingOrSelfPermission(
809 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700810 try {
811 return mConnector.doListCommand(
812 "tether dns list", NetdResponseCode.TetherDnsFwdTgtListResult);
813 } catch (NativeDaemonConnectorException e) {
814 throw new IllegalStateException(
815 "Unable to communicate to native daemon for listing tether dns");
816 }
San Mehat873f2142010-01-14 10:25:07 -0800817 }
818
819 public void enableNat(String internalInterface, String externalInterface)
820 throws IllegalStateException {
821 mContext.enforceCallingOrSelfPermission(
822 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700823 try {
824 mConnector.doCommand(
825 String.format("nat enable %s %s", internalInterface, externalInterface));
826 } catch (NativeDaemonConnectorException e) {
827 throw new IllegalStateException(
828 "Unable to communicate to native daemon for enabling NAT interface");
829 }
San Mehat873f2142010-01-14 10:25:07 -0800830 }
831
832 public void disableNat(String internalInterface, String externalInterface)
833 throws IllegalStateException {
834 mContext.enforceCallingOrSelfPermission(
835 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700836 try {
837 mConnector.doCommand(
838 String.format("nat disable %s %s", internalInterface, externalInterface));
839 } catch (NativeDaemonConnectorException e) {
840 throw new IllegalStateException(
841 "Unable to communicate to native daemon for disabling NAT interface");
842 }
San Mehat873f2142010-01-14 10:25:07 -0800843 }
San Mehat72759df2010-01-19 13:50:37 -0800844
845 public String[] listTtys() throws IllegalStateException {
846 mContext.enforceCallingOrSelfPermission(
847 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700848 try {
849 return mConnector.doListCommand("list_ttys", NetdResponseCode.TtyListResult);
850 } catch (NativeDaemonConnectorException e) {
851 throw new IllegalStateException(
852 "Unable to communicate to native daemon for listing TTYs");
853 }
San Mehat72759df2010-01-19 13:50:37 -0800854 }
855
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800856 public void attachPppd(String tty, String localAddr, String remoteAddr, String dns1Addr,
857 String dns2Addr) throws IllegalStateException {
San Mehat72759df2010-01-19 13:50:37 -0800858 try {
859 mContext.enforceCallingOrSelfPermission(
860 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800861 mConnector.doCommand(String.format("pppd attach %s %s %s %s %s", tty,
Robert Greenwalte5903732011-02-22 16:00:42 -0800862 NetworkUtils.numericToInetAddress(localAddr).getHostAddress(),
863 NetworkUtils.numericToInetAddress(remoteAddr).getHostAddress(),
864 NetworkUtils.numericToInetAddress(dns1Addr).getHostAddress(),
865 NetworkUtils.numericToInetAddress(dns2Addr).getHostAddress()));
866 } catch (IllegalArgumentException e) {
San Mehat72759df2010-01-19 13:50:37 -0800867 throw new IllegalStateException("Error resolving addr", e);
Kenny Roota80ce062010-06-01 13:23:53 -0700868 } catch (NativeDaemonConnectorException e) {
869 throw new IllegalStateException("Error communicating to native daemon to attach pppd", e);
San Mehat72759df2010-01-19 13:50:37 -0800870 }
871 }
872
873 public void detachPppd(String tty) throws IllegalStateException {
874 mContext.enforceCallingOrSelfPermission(
875 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700876 try {
877 mConnector.doCommand(String.format("pppd detach %s", tty));
878 } catch (NativeDaemonConnectorException e) {
879 throw new IllegalStateException("Error communicating to native daemon to detach pppd", e);
880 }
San Mehat72759df2010-01-19 13:50:37 -0800881 }
Robert Greenwaltce1200d2010-02-18 11:25:54 -0800882
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700883 public void startAccessPoint(WifiConfiguration wifiConfig, String wlanIface, String softapIface)
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800884 throws IllegalStateException {
885 mContext.enforceCallingOrSelfPermission(
886 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
887 mContext.enforceCallingOrSelfPermission(
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700888 android.Manifest.permission.CHANGE_WIFI_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700889 try {
Irfan Sheriffcb30b222011-07-29 20:54:52 -0700890 wifiFirmwareReload(wlanIface, "AP");
Kenny Roota80ce062010-06-01 13:23:53 -0700891 mConnector.doCommand(String.format("softap start " + wlanIface));
892 if (wifiConfig == null) {
893 mConnector.doCommand(String.format("softap set " + wlanIface + " " + softapIface));
894 } else {
895 /**
896 * softap set arg1 arg2 arg3 [arg4 arg5 arg6 arg7 arg8]
897 * argv1 - wlan interface
898 * argv2 - softap interface
899 * argv3 - SSID
900 * argv4 - Security
901 * argv5 - Key
902 * argv6 - Channel
903 * argv7 - Preamble
904 * argv8 - Max SCB
905 */
Irfan Sheriffec8d23a2011-02-16 17:00:33 -0800906 String str = String.format("softap set " + wlanIface + " " + softapIface +
907 " %s %s %s", convertQuotedString(wifiConfig.SSID),
908 getSecurityType(wifiConfig),
909 convertQuotedString(wifiConfig.preSharedKey));
Kenny Roota80ce062010-06-01 13:23:53 -0700910 mConnector.doCommand(str);
911 }
912 mConnector.doCommand(String.format("softap startap"));
913 } catch (NativeDaemonConnectorException e) {
914 throw new IllegalStateException("Error communicating to native daemon to start softap", e);
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800915 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800916 }
917
Irfan Sheriffa6e559e2010-05-24 14:55:42 -0700918 private String convertQuotedString(String s) {
Irfan Sheriff7baec0f2010-05-26 17:16:47 -0700919 if (s == null) {
920 return s;
921 }
922 /* Replace \ with \\, then " with \" and add quotes at end */
923 return '"' + s.replaceAll("\\\\","\\\\\\\\").replaceAll("\"","\\\\\"") + '"';
Irfan Sheriffa6e559e2010-05-24 14:55:42 -0700924 }
925
Irfan Sheriffec8d23a2011-02-16 17:00:33 -0800926 private String getSecurityType(WifiConfiguration wifiConfig) {
927 switch (wifiConfig.getAuthType()) {
928 case KeyMgmt.WPA_PSK:
929 return "wpa-psk";
930 case KeyMgmt.WPA2_PSK:
931 return "wpa2-psk";
932 default:
933 return "open";
934 }
935 }
936
Irfan Sheriffcb30b222011-07-29 20:54:52 -0700937 /* @param mode can be "AP", "STA" or "P2P" */
938 public void wifiFirmwareReload(String wlanIface, String mode) throws IllegalStateException {
939 mContext.enforceCallingOrSelfPermission(
940 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
941 mContext.enforceCallingOrSelfPermission(
942 android.Manifest.permission.CHANGE_WIFI_STATE, "NetworkManagementService");
943
944 try {
945 mConnector.doCommand(String.format("softap fwreload " + wlanIface + " " + mode));
946 } catch (NativeDaemonConnectorException e) {
947 throw new IllegalStateException("Error communicating to native daemon ", e);
948 }
949 }
950
Irfan Sheriff23eb2972011-07-22 15:21:10 -0700951 public void stopAccessPoint(String wlanIface) throws IllegalStateException {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800952 mContext.enforceCallingOrSelfPermission(
953 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
954 mContext.enforceCallingOrSelfPermission(
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700955 android.Manifest.permission.CHANGE_WIFI_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700956 try {
957 mConnector.doCommand("softap stopap");
Irfan Sheriff23eb2972011-07-22 15:21:10 -0700958 mConnector.doCommand("softap stop " + wlanIface);
Irfan Sheriffcb30b222011-07-29 20:54:52 -0700959 wifiFirmwareReload(wlanIface, "STA");
Kenny Roota80ce062010-06-01 13:23:53 -0700960 } catch (NativeDaemonConnectorException e) {
961 throw new IllegalStateException("Error communicating to native daemon to stop soft AP",
962 e);
963 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800964 }
965
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700966 public void setAccessPoint(WifiConfiguration wifiConfig, String wlanIface, String softapIface)
967 throws IllegalStateException {
968 mContext.enforceCallingOrSelfPermission(
969 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
970 mContext.enforceCallingOrSelfPermission(
971 android.Manifest.permission.CHANGE_WIFI_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700972 try {
973 if (wifiConfig == null) {
974 mConnector.doCommand(String.format("softap set " + wlanIface + " " + softapIface));
975 } else {
976 String str = String.format("softap set " + wlanIface + " " + softapIface
977 + " %s %s %s", convertQuotedString(wifiConfig.SSID),
Irfan Sheriffec8d23a2011-02-16 17:00:33 -0800978 getSecurityType(wifiConfig),
Kenny Roota80ce062010-06-01 13:23:53 -0700979 convertQuotedString(wifiConfig.preSharedKey));
980 mConnector.doCommand(str);
981 }
982 } catch (NativeDaemonConnectorException e) {
983 throw new IllegalStateException("Error communicating to native daemon to set soft AP",
984 e);
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700985 }
986 }
San Mehat91cac642010-03-31 14:31:36 -0700987
988 private long getInterfaceCounter(String iface, boolean rx) {
989 mContext.enforceCallingOrSelfPermission(
990 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
991 try {
Kenny Roota80ce062010-06-01 13:23:53 -0700992 String rsp;
993 try {
994 rsp = mConnector.doCommand(
995 String.format("interface read%scounter %s", (rx ? "rx" : "tx"), iface)).get(0);
996 } catch (NativeDaemonConnectorException e1) {
997 Slog.e(TAG, "Error communicating with native daemon", e1);
998 return -1;
999 }
1000
1001 String[] tok = rsp.split(" ");
1002 if (tok.length < 2) {
1003 Slog.e(TAG, String.format("Malformed response for reading %s interface",
1004 (rx ? "rx" : "tx")));
1005 return -1;
1006 }
1007
San Mehat91cac642010-03-31 14:31:36 -07001008 int code;
1009 try {
1010 code = Integer.parseInt(tok[0]);
1011 } catch (NumberFormatException nfe) {
1012 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
1013 return -1;
1014 }
1015 if ((rx && code != NetdResponseCode.InterfaceRxCounterResult) || (
1016 !rx && code != NetdResponseCode.InterfaceTxCounterResult)) {
1017 Slog.e(TAG, String.format("Unexpected response code %d", code));
1018 return -1;
1019 }
1020 return Long.parseLong(tok[1]);
1021 } catch (Exception e) {
1022 Slog.e(TAG, String.format(
1023 "Failed to read interface %s counters", (rx ? "rx" : "tx")), e);
1024 }
1025 return -1;
1026 }
1027
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001028 @Override
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001029 public NetworkStats getNetworkStatsSummary() {
1030 mContext.enforceCallingOrSelfPermission(
1031 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
1032
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001033 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 6);
1034 final NetworkStats.Entry entry = new NetworkStats.Entry();
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001035
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001036 final ArrayList<String> values = Lists.newArrayList();
1037
1038 BufferedReader reader = null;
1039 try {
1040 reader = new BufferedReader(new FileReader(mStatsIface));
1041
1042 // skip first two header lines
1043 reader.readLine();
1044 reader.readLine();
1045
1046 // parse remaining lines
1047 String line;
1048 while ((line = reader.readLine()) != null) {
1049 splitLine(line, values);
1050
1051 try {
1052 entry.iface = values.get(0);
1053 entry.uid = UID_ALL;
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001054 entry.set = SET_DEFAULT;
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001055 entry.tag = TAG_NONE;
1056 entry.rxBytes = Long.parseLong(values.get(1));
1057 entry.rxPackets = Long.parseLong(values.get(2));
1058 entry.txBytes = Long.parseLong(values.get(9));
1059 entry.txPackets = Long.parseLong(values.get(10));
1060
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001061 stats.addValues(entry);
1062 } catch (NumberFormatException e) {
1063 Slog.w(TAG, "problem parsing stats row '" + line + "': " + e);
1064 }
1065 }
Jeff Sharkey558a2322011-08-24 15:42:09 -07001066 } catch (NullPointerException e) {
1067 throw new IllegalStateException("problem parsing stats: " + e);
1068 } catch (NumberFormatException e) {
1069 throw new IllegalStateException("problem parsing stats: " + e);
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001070 } catch (IOException e) {
Jeff Sharkey558a2322011-08-24 15:42:09 -07001071 throw new IllegalStateException("problem parsing stats: " + e);
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001072 } finally {
1073 IoUtils.closeQuietly(reader);
1074 }
1075
Jeff Sharkey47eb1022011-08-25 17:48:52 -07001076 // splice in historical stats not reflected in mStatsIface
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001077 if (mBandwidthControlEnabled) {
Jeff Sharkey47eb1022011-08-25 17:48:52 -07001078 for (String iface : fileListWithoutNull(mStatsXtIface)) {
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001079 final File ifacePath = new File(mStatsXtIface, iface);
1080
1081 entry.iface = iface;
1082 entry.uid = UID_ALL;
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001083 entry.set = SET_DEFAULT;
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001084 entry.tag = TAG_NONE;
1085 entry.rxBytes = readSingleLongFromFile(new File(ifacePath, "rx_bytes"));
1086 entry.rxPackets = readSingleLongFromFile(new File(ifacePath, "rx_packets"));
1087 entry.txBytes = readSingleLongFromFile(new File(ifacePath, "tx_bytes"));
1088 entry.txPackets = readSingleLongFromFile(new File(ifacePath, "tx_packets"));
1089
Jeff Sharkey47eb1022011-08-25 17:48:52 -07001090 stats.combineValues(entry);
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001091 }
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001092 }
1093
Jeff Sharkey4a971222011-06-11 22:16:55 -07001094 return stats;
San Mehat91cac642010-03-31 14:31:36 -07001095 }
1096
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001097 @Override
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001098 public NetworkStats getNetworkStatsDetail() {
1099 mContext.enforceCallingOrSelfPermission(
1100 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
1101
Jeff Sharkey350083e2011-06-29 10:45:16 -07001102 if (mBandwidthControlEnabled) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001103 return getNetworkStatsDetailNetfilter(UID_ALL);
1104 } else {
1105 return getNetworkStatsDetailUidstat(UID_ALL);
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001106 }
San Mehat91cac642010-03-31 14:31:36 -07001107 }
1108
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001109 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001110 public void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001111 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1112
Jeff Sharkey350083e2011-06-29 10:45:16 -07001113 // silently discard when control disabled
1114 // TODO: eventually migrate to be always enabled
1115 if (!mBandwidthControlEnabled) return;
1116
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001117 synchronized (mQuotaLock) {
1118 if (mActiveQuotaIfaces.contains(iface)) {
1119 throw new IllegalStateException("iface " + iface + " already has quota");
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001120 }
1121
1122 final StringBuilder command = new StringBuilder();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001123 command.append("bandwidth setiquota ").append(iface).append(" ").append(quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001124
1125 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001126 // TODO: support quota shared across interfaces
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001127 mConnector.doCommand(command.toString());
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001128 mActiveQuotaIfaces.add(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001129 } catch (NativeDaemonConnectorException e) {
1130 throw new IllegalStateException("Error communicating to native daemon", e);
1131 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001132 }
1133 }
1134
1135 @Override
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001136 public void removeInterfaceQuota(String iface) {
1137 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1138
Jeff Sharkey350083e2011-06-29 10:45:16 -07001139 // silently discard when control disabled
1140 // TODO: eventually migrate to be always enabled
1141 if (!mBandwidthControlEnabled) return;
1142
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001143 synchronized (mQuotaLock) {
1144 if (!mActiveQuotaIfaces.contains(iface)) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001145 // TODO: eventually consider throwing
1146 return;
1147 }
1148
1149 final StringBuilder command = new StringBuilder();
1150 command.append("bandwidth removeiquota ").append(iface);
1151
1152 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001153 // TODO: support quota shared across interfaces
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001154 mConnector.doCommand(command.toString());
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001155 mActiveQuotaIfaces.remove(iface);
1156 mActiveAlertIfaces.remove(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001157 } catch (NativeDaemonConnectorException e) {
1158 throw new IllegalStateException("Error communicating to native daemon", e);
1159 }
1160 }
1161 }
1162
1163 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001164 public void setInterfaceAlert(String iface, long alertBytes) {
1165 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1166
1167 // silently discard when control disabled
1168 // TODO: eventually migrate to be always enabled
1169 if (!mBandwidthControlEnabled) return;
1170
1171 // quick sanity check
1172 if (!mActiveQuotaIfaces.contains(iface)) {
1173 throw new IllegalStateException("setting alert requires existing quota on iface");
1174 }
1175
1176 synchronized (mQuotaLock) {
1177 if (mActiveAlertIfaces.contains(iface)) {
1178 throw new IllegalStateException("iface " + iface + " already has alert");
1179 }
1180
1181 final StringBuilder command = new StringBuilder();
1182 command.append("bandwidth setinterfacealert ").append(iface).append(" ").append(
1183 alertBytes);
1184
1185 try {
1186 // TODO: support alert shared across interfaces
1187 mConnector.doCommand(command.toString());
1188 mActiveAlertIfaces.add(iface);
1189 } catch (NativeDaemonConnectorException e) {
1190 throw new IllegalStateException("Error communicating to native daemon", e);
1191 }
1192 }
1193 }
1194
1195 @Override
1196 public void removeInterfaceAlert(String iface) {
1197 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1198
1199 // silently discard when control disabled
1200 // TODO: eventually migrate to be always enabled
1201 if (!mBandwidthControlEnabled) return;
1202
1203 synchronized (mQuotaLock) {
1204 if (!mActiveAlertIfaces.contains(iface)) {
1205 // TODO: eventually consider throwing
1206 return;
1207 }
1208
1209 final StringBuilder command = new StringBuilder();
1210 command.append("bandwidth removeinterfacealert ").append(iface);
1211
1212 try {
1213 // TODO: support alert shared across interfaces
1214 mConnector.doCommand(command.toString());
1215 mActiveAlertIfaces.remove(iface);
1216 } catch (NativeDaemonConnectorException e) {
1217 throw new IllegalStateException("Error communicating to native daemon", e);
1218 }
1219 }
1220 }
1221
1222 @Override
1223 public void setGlobalAlert(long alertBytes) {
1224 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1225
1226 // silently discard when control disabled
1227 // TODO: eventually migrate to be always enabled
1228 if (!mBandwidthControlEnabled) return;
1229
1230 final StringBuilder command = new StringBuilder();
1231 command.append("bandwidth setglobalalert ").append(alertBytes);
1232
1233 try {
1234 mConnector.doCommand(command.toString());
1235 } catch (NativeDaemonConnectorException e) {
1236 throw new IllegalStateException("Error communicating to native daemon", e);
1237 }
1238 }
1239
1240 @Override
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001241 public void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
1242 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1243
Jeff Sharkey350083e2011-06-29 10:45:16 -07001244 // silently discard when control disabled
1245 // TODO: eventually migrate to be always enabled
1246 if (!mBandwidthControlEnabled) return;
1247
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001248 synchronized (mUidRejectOnQuota) {
1249 final boolean oldRejectOnQuota = mUidRejectOnQuota.get(uid, false);
1250 if (oldRejectOnQuota == rejectOnQuotaInterfaces) {
1251 // TODO: eventually consider throwing
1252 return;
1253 }
1254
1255 final StringBuilder command = new StringBuilder();
1256 command.append("bandwidth");
1257 if (rejectOnQuotaInterfaces) {
1258 command.append(" addnaughtyapps");
1259 } else {
1260 command.append(" removenaughtyapps");
1261 }
1262 command.append(" ").append(uid);
1263
1264 try {
1265 mConnector.doCommand(command.toString());
1266 if (rejectOnQuotaInterfaces) {
1267 mUidRejectOnQuota.put(uid, true);
1268 } else {
1269 mUidRejectOnQuota.delete(uid);
1270 }
1271 } catch (NativeDaemonConnectorException e) {
1272 throw new IllegalStateException("Error communicating to native daemon", e);
1273 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001274 }
1275 }
1276
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001277 @Override
1278 public boolean isBandwidthControlEnabled() {
1279 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1280 return mBandwidthControlEnabled;
1281 }
1282
1283 @Override
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001284 public NetworkStats getNetworkStatsUidDetail(int uid) {
1285 if (Binder.getCallingUid() != uid) {
1286 mContext.enforceCallingOrSelfPermission(
1287 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
1288 }
1289
Jeff Sharkey350083e2011-06-29 10:45:16 -07001290 if (mBandwidthControlEnabled) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001291 return getNetworkStatsDetailNetfilter(uid);
1292 } else {
1293 return getNetworkStatsDetailUidstat(uid);
1294 }
1295 }
1296
1297 /**
1298 * Build {@link NetworkStats} with detailed UID statistics.
1299 */
1300 private NetworkStats getNetworkStatsDetailNetfilter(int limitUid) {
1301 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 24);
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001302 final NetworkStats.Entry entry = new NetworkStats.Entry();
1303
Jeff Sharkeya63ba592011-07-19 23:47:12 -07001304 // TODO: remove knownLines check once 5087722 verified
1305 final HashSet<String> knownLines = Sets.newHashSet();
1306
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001307 final ArrayList<String> keys = Lists.newArrayList();
1308 final ArrayList<String> values = Lists.newArrayList();
1309 final HashMap<String, String> parsed = Maps.newHashMap();
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001310
1311 BufferedReader reader = null;
1312 try {
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001313 reader = new BufferedReader(new FileReader(mStatsXtUid));
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001314
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001315 // parse first line as header
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001316 String line = reader.readLine();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001317 splitLine(line, keys);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001318
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001319 // parse remaining lines
1320 while ((line = reader.readLine()) != null) {
1321 splitLine(line, values);
1322 parseLine(keys, values, parsed);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001323
Jeff Sharkeya63ba592011-07-19 23:47:12 -07001324 if (!knownLines.add(line)) {
1325 throw new IllegalStateException("encountered duplicate proc entry");
1326 }
1327
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001328 try {
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001329 entry.iface = parsed.get(KEY_IFACE);
Jeff Sharkeya63ba592011-07-19 23:47:12 -07001330 entry.uid = getParsedInt(parsed, KEY_UID);
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001331 entry.set = getParsedInt(parsed, KEY_COUNTER_SET);
1332 entry.tag = kernelToTag(parsed.get(KEY_TAG_HEX));
Jeff Sharkeya63ba592011-07-19 23:47:12 -07001333 entry.rxBytes = getParsedLong(parsed, KEY_RX_BYTES);
1334 entry.rxPackets = getParsedLong(parsed, KEY_RX_PACKETS);
1335 entry.txBytes = getParsedLong(parsed, KEY_TX_BYTES);
1336 entry.txPackets = getParsedLong(parsed, KEY_TX_PACKETS);
Jeff Sharkeyd03fd3f2011-06-19 20:55:09 -07001337
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001338 if (limitUid == UID_ALL || limitUid == entry.uid) {
1339 stats.addValues(entry);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001340 }
1341 } catch (NumberFormatException e) {
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001342 Slog.w(TAG, "problem parsing stats row '" + line + "': " + e);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001343 }
1344 }
Jeff Sharkey558a2322011-08-24 15:42:09 -07001345 } catch (NullPointerException e) {
1346 throw new IllegalStateException("problem parsing stats: " + e);
1347 } catch (NumberFormatException e) {
1348 throw new IllegalStateException("problem parsing stats: " + e);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001349 } catch (IOException e) {
Jeff Sharkey558a2322011-08-24 15:42:09 -07001350 throw new IllegalStateException("problem parsing stats: " + e);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001351 } finally {
1352 IoUtils.closeQuietly(reader);
1353 }
1354
Jeff Sharkey4a971222011-06-11 22:16:55 -07001355 return stats;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001356 }
1357
Jeff Sharkeya63ba592011-07-19 23:47:12 -07001358 private static int getParsedInt(HashMap<String, String> parsed, String key) {
1359 final String value = parsed.get(key);
1360 return value != null ? Integer.parseInt(value) : 0;
1361 }
1362
1363 private static long getParsedLong(HashMap<String, String> parsed, String key) {
1364 final String value = parsed.get(key);
1365 return value != null ? Long.parseLong(value) : 0;
1366 }
1367
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001368 /**
1369 * Build {@link NetworkStats} with detailed UID statistics.
1370 *
1371 * @deprecated since this uses older "uid_stat" data, and doesn't provide
1372 * tag-level granularity or additional variables.
1373 */
1374 @Deprecated
1375 private NetworkStats getNetworkStatsDetailUidstat(int limitUid) {
1376 final String[] knownUids;
1377 if (limitUid == UID_ALL) {
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001378 knownUids = fileListWithoutNull(mStatsUid);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001379 } else {
1380 knownUids = new String[] { String.valueOf(limitUid) };
1381 }
1382
1383 final NetworkStats stats = new NetworkStats(
1384 SystemClock.elapsedRealtime(), knownUids.length);
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001385 final NetworkStats.Entry entry = new NetworkStats.Entry();
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001386 for (String uid : knownUids) {
1387 final int uidInt = Integer.parseInt(uid);
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001388 final File uidPath = new File(mStatsUid, uid);
1389
1390 entry.iface = IFACE_ALL;
1391 entry.uid = uidInt;
1392 entry.tag = TAG_NONE;
1393 entry.rxBytes = readSingleLongFromFile(new File(uidPath, "tcp_rcv"));
1394 entry.rxPackets = readSingleLongFromFile(new File(uidPath, "tcp_rcv_pkt"));
1395 entry.txBytes = readSingleLongFromFile(new File(uidPath, "tcp_snd"));
1396 entry.txPackets = readSingleLongFromFile(new File(uidPath, "tcp_snd_pkt"));
1397
1398 stats.addValues(entry);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001399 }
1400
1401 return stats;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001402 }
1403
San Mehatf0db6e12010-04-07 15:22:10 -07001404 public void setInterfaceThrottle(String iface, int rxKbps, int txKbps) {
San Mehat91cac642010-03-31 14:31:36 -07001405 mContext.enforceCallingOrSelfPermission(
1406 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -07001407 try {
1408 mConnector.doCommand(String.format(
1409 "interface setthrottle %s %d %d", iface, rxKbps, txKbps));
1410 } catch (NativeDaemonConnectorException e) {
1411 Slog.e(TAG, "Error communicating with native daemon to set throttle", e);
1412 }
San Mehat91cac642010-03-31 14:31:36 -07001413 }
1414
1415 private int getInterfaceThrottle(String iface, boolean rx) {
1416 mContext.enforceCallingOrSelfPermission(
1417 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
1418 try {
Kenny Roota80ce062010-06-01 13:23:53 -07001419 String rsp;
1420 try {
1421 rsp = mConnector.doCommand(
1422 String.format("interface getthrottle %s %s", iface,
1423 (rx ? "rx" : "tx"))).get(0);
1424 } catch (NativeDaemonConnectorException e) {
1425 Slog.e(TAG, "Error communicating with native daemon to getthrottle", e);
1426 return -1;
1427 }
1428
1429 String[] tok = rsp.split(" ");
1430 if (tok.length < 2) {
1431 Slog.e(TAG, "Malformed response to getthrottle command");
1432 return -1;
1433 }
1434
San Mehat91cac642010-03-31 14:31:36 -07001435 int code;
1436 try {
1437 code = Integer.parseInt(tok[0]);
1438 } catch (NumberFormatException nfe) {
1439 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
1440 return -1;
1441 }
1442 if ((rx && code != NetdResponseCode.InterfaceRxThrottleResult) || (
1443 !rx && code != NetdResponseCode.InterfaceTxThrottleResult)) {
1444 Slog.e(TAG, String.format("Unexpected response code %d", code));
1445 return -1;
1446 }
1447 return Integer.parseInt(tok[1]);
1448 } catch (Exception e) {
1449 Slog.e(TAG, String.format(
1450 "Failed to read interface %s throttle value", (rx ? "rx" : "tx")), e);
1451 }
1452 return -1;
1453 }
1454
1455 public int getInterfaceRxThrottle(String iface) {
1456 return getInterfaceThrottle(iface, true);
1457 }
1458
1459 public int getInterfaceTxThrottle(String iface) {
1460 return getInterfaceThrottle(iface, false);
1461 }
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001462
1463 /**
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001464 * Split given line into {@link ArrayList}.
1465 */
1466 private static void splitLine(String line, ArrayList<String> outSplit) {
1467 outSplit.clear();
1468
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001469 final StringTokenizer t = new StringTokenizer(line, " \t\n\r\f:");
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001470 while (t.hasMoreTokens()) {
1471 outSplit.add(t.nextToken());
1472 }
1473 }
1474
1475 /**
1476 * Zip the two given {@link ArrayList} as key and value pairs into
1477 * {@link HashMap}.
1478 */
1479 private static void parseLine(
1480 ArrayList<String> keys, ArrayList<String> values, HashMap<String, String> outParsed) {
1481 outParsed.clear();
1482
1483 final int size = Math.min(keys.size(), values.size());
1484 for (int i = 0; i < size; i++) {
1485 outParsed.put(keys.get(i), values.get(i));
1486 }
1487 }
1488
1489 /**
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001490 * Utility method to read a single plain-text {@link Long} from the given
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001491 * {@link File}, usually from a {@code /proc/} filesystem.
1492 */
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001493 private static long readSingleLongFromFile(File file) {
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001494 try {
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001495 final byte[] buffer = IoUtils.readFileAsByteArray(file.toString());
1496 return Long.parseLong(new String(buffer).trim());
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001497 } catch (NumberFormatException e) {
1498 return -1;
1499 } catch (IOException e) {
1500 return -1;
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001501 }
1502 }
Jean-Baptiste Querud5299ff2011-07-07 08:46:09 -07001503
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001504 /**
1505 * Wrapper for {@link File#list()} that returns empty array instead of
1506 * {@code null}.
1507 */
1508 private static String[] fileListWithoutNull(File file) {
1509 final String[] list = file.list();
1510 return list != null ? list : new String[0];
1511 }
1512
Mattias Falk7475c0c2011-04-04 16:10:36 +02001513 public void setDefaultInterfaceForDns(String iface) throws IllegalStateException {
1514 mContext.enforceCallingOrSelfPermission(
1515 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
1516 try {
1517 String cmd = "resolver setdefaultif " + iface;
1518
1519 mConnector.doCommand(cmd);
1520 } catch (NativeDaemonConnectorException e) {
1521 throw new IllegalStateException(
1522 "Error communicating with native daemon to set default interface", e);
1523 }
1524 }
1525
1526 public void setDnsServersForInterface(String iface, String[] servers)
1527 throws IllegalStateException {
1528 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE,
1529 "NetworkManagementService");
1530 try {
1531 String cmd = "resolver setifdns " + iface;
1532 for (String s : servers) {
Robert Greenwalt572b7042011-07-25 17:00:13 -07001533 InetAddress a = NetworkUtils.numericToInetAddress(s);
1534 if (a.isAnyLocalAddress() == false) {
1535 cmd += " " + a.getHostAddress();
Mattias Falk7475c0c2011-04-04 16:10:36 +02001536 }
1537 }
Mattias Falk7475c0c2011-04-04 16:10:36 +02001538 mConnector.doCommand(cmd);
Robert Greenwalt572b7042011-07-25 17:00:13 -07001539 } catch (IllegalArgumentException e) {
1540 throw new IllegalStateException("Error setting dnsn for interface", e);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001541 } catch (NativeDaemonConnectorException e) {
1542 throw new IllegalStateException(
Robert Greenwalt572b7042011-07-25 17:00:13 -07001543 "Error communicating with native daemon to set dns for interface", e);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001544 }
1545 }
1546
1547 public void flushDefaultDnsCache() throws IllegalStateException {
1548 mContext.enforceCallingOrSelfPermission(
1549 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
1550 try {
1551 String cmd = "resolver flushdefaultif";
1552
1553 mConnector.doCommand(cmd);
1554 } catch (NativeDaemonConnectorException e) {
1555 throw new IllegalStateException(
1556 "Error communicating with native deamon to flush default interface", e);
1557 }
1558 }
1559
1560 public void flushInterfaceDnsCache(String iface) throws IllegalStateException {
1561 mContext.enforceCallingOrSelfPermission(
1562 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
1563 try {
1564 String cmd = "resolver flushif " + iface;
1565
1566 mConnector.doCommand(cmd);
1567 } catch (NativeDaemonConnectorException e) {
1568 throw new IllegalStateException(
Robert Greenwalt572b7042011-07-25 17:00:13 -07001569 "Error communicating with native daemon to flush interface " + iface, e);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001570 }
1571 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07001572
1573 /** {@inheritDoc} */
1574 public void monitor() {
1575 if (mConnector != null) {
1576 mConnector.monitor();
1577 }
1578 }
Jeff Sharkey47eb1022011-08-25 17:48:52 -07001579
1580 @Override
1581 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1582 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
1583
1584 pw.print("Bandwidth control enabled: "); pw.println(mBandwidthControlEnabled);
1585
1586 synchronized (mQuotaLock) {
1587 pw.print("Active quota ifaces: "); pw.println(mActiveQuotaIfaces.toString());
1588 pw.print("Active alert ifaces: "); pw.println(mActiveAlertIfaces.toString());
1589 }
1590
1591 synchronized (mUidRejectOnQuota) {
1592 pw.print("UID reject on quota ifaces: [");
1593 final int size = mUidRejectOnQuota.size();
1594 for (int i = 0; i < size; i++) {
1595 pw.print(mUidRejectOnQuota.keyAt(i));
1596 if (i < size - 1) pw.print(",");
1597 }
1598 pw.println("]");
1599 }
1600 }
San Mehat873f2142010-01-14 10:25:07 -08001601}