blob: c517965759fbe0d47951780f55192c2f4d701bb1 [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;
Robert Greenwalte3253922010-02-18 09:23:25 -0800126
127 public static final int InterfaceChange = 600;
JP Abgrall12b933d2011-07-14 18:09:22 -0700128 public static final int BandwidthControl = 601;
San Mehat873f2142010-01-14 10:25:07 -0800129 }
130
131 /**
132 * Binder context for this service
133 */
134 private Context mContext;
135
136 /**
137 * connector object for communicating with netd
138 */
139 private NativeDaemonConnector mConnector;
140
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700141 private Thread mThread;
142 private final CountDownLatch mConnectedSignal = new CountDownLatch(1);
143
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700144 // TODO: replace with RemoteCallbackList
San Mehat4d02d002010-01-22 16:07:46 -0800145 private ArrayList<INetworkManagementEventObserver> mObservers;
146
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700147 private Object mQuotaLock = new Object();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700148 /** Set of interfaces with active quotas. */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700149 private HashSet<String> mActiveQuotaIfaces = Sets.newHashSet();
150 /** Set of interfaces with active alerts. */
151 private HashSet<String> mActiveAlertIfaces = Sets.newHashSet();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700152 /** Set of UIDs with active reject rules. */
153 private SparseBooleanArray mUidRejectOnQuota = new SparseBooleanArray();
154
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700155 private volatile boolean mBandwidthControlEnabled;
Jeff Sharkey350083e2011-06-29 10:45:16 -0700156
San Mehat873f2142010-01-14 10:25:07 -0800157 /**
158 * Constructs a new NetworkManagementService instance
159 *
160 * @param context Binder context for this service
161 */
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700162 private NetworkManagementService(Context context, File procRoot) {
San Mehat873f2142010-01-14 10:25:07 -0800163 mContext = context;
San Mehat4d02d002010-01-22 16:07:46 -0800164 mObservers = new ArrayList<INetworkManagementEventObserver>();
165
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -0700166 mStatsUid = new File(procRoot, "uid_stat");
167 mStatsIface = new File(procRoot, "net/dev");
168 mStatsXtUid = new File(procRoot, "net/xt_qtaguid/stats");
169 mStatsXtIface = new File(procRoot, "net/xt_qtaguid/iface_stat");
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700170
Marco Nelissen62dbb222010-02-18 10:56:30 -0800171 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
172 return;
173 }
174
San Mehat873f2142010-01-14 10:25:07 -0800175 mConnector = new NativeDaemonConnector(
Kenny Root305bcbf2010-09-03 07:56:38 -0700176 new NetdCallbackReceiver(), "netd", 10, NETD_TAG);
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700177 mThread = new Thread(mConnector, NETD_TAG);
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700178
179 // Add ourself to the Watchdog monitors.
180 Watchdog.getInstance().addMonitor(this);
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700181 }
182
183 public static NetworkManagementService create(Context context) throws InterruptedException {
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700184 NetworkManagementService service = new NetworkManagementService(
185 context, new File("/proc/"));
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700186 if (DBG) Slog.d(TAG, "Creating NetworkManagementService");
187 service.mThread.start();
188 if (DBG) Slog.d(TAG, "Awaiting socket connection");
189 service.mConnectedSignal.await();
190 if (DBG) Slog.d(TAG, "Connected");
191 return service;
San Mehat873f2142010-01-14 10:25:07 -0800192 }
193
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700194 // @VisibleForTesting
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -0700195 public static NetworkManagementService createForTest(
196 Context context, File procRoot, boolean bandwidthControlEnabled) {
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700197 // TODO: eventually connect with mock netd
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -0700198 final NetworkManagementService service = new NetworkManagementService(context, procRoot);
199 service.mBandwidthControlEnabled = bandwidthControlEnabled;
200 return service;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700201 }
202
Jeff Sharkey350083e2011-06-29 10:45:16 -0700203 public void systemReady() {
Jeff Sharkey350083e2011-06-29 10:45:16 -0700204 // only enable bandwidth control when support exists, and requested by
205 // system setting.
Jeff Sharkey350083e2011-06-29 10:45:16 -0700206 final boolean hasKernelSupport = new File("/proc/net/xt_qtaguid/ctrl").exists();
207 final boolean shouldEnable =
Jeff Sharkey05355c32011-08-09 14:44:19 -0700208 Settings.Secure.getInt(mContext.getContentResolver(), NETSTATS_ENABLED, 1) != 0;
Jeff Sharkey350083e2011-06-29 10:45:16 -0700209
Jeff Sharkey350083e2011-06-29 10:45:16 -0700210 if (hasKernelSupport && shouldEnable) {
211 Slog.d(TAG, "enabling bandwidth control");
212 try {
213 mConnector.doCommand("bandwidth enable");
214 mBandwidthControlEnabled = true;
215 } catch (NativeDaemonConnectorException e) {
216 Slog.e(TAG, "problem enabling bandwidth controls", e);
217 }
218 } else {
219 Slog.d(TAG, "not enabling bandwidth control");
220 }
Jeff Sharkey62a2c8f2011-07-13 15:24:02 -0700221
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700222 SystemProperties.set(PROP_QTAGUID_ENABLED, mBandwidthControlEnabled ? "1" : "0");
Jeff Sharkey350083e2011-06-29 10:45:16 -0700223 }
224
San Mehat4d02d002010-01-22 16:07:46 -0800225 public void registerObserver(INetworkManagementEventObserver obs) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800226 Slog.d(TAG, "Registering observer");
San Mehat4d02d002010-01-22 16:07:46 -0800227 mObservers.add(obs);
228 }
229
230 public void unregisterObserver(INetworkManagementEventObserver obs) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800231 Slog.d(TAG, "Unregistering observer");
San Mehat4d02d002010-01-22 16:07:46 -0800232 mObservers.remove(mObservers.indexOf(obs));
233 }
234
235 /**
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700236 * Notify our observers of an interface status change
San Mehat4d02d002010-01-22 16:07:46 -0800237 */
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700238 private void notifyInterfaceStatusChanged(String iface, boolean up) {
San Mehat4d02d002010-01-22 16:07:46 -0800239 for (INetworkManagementEventObserver obs : mObservers) {
240 try {
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700241 obs.interfaceStatusChanged(iface, up);
242 } catch (Exception ex) {
243 Slog.w(TAG, "Observer notifier failed", ex);
244 }
245 }
246 }
247
248 /**
Mike J. Chenf59c7d02011-06-23 15:33:15 -0700249 * Notify our observers of an interface link state change
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700250 * (typically, an Ethernet cable has been plugged-in or unplugged).
251 */
252 private void notifyInterfaceLinkStateChanged(String iface, boolean up) {
253 for (INetworkManagementEventObserver obs : mObservers) {
254 try {
255 obs.interfaceLinkStateChanged(iface, up);
San Mehat4d02d002010-01-22 16:07:46 -0800256 } catch (Exception ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800257 Slog.w(TAG, "Observer notifier failed", ex);
San Mehat4d02d002010-01-22 16:07:46 -0800258 }
259 }
260 }
261
262 /**
263 * Notify our observers of an interface addition.
264 */
265 private void notifyInterfaceAdded(String iface) {
266 for (INetworkManagementEventObserver obs : mObservers) {
267 try {
268 obs.interfaceAdded(iface);
269 } catch (Exception ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800270 Slog.w(TAG, "Observer notifier failed", ex);
San Mehat4d02d002010-01-22 16:07:46 -0800271 }
272 }
273 }
274
275 /**
276 * Notify our observers of an interface removal.
277 */
278 private void notifyInterfaceRemoved(String iface) {
279 for (INetworkManagementEventObserver obs : mObservers) {
280 try {
281 obs.interfaceRemoved(iface);
282 } catch (Exception ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800283 Slog.w(TAG, "Observer notifier failed", ex);
San Mehat4d02d002010-01-22 16:07:46 -0800284 }
285 }
286 }
287
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700288 /**
JP Abgrall12b933d2011-07-14 18:09:22 -0700289 * Notify our observers of a limit reached.
290 */
291 private void notifyLimitReached(String limitName, String iface) {
292 for (INetworkManagementEventObserver obs : mObservers) {
293 try {
294 obs.limitReached(limitName, iface);
JP Abgrall12b933d2011-07-14 18:09:22 -0700295 } catch (Exception ex) {
296 Slog.w(TAG, "Observer notifier failed", ex);
297 }
298 }
299 }
300
301 /**
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700302 * Let us know the daemon is connected
303 */
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700304 protected void onDaemonConnected() {
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700305 if (DBG) Slog.d(TAG, "onConnected");
306 mConnectedSignal.countDown();
307 }
308
San Mehat4d02d002010-01-22 16:07:46 -0800309
San Mehat873f2142010-01-14 10:25:07 -0800310 //
311 // Netd Callback handling
312 //
313
314 class NetdCallbackReceiver implements INativeDaemonConnectorCallbacks {
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700315 /** {@inheritDoc} */
San Mehat873f2142010-01-14 10:25:07 -0800316 public void onDaemonConnected() {
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700317 NetworkManagementService.this.onDaemonConnected();
San Mehat873f2142010-01-14 10:25:07 -0800318 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700319
320 /** {@inheritDoc} */
San Mehat873f2142010-01-14 10:25:07 -0800321 public boolean onEvent(int code, String raw, String[] cooked) {
JP Abgrall12b933d2011-07-14 18:09:22 -0700322 switch (code) {
323 case NetdResponseCode.InterfaceChange:
324 /*
325 * a network interface change occured
326 * Format: "NNN Iface added <name>"
327 * "NNN Iface removed <name>"
328 * "NNN Iface changed <name> <up/down>"
329 * "NNN Iface linkstatus <name> <up/down>"
330 */
331 if (cooked.length < 4 || !cooked[1].equals("Iface")) {
332 throw new IllegalStateException(
333 String.format("Invalid event from daemon (%s)", raw));
334 }
335 if (cooked[2].equals("added")) {
336 notifyInterfaceAdded(cooked[3]);
337 return true;
338 } else if (cooked[2].equals("removed")) {
339 notifyInterfaceRemoved(cooked[3]);
340 return true;
341 } else if (cooked[2].equals("changed") && cooked.length == 5) {
342 notifyInterfaceStatusChanged(cooked[3], cooked[4].equals("up"));
343 return true;
344 } else if (cooked[2].equals("linkstate") && cooked.length == 5) {
345 notifyInterfaceLinkStateChanged(cooked[3], cooked[4].equals("up"));
346 return true;
347 }
Robert Greenwalte3253922010-02-18 09:23:25 -0800348 throw new IllegalStateException(
349 String.format("Invalid event from daemon (%s)", raw));
JP Abgrall12b933d2011-07-14 18:09:22 -0700350 // break;
351 case NetdResponseCode.BandwidthControl:
352 /*
353 * Bandwidth control needs some attention
354 * Format: "NNN limit alert <alertName> <ifaceName>"
355 */
356 if (cooked.length < 5 || !cooked[1].equals("limit")) {
357 throw new IllegalStateException(
358 String.format("Invalid event from daemon (%s)", raw));
359 }
360 if (cooked[2].equals("alert")) {
361 notifyLimitReached(cooked[3], cooked[4]);
362 return true;
363 }
364 throw new IllegalStateException(
365 String.format("Invalid event from daemon (%s)", raw));
366 // break;
367 default: break;
Robert Greenwalte3253922010-02-18 09:23:25 -0800368 }
369 return false;
San Mehat873f2142010-01-14 10:25:07 -0800370 }
371 }
372
San Mehated4fc8a2010-01-22 12:28:36 -0800373
San Mehat873f2142010-01-14 10:25:07 -0800374 //
375 // INetworkManagementService members
376 //
377
378 public String[] listInterfaces() throws IllegalStateException {
379 mContext.enforceCallingOrSelfPermission(
380 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
381
Kenny Roota80ce062010-06-01 13:23:53 -0700382 try {
383 return mConnector.doListCommand("interface list", NetdResponseCode.InterfaceListResult);
384 } catch (NativeDaemonConnectorException e) {
385 throw new IllegalStateException(
386 "Cannot communicate with native daemon to list interfaces");
387 }
San Mehated4fc8a2010-01-22 12:28:36 -0800388 }
389
390 public InterfaceConfiguration getInterfaceConfig(String iface) throws IllegalStateException {
Kenny Roota80ce062010-06-01 13:23:53 -0700391 String rsp;
392 try {
393 rsp = mConnector.doCommand("interface getcfg " + iface).get(0);
394 } catch (NativeDaemonConnectorException e) {
395 throw new IllegalStateException(
396 "Cannot communicate with native daemon to get interface config");
397 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800398 Slog.d(TAG, String.format("rsp <%s>", rsp));
San Mehated4fc8a2010-01-22 12:28:36 -0800399
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800400 // Rsp: 213 xx:xx:xx:xx:xx:xx yyy.yyy.yyy.yyy zzz [flag1 flag2 flag3]
San Mehated4fc8a2010-01-22 12:28:36 -0800401 StringTokenizer st = new StringTokenizer(rsp);
402
Kenny Roota80ce062010-06-01 13:23:53 -0700403 InterfaceConfiguration cfg;
San Mehated4fc8a2010-01-22 12:28:36 -0800404 try {
Kenny Roota80ce062010-06-01 13:23:53 -0700405 try {
406 int code = Integer.parseInt(st.nextToken(" "));
407 if (code != NetdResponseCode.InterfaceGetCfgResult) {
408 throw new IllegalStateException(
409 String.format("Expected code %d, but got %d",
410 NetdResponseCode.InterfaceGetCfgResult, code));
411 }
412 } catch (NumberFormatException nfe) {
San Mehated4fc8a2010-01-22 12:28:36 -0800413 throw new IllegalStateException(
Kenny Roota80ce062010-06-01 13:23:53 -0700414 String.format("Invalid response from daemon (%s)", rsp));
San Mehated4fc8a2010-01-22 12:28:36 -0800415 }
Kenny Roota80ce062010-06-01 13:23:53 -0700416
417 cfg = new InterfaceConfiguration();
418 cfg.hwAddr = st.nextToken(" ");
Robert Greenwalted126402011-01-28 15:34:55 -0800419 InetAddress addr = null;
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800420 int prefixLength = 0;
Kenny Roota80ce062010-06-01 13:23:53 -0700421 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800422 addr = NetworkUtils.numericToInetAddress(st.nextToken(" "));
423 } catch (IllegalArgumentException iae) {
424 Slog.e(TAG, "Failed to parse ipaddr", iae);
Kenny Roota80ce062010-06-01 13:23:53 -0700425 }
426
427 try {
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800428 prefixLength = Integer.parseInt(st.nextToken(" "));
429 } catch (NumberFormatException nfe) {
430 Slog.e(TAG, "Failed to parse prefixLength", nfe);
Kenny Roota80ce062010-06-01 13:23:53 -0700431 }
Robert Greenwalt04808c22010-12-13 17:01:41 -0800432
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800433 cfg.addr = new LinkAddress(addr, prefixLength);
Kenny Roota80ce062010-06-01 13:23:53 -0700434 cfg.interfaceFlags = st.nextToken("]").trim() +"]";
435 } catch (NoSuchElementException nsee) {
San Mehated4fc8a2010-01-22 12:28:36 -0800436 throw new IllegalStateException(
437 String.format("Invalid response from daemon (%s)", rsp));
438 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800439 Slog.d(TAG, String.format("flags <%s>", cfg.interfaceFlags));
San Mehated4fc8a2010-01-22 12:28:36 -0800440 return cfg;
441 }
442
443 public void setInterfaceConfig(
444 String iface, InterfaceConfiguration cfg) throws IllegalStateException {
Robert Greenwalted126402011-01-28 15:34:55 -0800445 LinkAddress linkAddr = cfg.addr;
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800446 if (linkAddr == null || linkAddr.getAddress() == null) {
447 throw new IllegalStateException("Null LinkAddress given");
Robert Greenwalted126402011-01-28 15:34:55 -0800448 }
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800449 String cmd = String.format("interface setcfg %s %s %d %s", iface,
450 linkAddr.getAddress().getHostAddress(),
451 linkAddr.getNetworkPrefixLength(),
452 cfg.interfaceFlags);
Kenny Roota80ce062010-06-01 13:23:53 -0700453 try {
454 mConnector.doCommand(cmd);
455 } catch (NativeDaemonConnectorException e) {
456 throw new IllegalStateException(
Robert Greenwalt81d5ad52010-12-16 11:27:38 -0800457 "Unable to communicate with native daemon to interface setcfg - " + e);
Kenny Roota80ce062010-06-01 13:23:53 -0700458 }
San Mehat873f2142010-01-14 10:25:07 -0800459 }
460
Irfan Sheriff7244c972011-08-05 20:40:45 -0700461 public void setInterfaceDown(String iface) throws IllegalStateException {
462 try {
463 InterfaceConfiguration ifcg = getInterfaceConfig(iface);
464 ifcg.interfaceFlags = ifcg.interfaceFlags.replace("up", "down");
465 setInterfaceConfig(iface, ifcg);
466 } catch (NativeDaemonConnectorException e) {
467 throw new IllegalStateException(
468 "Unable to communicate with native daemon for interface down - " + e);
469 }
470 }
471
472 public void setInterfaceUp(String iface) throws IllegalStateException {
473 try {
474 InterfaceConfiguration ifcg = getInterfaceConfig(iface);
475 ifcg.interfaceFlags = ifcg.interfaceFlags.replace("down", "up");
476 setInterfaceConfig(iface, ifcg);
477 } catch (NativeDaemonConnectorException e) {
478 throw new IllegalStateException(
479 "Unable to communicate with native daemon for interface up - " + e);
480 }
481 }
482
Irfan Sheriff73293612011-09-14 12:31:56 -0700483 public void setInterfaceIpv6PrivacyExtensions(String iface, boolean enable)
484 throws IllegalStateException {
485 String cmd = String.format("interface ipv6privacyextensions %s %s", iface,
486 enable ? "enable" : "disable");
487 try {
488 mConnector.doCommand(cmd);
489 } catch (NativeDaemonConnectorException e) {
490 throw new IllegalStateException(
491 "Unable to communicate with native daemon to set ipv6privacyextensions - " + e);
492 }
493 }
494
495
496
Irfan Sherifff5600612011-06-16 10:26:28 -0700497 /* TODO: This is right now a IPv4 only function. Works for wifi which loses its
498 IPv6 addresses on interface down, but we need to do full clean up here */
499 public void clearInterfaceAddresses(String iface) throws IllegalStateException {
500 String cmd = String.format("interface clearaddrs %s", iface);
501 try {
502 mConnector.doCommand(cmd);
503 } catch (NativeDaemonConnectorException e) {
504 throw new IllegalStateException(
505 "Unable to communicate with native daemon to interface clearallips - " + e);
506 }
507 }
508
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700509 public void addRoute(String interfaceName, RouteInfo route) {
510 modifyRoute(interfaceName, ADD, route);
511 }
512
513 public void removeRoute(String interfaceName, RouteInfo route) {
514 modifyRoute(interfaceName, REMOVE, route);
515 }
516
517 private void modifyRoute(String interfaceName, int action, RouteInfo route) {
518 ArrayList<String> rsp;
519
520 StringBuilder cmd;
521
522 switch (action) {
523 case ADD:
524 {
525 cmd = new StringBuilder("interface route add " + interfaceName);
526 break;
527 }
528 case REMOVE:
529 {
530 cmd = new StringBuilder("interface route remove " + interfaceName);
531 break;
532 }
533 default:
534 throw new IllegalStateException("Unknown action type " + action);
535 }
536
537 // create triplet: dest-ip-addr prefixlength gateway-ip-addr
538 LinkAddress la = route.getDestination();
539 cmd.append(' ');
540 cmd.append(la.getAddress().getHostAddress());
541 cmd.append(' ');
542 cmd.append(la.getNetworkPrefixLength());
543 cmd.append(' ');
544 if (route.getGateway() == null) {
545 if (la.getAddress() instanceof Inet4Address) {
546 cmd.append("0.0.0.0");
547 } else {
548 cmd.append ("::0");
549 }
550 } else {
551 cmd.append(route.getGateway().getHostAddress());
552 }
553 try {
554 rsp = mConnector.doCommand(cmd.toString());
555 } catch (NativeDaemonConnectorException e) {
556 throw new IllegalStateException(
557 "Unable to communicate with native dameon to add routes - "
558 + e);
559 }
560
561 for (String line : rsp) {
562 Log.v(TAG, "add route response is " + line);
563 }
564 }
565
566 private ArrayList<String> readRouteList(String filename) {
567 FileInputStream fstream = null;
568 ArrayList<String> list = new ArrayList<String>();
569
570 try {
571 fstream = new FileInputStream(filename);
572 DataInputStream in = new DataInputStream(fstream);
573 BufferedReader br = new BufferedReader(new InputStreamReader(in));
574 String s;
575
576 // throw away the title line
577
578 while (((s = br.readLine()) != null) && (s.length() != 0)) {
579 list.add(s);
580 }
581 } catch (IOException ex) {
582 // return current list, possibly empty
583 } finally {
584 if (fstream != null) {
585 try {
586 fstream.close();
587 } catch (IOException ex) {}
588 }
589 }
590
591 return list;
592 }
593
594 public RouteInfo[] getRoutes(String interfaceName) {
595 ArrayList<RouteInfo> routes = new ArrayList<RouteInfo>();
596
597 // v4 routes listed as:
598 // iface dest-addr gateway-addr flags refcnt use metric netmask mtu window IRTT
599 for (String s : readRouteList("/proc/net/route")) {
600 String[] fields = s.split("\t");
601
602 if (fields.length > 7) {
603 String iface = fields[0];
604
605 if (interfaceName.equals(iface)) {
606 String dest = fields[1];
607 String gate = fields[2];
608 String flags = fields[3]; // future use?
609 String mask = fields[7];
610 try {
611 // address stored as a hex string, ex: 0014A8C0
612 InetAddress destAddr =
613 NetworkUtils.intToInetAddress((int)Long.parseLong(dest, 16));
614 int prefixLength =
615 NetworkUtils.netmaskIntToPrefixLength(
616 (int)Long.parseLong(mask, 16));
617 LinkAddress linkAddress = new LinkAddress(destAddr, prefixLength);
618
619 // address stored as a hex string, ex 0014A8C0
620 InetAddress gatewayAddr =
621 NetworkUtils.intToInetAddress((int)Long.parseLong(gate, 16));
622
623 RouteInfo route = new RouteInfo(linkAddress, gatewayAddr);
624 routes.add(route);
625 } catch (Exception e) {
626 Log.e(TAG, "Error parsing route " + s + " : " + e);
627 continue;
628 }
629 }
630 }
631 }
632
633 // v6 routes listed as:
634 // dest-addr prefixlength ?? ?? gateway-addr ?? ?? ?? ?? iface
635 for (String s : readRouteList("/proc/net/ipv6_route")) {
636 String[]fields = s.split("\\s+");
637 if (fields.length > 9) {
638 String iface = fields[9].trim();
639 if (interfaceName.equals(iface)) {
640 String dest = fields[0];
641 String prefix = fields[1];
642 String gate = fields[4];
643
644 try {
645 // prefix length stored as a hex string, ex 40
646 int prefixLength = Integer.parseInt(prefix, 16);
647
648 // address stored as a 32 char hex string
649 // ex fe800000000000000000000000000000
650 InetAddress destAddr = NetworkUtils.hexToInet6Address(dest);
651 LinkAddress linkAddress = new LinkAddress(destAddr, prefixLength);
652
653 InetAddress gateAddr = NetworkUtils.hexToInet6Address(gate);
654
655 RouteInfo route = new RouteInfo(linkAddress, gateAddr);
656 routes.add(route);
657 } catch (Exception e) {
658 Log.e(TAG, "Error parsing route " + s + " : " + e);
659 continue;
660 }
661 }
662 }
663 }
664 return (RouteInfo[]) routes.toArray(new RouteInfo[0]);
665 }
666
San Mehat873f2142010-01-14 10:25:07 -0800667 public void shutdown() {
668 if (mContext.checkCallingOrSelfPermission(
669 android.Manifest.permission.SHUTDOWN)
670 != PackageManager.PERMISSION_GRANTED) {
671 throw new SecurityException("Requires SHUTDOWN permission");
672 }
673
Joe Onorato8a9b2202010-02-26 18:56:32 -0800674 Slog.d(TAG, "Shutting down");
San Mehat873f2142010-01-14 10:25:07 -0800675 }
676
677 public boolean getIpForwardingEnabled() throws IllegalStateException{
678 mContext.enforceCallingOrSelfPermission(
679 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
680
Kenny Roota80ce062010-06-01 13:23:53 -0700681 ArrayList<String> rsp;
682 try {
683 rsp = mConnector.doCommand("ipfwd status");
684 } catch (NativeDaemonConnectorException e) {
685 throw new IllegalStateException(
686 "Unable to communicate with native daemon to ipfwd status");
687 }
San Mehat873f2142010-01-14 10:25:07 -0800688
689 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700690 String[] tok = line.split(" ");
691 if (tok.length < 3) {
692 Slog.e(TAG, "Malformed response from native daemon: " + line);
693 return false;
694 }
695
San Mehat873f2142010-01-14 10:25:07 -0800696 int code = Integer.parseInt(tok[0]);
697 if (code == NetdResponseCode.IpFwdStatusResult) {
698 // 211 Forwarding <enabled/disabled>
Kenny Roota80ce062010-06-01 13:23:53 -0700699 return "enabled".equals(tok[2]);
San Mehat873f2142010-01-14 10:25:07 -0800700 } else {
701 throw new IllegalStateException(String.format("Unexpected response code %d", code));
702 }
703 }
704 throw new IllegalStateException("Got an empty response");
705 }
706
707 public void setIpForwardingEnabled(boolean enable) throws IllegalStateException {
708 mContext.enforceCallingOrSelfPermission(
709 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
710 mConnector.doCommand(String.format("ipfwd %sable", (enable ? "en" : "dis")));
711 }
712
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -0700713 public void startTethering(String[] dhcpRange)
San Mehat873f2142010-01-14 10:25:07 -0800714 throws IllegalStateException {
715 mContext.enforceCallingOrSelfPermission(
716 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -0700717 // cmd is "tether start first_start first_stop second_start second_stop ..."
718 // an odd number of addrs will fail
719 String cmd = "tether start";
720 for (String d : dhcpRange) {
721 cmd += " " + d;
722 }
Kenny Roota80ce062010-06-01 13:23:53 -0700723
724 try {
725 mConnector.doCommand(cmd);
726 } catch (NativeDaemonConnectorException e) {
727 throw new IllegalStateException("Unable to communicate to native daemon");
728 }
San Mehat873f2142010-01-14 10:25:07 -0800729 }
730
731 public void stopTethering() throws IllegalStateException {
732 mContext.enforceCallingOrSelfPermission(
733 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700734 try {
735 mConnector.doCommand("tether stop");
736 } catch (NativeDaemonConnectorException e) {
737 throw new IllegalStateException("Unable to communicate to native daemon to stop tether");
738 }
San Mehat873f2142010-01-14 10:25:07 -0800739 }
740
741 public boolean isTetheringStarted() throws IllegalStateException {
742 mContext.enforceCallingOrSelfPermission(
743 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
744
Kenny Roota80ce062010-06-01 13:23:53 -0700745 ArrayList<String> rsp;
746 try {
747 rsp = mConnector.doCommand("tether status");
748 } catch (NativeDaemonConnectorException e) {
749 throw new IllegalStateException(
750 "Unable to communicate to native daemon to get tether status");
751 }
San Mehat873f2142010-01-14 10:25:07 -0800752
753 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700754 String[] tok = line.split(" ");
755 if (tok.length < 3) {
756 throw new IllegalStateException("Malformed response for tether status: " + line);
757 }
San Mehat873f2142010-01-14 10:25:07 -0800758 int code = Integer.parseInt(tok[0]);
759 if (code == NetdResponseCode.TetherStatusResult) {
760 // XXX: Tethering services <started/stopped> <TBD>...
Kenny Roota80ce062010-06-01 13:23:53 -0700761 return "started".equals(tok[2]);
San Mehat873f2142010-01-14 10:25:07 -0800762 } else {
763 throw new IllegalStateException(String.format("Unexpected response code %d", code));
764 }
765 }
766 throw new IllegalStateException("Got an empty response");
767 }
768
769 public void tetherInterface(String iface) throws IllegalStateException {
770 mContext.enforceCallingOrSelfPermission(
771 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700772 try {
773 mConnector.doCommand("tether interface add " + iface);
774 } catch (NativeDaemonConnectorException e) {
775 throw new IllegalStateException(
776 "Unable to communicate to native daemon for adding tether interface");
777 }
San Mehat873f2142010-01-14 10:25:07 -0800778 }
779
780 public void untetherInterface(String iface) {
781 mContext.enforceCallingOrSelfPermission(
782 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700783 try {
784 mConnector.doCommand("tether interface remove " + iface);
785 } catch (NativeDaemonConnectorException e) {
786 throw new IllegalStateException(
787 "Unable to communicate to native daemon for removing tether interface");
788 }
San Mehat873f2142010-01-14 10:25:07 -0800789 }
790
791 public String[] listTetheredInterfaces() throws IllegalStateException {
792 mContext.enforceCallingOrSelfPermission(
793 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700794 try {
795 return mConnector.doListCommand(
796 "tether interface list", NetdResponseCode.TetherInterfaceListResult);
797 } catch (NativeDaemonConnectorException e) {
798 throw new IllegalStateException(
799 "Unable to communicate to native daemon for listing tether interfaces");
800 }
San Mehat873f2142010-01-14 10:25:07 -0800801 }
802
803 public void setDnsForwarders(String[] dns) throws IllegalStateException {
804 mContext.enforceCallingOrSelfPermission(
805 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
806 try {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800807 String cmd = "tether dns set";
San Mehat873f2142010-01-14 10:25:07 -0800808 for (String s : dns) {
Robert Greenwalte5903732011-02-22 16:00:42 -0800809 cmd += " " + NetworkUtils.numericToInetAddress(s).getHostAddress();
San Mehat873f2142010-01-14 10:25:07 -0800810 }
Kenny Roota80ce062010-06-01 13:23:53 -0700811 try {
812 mConnector.doCommand(cmd);
813 } catch (NativeDaemonConnectorException e) {
814 throw new IllegalStateException(
815 "Unable to communicate to native daemon for setting tether dns");
816 }
Robert Greenwalte5903732011-02-22 16:00:42 -0800817 } catch (IllegalArgumentException e) {
San Mehat873f2142010-01-14 10:25:07 -0800818 throw new IllegalStateException("Error resolving dns name", e);
819 }
820 }
821
822 public String[] getDnsForwarders() throws IllegalStateException {
823 mContext.enforceCallingOrSelfPermission(
824 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700825 try {
826 return mConnector.doListCommand(
827 "tether dns list", NetdResponseCode.TetherDnsFwdTgtListResult);
828 } catch (NativeDaemonConnectorException e) {
829 throw new IllegalStateException(
830 "Unable to communicate to native daemon for listing tether dns");
831 }
San Mehat873f2142010-01-14 10:25:07 -0800832 }
833
834 public void enableNat(String internalInterface, String externalInterface)
835 throws IllegalStateException {
836 mContext.enforceCallingOrSelfPermission(
837 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700838 try {
839 mConnector.doCommand(
840 String.format("nat enable %s %s", internalInterface, externalInterface));
841 } catch (NativeDaemonConnectorException e) {
842 throw new IllegalStateException(
843 "Unable to communicate to native daemon for enabling NAT interface");
844 }
San Mehat873f2142010-01-14 10:25:07 -0800845 }
846
847 public void disableNat(String internalInterface, String externalInterface)
848 throws IllegalStateException {
849 mContext.enforceCallingOrSelfPermission(
850 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700851 try {
852 mConnector.doCommand(
853 String.format("nat disable %s %s", internalInterface, externalInterface));
854 } catch (NativeDaemonConnectorException e) {
855 throw new IllegalStateException(
856 "Unable to communicate to native daemon for disabling NAT interface");
857 }
San Mehat873f2142010-01-14 10:25:07 -0800858 }
San Mehat72759df2010-01-19 13:50:37 -0800859
860 public String[] listTtys() throws IllegalStateException {
861 mContext.enforceCallingOrSelfPermission(
862 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700863 try {
864 return mConnector.doListCommand("list_ttys", NetdResponseCode.TtyListResult);
865 } catch (NativeDaemonConnectorException e) {
866 throw new IllegalStateException(
867 "Unable to communicate to native daemon for listing TTYs");
868 }
San Mehat72759df2010-01-19 13:50:37 -0800869 }
870
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800871 public void attachPppd(String tty, String localAddr, String remoteAddr, String dns1Addr,
872 String dns2Addr) throws IllegalStateException {
San Mehat72759df2010-01-19 13:50:37 -0800873 try {
874 mContext.enforceCallingOrSelfPermission(
875 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800876 mConnector.doCommand(String.format("pppd attach %s %s %s %s %s", tty,
Robert Greenwalte5903732011-02-22 16:00:42 -0800877 NetworkUtils.numericToInetAddress(localAddr).getHostAddress(),
878 NetworkUtils.numericToInetAddress(remoteAddr).getHostAddress(),
879 NetworkUtils.numericToInetAddress(dns1Addr).getHostAddress(),
880 NetworkUtils.numericToInetAddress(dns2Addr).getHostAddress()));
881 } catch (IllegalArgumentException e) {
San Mehat72759df2010-01-19 13:50:37 -0800882 throw new IllegalStateException("Error resolving addr", e);
Kenny Roota80ce062010-06-01 13:23:53 -0700883 } catch (NativeDaemonConnectorException e) {
884 throw new IllegalStateException("Error communicating to native daemon to attach pppd", e);
San Mehat72759df2010-01-19 13:50:37 -0800885 }
886 }
887
888 public void detachPppd(String tty) throws IllegalStateException {
889 mContext.enforceCallingOrSelfPermission(
890 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700891 try {
892 mConnector.doCommand(String.format("pppd detach %s", tty));
893 } catch (NativeDaemonConnectorException e) {
894 throw new IllegalStateException("Error communicating to native daemon to detach pppd", e);
895 }
San Mehat72759df2010-01-19 13:50:37 -0800896 }
Robert Greenwaltce1200d2010-02-18 11:25:54 -0800897
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700898 public void startAccessPoint(WifiConfiguration wifiConfig, String wlanIface, String softapIface)
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800899 throws IllegalStateException {
900 mContext.enforceCallingOrSelfPermission(
901 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
902 mContext.enforceCallingOrSelfPermission(
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700903 android.Manifest.permission.CHANGE_WIFI_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700904 try {
Irfan Sheriffcb30b222011-07-29 20:54:52 -0700905 wifiFirmwareReload(wlanIface, "AP");
Kenny Roota80ce062010-06-01 13:23:53 -0700906 mConnector.doCommand(String.format("softap start " + wlanIface));
907 if (wifiConfig == null) {
908 mConnector.doCommand(String.format("softap set " + wlanIface + " " + softapIface));
909 } else {
910 /**
911 * softap set arg1 arg2 arg3 [arg4 arg5 arg6 arg7 arg8]
912 * argv1 - wlan interface
913 * argv2 - softap interface
914 * argv3 - SSID
915 * argv4 - Security
916 * argv5 - Key
917 * argv6 - Channel
918 * argv7 - Preamble
919 * argv8 - Max SCB
920 */
Irfan Sheriffec8d23a2011-02-16 17:00:33 -0800921 String str = String.format("softap set " + wlanIface + " " + softapIface +
922 " %s %s %s", convertQuotedString(wifiConfig.SSID),
923 getSecurityType(wifiConfig),
924 convertQuotedString(wifiConfig.preSharedKey));
Kenny Roota80ce062010-06-01 13:23:53 -0700925 mConnector.doCommand(str);
926 }
927 mConnector.doCommand(String.format("softap startap"));
928 } catch (NativeDaemonConnectorException e) {
929 throw new IllegalStateException("Error communicating to native daemon to start softap", e);
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800930 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800931 }
932
Irfan Sheriffa6e559e2010-05-24 14:55:42 -0700933 private String convertQuotedString(String s) {
Irfan Sheriff7baec0f2010-05-26 17:16:47 -0700934 if (s == null) {
935 return s;
936 }
937 /* Replace \ with \\, then " with \" and add quotes at end */
938 return '"' + s.replaceAll("\\\\","\\\\\\\\").replaceAll("\"","\\\\\"") + '"';
Irfan Sheriffa6e559e2010-05-24 14:55:42 -0700939 }
940
Irfan Sheriffec8d23a2011-02-16 17:00:33 -0800941 private String getSecurityType(WifiConfiguration wifiConfig) {
942 switch (wifiConfig.getAuthType()) {
943 case KeyMgmt.WPA_PSK:
944 return "wpa-psk";
945 case KeyMgmt.WPA2_PSK:
946 return "wpa2-psk";
947 default:
948 return "open";
949 }
950 }
951
Irfan Sheriffcb30b222011-07-29 20:54:52 -0700952 /* @param mode can be "AP", "STA" or "P2P" */
953 public void wifiFirmwareReload(String wlanIface, String mode) throws IllegalStateException {
954 mContext.enforceCallingOrSelfPermission(
955 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
956 mContext.enforceCallingOrSelfPermission(
957 android.Manifest.permission.CHANGE_WIFI_STATE, "NetworkManagementService");
958
959 try {
960 mConnector.doCommand(String.format("softap fwreload " + wlanIface + " " + mode));
961 } catch (NativeDaemonConnectorException e) {
962 throw new IllegalStateException("Error communicating to native daemon ", e);
963 }
964 }
965
Irfan Sheriff23eb2972011-07-22 15:21:10 -0700966 public void stopAccessPoint(String wlanIface) throws IllegalStateException {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800967 mContext.enforceCallingOrSelfPermission(
968 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
969 mContext.enforceCallingOrSelfPermission(
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700970 android.Manifest.permission.CHANGE_WIFI_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700971 try {
972 mConnector.doCommand("softap stopap");
Irfan Sheriff23eb2972011-07-22 15:21:10 -0700973 mConnector.doCommand("softap stop " + wlanIface);
Irfan Sheriffcb30b222011-07-29 20:54:52 -0700974 wifiFirmwareReload(wlanIface, "STA");
Kenny Roota80ce062010-06-01 13:23:53 -0700975 } catch (NativeDaemonConnectorException e) {
976 throw new IllegalStateException("Error communicating to native daemon to stop soft AP",
977 e);
978 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800979 }
980
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700981 public void setAccessPoint(WifiConfiguration wifiConfig, String wlanIface, String softapIface)
982 throws IllegalStateException {
983 mContext.enforceCallingOrSelfPermission(
984 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
985 mContext.enforceCallingOrSelfPermission(
986 android.Manifest.permission.CHANGE_WIFI_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700987 try {
988 if (wifiConfig == null) {
989 mConnector.doCommand(String.format("softap set " + wlanIface + " " + softapIface));
990 } else {
991 String str = String.format("softap set " + wlanIface + " " + softapIface
992 + " %s %s %s", convertQuotedString(wifiConfig.SSID),
Irfan Sheriffec8d23a2011-02-16 17:00:33 -0800993 getSecurityType(wifiConfig),
Kenny Roota80ce062010-06-01 13:23:53 -0700994 convertQuotedString(wifiConfig.preSharedKey));
995 mConnector.doCommand(str);
996 }
997 } catch (NativeDaemonConnectorException e) {
998 throw new IllegalStateException("Error communicating to native daemon to set soft AP",
999 e);
Irfan Sheriffc2f54c22010-03-18 14:02:22 -07001000 }
1001 }
San Mehat91cac642010-03-31 14:31:36 -07001002
1003 private long getInterfaceCounter(String iface, boolean rx) {
1004 mContext.enforceCallingOrSelfPermission(
1005 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
1006 try {
Kenny Roota80ce062010-06-01 13:23:53 -07001007 String rsp;
1008 try {
1009 rsp = mConnector.doCommand(
1010 String.format("interface read%scounter %s", (rx ? "rx" : "tx"), iface)).get(0);
1011 } catch (NativeDaemonConnectorException e1) {
1012 Slog.e(TAG, "Error communicating with native daemon", e1);
1013 return -1;
1014 }
1015
1016 String[] tok = rsp.split(" ");
1017 if (tok.length < 2) {
1018 Slog.e(TAG, String.format("Malformed response for reading %s interface",
1019 (rx ? "rx" : "tx")));
1020 return -1;
1021 }
1022
San Mehat91cac642010-03-31 14:31:36 -07001023 int code;
1024 try {
1025 code = Integer.parseInt(tok[0]);
1026 } catch (NumberFormatException nfe) {
1027 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
1028 return -1;
1029 }
1030 if ((rx && code != NetdResponseCode.InterfaceRxCounterResult) || (
1031 !rx && code != NetdResponseCode.InterfaceTxCounterResult)) {
1032 Slog.e(TAG, String.format("Unexpected response code %d", code));
1033 return -1;
1034 }
1035 return Long.parseLong(tok[1]);
1036 } catch (Exception e) {
1037 Slog.e(TAG, String.format(
1038 "Failed to read interface %s counters", (rx ? "rx" : "tx")), e);
1039 }
1040 return -1;
1041 }
1042
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001043 @Override
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001044 public NetworkStats getNetworkStatsSummary() {
1045 mContext.enforceCallingOrSelfPermission(
1046 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
1047
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001048 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 6);
1049 final NetworkStats.Entry entry = new NetworkStats.Entry();
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001050
Jeff Sharkey0fea8232011-09-01 01:07:31 -07001051 final HashSet<String> knownIfaces = Sets.newHashSet();
1052 final HashSet<String> activeIfaces = Sets.newHashSet();
1053
1054 // collect any historical stats and active state
1055 // TODO: migrate to reading from single file
1056 if (mBandwidthControlEnabled) {
1057 for (String iface : fileListWithoutNull(mStatsXtIface)) {
1058 final File ifacePath = new File(mStatsXtIface, iface);
1059
1060 final long active = readSingleLongFromFile(new File(ifacePath, "active"));
1061 if (active == 1) {
1062 knownIfaces.add(iface);
1063 activeIfaces.add(iface);
1064 } else if (active == 0) {
1065 knownIfaces.add(iface);
1066 } else {
1067 continue;
1068 }
1069
1070 entry.iface = iface;
1071 entry.uid = UID_ALL;
1072 entry.set = SET_DEFAULT;
1073 entry.tag = TAG_NONE;
1074 entry.rxBytes = readSingleLongFromFile(new File(ifacePath, "rx_bytes"));
1075 entry.rxPackets = readSingleLongFromFile(new File(ifacePath, "rx_packets"));
1076 entry.txBytes = readSingleLongFromFile(new File(ifacePath, "tx_bytes"));
1077 entry.txPackets = readSingleLongFromFile(new File(ifacePath, "tx_packets"));
1078
1079 stats.addValues(entry);
1080 }
1081 }
1082
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001083 final ArrayList<String> values = Lists.newArrayList();
1084
1085 BufferedReader reader = null;
1086 try {
1087 reader = new BufferedReader(new FileReader(mStatsIface));
1088
1089 // skip first two header lines
1090 reader.readLine();
1091 reader.readLine();
1092
1093 // parse remaining lines
1094 String line;
1095 while ((line = reader.readLine()) != null) {
1096 splitLine(line, values);
1097
1098 try {
1099 entry.iface = values.get(0);
1100 entry.uid = UID_ALL;
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001101 entry.set = SET_DEFAULT;
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001102 entry.tag = TAG_NONE;
1103 entry.rxBytes = Long.parseLong(values.get(1));
1104 entry.rxPackets = Long.parseLong(values.get(2));
1105 entry.txBytes = Long.parseLong(values.get(9));
1106 entry.txPackets = Long.parseLong(values.get(10));
1107
Jeff Sharkey0fea8232011-09-01 01:07:31 -07001108 if (activeIfaces.contains(entry.iface)) {
1109 // combine stats when iface is active
1110 stats.combineValues(entry);
1111 } else if (!knownIfaces.contains(entry.iface)) {
1112 // add stats when iface is unknown
1113 stats.addValues(entry);
1114 }
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001115 } catch (NumberFormatException e) {
1116 Slog.w(TAG, "problem parsing stats row '" + line + "': " + e);
1117 }
1118 }
Jeff Sharkey558a2322011-08-24 15:42:09 -07001119 } catch (NullPointerException e) {
1120 throw new IllegalStateException("problem parsing stats: " + e);
1121 } catch (NumberFormatException e) {
1122 throw new IllegalStateException("problem parsing stats: " + e);
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001123 } catch (IOException e) {
Jeff Sharkey558a2322011-08-24 15:42:09 -07001124 throw new IllegalStateException("problem parsing stats: " + e);
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001125 } finally {
1126 IoUtils.closeQuietly(reader);
1127 }
1128
Jeff Sharkey4a971222011-06-11 22:16:55 -07001129 return stats;
San Mehat91cac642010-03-31 14:31:36 -07001130 }
1131
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001132 @Override
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001133 public NetworkStats getNetworkStatsDetail() {
1134 mContext.enforceCallingOrSelfPermission(
1135 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
1136
Jeff Sharkey350083e2011-06-29 10:45:16 -07001137 if (mBandwidthControlEnabled) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001138 return getNetworkStatsDetailNetfilter(UID_ALL);
1139 } else {
1140 return getNetworkStatsDetailUidstat(UID_ALL);
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001141 }
San Mehat91cac642010-03-31 14:31:36 -07001142 }
1143
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001144 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001145 public void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001146 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1147
Jeff Sharkey350083e2011-06-29 10:45:16 -07001148 // silently discard when control disabled
1149 // TODO: eventually migrate to be always enabled
1150 if (!mBandwidthControlEnabled) return;
1151
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001152 synchronized (mQuotaLock) {
1153 if (mActiveQuotaIfaces.contains(iface)) {
1154 throw new IllegalStateException("iface " + iface + " already has quota");
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001155 }
1156
1157 final StringBuilder command = new StringBuilder();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001158 command.append("bandwidth setiquota ").append(iface).append(" ").append(quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001159
1160 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001161 // TODO: support quota shared across interfaces
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001162 mConnector.doCommand(command.toString());
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001163 mActiveQuotaIfaces.add(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001164 } catch (NativeDaemonConnectorException e) {
1165 throw new IllegalStateException("Error communicating to native daemon", e);
1166 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001167 }
1168 }
1169
1170 @Override
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001171 public void removeInterfaceQuota(String iface) {
1172 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1173
Jeff Sharkey350083e2011-06-29 10:45:16 -07001174 // silently discard when control disabled
1175 // TODO: eventually migrate to be always enabled
1176 if (!mBandwidthControlEnabled) return;
1177
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001178 synchronized (mQuotaLock) {
1179 if (!mActiveQuotaIfaces.contains(iface)) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001180 // TODO: eventually consider throwing
1181 return;
1182 }
1183
1184 final StringBuilder command = new StringBuilder();
1185 command.append("bandwidth removeiquota ").append(iface);
1186
1187 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001188 // TODO: support quota shared across interfaces
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001189 mConnector.doCommand(command.toString());
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001190 mActiveQuotaIfaces.remove(iface);
1191 mActiveAlertIfaces.remove(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001192 } catch (NativeDaemonConnectorException e) {
1193 throw new IllegalStateException("Error communicating to native daemon", e);
1194 }
1195 }
1196 }
1197
1198 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001199 public void setInterfaceAlert(String iface, long alertBytes) {
1200 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1201
1202 // silently discard when control disabled
1203 // TODO: eventually migrate to be always enabled
1204 if (!mBandwidthControlEnabled) return;
1205
1206 // quick sanity check
1207 if (!mActiveQuotaIfaces.contains(iface)) {
1208 throw new IllegalStateException("setting alert requires existing quota on iface");
1209 }
1210
1211 synchronized (mQuotaLock) {
1212 if (mActiveAlertIfaces.contains(iface)) {
1213 throw new IllegalStateException("iface " + iface + " already has alert");
1214 }
1215
1216 final StringBuilder command = new StringBuilder();
1217 command.append("bandwidth setinterfacealert ").append(iface).append(" ").append(
1218 alertBytes);
1219
1220 try {
1221 // TODO: support alert shared across interfaces
1222 mConnector.doCommand(command.toString());
1223 mActiveAlertIfaces.add(iface);
1224 } catch (NativeDaemonConnectorException e) {
1225 throw new IllegalStateException("Error communicating to native daemon", e);
1226 }
1227 }
1228 }
1229
1230 @Override
1231 public void removeInterfaceAlert(String iface) {
1232 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1233
1234 // silently discard when control disabled
1235 // TODO: eventually migrate to be always enabled
1236 if (!mBandwidthControlEnabled) return;
1237
1238 synchronized (mQuotaLock) {
1239 if (!mActiveAlertIfaces.contains(iface)) {
1240 // TODO: eventually consider throwing
1241 return;
1242 }
1243
1244 final StringBuilder command = new StringBuilder();
1245 command.append("bandwidth removeinterfacealert ").append(iface);
1246
1247 try {
1248 // TODO: support alert shared across interfaces
1249 mConnector.doCommand(command.toString());
1250 mActiveAlertIfaces.remove(iface);
1251 } catch (NativeDaemonConnectorException e) {
1252 throw new IllegalStateException("Error communicating to native daemon", e);
1253 }
1254 }
1255 }
1256
1257 @Override
1258 public void setGlobalAlert(long alertBytes) {
1259 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1260
1261 // silently discard when control disabled
1262 // TODO: eventually migrate to be always enabled
1263 if (!mBandwidthControlEnabled) return;
1264
1265 final StringBuilder command = new StringBuilder();
1266 command.append("bandwidth setglobalalert ").append(alertBytes);
1267
1268 try {
1269 mConnector.doCommand(command.toString());
1270 } catch (NativeDaemonConnectorException e) {
1271 throw new IllegalStateException("Error communicating to native daemon", e);
1272 }
1273 }
1274
1275 @Override
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001276 public void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
1277 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1278
Jeff Sharkey350083e2011-06-29 10:45:16 -07001279 // silently discard when control disabled
1280 // TODO: eventually migrate to be always enabled
1281 if (!mBandwidthControlEnabled) return;
1282
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001283 synchronized (mUidRejectOnQuota) {
1284 final boolean oldRejectOnQuota = mUidRejectOnQuota.get(uid, false);
1285 if (oldRejectOnQuota == rejectOnQuotaInterfaces) {
1286 // TODO: eventually consider throwing
1287 return;
1288 }
1289
1290 final StringBuilder command = new StringBuilder();
1291 command.append("bandwidth");
1292 if (rejectOnQuotaInterfaces) {
1293 command.append(" addnaughtyapps");
1294 } else {
1295 command.append(" removenaughtyapps");
1296 }
1297 command.append(" ").append(uid);
1298
1299 try {
1300 mConnector.doCommand(command.toString());
1301 if (rejectOnQuotaInterfaces) {
1302 mUidRejectOnQuota.put(uid, true);
1303 } else {
1304 mUidRejectOnQuota.delete(uid);
1305 }
1306 } catch (NativeDaemonConnectorException e) {
1307 throw new IllegalStateException("Error communicating to native daemon", e);
1308 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001309 }
1310 }
1311
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001312 @Override
1313 public boolean isBandwidthControlEnabled() {
1314 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1315 return mBandwidthControlEnabled;
1316 }
1317
1318 @Override
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001319 public NetworkStats getNetworkStatsUidDetail(int uid) {
1320 if (Binder.getCallingUid() != uid) {
1321 mContext.enforceCallingOrSelfPermission(
1322 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
1323 }
1324
Jeff Sharkey350083e2011-06-29 10:45:16 -07001325 if (mBandwidthControlEnabled) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001326 return getNetworkStatsDetailNetfilter(uid);
1327 } else {
1328 return getNetworkStatsDetailUidstat(uid);
1329 }
1330 }
1331
1332 /**
1333 * Build {@link NetworkStats} with detailed UID statistics.
1334 */
1335 private NetworkStats getNetworkStatsDetailNetfilter(int limitUid) {
1336 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 24);
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001337 final NetworkStats.Entry entry = new NetworkStats.Entry();
1338
Jeff Sharkeya63ba592011-07-19 23:47:12 -07001339 // TODO: remove knownLines check once 5087722 verified
1340 final HashSet<String> knownLines = Sets.newHashSet();
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001341 // TODO: remove lastIdx check once 5270106 verified
JP Abgrall6acf39b2011-09-08 15:13:26 -07001342 int lastIdx;
Jeff Sharkeya63ba592011-07-19 23:47:12 -07001343
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001344 final ArrayList<String> keys = Lists.newArrayList();
1345 final ArrayList<String> values = Lists.newArrayList();
1346 final HashMap<String, String> parsed = Maps.newHashMap();
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001347
1348 BufferedReader reader = null;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001349 String line = null;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001350 try {
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001351 reader = new BufferedReader(new FileReader(mStatsXtUid));
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001352
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001353 // parse first line as header
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001354 line = reader.readLine();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001355 splitLine(line, keys);
JP Abgrall6acf39b2011-09-08 15:13:26 -07001356 lastIdx = 1;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001357
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001358 // parse remaining lines
1359 while ((line = reader.readLine()) != null) {
1360 splitLine(line, values);
1361 parseLine(keys, values, parsed);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001362
Jeff Sharkeya63ba592011-07-19 23:47:12 -07001363 if (!knownLines.add(line)) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001364 throw new IllegalStateException("duplicate proc entry: " + line);
Jeff Sharkeya63ba592011-07-19 23:47:12 -07001365 }
1366
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001367 final int idx = getParsedInt(parsed, KEY_IDX);
JP Abgrall6acf39b2011-09-08 15:13:26 -07001368 if (idx != lastIdx + 1) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001369 throw new IllegalStateException(
1370 "inconsistent idx=" + idx + " after lastIdx=" + lastIdx);
1371 }
1372 lastIdx = idx;
Jeff Sharkeyd03fd3f2011-06-19 20:55:09 -07001373
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001374 entry.iface = parsed.get(KEY_IFACE);
1375 entry.uid = getParsedInt(parsed, KEY_UID);
1376 entry.set = getParsedInt(parsed, KEY_COUNTER_SET);
1377 entry.tag = kernelToTag(parsed.get(KEY_TAG_HEX));
1378 entry.rxBytes = getParsedLong(parsed, KEY_RX_BYTES);
1379 entry.rxPackets = getParsedLong(parsed, KEY_RX_PACKETS);
1380 entry.txBytes = getParsedLong(parsed, KEY_TX_BYTES);
1381 entry.txPackets = getParsedLong(parsed, KEY_TX_PACKETS);
1382
1383 if (limitUid == UID_ALL || limitUid == entry.uid) {
1384 stats.addValues(entry);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001385 }
1386 }
Jeff Sharkey558a2322011-08-24 15:42:09 -07001387 } catch (NullPointerException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001388 throw new IllegalStateException("problem parsing line: " + line, e);
Jeff Sharkey558a2322011-08-24 15:42:09 -07001389 } catch (NumberFormatException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001390 throw new IllegalStateException("problem parsing line: " + line, e);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001391 } catch (IOException 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 } finally {
1394 IoUtils.closeQuietly(reader);
1395 }
1396
Jeff Sharkey4a971222011-06-11 22:16:55 -07001397 return stats;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001398 }
1399
Jeff Sharkeya63ba592011-07-19 23:47:12 -07001400 private static int getParsedInt(HashMap<String, String> parsed, String key) {
1401 final String value = parsed.get(key);
1402 return value != null ? Integer.parseInt(value) : 0;
1403 }
1404
1405 private static long getParsedLong(HashMap<String, String> parsed, String key) {
1406 final String value = parsed.get(key);
1407 return value != null ? Long.parseLong(value) : 0;
1408 }
1409
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001410 /**
1411 * Build {@link NetworkStats} with detailed UID statistics.
1412 *
1413 * @deprecated since this uses older "uid_stat" data, and doesn't provide
1414 * tag-level granularity or additional variables.
1415 */
1416 @Deprecated
1417 private NetworkStats getNetworkStatsDetailUidstat(int limitUid) {
1418 final String[] knownUids;
1419 if (limitUid == UID_ALL) {
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001420 knownUids = fileListWithoutNull(mStatsUid);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001421 } else {
1422 knownUids = new String[] { String.valueOf(limitUid) };
1423 }
1424
1425 final NetworkStats stats = new NetworkStats(
1426 SystemClock.elapsedRealtime(), knownUids.length);
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001427 final NetworkStats.Entry entry = new NetworkStats.Entry();
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001428 for (String uid : knownUids) {
1429 final int uidInt = Integer.parseInt(uid);
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001430 final File uidPath = new File(mStatsUid, uid);
1431
1432 entry.iface = IFACE_ALL;
1433 entry.uid = uidInt;
1434 entry.tag = TAG_NONE;
1435 entry.rxBytes = readSingleLongFromFile(new File(uidPath, "tcp_rcv"));
1436 entry.rxPackets = readSingleLongFromFile(new File(uidPath, "tcp_rcv_pkt"));
1437 entry.txBytes = readSingleLongFromFile(new File(uidPath, "tcp_snd"));
1438 entry.txPackets = readSingleLongFromFile(new File(uidPath, "tcp_snd_pkt"));
1439
1440 stats.addValues(entry);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001441 }
1442
1443 return stats;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001444 }
1445
San Mehatf0db6e12010-04-07 15:22:10 -07001446 public void setInterfaceThrottle(String iface, int rxKbps, int txKbps) {
San Mehat91cac642010-03-31 14:31:36 -07001447 mContext.enforceCallingOrSelfPermission(
1448 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -07001449 try {
1450 mConnector.doCommand(String.format(
1451 "interface setthrottle %s %d %d", iface, rxKbps, txKbps));
1452 } catch (NativeDaemonConnectorException e) {
1453 Slog.e(TAG, "Error communicating with native daemon to set throttle", e);
1454 }
San Mehat91cac642010-03-31 14:31:36 -07001455 }
1456
1457 private int getInterfaceThrottle(String iface, boolean rx) {
1458 mContext.enforceCallingOrSelfPermission(
1459 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
1460 try {
Kenny Roota80ce062010-06-01 13:23:53 -07001461 String rsp;
1462 try {
1463 rsp = mConnector.doCommand(
1464 String.format("interface getthrottle %s %s", iface,
1465 (rx ? "rx" : "tx"))).get(0);
1466 } catch (NativeDaemonConnectorException e) {
1467 Slog.e(TAG, "Error communicating with native daemon to getthrottle", e);
1468 return -1;
1469 }
1470
1471 String[] tok = rsp.split(" ");
1472 if (tok.length < 2) {
1473 Slog.e(TAG, "Malformed response to getthrottle command");
1474 return -1;
1475 }
1476
San Mehat91cac642010-03-31 14:31:36 -07001477 int code;
1478 try {
1479 code = Integer.parseInt(tok[0]);
1480 } catch (NumberFormatException nfe) {
1481 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
1482 return -1;
1483 }
1484 if ((rx && code != NetdResponseCode.InterfaceRxThrottleResult) || (
1485 !rx && code != NetdResponseCode.InterfaceTxThrottleResult)) {
1486 Slog.e(TAG, String.format("Unexpected response code %d", code));
1487 return -1;
1488 }
1489 return Integer.parseInt(tok[1]);
1490 } catch (Exception e) {
1491 Slog.e(TAG, String.format(
1492 "Failed to read interface %s throttle value", (rx ? "rx" : "tx")), e);
1493 }
1494 return -1;
1495 }
1496
1497 public int getInterfaceRxThrottle(String iface) {
1498 return getInterfaceThrottle(iface, true);
1499 }
1500
1501 public int getInterfaceTxThrottle(String iface) {
1502 return getInterfaceThrottle(iface, false);
1503 }
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001504
1505 /**
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001506 * Split given line into {@link ArrayList}.
1507 */
1508 private static void splitLine(String line, ArrayList<String> outSplit) {
1509 outSplit.clear();
1510
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001511 final StringTokenizer t = new StringTokenizer(line, " \t\n\r\f:");
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001512 while (t.hasMoreTokens()) {
1513 outSplit.add(t.nextToken());
1514 }
1515 }
1516
1517 /**
1518 * Zip the two given {@link ArrayList} as key and value pairs into
1519 * {@link HashMap}.
1520 */
1521 private static void parseLine(
1522 ArrayList<String> keys, ArrayList<String> values, HashMap<String, String> outParsed) {
1523 outParsed.clear();
1524
1525 final int size = Math.min(keys.size(), values.size());
1526 for (int i = 0; i < size; i++) {
1527 outParsed.put(keys.get(i), values.get(i));
1528 }
1529 }
1530
1531 /**
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001532 * Utility method to read a single plain-text {@link Long} from the given
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001533 * {@link File}, usually from a {@code /proc/} filesystem.
1534 */
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001535 private static long readSingleLongFromFile(File file) {
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001536 try {
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001537 final byte[] buffer = IoUtils.readFileAsByteArray(file.toString());
1538 return Long.parseLong(new String(buffer).trim());
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001539 } catch (NumberFormatException e) {
1540 return -1;
1541 } catch (IOException e) {
1542 return -1;
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001543 }
1544 }
Jean-Baptiste Querud5299ff2011-07-07 08:46:09 -07001545
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001546 /**
1547 * Wrapper for {@link File#list()} that returns empty array instead of
1548 * {@code null}.
1549 */
1550 private static String[] fileListWithoutNull(File file) {
1551 final String[] list = file.list();
1552 return list != null ? list : new String[0];
1553 }
1554
Mattias Falk7475c0c2011-04-04 16:10:36 +02001555 public void setDefaultInterfaceForDns(String iface) throws IllegalStateException {
1556 mContext.enforceCallingOrSelfPermission(
1557 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
1558 try {
1559 String cmd = "resolver setdefaultif " + iface;
1560
1561 mConnector.doCommand(cmd);
1562 } catch (NativeDaemonConnectorException e) {
1563 throw new IllegalStateException(
1564 "Error communicating with native daemon to set default interface", e);
1565 }
1566 }
1567
1568 public void setDnsServersForInterface(String iface, String[] servers)
1569 throws IllegalStateException {
1570 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE,
1571 "NetworkManagementService");
1572 try {
1573 String cmd = "resolver setifdns " + iface;
1574 for (String s : servers) {
Robert Greenwalt572b7042011-07-25 17:00:13 -07001575 InetAddress a = NetworkUtils.numericToInetAddress(s);
1576 if (a.isAnyLocalAddress() == false) {
1577 cmd += " " + a.getHostAddress();
Mattias Falk7475c0c2011-04-04 16:10:36 +02001578 }
1579 }
Mattias Falk7475c0c2011-04-04 16:10:36 +02001580 mConnector.doCommand(cmd);
Robert Greenwalt572b7042011-07-25 17:00:13 -07001581 } catch (IllegalArgumentException e) {
1582 throw new IllegalStateException("Error setting dnsn for interface", e);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001583 } catch (NativeDaemonConnectorException e) {
1584 throw new IllegalStateException(
Robert Greenwalt572b7042011-07-25 17:00:13 -07001585 "Error communicating with native daemon to set dns for interface", e);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001586 }
1587 }
1588
1589 public void flushDefaultDnsCache() throws IllegalStateException {
1590 mContext.enforceCallingOrSelfPermission(
1591 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
1592 try {
1593 String cmd = "resolver flushdefaultif";
1594
1595 mConnector.doCommand(cmd);
1596 } catch (NativeDaemonConnectorException e) {
1597 throw new IllegalStateException(
1598 "Error communicating with native deamon to flush default interface", e);
1599 }
1600 }
1601
1602 public void flushInterfaceDnsCache(String iface) throws IllegalStateException {
1603 mContext.enforceCallingOrSelfPermission(
1604 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
1605 try {
1606 String cmd = "resolver flushif " + iface;
1607
1608 mConnector.doCommand(cmd);
1609 } catch (NativeDaemonConnectorException e) {
1610 throw new IllegalStateException(
Robert Greenwalt572b7042011-07-25 17:00:13 -07001611 "Error communicating with native daemon to flush interface " + iface, e);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001612 }
1613 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07001614
1615 /** {@inheritDoc} */
1616 public void monitor() {
1617 if (mConnector != null) {
1618 mConnector.monitor();
1619 }
1620 }
Jeff Sharkey47eb1022011-08-25 17:48:52 -07001621
1622 @Override
1623 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1624 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
1625
1626 pw.print("Bandwidth control enabled: "); pw.println(mBandwidthControlEnabled);
1627
1628 synchronized (mQuotaLock) {
1629 pw.print("Active quota ifaces: "); pw.println(mActiveQuotaIfaces.toString());
1630 pw.print("Active alert ifaces: "); pw.println(mActiveAlertIfaces.toString());
1631 }
1632
1633 synchronized (mUidRejectOnQuota) {
1634 pw.print("UID reject on quota ifaces: [");
1635 final int size = mUidRejectOnQuota.size();
1636 for (int i = 0; i < size; i++) {
1637 pw.print(mUidRejectOnQuota.keyAt(i));
1638 if (i < size - 1) pw.print(",");
1639 }
1640 pw.println("]");
1641 }
1642 }
San Mehat873f2142010-01-14 10:25:07 -08001643}