blob: aacaa6a5a09ed24d5db0096ff5ccf770077c87c3 [file] [log] [blame]
San Mehat873f2142010-01-14 10:25:07 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkey47eb1022011-08-25 17:48:52 -070019import static android.Manifest.permission.DUMP;
Jeff Sharkey350083e2011-06-29 10:45:16 -070020import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070021import static android.net.NetworkStats.IFACE_ALL;
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -070022import static android.net.NetworkStats.SET_DEFAULT;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070023import static android.net.NetworkStats.TAG_NONE;
24import static android.net.NetworkStats.UID_ALL;
Jeff Sharkey350083e2011-06-29 10:45:16 -070025import static android.provider.Settings.Secure.NETSTATS_ENABLED;
Jeff Sharkeya63ba592011-07-19 23:47:12 -070026import static com.android.server.NetworkManagementSocketTagger.PROP_QTAGUID_ENABLED;
27import static com.android.server.NetworkManagementSocketTagger.kernelToTag;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070028
San Mehat873f2142010-01-14 10:25:07 -080029import android.content.Context;
San Mehat873f2142010-01-14 10:25:07 -080030import android.content.pm.PackageManager;
San Mehat4d02d002010-01-22 16:07:46 -080031import android.net.INetworkManagementEventObserver;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -070032import android.net.InterfaceConfiguration;
Robert Greenwalted126402011-01-28 15:34:55 -080033import android.net.LinkAddress;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -070034import android.net.NetworkStats;
Robert Greenwalted126402011-01-28 15:34:55 -080035import android.net.NetworkUtils;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -070036import android.net.RouteInfo;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080037import android.net.wifi.WifiConfiguration;
38import android.net.wifi.WifiConfiguration.KeyMgmt;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -070039import android.os.Binder;
San Mehat873f2142010-01-14 10:25:07 -080040import android.os.INetworkManagementService;
Jeff Sharkey9a13f362011-04-26 16:25:36 -070041import android.os.SystemClock;
Marco Nelissen62dbb222010-02-18 10:56:30 -080042import android.os.SystemProperties;
Jeff Sharkey350083e2011-06-29 10:45:16 -070043import android.provider.Settings;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080044import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080045import android.util.Slog;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -070046import android.util.SparseBooleanArray;
San Mehat873f2142010-01-14 10:25:07 -080047
Jeff Sharkey4414cea2011-06-24 17:05:24 -070048import com.google.android.collect.Lists;
49import com.google.android.collect.Maps;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -070050import com.google.android.collect.Sets;
Jeff Sharkey4414cea2011-06-24 17:05:24 -070051
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -070052import java.io.BufferedReader;
53import java.io.DataInputStream;
San Mehat873f2142010-01-14 10:25:07 -080054import java.io.File;
Jeff Sharkey47eb1022011-08-25 17:48:52 -070055import java.io.FileDescriptor;
Jeff Sharkey9a13f362011-04-26 16:25:36 -070056import java.io.FileInputStream;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070057import java.io.FileReader;
Jeff Sharkey9a13f362011-04-26 16:25:36 -070058import java.io.IOException;
Jeff Sharkey9a13f362011-04-26 16:25:36 -070059import java.io.InputStreamReader;
Jeff Sharkey47eb1022011-08-25 17:48:52 -070060import java.io.PrintWriter;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -070061import java.net.Inet4Address;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -070062import java.net.InetAddress;
63import java.util.ArrayList;
Jeff Sharkey4414cea2011-06-24 17:05:24 -070064import java.util.HashMap;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -070065import java.util.HashSet;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -070066import java.util.NoSuchElementException;
67import java.util.StringTokenizer;
Robert Greenwalte5c3afb2010-09-22 14:32:35 -070068import java.util.concurrent.CountDownLatch;
San Mehat873f2142010-01-14 10:25:07 -080069
Jeff Sharkey9a13f362011-04-26 16:25:36 -070070import libcore.io.IoUtils;
71
San Mehat873f2142010-01-14 10:25:07 -080072/**
73 * @hide
74 */
Jeff Sharkey8e9992a2011-08-23 18:37:23 -070075public class NetworkManagementService extends INetworkManagementService.Stub
76 implements Watchdog.Monitor {
Jeff Sharkeyeedcb952011-05-17 14:55:15 -070077 private static final String TAG = "NetworkManagementService";
Dianne Hackborncef65ee2010-09-30 18:27:22 -070078 private static final boolean DBG = false;
Kenny Root305bcbf2010-09-03 07:56:38 -070079 private static final String NETD_TAG = "NetdConnector";
80
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -070081 private static final int ADD = 1;
82 private static final int REMOVE = 2;
83
Jeff Sharkey4414cea2011-06-24 17:05:24 -070084 /** Path to {@code /proc/uid_stat}. */
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070085 @Deprecated
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -070086 private final File mStatsUid;
87 /** Path to {@code /proc/net/dev}. */
88 private final File mStatsIface;
Jeff Sharkey4414cea2011-06-24 17:05:24 -070089 /** Path to {@code /proc/net/xt_qtaguid/stats}. */
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -070090 private final File mStatsXtUid;
91 /** Path to {@code /proc/net/xt_qtaguid/iface_stat}. */
92 private final File mStatsXtIface;
Jeff Sharkey4414cea2011-06-24 17:05:24 -070093
Jeff Sharkey8e9992a2011-08-23 18:37:23 -070094 /**
95 * Name representing {@link #setGlobalAlert(long)} limit when delivered to
96 * {@link INetworkManagementEventObserver#limitReached(String, String)}.
97 */
98 public static final String LIMIT_GLOBAL_ALERT = "globalAlert";
99
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -0700100 /** {@link #mStatsXtUid} headers. */
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700101 private static final String KEY_IDX = "idx";
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700102 private static final String KEY_IFACE = "iface";
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700103 private static final String KEY_UID = "uid_tag_int";
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -0700104 private static final String KEY_COUNTER_SET = "cnt_set";
105 private static final String KEY_TAG_HEX = "acct_tag_hex";
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700106 private static final String KEY_RX_BYTES = "rx_bytes";
107 private static final String KEY_RX_PACKETS = "rx_packets";
108 private static final String KEY_TX_BYTES = "tx_bytes";
109 private static final String KEY_TX_PACKETS = "tx_packets";
Jeff Sharkeyeedcb952011-05-17 14:55:15 -0700110
San Mehat873f2142010-01-14 10:25:07 -0800111 class NetdResponseCode {
JP Abgrall12b933d2011-07-14 18:09:22 -0700112 /* Keep in sync with system/netd/ResponseCode.h */
San Mehat873f2142010-01-14 10:25:07 -0800113 public static final int InterfaceListResult = 110;
114 public static final int TetherInterfaceListResult = 111;
115 public static final int TetherDnsFwdTgtListResult = 112;
San Mehat72759df2010-01-19 13:50:37 -0800116 public static final int TtyListResult = 113;
San Mehat873f2142010-01-14 10:25:07 -0800117
118 public static final int TetherStatusResult = 210;
119 public static final int IpFwdStatusResult = 211;
San Mehated4fc8a2010-01-22 12:28:36 -0800120 public static final int InterfaceGetCfgResult = 213;
Robert Greenwalte3253922010-02-18 09:23:25 -0800121 public static final int SoftapStatusResult = 214;
San Mehat91cac642010-03-31 14:31:36 -0700122 public static final int InterfaceRxCounterResult = 216;
123 public static final int InterfaceTxCounterResult = 217;
124 public static final int InterfaceRxThrottleResult = 218;
125 public static final int InterfaceTxThrottleResult = 219;
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -0700126 public static final int QuotaCounterResult = 220;
127 public static final int TetheringStatsResult = 221;
Robert Greenwalte3253922010-02-18 09:23:25 -0800128
129 public static final int InterfaceChange = 600;
JP Abgrall12b933d2011-07-14 18:09:22 -0700130 public static final int BandwidthControl = 601;
San Mehat873f2142010-01-14 10:25:07 -0800131 }
132
133 /**
134 * Binder context for this service
135 */
136 private Context mContext;
137
138 /**
139 * connector object for communicating with netd
140 */
141 private NativeDaemonConnector mConnector;
142
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700143 private Thread mThread;
144 private final CountDownLatch mConnectedSignal = new CountDownLatch(1);
145
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700146 // TODO: replace with RemoteCallbackList
San Mehat4d02d002010-01-22 16:07:46 -0800147 private ArrayList<INetworkManagementEventObserver> mObservers;
148
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700149 private Object mQuotaLock = new Object();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700150 /** Set of interfaces with active quotas. */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700151 private HashSet<String> mActiveQuotaIfaces = Sets.newHashSet();
152 /** Set of interfaces with active alerts. */
153 private HashSet<String> mActiveAlertIfaces = Sets.newHashSet();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700154 /** Set of UIDs with active reject rules. */
155 private SparseBooleanArray mUidRejectOnQuota = new SparseBooleanArray();
156
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700157 private volatile boolean mBandwidthControlEnabled;
Jeff Sharkey350083e2011-06-29 10:45:16 -0700158
San Mehat873f2142010-01-14 10:25:07 -0800159 /**
160 * Constructs a new NetworkManagementService instance
161 *
162 * @param context Binder context for this service
163 */
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700164 private NetworkManagementService(Context context, File procRoot) {
San Mehat873f2142010-01-14 10:25:07 -0800165 mContext = context;
San Mehat4d02d002010-01-22 16:07:46 -0800166 mObservers = new ArrayList<INetworkManagementEventObserver>();
167
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -0700168 mStatsUid = new File(procRoot, "uid_stat");
169 mStatsIface = new File(procRoot, "net/dev");
170 mStatsXtUid = new File(procRoot, "net/xt_qtaguid/stats");
171 mStatsXtIface = new File(procRoot, "net/xt_qtaguid/iface_stat");
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700172
Marco Nelissen62dbb222010-02-18 10:56:30 -0800173 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
174 return;
175 }
176
San Mehat873f2142010-01-14 10:25:07 -0800177 mConnector = new NativeDaemonConnector(
Kenny Root305bcbf2010-09-03 07:56:38 -0700178 new NetdCallbackReceiver(), "netd", 10, NETD_TAG);
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700179 mThread = new Thread(mConnector, NETD_TAG);
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700180
181 // Add ourself to the Watchdog monitors.
182 Watchdog.getInstance().addMonitor(this);
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700183 }
184
185 public static NetworkManagementService create(Context context) throws InterruptedException {
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700186 NetworkManagementService service = new NetworkManagementService(
187 context, new File("/proc/"));
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700188 if (DBG) Slog.d(TAG, "Creating NetworkManagementService");
189 service.mThread.start();
190 if (DBG) Slog.d(TAG, "Awaiting socket connection");
191 service.mConnectedSignal.await();
192 if (DBG) Slog.d(TAG, "Connected");
193 return service;
San Mehat873f2142010-01-14 10:25:07 -0800194 }
195
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700196 // @VisibleForTesting
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -0700197 public static NetworkManagementService createForTest(
198 Context context, File procRoot, boolean bandwidthControlEnabled) {
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700199 // TODO: eventually connect with mock netd
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -0700200 final NetworkManagementService service = new NetworkManagementService(context, procRoot);
201 service.mBandwidthControlEnabled = bandwidthControlEnabled;
202 return service;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700203 }
204
Jeff Sharkey350083e2011-06-29 10:45:16 -0700205 public void systemReady() {
Jeff Sharkey350083e2011-06-29 10:45:16 -0700206 // only enable bandwidth control when support exists, and requested by
207 // system setting.
Jeff Sharkey350083e2011-06-29 10:45:16 -0700208 final boolean hasKernelSupport = new File("/proc/net/xt_qtaguid/ctrl").exists();
209 final boolean shouldEnable =
Jeff Sharkey05355c32011-08-09 14:44:19 -0700210 Settings.Secure.getInt(mContext.getContentResolver(), NETSTATS_ENABLED, 1) != 0;
Jeff Sharkey350083e2011-06-29 10:45:16 -0700211
Jeff Sharkey350083e2011-06-29 10:45:16 -0700212 if (hasKernelSupport && shouldEnable) {
213 Slog.d(TAG, "enabling bandwidth control");
214 try {
215 mConnector.doCommand("bandwidth enable");
216 mBandwidthControlEnabled = true;
217 } catch (NativeDaemonConnectorException e) {
218 Slog.e(TAG, "problem enabling bandwidth controls", e);
219 }
220 } else {
221 Slog.d(TAG, "not enabling bandwidth control");
222 }
Jeff Sharkey62a2c8f2011-07-13 15:24:02 -0700223
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700224 SystemProperties.set(PROP_QTAGUID_ENABLED, mBandwidthControlEnabled ? "1" : "0");
Jeff Sharkey350083e2011-06-29 10:45:16 -0700225 }
226
San Mehat4d02d002010-01-22 16:07:46 -0800227 public void registerObserver(INetworkManagementEventObserver obs) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800228 Slog.d(TAG, "Registering observer");
San Mehat4d02d002010-01-22 16:07:46 -0800229 mObservers.add(obs);
230 }
231
232 public void unregisterObserver(INetworkManagementEventObserver obs) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800233 Slog.d(TAG, "Unregistering observer");
San Mehat4d02d002010-01-22 16:07:46 -0800234 mObservers.remove(mObservers.indexOf(obs));
235 }
236
237 /**
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700238 * Notify our observers of an interface status change
San Mehat4d02d002010-01-22 16:07:46 -0800239 */
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700240 private void notifyInterfaceStatusChanged(String iface, boolean up) {
San Mehat4d02d002010-01-22 16:07:46 -0800241 for (INetworkManagementEventObserver obs : mObservers) {
242 try {
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700243 obs.interfaceStatusChanged(iface, up);
244 } catch (Exception ex) {
245 Slog.w(TAG, "Observer notifier failed", ex);
246 }
247 }
248 }
249
250 /**
Mike J. Chenf59c7d02011-06-23 15:33:15 -0700251 * Notify our observers of an interface link state change
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700252 * (typically, an Ethernet cable has been plugged-in or unplugged).
253 */
254 private void notifyInterfaceLinkStateChanged(String iface, boolean up) {
255 for (INetworkManagementEventObserver obs : mObservers) {
256 try {
257 obs.interfaceLinkStateChanged(iface, up);
San Mehat4d02d002010-01-22 16:07:46 -0800258 } catch (Exception ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800259 Slog.w(TAG, "Observer notifier failed", ex);
San Mehat4d02d002010-01-22 16:07:46 -0800260 }
261 }
262 }
263
264 /**
265 * Notify our observers of an interface addition.
266 */
267 private void notifyInterfaceAdded(String iface) {
268 for (INetworkManagementEventObserver obs : mObservers) {
269 try {
270 obs.interfaceAdded(iface);
271 } catch (Exception ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800272 Slog.w(TAG, "Observer notifier failed", ex);
San Mehat4d02d002010-01-22 16:07:46 -0800273 }
274 }
275 }
276
277 /**
278 * Notify our observers of an interface removal.
279 */
280 private void notifyInterfaceRemoved(String iface) {
281 for (INetworkManagementEventObserver obs : mObservers) {
282 try {
283 obs.interfaceRemoved(iface);
284 } catch (Exception ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800285 Slog.w(TAG, "Observer notifier failed", ex);
San Mehat4d02d002010-01-22 16:07:46 -0800286 }
287 }
288 }
289
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700290 /**
JP Abgrall12b933d2011-07-14 18:09:22 -0700291 * Notify our observers of a limit reached.
292 */
293 private void notifyLimitReached(String limitName, String iface) {
294 for (INetworkManagementEventObserver obs : mObservers) {
295 try {
296 obs.limitReached(limitName, iface);
JP Abgrall12b933d2011-07-14 18:09:22 -0700297 } catch (Exception ex) {
298 Slog.w(TAG, "Observer notifier failed", ex);
299 }
300 }
301 }
302
303 /**
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700304 * Let us know the daemon is connected
305 */
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700306 protected void onDaemonConnected() {
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700307 if (DBG) Slog.d(TAG, "onConnected");
308 mConnectedSignal.countDown();
309 }
310
San Mehat4d02d002010-01-22 16:07:46 -0800311
San Mehat873f2142010-01-14 10:25:07 -0800312 //
313 // Netd Callback handling
314 //
315
316 class NetdCallbackReceiver implements INativeDaemonConnectorCallbacks {
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700317 /** {@inheritDoc} */
San Mehat873f2142010-01-14 10:25:07 -0800318 public void onDaemonConnected() {
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700319 NetworkManagementService.this.onDaemonConnected();
San Mehat873f2142010-01-14 10:25:07 -0800320 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700321
322 /** {@inheritDoc} */
San Mehat873f2142010-01-14 10:25:07 -0800323 public boolean onEvent(int code, String raw, String[] cooked) {
JP Abgrall12b933d2011-07-14 18:09:22 -0700324 switch (code) {
325 case NetdResponseCode.InterfaceChange:
326 /*
327 * a network interface change occured
328 * Format: "NNN Iface added <name>"
329 * "NNN Iface removed <name>"
330 * "NNN Iface changed <name> <up/down>"
331 * "NNN Iface linkstatus <name> <up/down>"
332 */
333 if (cooked.length < 4 || !cooked[1].equals("Iface")) {
334 throw new IllegalStateException(
335 String.format("Invalid event from daemon (%s)", raw));
336 }
337 if (cooked[2].equals("added")) {
338 notifyInterfaceAdded(cooked[3]);
339 return true;
340 } else if (cooked[2].equals("removed")) {
341 notifyInterfaceRemoved(cooked[3]);
342 return true;
343 } else if (cooked[2].equals("changed") && cooked.length == 5) {
344 notifyInterfaceStatusChanged(cooked[3], cooked[4].equals("up"));
345 return true;
346 } else if (cooked[2].equals("linkstate") && cooked.length == 5) {
347 notifyInterfaceLinkStateChanged(cooked[3], cooked[4].equals("up"));
348 return true;
349 }
Robert Greenwalte3253922010-02-18 09:23:25 -0800350 throw new IllegalStateException(
351 String.format("Invalid event from daemon (%s)", raw));
JP Abgrall12b933d2011-07-14 18:09:22 -0700352 // break;
353 case NetdResponseCode.BandwidthControl:
354 /*
355 * Bandwidth control needs some attention
356 * Format: "NNN limit alert <alertName> <ifaceName>"
357 */
358 if (cooked.length < 5 || !cooked[1].equals("limit")) {
359 throw new IllegalStateException(
360 String.format("Invalid event from daemon (%s)", raw));
361 }
362 if (cooked[2].equals("alert")) {
363 notifyLimitReached(cooked[3], cooked[4]);
364 return true;
365 }
366 throw new IllegalStateException(
367 String.format("Invalid event from daemon (%s)", raw));
368 // break;
369 default: break;
Robert Greenwalte3253922010-02-18 09:23:25 -0800370 }
371 return false;
San Mehat873f2142010-01-14 10:25:07 -0800372 }
373 }
374
San Mehated4fc8a2010-01-22 12:28:36 -0800375
San Mehat873f2142010-01-14 10:25:07 -0800376 //
377 // INetworkManagementService members
378 //
379
380 public String[] listInterfaces() throws IllegalStateException {
381 mContext.enforceCallingOrSelfPermission(
382 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
383
Kenny Roota80ce062010-06-01 13:23:53 -0700384 try {
385 return mConnector.doListCommand("interface list", NetdResponseCode.InterfaceListResult);
386 } catch (NativeDaemonConnectorException e) {
387 throw new IllegalStateException(
388 "Cannot communicate with native daemon to list interfaces");
389 }
San Mehated4fc8a2010-01-22 12:28:36 -0800390 }
391
392 public InterfaceConfiguration getInterfaceConfig(String iface) throws IllegalStateException {
Kenny Roota80ce062010-06-01 13:23:53 -0700393 String rsp;
394 try {
395 rsp = mConnector.doCommand("interface getcfg " + iface).get(0);
396 } catch (NativeDaemonConnectorException e) {
397 throw new IllegalStateException(
398 "Cannot communicate with native daemon to get interface config");
399 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800400 Slog.d(TAG, String.format("rsp <%s>", rsp));
San Mehated4fc8a2010-01-22 12:28:36 -0800401
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800402 // Rsp: 213 xx:xx:xx:xx:xx:xx yyy.yyy.yyy.yyy zzz [flag1 flag2 flag3]
San Mehated4fc8a2010-01-22 12:28:36 -0800403 StringTokenizer st = new StringTokenizer(rsp);
404
Kenny Roota80ce062010-06-01 13:23:53 -0700405 InterfaceConfiguration cfg;
San Mehated4fc8a2010-01-22 12:28:36 -0800406 try {
Kenny Roota80ce062010-06-01 13:23:53 -0700407 try {
408 int code = Integer.parseInt(st.nextToken(" "));
409 if (code != NetdResponseCode.InterfaceGetCfgResult) {
410 throw new IllegalStateException(
411 String.format("Expected code %d, but got %d",
412 NetdResponseCode.InterfaceGetCfgResult, code));
413 }
414 } catch (NumberFormatException nfe) {
San Mehated4fc8a2010-01-22 12:28:36 -0800415 throw new IllegalStateException(
Kenny Roota80ce062010-06-01 13:23:53 -0700416 String.format("Invalid response from daemon (%s)", rsp));
San Mehated4fc8a2010-01-22 12:28:36 -0800417 }
Kenny Roota80ce062010-06-01 13:23:53 -0700418
419 cfg = new InterfaceConfiguration();
420 cfg.hwAddr = st.nextToken(" ");
Robert Greenwalted126402011-01-28 15:34:55 -0800421 InetAddress addr = null;
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800422 int prefixLength = 0;
Kenny Roota80ce062010-06-01 13:23:53 -0700423 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800424 addr = NetworkUtils.numericToInetAddress(st.nextToken(" "));
425 } catch (IllegalArgumentException iae) {
426 Slog.e(TAG, "Failed to parse ipaddr", iae);
Kenny Roota80ce062010-06-01 13:23:53 -0700427 }
428
429 try {
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800430 prefixLength = Integer.parseInt(st.nextToken(" "));
431 } catch (NumberFormatException nfe) {
432 Slog.e(TAG, "Failed to parse prefixLength", nfe);
Kenny Roota80ce062010-06-01 13:23:53 -0700433 }
Robert Greenwalt04808c22010-12-13 17:01:41 -0800434
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800435 cfg.addr = new LinkAddress(addr, prefixLength);
Kenny Roota80ce062010-06-01 13:23:53 -0700436 cfg.interfaceFlags = st.nextToken("]").trim() +"]";
437 } catch (NoSuchElementException nsee) {
San Mehated4fc8a2010-01-22 12:28:36 -0800438 throw new IllegalStateException(
439 String.format("Invalid response from daemon (%s)", rsp));
440 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800441 Slog.d(TAG, String.format("flags <%s>", cfg.interfaceFlags));
San Mehated4fc8a2010-01-22 12:28:36 -0800442 return cfg;
443 }
444
445 public void setInterfaceConfig(
446 String iface, InterfaceConfiguration cfg) throws IllegalStateException {
Robert Greenwalted126402011-01-28 15:34:55 -0800447 LinkAddress linkAddr = cfg.addr;
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800448 if (linkAddr == null || linkAddr.getAddress() == null) {
449 throw new IllegalStateException("Null LinkAddress given");
Robert Greenwalted126402011-01-28 15:34:55 -0800450 }
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800451 String cmd = String.format("interface setcfg %s %s %d %s", iface,
452 linkAddr.getAddress().getHostAddress(),
453 linkAddr.getNetworkPrefixLength(),
454 cfg.interfaceFlags);
Kenny Roota80ce062010-06-01 13:23:53 -0700455 try {
456 mConnector.doCommand(cmd);
457 } catch (NativeDaemonConnectorException e) {
458 throw new IllegalStateException(
Robert Greenwalt81d5ad52010-12-16 11:27:38 -0800459 "Unable to communicate with native daemon to interface setcfg - " + e);
Kenny Roota80ce062010-06-01 13:23:53 -0700460 }
San Mehat873f2142010-01-14 10:25:07 -0800461 }
462
Irfan Sheriff7244c972011-08-05 20:40:45 -0700463 public void setInterfaceDown(String iface) throws IllegalStateException {
464 try {
465 InterfaceConfiguration ifcg = getInterfaceConfig(iface);
466 ifcg.interfaceFlags = ifcg.interfaceFlags.replace("up", "down");
467 setInterfaceConfig(iface, ifcg);
468 } catch (NativeDaemonConnectorException e) {
469 throw new IllegalStateException(
470 "Unable to communicate with native daemon for interface down - " + e);
471 }
472 }
473
474 public void setInterfaceUp(String iface) throws IllegalStateException {
475 try {
476 InterfaceConfiguration ifcg = getInterfaceConfig(iface);
477 ifcg.interfaceFlags = ifcg.interfaceFlags.replace("down", "up");
478 setInterfaceConfig(iface, ifcg);
479 } catch (NativeDaemonConnectorException e) {
480 throw new IllegalStateException(
481 "Unable to communicate with native daemon for interface up - " + e);
482 }
483 }
484
Irfan Sheriff73293612011-09-14 12:31:56 -0700485 public void setInterfaceIpv6PrivacyExtensions(String iface, boolean enable)
486 throws IllegalStateException {
487 String cmd = String.format("interface ipv6privacyextensions %s %s", iface,
488 enable ? "enable" : "disable");
489 try {
490 mConnector.doCommand(cmd);
491 } catch (NativeDaemonConnectorException e) {
492 throw new IllegalStateException(
493 "Unable to communicate with native daemon to set ipv6privacyextensions - " + e);
494 }
495 }
496
497
498
Irfan Sherifff5600612011-06-16 10:26:28 -0700499 /* TODO: This is right now a IPv4 only function. Works for wifi which loses its
500 IPv6 addresses on interface down, but we need to do full clean up here */
501 public void clearInterfaceAddresses(String iface) throws IllegalStateException {
502 String cmd = String.format("interface clearaddrs %s", iface);
503 try {
504 mConnector.doCommand(cmd);
505 } catch (NativeDaemonConnectorException e) {
506 throw new IllegalStateException(
507 "Unable to communicate with native daemon to interface clearallips - " + e);
508 }
509 }
510
repo sync7960d9f2011-09-29 12:40:02 -0700511 public void enableIpv6(String iface) throws IllegalStateException {
512 mContext.enforceCallingOrSelfPermission(
513 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
514 try {
515 mConnector.doCommand(String.format("interface ipv6 %s enable", iface));
516 } catch (NativeDaemonConnectorException e) {
517 throw new IllegalStateException(
518 "Unable to communicate to native daemon for enabling ipv6");
519 }
520 }
521
522 public void disableIpv6(String iface) throws IllegalStateException {
523 mContext.enforceCallingOrSelfPermission(
524 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
525 try {
526 mConnector.doCommand(String.format("interface ipv6 %s disable", iface));
527 } catch (NativeDaemonConnectorException e) {
528 throw new IllegalStateException(
529 "Unable to communicate to native daemon for disabling ipv6");
530 }
531 }
532
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700533 public void addRoute(String interfaceName, RouteInfo route) {
534 modifyRoute(interfaceName, ADD, route);
535 }
536
537 public void removeRoute(String interfaceName, RouteInfo route) {
538 modifyRoute(interfaceName, REMOVE, route);
539 }
540
541 private void modifyRoute(String interfaceName, int action, RouteInfo route) {
542 ArrayList<String> rsp;
543
544 StringBuilder cmd;
545
546 switch (action) {
547 case ADD:
548 {
549 cmd = new StringBuilder("interface route add " + interfaceName);
550 break;
551 }
552 case REMOVE:
553 {
554 cmd = new StringBuilder("interface route remove " + interfaceName);
555 break;
556 }
557 default:
558 throw new IllegalStateException("Unknown action type " + action);
559 }
560
561 // create triplet: dest-ip-addr prefixlength gateway-ip-addr
562 LinkAddress la = route.getDestination();
563 cmd.append(' ');
564 cmd.append(la.getAddress().getHostAddress());
565 cmd.append(' ');
566 cmd.append(la.getNetworkPrefixLength());
567 cmd.append(' ');
568 if (route.getGateway() == null) {
569 if (la.getAddress() instanceof Inet4Address) {
570 cmd.append("0.0.0.0");
571 } else {
572 cmd.append ("::0");
573 }
574 } else {
575 cmd.append(route.getGateway().getHostAddress());
576 }
577 try {
578 rsp = mConnector.doCommand(cmd.toString());
579 } catch (NativeDaemonConnectorException e) {
580 throw new IllegalStateException(
581 "Unable to communicate with native dameon to add routes - "
582 + e);
583 }
584
Wink Savillec9acde92011-09-21 11:05:43 -0700585 if (DBG) {
586 for (String line : rsp) {
587 Log.v(TAG, "add route response is " + line);
588 }
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700589 }
590 }
591
592 private ArrayList<String> readRouteList(String filename) {
593 FileInputStream fstream = null;
594 ArrayList<String> list = new ArrayList<String>();
595
596 try {
597 fstream = new FileInputStream(filename);
598 DataInputStream in = new DataInputStream(fstream);
599 BufferedReader br = new BufferedReader(new InputStreamReader(in));
600 String s;
601
602 // throw away the title line
603
604 while (((s = br.readLine()) != null) && (s.length() != 0)) {
605 list.add(s);
606 }
607 } catch (IOException ex) {
608 // return current list, possibly empty
609 } finally {
610 if (fstream != null) {
611 try {
612 fstream.close();
613 } catch (IOException ex) {}
614 }
615 }
616
617 return list;
618 }
619
620 public RouteInfo[] getRoutes(String interfaceName) {
621 ArrayList<RouteInfo> routes = new ArrayList<RouteInfo>();
622
623 // v4 routes listed as:
624 // iface dest-addr gateway-addr flags refcnt use metric netmask mtu window IRTT
625 for (String s : readRouteList("/proc/net/route")) {
626 String[] fields = s.split("\t");
627
628 if (fields.length > 7) {
629 String iface = fields[0];
630
631 if (interfaceName.equals(iface)) {
632 String dest = fields[1];
633 String gate = fields[2];
634 String flags = fields[3]; // future use?
635 String mask = fields[7];
636 try {
637 // address stored as a hex string, ex: 0014A8C0
638 InetAddress destAddr =
639 NetworkUtils.intToInetAddress((int)Long.parseLong(dest, 16));
640 int prefixLength =
641 NetworkUtils.netmaskIntToPrefixLength(
642 (int)Long.parseLong(mask, 16));
643 LinkAddress linkAddress = new LinkAddress(destAddr, prefixLength);
644
645 // address stored as a hex string, ex 0014A8C0
646 InetAddress gatewayAddr =
647 NetworkUtils.intToInetAddress((int)Long.parseLong(gate, 16));
648
649 RouteInfo route = new RouteInfo(linkAddress, gatewayAddr);
650 routes.add(route);
651 } catch (Exception e) {
652 Log.e(TAG, "Error parsing route " + s + " : " + e);
653 continue;
654 }
655 }
656 }
657 }
658
659 // v6 routes listed as:
660 // dest-addr prefixlength ?? ?? gateway-addr ?? ?? ?? ?? iface
661 for (String s : readRouteList("/proc/net/ipv6_route")) {
662 String[]fields = s.split("\\s+");
663 if (fields.length > 9) {
664 String iface = fields[9].trim();
665 if (interfaceName.equals(iface)) {
666 String dest = fields[0];
667 String prefix = fields[1];
668 String gate = fields[4];
669
670 try {
671 // prefix length stored as a hex string, ex 40
672 int prefixLength = Integer.parseInt(prefix, 16);
673
674 // address stored as a 32 char hex string
675 // ex fe800000000000000000000000000000
676 InetAddress destAddr = NetworkUtils.hexToInet6Address(dest);
677 LinkAddress linkAddress = new LinkAddress(destAddr, prefixLength);
678
679 InetAddress gateAddr = NetworkUtils.hexToInet6Address(gate);
680
681 RouteInfo route = new RouteInfo(linkAddress, gateAddr);
682 routes.add(route);
683 } catch (Exception e) {
684 Log.e(TAG, "Error parsing route " + s + " : " + e);
685 continue;
686 }
687 }
688 }
689 }
690 return (RouteInfo[]) routes.toArray(new RouteInfo[0]);
691 }
692
San Mehat873f2142010-01-14 10:25:07 -0800693 public void shutdown() {
694 if (mContext.checkCallingOrSelfPermission(
695 android.Manifest.permission.SHUTDOWN)
696 != PackageManager.PERMISSION_GRANTED) {
697 throw new SecurityException("Requires SHUTDOWN permission");
698 }
699
Joe Onorato8a9b2202010-02-26 18:56:32 -0800700 Slog.d(TAG, "Shutting down");
San Mehat873f2142010-01-14 10:25:07 -0800701 }
702
703 public boolean getIpForwardingEnabled() throws IllegalStateException{
704 mContext.enforceCallingOrSelfPermission(
705 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
706
Kenny Roota80ce062010-06-01 13:23:53 -0700707 ArrayList<String> rsp;
708 try {
709 rsp = mConnector.doCommand("ipfwd status");
710 } catch (NativeDaemonConnectorException e) {
711 throw new IllegalStateException(
712 "Unable to communicate with native daemon to ipfwd status");
713 }
San Mehat873f2142010-01-14 10:25:07 -0800714
715 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700716 String[] tok = line.split(" ");
717 if (tok.length < 3) {
718 Slog.e(TAG, "Malformed response from native daemon: " + line);
719 return false;
720 }
721
San Mehat873f2142010-01-14 10:25:07 -0800722 int code = Integer.parseInt(tok[0]);
723 if (code == NetdResponseCode.IpFwdStatusResult) {
724 // 211 Forwarding <enabled/disabled>
Kenny Roota80ce062010-06-01 13:23:53 -0700725 return "enabled".equals(tok[2]);
San Mehat873f2142010-01-14 10:25:07 -0800726 } else {
727 throw new IllegalStateException(String.format("Unexpected response code %d", code));
728 }
729 }
730 throw new IllegalStateException("Got an empty response");
731 }
732
733 public void setIpForwardingEnabled(boolean enable) throws IllegalStateException {
734 mContext.enforceCallingOrSelfPermission(
735 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
736 mConnector.doCommand(String.format("ipfwd %sable", (enable ? "en" : "dis")));
737 }
738
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -0700739 public void startTethering(String[] dhcpRange)
San Mehat873f2142010-01-14 10:25:07 -0800740 throws IllegalStateException {
741 mContext.enforceCallingOrSelfPermission(
742 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -0700743 // cmd is "tether start first_start first_stop second_start second_stop ..."
744 // an odd number of addrs will fail
745 String cmd = "tether start";
746 for (String d : dhcpRange) {
747 cmd += " " + d;
748 }
Kenny Roota80ce062010-06-01 13:23:53 -0700749
750 try {
751 mConnector.doCommand(cmd);
752 } catch (NativeDaemonConnectorException e) {
753 throw new IllegalStateException("Unable to communicate to native daemon");
754 }
San Mehat873f2142010-01-14 10:25:07 -0800755 }
756
757 public void stopTethering() throws IllegalStateException {
758 mContext.enforceCallingOrSelfPermission(
759 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700760 try {
761 mConnector.doCommand("tether stop");
762 } catch (NativeDaemonConnectorException e) {
763 throw new IllegalStateException("Unable to communicate to native daemon to stop tether");
764 }
San Mehat873f2142010-01-14 10:25:07 -0800765 }
766
767 public boolean isTetheringStarted() throws IllegalStateException {
768 mContext.enforceCallingOrSelfPermission(
769 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
770
Kenny Roota80ce062010-06-01 13:23:53 -0700771 ArrayList<String> rsp;
772 try {
773 rsp = mConnector.doCommand("tether status");
774 } catch (NativeDaemonConnectorException e) {
775 throw new IllegalStateException(
776 "Unable to communicate to native daemon to get tether status");
777 }
San Mehat873f2142010-01-14 10:25:07 -0800778
779 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700780 String[] tok = line.split(" ");
781 if (tok.length < 3) {
782 throw new IllegalStateException("Malformed response for tether status: " + line);
783 }
San Mehat873f2142010-01-14 10:25:07 -0800784 int code = Integer.parseInt(tok[0]);
785 if (code == NetdResponseCode.TetherStatusResult) {
786 // XXX: Tethering services <started/stopped> <TBD>...
Kenny Roota80ce062010-06-01 13:23:53 -0700787 return "started".equals(tok[2]);
San Mehat873f2142010-01-14 10:25:07 -0800788 } else {
789 throw new IllegalStateException(String.format("Unexpected response code %d", code));
790 }
791 }
792 throw new IllegalStateException("Got an empty response");
793 }
794
795 public void tetherInterface(String iface) throws IllegalStateException {
796 mContext.enforceCallingOrSelfPermission(
797 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700798 try {
799 mConnector.doCommand("tether interface add " + iface);
800 } catch (NativeDaemonConnectorException e) {
801 throw new IllegalStateException(
802 "Unable to communicate to native daemon for adding tether interface");
803 }
San Mehat873f2142010-01-14 10:25:07 -0800804 }
805
806 public void untetherInterface(String iface) {
807 mContext.enforceCallingOrSelfPermission(
808 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700809 try {
810 mConnector.doCommand("tether interface remove " + iface);
811 } catch (NativeDaemonConnectorException e) {
812 throw new IllegalStateException(
813 "Unable to communicate to native daemon for removing tether interface");
814 }
San Mehat873f2142010-01-14 10:25:07 -0800815 }
816
817 public String[] listTetheredInterfaces() throws IllegalStateException {
818 mContext.enforceCallingOrSelfPermission(
819 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700820 try {
821 return mConnector.doListCommand(
822 "tether interface list", NetdResponseCode.TetherInterfaceListResult);
823 } catch (NativeDaemonConnectorException e) {
824 throw new IllegalStateException(
825 "Unable to communicate to native daemon for listing tether interfaces");
826 }
San Mehat873f2142010-01-14 10:25:07 -0800827 }
828
829 public void setDnsForwarders(String[] dns) throws IllegalStateException {
830 mContext.enforceCallingOrSelfPermission(
831 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
832 try {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800833 String cmd = "tether dns set";
San Mehat873f2142010-01-14 10:25:07 -0800834 for (String s : dns) {
Robert Greenwalte5903732011-02-22 16:00:42 -0800835 cmd += " " + NetworkUtils.numericToInetAddress(s).getHostAddress();
San Mehat873f2142010-01-14 10:25:07 -0800836 }
Kenny Roota80ce062010-06-01 13:23:53 -0700837 try {
838 mConnector.doCommand(cmd);
839 } catch (NativeDaemonConnectorException e) {
840 throw new IllegalStateException(
841 "Unable to communicate to native daemon for setting tether dns");
842 }
Robert Greenwalte5903732011-02-22 16:00:42 -0800843 } catch (IllegalArgumentException e) {
San Mehat873f2142010-01-14 10:25:07 -0800844 throw new IllegalStateException("Error resolving dns name", e);
845 }
846 }
847
848 public String[] getDnsForwarders() throws IllegalStateException {
849 mContext.enforceCallingOrSelfPermission(
850 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700851 try {
852 return mConnector.doListCommand(
853 "tether dns list", NetdResponseCode.TetherDnsFwdTgtListResult);
854 } catch (NativeDaemonConnectorException e) {
855 throw new IllegalStateException(
856 "Unable to communicate to native daemon for listing tether dns");
857 }
San Mehat873f2142010-01-14 10:25:07 -0800858 }
859
860 public void enableNat(String internalInterface, String externalInterface)
861 throws IllegalStateException {
862 mContext.enforceCallingOrSelfPermission(
863 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700864 try {
865 mConnector.doCommand(
866 String.format("nat enable %s %s", internalInterface, externalInterface));
867 } catch (NativeDaemonConnectorException e) {
868 throw new IllegalStateException(
869 "Unable to communicate to native daemon for enabling NAT interface");
870 }
San Mehat873f2142010-01-14 10:25:07 -0800871 }
872
873 public void disableNat(String internalInterface, String externalInterface)
874 throws IllegalStateException {
875 mContext.enforceCallingOrSelfPermission(
876 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700877 try {
878 mConnector.doCommand(
879 String.format("nat disable %s %s", internalInterface, externalInterface));
880 } catch (NativeDaemonConnectorException e) {
881 throw new IllegalStateException(
882 "Unable to communicate to native daemon for disabling NAT interface");
883 }
San Mehat873f2142010-01-14 10:25:07 -0800884 }
San Mehat72759df2010-01-19 13:50:37 -0800885
886 public String[] listTtys() throws IllegalStateException {
887 mContext.enforceCallingOrSelfPermission(
888 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700889 try {
890 return mConnector.doListCommand("list_ttys", NetdResponseCode.TtyListResult);
891 } catch (NativeDaemonConnectorException e) {
892 throw new IllegalStateException(
893 "Unable to communicate to native daemon for listing TTYs");
894 }
San Mehat72759df2010-01-19 13:50:37 -0800895 }
896
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800897 public void attachPppd(String tty, String localAddr, String remoteAddr, String dns1Addr,
898 String dns2Addr) throws IllegalStateException {
San Mehat72759df2010-01-19 13:50:37 -0800899 try {
900 mContext.enforceCallingOrSelfPermission(
901 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800902 mConnector.doCommand(String.format("pppd attach %s %s %s %s %s", tty,
Robert Greenwalte5903732011-02-22 16:00:42 -0800903 NetworkUtils.numericToInetAddress(localAddr).getHostAddress(),
904 NetworkUtils.numericToInetAddress(remoteAddr).getHostAddress(),
905 NetworkUtils.numericToInetAddress(dns1Addr).getHostAddress(),
906 NetworkUtils.numericToInetAddress(dns2Addr).getHostAddress()));
907 } catch (IllegalArgumentException e) {
San Mehat72759df2010-01-19 13:50:37 -0800908 throw new IllegalStateException("Error resolving addr", e);
Kenny Roota80ce062010-06-01 13:23:53 -0700909 } catch (NativeDaemonConnectorException e) {
910 throw new IllegalStateException("Error communicating to native daemon to attach pppd", e);
San Mehat72759df2010-01-19 13:50:37 -0800911 }
912 }
913
914 public void detachPppd(String tty) throws IllegalStateException {
915 mContext.enforceCallingOrSelfPermission(
916 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700917 try {
918 mConnector.doCommand(String.format("pppd detach %s", tty));
919 } catch (NativeDaemonConnectorException e) {
920 throw new IllegalStateException("Error communicating to native daemon to detach pppd", e);
921 }
San Mehat72759df2010-01-19 13:50:37 -0800922 }
Robert Greenwaltce1200d2010-02-18 11:25:54 -0800923
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700924 public void startAccessPoint(WifiConfiguration wifiConfig, String wlanIface, String softapIface)
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800925 throws IllegalStateException {
926 mContext.enforceCallingOrSelfPermission(
927 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
928 mContext.enforceCallingOrSelfPermission(
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700929 android.Manifest.permission.CHANGE_WIFI_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700930 try {
Irfan Sheriffcb30b222011-07-29 20:54:52 -0700931 wifiFirmwareReload(wlanIface, "AP");
Kenny Roota80ce062010-06-01 13:23:53 -0700932 mConnector.doCommand(String.format("softap start " + wlanIface));
933 if (wifiConfig == null) {
934 mConnector.doCommand(String.format("softap set " + wlanIface + " " + softapIface));
935 } else {
936 /**
937 * softap set arg1 arg2 arg3 [arg4 arg5 arg6 arg7 arg8]
938 * argv1 - wlan interface
939 * argv2 - softap interface
940 * argv3 - SSID
941 * argv4 - Security
942 * argv5 - Key
943 * argv6 - Channel
944 * argv7 - Preamble
945 * argv8 - Max SCB
946 */
Irfan Sheriffec8d23a2011-02-16 17:00:33 -0800947 String str = String.format("softap set " + wlanIface + " " + softapIface +
948 " %s %s %s", convertQuotedString(wifiConfig.SSID),
949 getSecurityType(wifiConfig),
950 convertQuotedString(wifiConfig.preSharedKey));
Kenny Roota80ce062010-06-01 13:23:53 -0700951 mConnector.doCommand(str);
952 }
953 mConnector.doCommand(String.format("softap startap"));
954 } catch (NativeDaemonConnectorException e) {
955 throw new IllegalStateException("Error communicating to native daemon to start softap", e);
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800956 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800957 }
958
Irfan Sheriffa6e559e2010-05-24 14:55:42 -0700959 private String convertQuotedString(String s) {
Irfan Sheriff7baec0f2010-05-26 17:16:47 -0700960 if (s == null) {
961 return s;
962 }
963 /* Replace \ with \\, then " with \" and add quotes at end */
964 return '"' + s.replaceAll("\\\\","\\\\\\\\").replaceAll("\"","\\\\\"") + '"';
Irfan Sheriffa6e559e2010-05-24 14:55:42 -0700965 }
966
Irfan Sheriffec8d23a2011-02-16 17:00:33 -0800967 private String getSecurityType(WifiConfiguration wifiConfig) {
968 switch (wifiConfig.getAuthType()) {
969 case KeyMgmt.WPA_PSK:
970 return "wpa-psk";
971 case KeyMgmt.WPA2_PSK:
972 return "wpa2-psk";
973 default:
974 return "open";
975 }
976 }
977
Irfan Sheriffcb30b222011-07-29 20:54:52 -0700978 /* @param mode can be "AP", "STA" or "P2P" */
979 public void wifiFirmwareReload(String wlanIface, String mode) throws IllegalStateException {
980 mContext.enforceCallingOrSelfPermission(
981 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
982 mContext.enforceCallingOrSelfPermission(
983 android.Manifest.permission.CHANGE_WIFI_STATE, "NetworkManagementService");
984
985 try {
986 mConnector.doCommand(String.format("softap fwreload " + wlanIface + " " + mode));
987 } catch (NativeDaemonConnectorException e) {
988 throw new IllegalStateException("Error communicating to native daemon ", e);
989 }
990 }
991
Irfan Sheriff23eb2972011-07-22 15:21:10 -0700992 public void stopAccessPoint(String wlanIface) throws IllegalStateException {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800993 mContext.enforceCallingOrSelfPermission(
994 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
995 mContext.enforceCallingOrSelfPermission(
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700996 android.Manifest.permission.CHANGE_WIFI_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -0700997 try {
998 mConnector.doCommand("softap stopap");
Irfan Sheriff23eb2972011-07-22 15:21:10 -0700999 mConnector.doCommand("softap stop " + wlanIface);
Irfan Sheriffcb30b222011-07-29 20:54:52 -07001000 wifiFirmwareReload(wlanIface, "STA");
Kenny Roota80ce062010-06-01 13:23:53 -07001001 } catch (NativeDaemonConnectorException e) {
1002 throw new IllegalStateException("Error communicating to native daemon to stop soft AP",
1003 e);
1004 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001005 }
1006
Irfan Sheriffc2f54c22010-03-18 14:02:22 -07001007 public void setAccessPoint(WifiConfiguration wifiConfig, String wlanIface, String softapIface)
1008 throws IllegalStateException {
1009 mContext.enforceCallingOrSelfPermission(
1010 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
1011 mContext.enforceCallingOrSelfPermission(
1012 android.Manifest.permission.CHANGE_WIFI_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -07001013 try {
1014 if (wifiConfig == null) {
1015 mConnector.doCommand(String.format("softap set " + wlanIface + " " + softapIface));
1016 } else {
1017 String str = String.format("softap set " + wlanIface + " " + softapIface
1018 + " %s %s %s", convertQuotedString(wifiConfig.SSID),
Irfan Sheriffec8d23a2011-02-16 17:00:33 -08001019 getSecurityType(wifiConfig),
Kenny Roota80ce062010-06-01 13:23:53 -07001020 convertQuotedString(wifiConfig.preSharedKey));
1021 mConnector.doCommand(str);
1022 }
1023 } catch (NativeDaemonConnectorException e) {
1024 throw new IllegalStateException("Error communicating to native daemon to set soft AP",
1025 e);
Irfan Sheriffc2f54c22010-03-18 14:02:22 -07001026 }
1027 }
San Mehat91cac642010-03-31 14:31:36 -07001028
1029 private long getInterfaceCounter(String iface, boolean rx) {
1030 mContext.enforceCallingOrSelfPermission(
1031 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
1032 try {
Kenny Roota80ce062010-06-01 13:23:53 -07001033 String rsp;
1034 try {
1035 rsp = mConnector.doCommand(
1036 String.format("interface read%scounter %s", (rx ? "rx" : "tx"), iface)).get(0);
1037 } catch (NativeDaemonConnectorException e1) {
1038 Slog.e(TAG, "Error communicating with native daemon", e1);
1039 return -1;
1040 }
1041
1042 String[] tok = rsp.split(" ");
1043 if (tok.length < 2) {
1044 Slog.e(TAG, String.format("Malformed response for reading %s interface",
1045 (rx ? "rx" : "tx")));
1046 return -1;
1047 }
1048
San Mehat91cac642010-03-31 14:31:36 -07001049 int code;
1050 try {
1051 code = Integer.parseInt(tok[0]);
1052 } catch (NumberFormatException nfe) {
1053 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
1054 return -1;
1055 }
1056 if ((rx && code != NetdResponseCode.InterfaceRxCounterResult) || (
1057 !rx && code != NetdResponseCode.InterfaceTxCounterResult)) {
1058 Slog.e(TAG, String.format("Unexpected response code %d", code));
1059 return -1;
1060 }
1061 return Long.parseLong(tok[1]);
1062 } catch (Exception e) {
1063 Slog.e(TAG, String.format(
1064 "Failed to read interface %s counters", (rx ? "rx" : "tx")), e);
1065 }
1066 return -1;
1067 }
1068
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001069 @Override
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001070 public NetworkStats getNetworkStatsSummary() {
1071 mContext.enforceCallingOrSelfPermission(
1072 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
1073
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001074 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 6);
1075 final NetworkStats.Entry entry = new NetworkStats.Entry();
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001076
Jeff Sharkey0fea8232011-09-01 01:07:31 -07001077 final HashSet<String> knownIfaces = Sets.newHashSet();
1078 final HashSet<String> activeIfaces = Sets.newHashSet();
1079
1080 // collect any historical stats and active state
1081 // TODO: migrate to reading from single file
1082 if (mBandwidthControlEnabled) {
1083 for (String iface : fileListWithoutNull(mStatsXtIface)) {
1084 final File ifacePath = new File(mStatsXtIface, iface);
1085
1086 final long active = readSingleLongFromFile(new File(ifacePath, "active"));
1087 if (active == 1) {
1088 knownIfaces.add(iface);
1089 activeIfaces.add(iface);
1090 } else if (active == 0) {
1091 knownIfaces.add(iface);
1092 } else {
1093 continue;
1094 }
1095
1096 entry.iface = iface;
1097 entry.uid = UID_ALL;
1098 entry.set = SET_DEFAULT;
1099 entry.tag = TAG_NONE;
1100 entry.rxBytes = readSingleLongFromFile(new File(ifacePath, "rx_bytes"));
1101 entry.rxPackets = readSingleLongFromFile(new File(ifacePath, "rx_packets"));
1102 entry.txBytes = readSingleLongFromFile(new File(ifacePath, "tx_bytes"));
1103 entry.txPackets = readSingleLongFromFile(new File(ifacePath, "tx_packets"));
1104
1105 stats.addValues(entry);
1106 }
1107 }
1108
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001109 final ArrayList<String> values = Lists.newArrayList();
1110
1111 BufferedReader reader = null;
1112 try {
1113 reader = new BufferedReader(new FileReader(mStatsIface));
1114
1115 // skip first two header lines
1116 reader.readLine();
1117 reader.readLine();
1118
1119 // parse remaining lines
1120 String line;
1121 while ((line = reader.readLine()) != null) {
1122 splitLine(line, values);
1123
1124 try {
1125 entry.iface = values.get(0);
1126 entry.uid = UID_ALL;
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001127 entry.set = SET_DEFAULT;
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001128 entry.tag = TAG_NONE;
1129 entry.rxBytes = Long.parseLong(values.get(1));
1130 entry.rxPackets = Long.parseLong(values.get(2));
1131 entry.txBytes = Long.parseLong(values.get(9));
1132 entry.txPackets = Long.parseLong(values.get(10));
1133
Jeff Sharkey0fea8232011-09-01 01:07:31 -07001134 if (activeIfaces.contains(entry.iface)) {
1135 // combine stats when iface is active
1136 stats.combineValues(entry);
1137 } else if (!knownIfaces.contains(entry.iface)) {
1138 // add stats when iface is unknown
1139 stats.addValues(entry);
1140 }
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001141 } catch (NumberFormatException e) {
1142 Slog.w(TAG, "problem parsing stats row '" + line + "': " + e);
1143 }
1144 }
Jeff Sharkey558a2322011-08-24 15:42:09 -07001145 } catch (NullPointerException e) {
1146 throw new IllegalStateException("problem parsing stats: " + e);
1147 } catch (NumberFormatException e) {
1148 throw new IllegalStateException("problem parsing stats: " + e);
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001149 } catch (IOException e) {
Jeff Sharkey558a2322011-08-24 15:42:09 -07001150 throw new IllegalStateException("problem parsing stats: " + e);
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001151 } finally {
1152 IoUtils.closeQuietly(reader);
1153 }
1154
Jeff Sharkey4a971222011-06-11 22:16:55 -07001155 return stats;
San Mehat91cac642010-03-31 14:31:36 -07001156 }
1157
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001158 @Override
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001159 public NetworkStats getNetworkStatsDetail() {
1160 mContext.enforceCallingOrSelfPermission(
1161 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
1162
Jeff Sharkey350083e2011-06-29 10:45:16 -07001163 if (mBandwidthControlEnabled) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001164 return getNetworkStatsDetailNetfilter(UID_ALL);
1165 } else {
1166 return getNetworkStatsDetailUidstat(UID_ALL);
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001167 }
San Mehat91cac642010-03-31 14:31:36 -07001168 }
1169
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001170 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001171 public void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001172 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)) {
1180 throw new IllegalStateException("iface " + iface + " already has quota");
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001181 }
1182
1183 final StringBuilder command = new StringBuilder();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001184 command.append("bandwidth setiquota ").append(iface).append(" ").append(quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001185
1186 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001187 // TODO: support quota shared across interfaces
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001188 mConnector.doCommand(command.toString());
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001189 mActiveQuotaIfaces.add(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001190 } catch (NativeDaemonConnectorException e) {
1191 throw new IllegalStateException("Error communicating to native daemon", e);
1192 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001193 }
1194 }
1195
1196 @Override
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001197 public void removeInterfaceQuota(String iface) {
1198 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1199
Jeff Sharkey350083e2011-06-29 10:45:16 -07001200 // silently discard when control disabled
1201 // TODO: eventually migrate to be always enabled
1202 if (!mBandwidthControlEnabled) return;
1203
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001204 synchronized (mQuotaLock) {
1205 if (!mActiveQuotaIfaces.contains(iface)) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001206 // TODO: eventually consider throwing
1207 return;
1208 }
1209
1210 final StringBuilder command = new StringBuilder();
1211 command.append("bandwidth removeiquota ").append(iface);
1212
1213 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001214 // TODO: support quota shared across interfaces
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001215 mConnector.doCommand(command.toString());
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001216 mActiveQuotaIfaces.remove(iface);
1217 mActiveAlertIfaces.remove(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001218 } catch (NativeDaemonConnectorException e) {
1219 throw new IllegalStateException("Error communicating to native daemon", e);
1220 }
1221 }
1222 }
1223
1224 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001225 public void setInterfaceAlert(String iface, long alertBytes) {
1226 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1227
1228 // silently discard when control disabled
1229 // TODO: eventually migrate to be always enabled
1230 if (!mBandwidthControlEnabled) return;
1231
1232 // quick sanity check
1233 if (!mActiveQuotaIfaces.contains(iface)) {
1234 throw new IllegalStateException("setting alert requires existing quota on iface");
1235 }
1236
1237 synchronized (mQuotaLock) {
1238 if (mActiveAlertIfaces.contains(iface)) {
1239 throw new IllegalStateException("iface " + iface + " already has alert");
1240 }
1241
1242 final StringBuilder command = new StringBuilder();
1243 command.append("bandwidth setinterfacealert ").append(iface).append(" ").append(
1244 alertBytes);
1245
1246 try {
1247 // TODO: support alert shared across interfaces
1248 mConnector.doCommand(command.toString());
1249 mActiveAlertIfaces.add(iface);
1250 } catch (NativeDaemonConnectorException e) {
1251 throw new IllegalStateException("Error communicating to native daemon", e);
1252 }
1253 }
1254 }
1255
1256 @Override
1257 public void removeInterfaceAlert(String iface) {
1258 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1259
1260 // silently discard when control disabled
1261 // TODO: eventually migrate to be always enabled
1262 if (!mBandwidthControlEnabled) return;
1263
1264 synchronized (mQuotaLock) {
1265 if (!mActiveAlertIfaces.contains(iface)) {
1266 // TODO: eventually consider throwing
1267 return;
1268 }
1269
1270 final StringBuilder command = new StringBuilder();
1271 command.append("bandwidth removeinterfacealert ").append(iface);
1272
1273 try {
1274 // TODO: support alert shared across interfaces
1275 mConnector.doCommand(command.toString());
1276 mActiveAlertIfaces.remove(iface);
1277 } catch (NativeDaemonConnectorException e) {
1278 throw new IllegalStateException("Error communicating to native daemon", e);
1279 }
1280 }
1281 }
1282
1283 @Override
1284 public void setGlobalAlert(long alertBytes) {
1285 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1286
1287 // silently discard when control disabled
1288 // TODO: eventually migrate to be always enabled
1289 if (!mBandwidthControlEnabled) return;
1290
1291 final StringBuilder command = new StringBuilder();
1292 command.append("bandwidth setglobalalert ").append(alertBytes);
1293
1294 try {
1295 mConnector.doCommand(command.toString());
1296 } catch (NativeDaemonConnectorException e) {
1297 throw new IllegalStateException("Error communicating to native daemon", e);
1298 }
1299 }
1300
1301 @Override
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001302 public void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
1303 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1304
Jeff Sharkey350083e2011-06-29 10:45:16 -07001305 // silently discard when control disabled
1306 // TODO: eventually migrate to be always enabled
1307 if (!mBandwidthControlEnabled) return;
1308
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001309 synchronized (mUidRejectOnQuota) {
1310 final boolean oldRejectOnQuota = mUidRejectOnQuota.get(uid, false);
1311 if (oldRejectOnQuota == rejectOnQuotaInterfaces) {
1312 // TODO: eventually consider throwing
1313 return;
1314 }
1315
1316 final StringBuilder command = new StringBuilder();
1317 command.append("bandwidth");
1318 if (rejectOnQuotaInterfaces) {
1319 command.append(" addnaughtyapps");
1320 } else {
1321 command.append(" removenaughtyapps");
1322 }
1323 command.append(" ").append(uid);
1324
1325 try {
1326 mConnector.doCommand(command.toString());
1327 if (rejectOnQuotaInterfaces) {
1328 mUidRejectOnQuota.put(uid, true);
1329 } else {
1330 mUidRejectOnQuota.delete(uid);
1331 }
1332 } catch (NativeDaemonConnectorException e) {
1333 throw new IllegalStateException("Error communicating to native daemon", e);
1334 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001335 }
1336 }
1337
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001338 @Override
1339 public boolean isBandwidthControlEnabled() {
1340 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1341 return mBandwidthControlEnabled;
1342 }
1343
1344 @Override
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001345 public NetworkStats getNetworkStatsUidDetail(int uid) {
1346 if (Binder.getCallingUid() != uid) {
1347 mContext.enforceCallingOrSelfPermission(
1348 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
1349 }
1350
Jeff Sharkey350083e2011-06-29 10:45:16 -07001351 if (mBandwidthControlEnabled) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001352 return getNetworkStatsDetailNetfilter(uid);
1353 } else {
1354 return getNetworkStatsDetailUidstat(uid);
1355 }
1356 }
1357
1358 /**
1359 * Build {@link NetworkStats} with detailed UID statistics.
1360 */
1361 private NetworkStats getNetworkStatsDetailNetfilter(int limitUid) {
1362 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 24);
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001363 final NetworkStats.Entry entry = new NetworkStats.Entry();
1364
Jeff Sharkeya63ba592011-07-19 23:47:12 -07001365 // TODO: remove knownLines check once 5087722 verified
1366 final HashSet<String> knownLines = Sets.newHashSet();
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001367 // TODO: remove lastIdx check once 5270106 verified
JP Abgrall6acf39b2011-09-08 15:13:26 -07001368 int lastIdx;
Jeff Sharkeya63ba592011-07-19 23:47:12 -07001369
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001370 final ArrayList<String> keys = Lists.newArrayList();
1371 final ArrayList<String> values = Lists.newArrayList();
1372 final HashMap<String, String> parsed = Maps.newHashMap();
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001373
1374 BufferedReader reader = null;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001375 String line = null;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001376 try {
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001377 reader = new BufferedReader(new FileReader(mStatsXtUid));
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001378
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001379 // parse first line as header
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001380 line = reader.readLine();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001381 splitLine(line, keys);
JP Abgrall6acf39b2011-09-08 15:13:26 -07001382 lastIdx = 1;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001383
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001384 // parse remaining lines
1385 while ((line = reader.readLine()) != null) {
1386 splitLine(line, values);
1387 parseLine(keys, values, parsed);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001388
Jeff Sharkeya63ba592011-07-19 23:47:12 -07001389 if (!knownLines.add(line)) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001390 throw new IllegalStateException("duplicate proc entry: " + line);
Jeff Sharkeya63ba592011-07-19 23:47:12 -07001391 }
1392
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001393 final int idx = getParsedInt(parsed, KEY_IDX);
JP Abgrall6acf39b2011-09-08 15:13:26 -07001394 if (idx != lastIdx + 1) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001395 throw new IllegalStateException(
1396 "inconsistent idx=" + idx + " after lastIdx=" + lastIdx);
1397 }
1398 lastIdx = idx;
Jeff Sharkeyd03fd3f2011-06-19 20:55:09 -07001399
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001400 entry.iface = parsed.get(KEY_IFACE);
1401 entry.uid = getParsedInt(parsed, KEY_UID);
1402 entry.set = getParsedInt(parsed, KEY_COUNTER_SET);
1403 entry.tag = kernelToTag(parsed.get(KEY_TAG_HEX));
1404 entry.rxBytes = getParsedLong(parsed, KEY_RX_BYTES);
1405 entry.rxPackets = getParsedLong(parsed, KEY_RX_PACKETS);
1406 entry.txBytes = getParsedLong(parsed, KEY_TX_BYTES);
1407 entry.txPackets = getParsedLong(parsed, KEY_TX_PACKETS);
1408
1409 if (limitUid == UID_ALL || limitUid == entry.uid) {
1410 stats.addValues(entry);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001411 }
1412 }
Jeff Sharkey558a2322011-08-24 15:42:09 -07001413 } catch (NullPointerException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001414 throw new IllegalStateException("problem parsing line: " + line, e);
Jeff Sharkey558a2322011-08-24 15:42:09 -07001415 } catch (NumberFormatException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001416 throw new IllegalStateException("problem parsing line: " + line, e);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001417 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001418 throw new IllegalStateException("problem parsing line: " + line, e);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001419 } finally {
1420 IoUtils.closeQuietly(reader);
1421 }
1422
Jeff Sharkey4a971222011-06-11 22:16:55 -07001423 return stats;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001424 }
1425
Jeff Sharkeya63ba592011-07-19 23:47:12 -07001426 private static int getParsedInt(HashMap<String, String> parsed, String key) {
1427 final String value = parsed.get(key);
1428 return value != null ? Integer.parseInt(value) : 0;
1429 }
1430
1431 private static long getParsedLong(HashMap<String, String> parsed, String key) {
1432 final String value = parsed.get(key);
1433 return value != null ? Long.parseLong(value) : 0;
1434 }
1435
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001436 /**
1437 * Build {@link NetworkStats} with detailed UID statistics.
1438 *
1439 * @deprecated since this uses older "uid_stat" data, and doesn't provide
1440 * tag-level granularity or additional variables.
1441 */
1442 @Deprecated
1443 private NetworkStats getNetworkStatsDetailUidstat(int limitUid) {
1444 final String[] knownUids;
1445 if (limitUid == UID_ALL) {
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001446 knownUids = fileListWithoutNull(mStatsUid);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001447 } else {
1448 knownUids = new String[] { String.valueOf(limitUid) };
1449 }
1450
1451 final NetworkStats stats = new NetworkStats(
1452 SystemClock.elapsedRealtime(), knownUids.length);
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001453 final NetworkStats.Entry entry = new NetworkStats.Entry();
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001454 for (String uid : knownUids) {
1455 final int uidInt = Integer.parseInt(uid);
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001456 final File uidPath = new File(mStatsUid, uid);
1457
1458 entry.iface = IFACE_ALL;
1459 entry.uid = uidInt;
1460 entry.tag = TAG_NONE;
1461 entry.rxBytes = readSingleLongFromFile(new File(uidPath, "tcp_rcv"));
1462 entry.rxPackets = readSingleLongFromFile(new File(uidPath, "tcp_rcv_pkt"));
1463 entry.txBytes = readSingleLongFromFile(new File(uidPath, "tcp_snd"));
1464 entry.txPackets = readSingleLongFromFile(new File(uidPath, "tcp_snd_pkt"));
1465
1466 stats.addValues(entry);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001467 }
1468
1469 return stats;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001470 }
1471
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001472 @Override
1473 public NetworkStats getNetworkStatsTethering(String[] ifacePairs) {
1474 mContext.enforceCallingOrSelfPermission(
1475 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
1476
1477 if (ifacePairs.length % 2 != 0) {
1478 throw new IllegalArgumentException(
1479 "unexpected ifacePairs; length=" + ifacePairs.length);
1480 }
1481
1482 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 1);
1483 for (int i = 0; i < ifacePairs.length; i += 2) {
1484 final String ifaceIn = ifacePairs[i];
1485 final String ifaceOut = ifacePairs[i + 1];
1486 if (ifaceIn != null && ifaceOut != null) {
1487 stats.combineValues(getNetworkStatsTethering(ifaceIn, ifaceOut));
1488 }
1489 }
1490 return stats;
1491 }
1492
1493 private NetworkStats.Entry getNetworkStatsTethering(String ifaceIn, String ifaceOut) {
1494 final StringBuilder command = new StringBuilder();
1495 command.append("bandwidth gettetherstats ").append(ifaceIn).append(" ").append(ifaceOut);
1496
1497 final String rsp;
1498 try {
1499 rsp = mConnector.doCommand(command.toString()).get(0);
1500 } catch (NativeDaemonConnectorException e) {
1501 throw new IllegalStateException("Error communicating to native daemon", e);
1502 }
1503
1504 final String[] tok = rsp.split(" ");
1505 /* Expecting: "code ifaceIn ifaceOut rx_bytes rx_packets tx_bytes tx_packets" */
1506 if (tok.length != 7) {
1507 throw new IllegalStateException("Native daemon returned unexpected result: " + rsp);
1508 }
1509
1510 final int code;
1511 try {
1512 code = Integer.parseInt(tok[0]);
1513 } catch (NumberFormatException e) {
1514 throw new IllegalStateException(
1515 "Failed to parse native daemon return code for " + ifaceIn + " " + ifaceOut);
1516 }
1517 if (code != NetdResponseCode.TetheringStatsResult) {
1518 throw new IllegalStateException(
1519 "Unexpected return code from native daemon for " + ifaceIn + " " + ifaceOut);
1520 }
1521
1522 try {
1523 final NetworkStats.Entry entry = new NetworkStats.Entry();
1524 entry.iface = ifaceIn;
1525 entry.uid = UID_ALL;
1526 entry.set = SET_DEFAULT;
1527 entry.tag = TAG_NONE;
1528 entry.rxBytes = Long.parseLong(tok[3]);
1529 entry.rxPackets = Long.parseLong(tok[4]);
1530 entry.txBytes = Long.parseLong(tok[5]);
1531 entry.txPackets = Long.parseLong(tok[6]);
1532 return entry;
1533 } catch (NumberFormatException e) {
1534 throw new IllegalStateException(
1535 "problem parsing tethering stats for " + ifaceIn + " " + ifaceOut + ": " + e);
1536 }
1537 }
1538
San Mehatf0db6e12010-04-07 15:22:10 -07001539 public void setInterfaceThrottle(String iface, int rxKbps, int txKbps) {
San Mehat91cac642010-03-31 14:31:36 -07001540 mContext.enforceCallingOrSelfPermission(
1541 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
Kenny Roota80ce062010-06-01 13:23:53 -07001542 try {
1543 mConnector.doCommand(String.format(
1544 "interface setthrottle %s %d %d", iface, rxKbps, txKbps));
1545 } catch (NativeDaemonConnectorException e) {
1546 Slog.e(TAG, "Error communicating with native daemon to set throttle", e);
1547 }
San Mehat91cac642010-03-31 14:31:36 -07001548 }
1549
1550 private int getInterfaceThrottle(String iface, boolean rx) {
1551 mContext.enforceCallingOrSelfPermission(
1552 android.Manifest.permission.ACCESS_NETWORK_STATE, "NetworkManagementService");
1553 try {
Kenny Roota80ce062010-06-01 13:23:53 -07001554 String rsp;
1555 try {
1556 rsp = mConnector.doCommand(
1557 String.format("interface getthrottle %s %s", iface,
1558 (rx ? "rx" : "tx"))).get(0);
1559 } catch (NativeDaemonConnectorException e) {
1560 Slog.e(TAG, "Error communicating with native daemon to getthrottle", e);
1561 return -1;
1562 }
1563
1564 String[] tok = rsp.split(" ");
1565 if (tok.length < 2) {
1566 Slog.e(TAG, "Malformed response to getthrottle command");
1567 return -1;
1568 }
1569
San Mehat91cac642010-03-31 14:31:36 -07001570 int code;
1571 try {
1572 code = Integer.parseInt(tok[0]);
1573 } catch (NumberFormatException nfe) {
1574 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
1575 return -1;
1576 }
1577 if ((rx && code != NetdResponseCode.InterfaceRxThrottleResult) || (
1578 !rx && code != NetdResponseCode.InterfaceTxThrottleResult)) {
1579 Slog.e(TAG, String.format("Unexpected response code %d", code));
1580 return -1;
1581 }
1582 return Integer.parseInt(tok[1]);
1583 } catch (Exception e) {
1584 Slog.e(TAG, String.format(
1585 "Failed to read interface %s throttle value", (rx ? "rx" : "tx")), e);
1586 }
1587 return -1;
1588 }
1589
1590 public int getInterfaceRxThrottle(String iface) {
1591 return getInterfaceThrottle(iface, true);
1592 }
1593
1594 public int getInterfaceTxThrottle(String iface) {
1595 return getInterfaceThrottle(iface, false);
1596 }
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001597
1598 /**
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001599 * Split given line into {@link ArrayList}.
1600 */
1601 private static void splitLine(String line, ArrayList<String> outSplit) {
1602 outSplit.clear();
1603
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001604 final StringTokenizer t = new StringTokenizer(line, " \t\n\r\f:");
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001605 while (t.hasMoreTokens()) {
1606 outSplit.add(t.nextToken());
1607 }
1608 }
1609
1610 /**
1611 * Zip the two given {@link ArrayList} as key and value pairs into
1612 * {@link HashMap}.
1613 */
1614 private static void parseLine(
1615 ArrayList<String> keys, ArrayList<String> values, HashMap<String, String> outParsed) {
1616 outParsed.clear();
1617
1618 final int size = Math.min(keys.size(), values.size());
1619 for (int i = 0; i < size; i++) {
1620 outParsed.put(keys.get(i), values.get(i));
1621 }
1622 }
1623
1624 /**
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001625 * Utility method to read a single plain-text {@link Long} from the given
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001626 * {@link File}, usually from a {@code /proc/} filesystem.
1627 */
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001628 private static long readSingleLongFromFile(File file) {
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001629 try {
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001630 final byte[] buffer = IoUtils.readFileAsByteArray(file.toString());
1631 return Long.parseLong(new String(buffer).trim());
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001632 } catch (NumberFormatException e) {
1633 return -1;
1634 } catch (IOException e) {
1635 return -1;
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001636 }
1637 }
Jean-Baptiste Querud5299ff2011-07-07 08:46:09 -07001638
Jeff Sharkeyfd8be3e2011-07-11 14:36:15 -07001639 /**
1640 * Wrapper for {@link File#list()} that returns empty array instead of
1641 * {@code null}.
1642 */
1643 private static String[] fileListWithoutNull(File file) {
1644 final String[] list = file.list();
1645 return list != null ? list : new String[0];
1646 }
1647
Mattias Falk7475c0c2011-04-04 16:10:36 +02001648 public void setDefaultInterfaceForDns(String iface) throws IllegalStateException {
1649 mContext.enforceCallingOrSelfPermission(
1650 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
1651 try {
1652 String cmd = "resolver setdefaultif " + iface;
1653
1654 mConnector.doCommand(cmd);
1655 } catch (NativeDaemonConnectorException e) {
1656 throw new IllegalStateException(
1657 "Error communicating with native daemon to set default interface", e);
1658 }
1659 }
1660
1661 public void setDnsServersForInterface(String iface, String[] servers)
1662 throws IllegalStateException {
1663 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE,
1664 "NetworkManagementService");
1665 try {
1666 String cmd = "resolver setifdns " + iface;
1667 for (String s : servers) {
Robert Greenwalt572b7042011-07-25 17:00:13 -07001668 InetAddress a = NetworkUtils.numericToInetAddress(s);
1669 if (a.isAnyLocalAddress() == false) {
1670 cmd += " " + a.getHostAddress();
Mattias Falk7475c0c2011-04-04 16:10:36 +02001671 }
1672 }
Mattias Falk7475c0c2011-04-04 16:10:36 +02001673 mConnector.doCommand(cmd);
Robert Greenwalt572b7042011-07-25 17:00:13 -07001674 } catch (IllegalArgumentException e) {
1675 throw new IllegalStateException("Error setting dnsn for interface", e);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001676 } catch (NativeDaemonConnectorException e) {
1677 throw new IllegalStateException(
Robert Greenwalt572b7042011-07-25 17:00:13 -07001678 "Error communicating with native daemon to set dns for interface", e);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001679 }
1680 }
1681
1682 public void flushDefaultDnsCache() throws IllegalStateException {
1683 mContext.enforceCallingOrSelfPermission(
1684 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
1685 try {
1686 String cmd = "resolver flushdefaultif";
1687
1688 mConnector.doCommand(cmd);
1689 } catch (NativeDaemonConnectorException e) {
1690 throw new IllegalStateException(
1691 "Error communicating with native deamon to flush default interface", e);
1692 }
1693 }
1694
1695 public void flushInterfaceDnsCache(String iface) throws IllegalStateException {
1696 mContext.enforceCallingOrSelfPermission(
1697 android.Manifest.permission.CHANGE_NETWORK_STATE, "NetworkManagementService");
1698 try {
1699 String cmd = "resolver flushif " + iface;
1700
1701 mConnector.doCommand(cmd);
1702 } catch (NativeDaemonConnectorException e) {
1703 throw new IllegalStateException(
Robert Greenwalt572b7042011-07-25 17:00:13 -07001704 "Error communicating with native daemon to flush interface " + iface, e);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001705 }
1706 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07001707
1708 /** {@inheritDoc} */
1709 public void monitor() {
1710 if (mConnector != null) {
1711 mConnector.monitor();
1712 }
1713 }
Jeff Sharkey47eb1022011-08-25 17:48:52 -07001714
1715 @Override
1716 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1717 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
1718
1719 pw.print("Bandwidth control enabled: "); pw.println(mBandwidthControlEnabled);
1720
1721 synchronized (mQuotaLock) {
1722 pw.print("Active quota ifaces: "); pw.println(mActiveQuotaIfaces.toString());
1723 pw.print("Active alert ifaces: "); pw.println(mActiveAlertIfaces.toString());
1724 }
1725
1726 synchronized (mUidRejectOnQuota) {
1727 pw.print("UID reject on quota ifaces: [");
1728 final int size = mUidRejectOnQuota.size();
1729 for (int i = 0; i < size; i++) {
1730 pw.print(mUidRejectOnQuota.keyAt(i));
1731 if (i < size - 1) pw.print(",");
1732 }
1733 pw.println("]");
1734 }
1735 }
San Mehat873f2142010-01-14 10:25:07 -08001736}