blob: b58ba737c145ea15c5c14c01132a2c2051b1c3dc [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 Sharkeyb0aec072011-10-14 18:32:24 -070019import static android.Manifest.permission.ACCESS_NETWORK_STATE;
20import static android.Manifest.permission.CHANGE_NETWORK_STATE;
Jeff Sharkeyaf75c332011-11-18 12:41:12 -080021import static android.Manifest.permission.CHANGE_WIFI_STATE;
Jeff Sharkey47eb1022011-08-25 17:48:52 -070022import static android.Manifest.permission.DUMP;
Jeff Sharkey350083e2011-06-29 10:45:16 -070023import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkeyaf75c332011-11-18 12:41:12 -080024import static android.Manifest.permission.SHUTDOWN;
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -070025import static android.net.NetworkStats.SET_DEFAULT;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070026import static android.net.NetworkStats.TAG_NONE;
27import static android.net.NetworkStats.UID_ALL;
Jeff Sharkeyae2c1812011-10-04 13:11:40 -070028import static android.net.TrafficStats.UID_TETHERING;
Jeff Sharkey350083e2011-06-29 10:45:16 -070029import static android.provider.Settings.Secure.NETSTATS_ENABLED;
Jeff Sharkeya63ba592011-07-19 23:47:12 -070030import static com.android.server.NetworkManagementSocketTagger.PROP_QTAGUID_ENABLED;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070031
San Mehat873f2142010-01-14 10:25:07 -080032import android.content.Context;
San Mehat4d02d002010-01-22 16:07:46 -080033import android.net.INetworkManagementEventObserver;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -070034import android.net.InterfaceConfiguration;
Robert Greenwalted126402011-01-28 15:34:55 -080035import android.net.LinkAddress;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -070036import android.net.NetworkStats;
Robert Greenwalted126402011-01-28 15:34:55 -080037import android.net.NetworkUtils;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -070038import android.net.RouteInfo;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080039import android.net.wifi.WifiConfiguration;
40import android.net.wifi.WifiConfiguration.KeyMgmt;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -070041import android.os.Binder;
San Mehat873f2142010-01-14 10:25:07 -080042import android.os.INetworkManagementService;
Jeff Sharkey9a13f362011-04-26 16:25:36 -070043import android.os.SystemClock;
Marco Nelissen62dbb222010-02-18 10:56:30 -080044import android.os.SystemProperties;
Jeff Sharkey350083e2011-06-29 10:45:16 -070045import android.provider.Settings;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080046import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080047import android.util.Slog;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -070048import android.util.SparseBooleanArray;
San Mehat873f2142010-01-14 10:25:07 -080049
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070050import com.android.internal.net.NetworkStatsFactory;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -070051import com.google.android.collect.Sets;
Jeff Sharkey4414cea2011-06-24 17:05:24 -070052
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -070053import java.io.BufferedReader;
54import java.io.DataInputStream;
San Mehat873f2142010-01-14 10:25:07 -080055import java.io.File;
Jeff Sharkey47eb1022011-08-25 17:48:52 -070056import java.io.FileDescriptor;
Jeff Sharkey9a13f362011-04-26 16:25:36 -070057import java.io.FileInputStream;
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;
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -070063import java.net.InterfaceAddress;
64import java.net.NetworkInterface;
65import java.net.SocketException;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -070066import java.util.ArrayList;
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -070067import java.util.Collection;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -070068import java.util.HashSet;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -070069import java.util.NoSuchElementException;
70import java.util.StringTokenizer;
Robert Greenwalte5c3afb2010-09-22 14:32:35 -070071import java.util.concurrent.CountDownLatch;
San Mehat873f2142010-01-14 10:25:07 -080072
73/**
74 * @hide
75 */
Jeff Sharkey8e9992a2011-08-23 18:37:23 -070076public class NetworkManagementService extends INetworkManagementService.Stub
77 implements Watchdog.Monitor {
Jeff Sharkeyeedcb952011-05-17 14:55:15 -070078 private static final String TAG = "NetworkManagementService";
Dianne Hackborncef65ee2010-09-30 18:27:22 -070079 private static final boolean DBG = false;
Kenny Root305bcbf2010-09-03 07:56:38 -070080 private static final String NETD_TAG = "NetdConnector";
81
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -070082 private static final int ADD = 1;
83 private static final int REMOVE = 2;
84
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -070085 private static final String DEFAULT = "default";
86 private static final String SECONDARY = "secondary";
87
Jeff Sharkey8e9992a2011-08-23 18:37:23 -070088 /**
89 * Name representing {@link #setGlobalAlert(long)} limit when delivered to
90 * {@link INetworkManagementEventObserver#limitReached(String, String)}.
91 */
92 public static final String LIMIT_GLOBAL_ALERT = "globalAlert";
93
San Mehat873f2142010-01-14 10:25:07 -080094 class NetdResponseCode {
JP Abgrall12b933d2011-07-14 18:09:22 -070095 /* Keep in sync with system/netd/ResponseCode.h */
San Mehat873f2142010-01-14 10:25:07 -080096 public static final int InterfaceListResult = 110;
97 public static final int TetherInterfaceListResult = 111;
98 public static final int TetherDnsFwdTgtListResult = 112;
San Mehat72759df2010-01-19 13:50:37 -080099 public static final int TtyListResult = 113;
San Mehat873f2142010-01-14 10:25:07 -0800100
101 public static final int TetherStatusResult = 210;
102 public static final int IpFwdStatusResult = 211;
San Mehated4fc8a2010-01-22 12:28:36 -0800103 public static final int InterfaceGetCfgResult = 213;
Robert Greenwalte3253922010-02-18 09:23:25 -0800104 public static final int SoftapStatusResult = 214;
San Mehat91cac642010-03-31 14:31:36 -0700105 public static final int InterfaceRxCounterResult = 216;
106 public static final int InterfaceTxCounterResult = 217;
107 public static final int InterfaceRxThrottleResult = 218;
108 public static final int InterfaceTxThrottleResult = 219;
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -0700109 public static final int QuotaCounterResult = 220;
110 public static final int TetheringStatsResult = 221;
Robert Greenwalte3253922010-02-18 09:23:25 -0800111
112 public static final int InterfaceChange = 600;
JP Abgrall12b933d2011-07-14 18:09:22 -0700113 public static final int BandwidthControl = 601;
San Mehat873f2142010-01-14 10:25:07 -0800114 }
115
116 /**
117 * Binder context for this service
118 */
119 private Context mContext;
120
121 /**
122 * connector object for communicating with netd
123 */
124 private NativeDaemonConnector mConnector;
125
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700126 private Thread mThread;
127 private final CountDownLatch mConnectedSignal = new CountDownLatch(1);
128
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700129 // TODO: replace with RemoteCallbackList
San Mehat4d02d002010-01-22 16:07:46 -0800130 private ArrayList<INetworkManagementEventObserver> mObservers;
131
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700132 private final NetworkStatsFactory mStatsFactory = new NetworkStatsFactory();
133
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700134 private Object mQuotaLock = new Object();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700135 /** Set of interfaces with active quotas. */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700136 private HashSet<String> mActiveQuotaIfaces = Sets.newHashSet();
137 /** Set of interfaces with active alerts. */
138 private HashSet<String> mActiveAlertIfaces = Sets.newHashSet();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700139 /** Set of UIDs with active reject rules. */
140 private SparseBooleanArray mUidRejectOnQuota = new SparseBooleanArray();
141
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700142 private volatile boolean mBandwidthControlEnabled;
Jeff Sharkey350083e2011-06-29 10:45:16 -0700143
San Mehat873f2142010-01-14 10:25:07 -0800144 /**
145 * Constructs a new NetworkManagementService instance
146 *
147 * @param context Binder context for this service
148 */
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700149 private NetworkManagementService(Context context) {
San Mehat873f2142010-01-14 10:25:07 -0800150 mContext = context;
San Mehat4d02d002010-01-22 16:07:46 -0800151 mObservers = new ArrayList<INetworkManagementEventObserver>();
152
Marco Nelissen62dbb222010-02-18 10:56:30 -0800153 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
154 return;
155 }
156
San Mehat873f2142010-01-14 10:25:07 -0800157 mConnector = new NativeDaemonConnector(
Kenny Root305bcbf2010-09-03 07:56:38 -0700158 new NetdCallbackReceiver(), "netd", 10, NETD_TAG);
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700159 mThread = new Thread(mConnector, NETD_TAG);
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700160
161 // Add ourself to the Watchdog monitors.
162 Watchdog.getInstance().addMonitor(this);
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700163 }
164
165 public static NetworkManagementService create(Context context) throws InterruptedException {
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700166 NetworkManagementService service = new NetworkManagementService(context);
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700167 if (DBG) Slog.d(TAG, "Creating NetworkManagementService");
168 service.mThread.start();
169 if (DBG) Slog.d(TAG, "Awaiting socket connection");
170 service.mConnectedSignal.await();
171 if (DBG) Slog.d(TAG, "Connected");
172 return service;
San Mehat873f2142010-01-14 10:25:07 -0800173 }
174
Jeff Sharkey350083e2011-06-29 10:45:16 -0700175 public void systemReady() {
Jeff Sharkey350083e2011-06-29 10:45:16 -0700176 // only enable bandwidth control when support exists, and requested by
177 // system setting.
Jeff Sharkey350083e2011-06-29 10:45:16 -0700178 final boolean hasKernelSupport = new File("/proc/net/xt_qtaguid/ctrl").exists();
179 final boolean shouldEnable =
Jeff Sharkey05355c32011-08-09 14:44:19 -0700180 Settings.Secure.getInt(mContext.getContentResolver(), NETSTATS_ENABLED, 1) != 0;
Jeff Sharkey350083e2011-06-29 10:45:16 -0700181
Jeff Sharkey350083e2011-06-29 10:45:16 -0700182 if (hasKernelSupport && shouldEnable) {
183 Slog.d(TAG, "enabling bandwidth control");
184 try {
185 mConnector.doCommand("bandwidth enable");
186 mBandwidthControlEnabled = true;
187 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700188 Log.wtf(TAG, "problem enabling bandwidth controls", e);
Jeff Sharkey350083e2011-06-29 10:45:16 -0700189 }
190 } else {
191 Slog.d(TAG, "not enabling bandwidth control");
192 }
Jeff Sharkey62a2c8f2011-07-13 15:24:02 -0700193
Jeff Sharkeya63ba592011-07-19 23:47:12 -0700194 SystemProperties.set(PROP_QTAGUID_ENABLED, mBandwidthControlEnabled ? "1" : "0");
Jeff Sharkey350083e2011-06-29 10:45:16 -0700195 }
196
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800197 @Override
San Mehat4d02d002010-01-22 16:07:46 -0800198 public void registerObserver(INetworkManagementEventObserver obs) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800199 Slog.d(TAG, "Registering observer");
San Mehat4d02d002010-01-22 16:07:46 -0800200 mObservers.add(obs);
201 }
202
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800203 @Override
San Mehat4d02d002010-01-22 16:07:46 -0800204 public void unregisterObserver(INetworkManagementEventObserver obs) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800205 Slog.d(TAG, "Unregistering observer");
San Mehat4d02d002010-01-22 16:07:46 -0800206 mObservers.remove(mObservers.indexOf(obs));
207 }
208
209 /**
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700210 * Notify our observers of an interface status change
San Mehat4d02d002010-01-22 16:07:46 -0800211 */
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700212 private void notifyInterfaceStatusChanged(String iface, boolean up) {
San Mehat4d02d002010-01-22 16:07:46 -0800213 for (INetworkManagementEventObserver obs : mObservers) {
214 try {
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700215 obs.interfaceStatusChanged(iface, up);
216 } catch (Exception ex) {
217 Slog.w(TAG, "Observer notifier failed", ex);
218 }
219 }
220 }
221
222 /**
Mike J. Chenf59c7d02011-06-23 15:33:15 -0700223 * Notify our observers of an interface link state change
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700224 * (typically, an Ethernet cable has been plugged-in or unplugged).
225 */
226 private void notifyInterfaceLinkStateChanged(String iface, boolean up) {
227 for (INetworkManagementEventObserver obs : mObservers) {
228 try {
229 obs.interfaceLinkStateChanged(iface, up);
San Mehat4d02d002010-01-22 16:07:46 -0800230 } catch (Exception ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800231 Slog.w(TAG, "Observer notifier failed", ex);
San Mehat4d02d002010-01-22 16:07:46 -0800232 }
233 }
234 }
235
236 /**
237 * Notify our observers of an interface addition.
238 */
239 private void notifyInterfaceAdded(String iface) {
240 for (INetworkManagementEventObserver obs : mObservers) {
241 try {
242 obs.interfaceAdded(iface);
243 } catch (Exception ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800244 Slog.w(TAG, "Observer notifier failed", ex);
San Mehat4d02d002010-01-22 16:07:46 -0800245 }
246 }
247 }
248
249 /**
250 * Notify our observers of an interface removal.
251 */
252 private void notifyInterfaceRemoved(String iface) {
Jeff Sharkey89b8a212011-10-11 11:58:11 -0700253 // netd already clears out quota and alerts for removed ifaces; update
254 // our sanity-checking state.
255 mActiveAlertIfaces.remove(iface);
256 mActiveQuotaIfaces.remove(iface);
257
San Mehat4d02d002010-01-22 16:07:46 -0800258 for (INetworkManagementEventObserver obs : mObservers) {
259 try {
260 obs.interfaceRemoved(iface);
261 } catch (Exception ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800262 Slog.w(TAG, "Observer notifier failed", ex);
San Mehat4d02d002010-01-22 16:07:46 -0800263 }
264 }
265 }
266
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700267 /**
JP Abgrall12b933d2011-07-14 18:09:22 -0700268 * Notify our observers of a limit reached.
269 */
270 private void notifyLimitReached(String limitName, String iface) {
271 for (INetworkManagementEventObserver obs : mObservers) {
272 try {
273 obs.limitReached(limitName, iface);
JP Abgrall12b933d2011-07-14 18:09:22 -0700274 } catch (Exception ex) {
275 Slog.w(TAG, "Observer notifier failed", ex);
276 }
277 }
278 }
279
280 /**
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700281 * Let us know the daemon is connected
282 */
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700283 protected void onDaemonConnected() {
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700284 if (DBG) Slog.d(TAG, "onConnected");
285 mConnectedSignal.countDown();
286 }
287
San Mehat4d02d002010-01-22 16:07:46 -0800288
San Mehat873f2142010-01-14 10:25:07 -0800289 //
290 // Netd Callback handling
291 //
292
293 class NetdCallbackReceiver implements INativeDaemonConnectorCallbacks {
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700294 /** {@inheritDoc} */
San Mehat873f2142010-01-14 10:25:07 -0800295 public void onDaemonConnected() {
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700296 NetworkManagementService.this.onDaemonConnected();
San Mehat873f2142010-01-14 10:25:07 -0800297 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700298
299 /** {@inheritDoc} */
San Mehat873f2142010-01-14 10:25:07 -0800300 public boolean onEvent(int code, String raw, String[] cooked) {
JP Abgrall12b933d2011-07-14 18:09:22 -0700301 switch (code) {
302 case NetdResponseCode.InterfaceChange:
303 /*
304 * a network interface change occured
305 * Format: "NNN Iface added <name>"
306 * "NNN Iface removed <name>"
307 * "NNN Iface changed <name> <up/down>"
308 * "NNN Iface linkstatus <name> <up/down>"
309 */
310 if (cooked.length < 4 || !cooked[1].equals("Iface")) {
311 throw new IllegalStateException(
312 String.format("Invalid event from daemon (%s)", raw));
313 }
314 if (cooked[2].equals("added")) {
315 notifyInterfaceAdded(cooked[3]);
316 return true;
317 } else if (cooked[2].equals("removed")) {
318 notifyInterfaceRemoved(cooked[3]);
319 return true;
320 } else if (cooked[2].equals("changed") && cooked.length == 5) {
321 notifyInterfaceStatusChanged(cooked[3], cooked[4].equals("up"));
322 return true;
323 } else if (cooked[2].equals("linkstate") && cooked.length == 5) {
324 notifyInterfaceLinkStateChanged(cooked[3], cooked[4].equals("up"));
325 return true;
326 }
Robert Greenwalte3253922010-02-18 09:23:25 -0800327 throw new IllegalStateException(
328 String.format("Invalid event from daemon (%s)", raw));
JP Abgrall12b933d2011-07-14 18:09:22 -0700329 // break;
330 case NetdResponseCode.BandwidthControl:
331 /*
332 * Bandwidth control needs some attention
333 * Format: "NNN limit alert <alertName> <ifaceName>"
334 */
335 if (cooked.length < 5 || !cooked[1].equals("limit")) {
336 throw new IllegalStateException(
337 String.format("Invalid event from daemon (%s)", raw));
338 }
339 if (cooked[2].equals("alert")) {
340 notifyLimitReached(cooked[3], cooked[4]);
341 return true;
342 }
343 throw new IllegalStateException(
344 String.format("Invalid event from daemon (%s)", raw));
345 // break;
346 default: break;
Robert Greenwalte3253922010-02-18 09:23:25 -0800347 }
348 return false;
San Mehat873f2142010-01-14 10:25:07 -0800349 }
350 }
351
San Mehated4fc8a2010-01-22 12:28:36 -0800352
San Mehat873f2142010-01-14 10:25:07 -0800353 //
354 // INetworkManagementService members
355 //
356
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800357 @Override
358 public String[] listInterfaces() {
359 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700360 try {
361 return mConnector.doListCommand("interface list", NetdResponseCode.InterfaceListResult);
362 } catch (NativeDaemonConnectorException e) {
363 throw new IllegalStateException(
364 "Cannot communicate with native daemon to list interfaces");
365 }
San Mehated4fc8a2010-01-22 12:28:36 -0800366 }
367
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800368 @Override
369 public InterfaceConfiguration getInterfaceConfig(String iface) {
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700370 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700371 String rsp;
372 try {
373 rsp = mConnector.doCommand("interface getcfg " + iface).get(0);
374 } catch (NativeDaemonConnectorException e) {
375 throw new IllegalStateException(
376 "Cannot communicate with native daemon to get interface config");
377 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800378 Slog.d(TAG, String.format("rsp <%s>", rsp));
San Mehated4fc8a2010-01-22 12:28:36 -0800379
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800380 // Rsp: 213 xx:xx:xx:xx:xx:xx yyy.yyy.yyy.yyy zzz [flag1 flag2 flag3]
San Mehated4fc8a2010-01-22 12:28:36 -0800381 StringTokenizer st = new StringTokenizer(rsp);
382
Kenny Roota80ce062010-06-01 13:23:53 -0700383 InterfaceConfiguration cfg;
San Mehated4fc8a2010-01-22 12:28:36 -0800384 try {
Kenny Roota80ce062010-06-01 13:23:53 -0700385 try {
386 int code = Integer.parseInt(st.nextToken(" "));
387 if (code != NetdResponseCode.InterfaceGetCfgResult) {
388 throw new IllegalStateException(
389 String.format("Expected code %d, but got %d",
390 NetdResponseCode.InterfaceGetCfgResult, code));
391 }
392 } catch (NumberFormatException nfe) {
San Mehated4fc8a2010-01-22 12:28:36 -0800393 throw new IllegalStateException(
Kenny Roota80ce062010-06-01 13:23:53 -0700394 String.format("Invalid response from daemon (%s)", rsp));
San Mehated4fc8a2010-01-22 12:28:36 -0800395 }
Kenny Roota80ce062010-06-01 13:23:53 -0700396
397 cfg = new InterfaceConfiguration();
398 cfg.hwAddr = st.nextToken(" ");
Robert Greenwalted126402011-01-28 15:34:55 -0800399 InetAddress addr = null;
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800400 int prefixLength = 0;
Kenny Roota80ce062010-06-01 13:23:53 -0700401 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800402 addr = NetworkUtils.numericToInetAddress(st.nextToken(" "));
403 } catch (IllegalArgumentException iae) {
404 Slog.e(TAG, "Failed to parse ipaddr", iae);
Kenny Roota80ce062010-06-01 13:23:53 -0700405 }
406
407 try {
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800408 prefixLength = Integer.parseInt(st.nextToken(" "));
409 } catch (NumberFormatException nfe) {
410 Slog.e(TAG, "Failed to parse prefixLength", nfe);
Kenny Roota80ce062010-06-01 13:23:53 -0700411 }
Robert Greenwalt04808c22010-12-13 17:01:41 -0800412
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800413 cfg.addr = new LinkAddress(addr, prefixLength);
Kenny Roota80ce062010-06-01 13:23:53 -0700414 cfg.interfaceFlags = st.nextToken("]").trim() +"]";
415 } catch (NoSuchElementException nsee) {
San Mehated4fc8a2010-01-22 12:28:36 -0800416 throw new IllegalStateException(
417 String.format("Invalid response from daemon (%s)", rsp));
418 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800419 Slog.d(TAG, String.format("flags <%s>", cfg.interfaceFlags));
San Mehated4fc8a2010-01-22 12:28:36 -0800420 return cfg;
421 }
422
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800423 @Override
424 public void setInterfaceConfig(String iface, InterfaceConfiguration cfg) {
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700425 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Robert Greenwalted126402011-01-28 15:34:55 -0800426 LinkAddress linkAddr = cfg.addr;
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800427 if (linkAddr == null || linkAddr.getAddress() == null) {
428 throw new IllegalStateException("Null LinkAddress given");
Robert Greenwalted126402011-01-28 15:34:55 -0800429 }
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800430 String cmd = String.format("interface setcfg %s %s %d %s", iface,
431 linkAddr.getAddress().getHostAddress(),
432 linkAddr.getNetworkPrefixLength(),
433 cfg.interfaceFlags);
Kenny Roota80ce062010-06-01 13:23:53 -0700434 try {
435 mConnector.doCommand(cmd);
436 } catch (NativeDaemonConnectorException e) {
437 throw new IllegalStateException(
Robert Greenwalt81d5ad52010-12-16 11:27:38 -0800438 "Unable to communicate with native daemon to interface setcfg - " + e);
Kenny Roota80ce062010-06-01 13:23:53 -0700439 }
San Mehat873f2142010-01-14 10:25:07 -0800440 }
441
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800442 @Override
443 public void setInterfaceDown(String iface) {
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700444 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Irfan Sheriff7244c972011-08-05 20:40:45 -0700445 try {
446 InterfaceConfiguration ifcg = getInterfaceConfig(iface);
447 ifcg.interfaceFlags = ifcg.interfaceFlags.replace("up", "down");
448 setInterfaceConfig(iface, ifcg);
449 } catch (NativeDaemonConnectorException e) {
450 throw new IllegalStateException(
451 "Unable to communicate with native daemon for interface down - " + e);
452 }
453 }
454
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800455 @Override
456 public void setInterfaceUp(String iface) {
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700457 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Irfan Sheriff7244c972011-08-05 20:40:45 -0700458 try {
459 InterfaceConfiguration ifcg = getInterfaceConfig(iface);
460 ifcg.interfaceFlags = ifcg.interfaceFlags.replace("down", "up");
461 setInterfaceConfig(iface, ifcg);
462 } catch (NativeDaemonConnectorException e) {
463 throw new IllegalStateException(
464 "Unable to communicate with native daemon for interface up - " + e);
465 }
466 }
467
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800468 @Override
469 public void setInterfaceIpv6PrivacyExtensions(String iface, boolean enable) {
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700470 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Irfan Sheriff73293612011-09-14 12:31:56 -0700471 String cmd = String.format("interface ipv6privacyextensions %s %s", iface,
472 enable ? "enable" : "disable");
473 try {
474 mConnector.doCommand(cmd);
475 } catch (NativeDaemonConnectorException e) {
476 throw new IllegalStateException(
477 "Unable to communicate with native daemon to set ipv6privacyextensions - " + e);
478 }
479 }
480
Irfan Sherifff5600612011-06-16 10:26:28 -0700481 /* TODO: This is right now a IPv4 only function. Works for wifi which loses its
482 IPv6 addresses on interface down, but we need to do full clean up here */
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800483 @Override
484 public void clearInterfaceAddresses(String iface) {
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700485 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
486 String cmd = String.format("interface clearaddrs %s", iface);
Irfan Sherifff5600612011-06-16 10:26:28 -0700487 try {
488 mConnector.doCommand(cmd);
489 } catch (NativeDaemonConnectorException e) {
490 throw new IllegalStateException(
491 "Unable to communicate with native daemon to interface clearallips - " + e);
492 }
493 }
494
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800495 @Override
496 public void enableIpv6(String iface) {
497 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
repo sync7960d9f2011-09-29 12:40:02 -0700498 try {
499 mConnector.doCommand(String.format("interface ipv6 %s enable", iface));
500 } catch (NativeDaemonConnectorException e) {
501 throw new IllegalStateException(
502 "Unable to communicate to native daemon for enabling ipv6");
503 }
504 }
505
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800506 @Override
507 public void disableIpv6(String iface) {
508 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
repo sync7960d9f2011-09-29 12:40:02 -0700509 try {
510 mConnector.doCommand(String.format("interface ipv6 %s disable", iface));
511 } catch (NativeDaemonConnectorException e) {
512 throw new IllegalStateException(
513 "Unable to communicate to native daemon for disabling ipv6");
514 }
515 }
516
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800517 @Override
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700518 public void addRoute(String interfaceName, RouteInfo route) {
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700519 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700520 modifyRoute(interfaceName, ADD, route, DEFAULT);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700521 }
522
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800523 @Override
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700524 public void removeRoute(String interfaceName, RouteInfo route) {
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700525 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700526 modifyRoute(interfaceName, REMOVE, route, DEFAULT);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700527 }
528
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800529 @Override
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700530 public void addSecondaryRoute(String interfaceName, RouteInfo route) {
531 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
532 modifyRoute(interfaceName, ADD, route, SECONDARY);
533 }
534
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800535 @Override
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700536 public void removeSecondaryRoute(String interfaceName, RouteInfo route) {
537 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
538 modifyRoute(interfaceName, REMOVE, route, SECONDARY);
539 }
540
541 private void modifyRoute(String interfaceName, int action, RouteInfo route, String type) {
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700542 ArrayList<String> rsp;
543
544 StringBuilder cmd;
545
546 switch (action) {
547 case ADD:
548 {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700549 cmd = new StringBuilder("interface route add " + interfaceName + " " + type);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700550 break;
551 }
552 case REMOVE:
553 {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700554 cmd = new StringBuilder("interface route remove " + interfaceName + " " + type);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700555 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
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800620 @Override
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700621 public RouteInfo[] getRoutes(String interfaceName) {
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700622 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700623 ArrayList<RouteInfo> routes = new ArrayList<RouteInfo>();
624
625 // v4 routes listed as:
626 // iface dest-addr gateway-addr flags refcnt use metric netmask mtu window IRTT
627 for (String s : readRouteList("/proc/net/route")) {
628 String[] fields = s.split("\t");
629
630 if (fields.length > 7) {
631 String iface = fields[0];
632
633 if (interfaceName.equals(iface)) {
634 String dest = fields[1];
635 String gate = fields[2];
636 String flags = fields[3]; // future use?
637 String mask = fields[7];
638 try {
639 // address stored as a hex string, ex: 0014A8C0
640 InetAddress destAddr =
641 NetworkUtils.intToInetAddress((int)Long.parseLong(dest, 16));
642 int prefixLength =
643 NetworkUtils.netmaskIntToPrefixLength(
644 (int)Long.parseLong(mask, 16));
645 LinkAddress linkAddress = new LinkAddress(destAddr, prefixLength);
646
647 // address stored as a hex string, ex 0014A8C0
648 InetAddress gatewayAddr =
649 NetworkUtils.intToInetAddress((int)Long.parseLong(gate, 16));
650
651 RouteInfo route = new RouteInfo(linkAddress, gatewayAddr);
652 routes.add(route);
653 } catch (Exception e) {
654 Log.e(TAG, "Error parsing route " + s + " : " + e);
655 continue;
656 }
657 }
658 }
659 }
660
661 // v6 routes listed as:
662 // dest-addr prefixlength ?? ?? gateway-addr ?? ?? ?? ?? iface
663 for (String s : readRouteList("/proc/net/ipv6_route")) {
664 String[]fields = s.split("\\s+");
665 if (fields.length > 9) {
666 String iface = fields[9].trim();
667 if (interfaceName.equals(iface)) {
668 String dest = fields[0];
669 String prefix = fields[1];
670 String gate = fields[4];
671
672 try {
673 // prefix length stored as a hex string, ex 40
674 int prefixLength = Integer.parseInt(prefix, 16);
675
676 // address stored as a 32 char hex string
677 // ex fe800000000000000000000000000000
678 InetAddress destAddr = NetworkUtils.hexToInet6Address(dest);
679 LinkAddress linkAddress = new LinkAddress(destAddr, prefixLength);
680
681 InetAddress gateAddr = NetworkUtils.hexToInet6Address(gate);
682
683 RouteInfo route = new RouteInfo(linkAddress, gateAddr);
684 routes.add(route);
685 } catch (Exception e) {
686 Log.e(TAG, "Error parsing route " + s + " : " + e);
687 continue;
688 }
689 }
690 }
691 }
692 return (RouteInfo[]) routes.toArray(new RouteInfo[0]);
693 }
694
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800695 @Override
San Mehat873f2142010-01-14 10:25:07 -0800696 public void shutdown() {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800697 // TODO: remove from aidl if nobody calls externally
698 mContext.enforceCallingOrSelfPermission(SHUTDOWN, TAG);
San Mehat873f2142010-01-14 10:25:07 -0800699
Joe Onorato8a9b2202010-02-26 18:56:32 -0800700 Slog.d(TAG, "Shutting down");
San Mehat873f2142010-01-14 10:25:07 -0800701 }
702
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800703 @Override
San Mehat873f2142010-01-14 10:25:07 -0800704 public boolean getIpForwardingEnabled() throws IllegalStateException{
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800705 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
San Mehat873f2142010-01-14 10:25:07 -0800706
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
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800733 @Override
734 public void setIpForwardingEnabled(boolean enable) {
735 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
San Mehat873f2142010-01-14 10:25:07 -0800736 mConnector.doCommand(String.format("ipfwd %sable", (enable ? "en" : "dis")));
737 }
738
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800739 @Override
740 public void startTethering(String[] dhcpRange) {
741 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -0700742 // cmd is "tether start first_start first_stop second_start second_stop ..."
743 // an odd number of addrs will fail
744 String cmd = "tether start";
745 for (String d : dhcpRange) {
746 cmd += " " + d;
747 }
Kenny Roota80ce062010-06-01 13:23:53 -0700748
749 try {
750 mConnector.doCommand(cmd);
751 } catch (NativeDaemonConnectorException e) {
752 throw new IllegalStateException("Unable to communicate to native daemon");
753 }
San Mehat873f2142010-01-14 10:25:07 -0800754 }
755
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800756 @Override
757 public void stopTethering() {
758 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700759 try {
760 mConnector.doCommand("tether stop");
761 } catch (NativeDaemonConnectorException e) {
762 throw new IllegalStateException("Unable to communicate to native daemon to stop tether");
763 }
San Mehat873f2142010-01-14 10:25:07 -0800764 }
765
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800766 @Override
767 public boolean isTetheringStarted() {
768 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
San Mehat873f2142010-01-14 10:25:07 -0800769
Kenny Roota80ce062010-06-01 13:23:53 -0700770 ArrayList<String> rsp;
771 try {
772 rsp = mConnector.doCommand("tether status");
773 } catch (NativeDaemonConnectorException e) {
774 throw new IllegalStateException(
775 "Unable to communicate to native daemon to get tether status");
776 }
San Mehat873f2142010-01-14 10:25:07 -0800777
778 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700779 String[] tok = line.split(" ");
780 if (tok.length < 3) {
781 throw new IllegalStateException("Malformed response for tether status: " + line);
782 }
San Mehat873f2142010-01-14 10:25:07 -0800783 int code = Integer.parseInt(tok[0]);
784 if (code == NetdResponseCode.TetherStatusResult) {
785 // XXX: Tethering services <started/stopped> <TBD>...
Kenny Roota80ce062010-06-01 13:23:53 -0700786 return "started".equals(tok[2]);
San Mehat873f2142010-01-14 10:25:07 -0800787 } else {
788 throw new IllegalStateException(String.format("Unexpected response code %d", code));
789 }
790 }
791 throw new IllegalStateException("Got an empty response");
792 }
793
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800794 @Override
795 public void tetherInterface(String iface) {
796 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700797 try {
798 mConnector.doCommand("tether interface add " + iface);
799 } catch (NativeDaemonConnectorException e) {
800 throw new IllegalStateException(
801 "Unable to communicate to native daemon for adding tether interface");
802 }
San Mehat873f2142010-01-14 10:25:07 -0800803 }
804
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800805 @Override
San Mehat873f2142010-01-14 10:25:07 -0800806 public void untetherInterface(String iface) {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800807 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700808 try {
809 mConnector.doCommand("tether interface remove " + iface);
810 } catch (NativeDaemonConnectorException e) {
811 throw new IllegalStateException(
812 "Unable to communicate to native daemon for removing tether interface");
813 }
San Mehat873f2142010-01-14 10:25:07 -0800814 }
815
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800816 @Override
817 public String[] listTetheredInterfaces() {
818 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700819 try {
820 return mConnector.doListCommand(
821 "tether interface list", NetdResponseCode.TetherInterfaceListResult);
822 } catch (NativeDaemonConnectorException e) {
823 throw new IllegalStateException(
824 "Unable to communicate to native daemon for listing tether interfaces");
825 }
San Mehat873f2142010-01-14 10:25:07 -0800826 }
827
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800828 @Override
829 public void setDnsForwarders(String[] dns) {
830 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
San Mehat873f2142010-01-14 10:25:07 -0800831 try {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800832 String cmd = "tether dns set";
San Mehat873f2142010-01-14 10:25:07 -0800833 for (String s : dns) {
Robert Greenwalte5903732011-02-22 16:00:42 -0800834 cmd += " " + NetworkUtils.numericToInetAddress(s).getHostAddress();
San Mehat873f2142010-01-14 10:25:07 -0800835 }
Kenny Roota80ce062010-06-01 13:23:53 -0700836 try {
837 mConnector.doCommand(cmd);
838 } catch (NativeDaemonConnectorException e) {
839 throw new IllegalStateException(
840 "Unable to communicate to native daemon for setting tether dns");
841 }
Robert Greenwalte5903732011-02-22 16:00:42 -0800842 } catch (IllegalArgumentException e) {
San Mehat873f2142010-01-14 10:25:07 -0800843 throw new IllegalStateException("Error resolving dns name", e);
844 }
845 }
846
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800847 @Override
848 public String[] getDnsForwarders() {
849 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700850 try {
851 return mConnector.doListCommand(
852 "tether dns list", NetdResponseCode.TetherDnsFwdTgtListResult);
853 } catch (NativeDaemonConnectorException e) {
854 throw new IllegalStateException(
855 "Unable to communicate to native daemon for listing tether dns");
856 }
San Mehat873f2142010-01-14 10:25:07 -0800857 }
858
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700859 private void modifyNat(String cmd, String internalInterface, String externalInterface)
860 throws SocketException {
861 cmd = String.format("nat %s %s %s", cmd, internalInterface, externalInterface);
862
863 NetworkInterface internalNetworkInterface =
864 NetworkInterface.getByName(internalInterface);
865 Collection<InterfaceAddress>interfaceAddresses =
866 internalNetworkInterface.getInterfaceAddresses();
867 cmd += " " + interfaceAddresses.size();
868 for (InterfaceAddress ia : interfaceAddresses) {
869 InetAddress addr = NetworkUtils.getNetworkPart(ia.getAddress(),
870 ia.getNetworkPrefixLength());
871 cmd = cmd + " " + addr.getHostAddress() + "/" + ia.getNetworkPrefixLength();
872 }
873
874 mConnector.doCommand(cmd);
875 }
876
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800877 @Override
878 public void enableNat(String internalInterface, String externalInterface) {
879 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700880 if (DBG) Log.d(TAG, "enableNat(" + internalInterface + ", " + externalInterface + ")");
Kenny Roota80ce062010-06-01 13:23:53 -0700881 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700882 modifyNat("enable", internalInterface, externalInterface);
883 } catch (Exception e) {
884 Log.e(TAG, "enableNat got Exception " + e.toString());
Kenny Roota80ce062010-06-01 13:23:53 -0700885 throw new IllegalStateException(
886 "Unable to communicate to native daemon for enabling NAT interface");
887 }
San Mehat873f2142010-01-14 10:25:07 -0800888 }
889
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800890 @Override
891 public void disableNat(String internalInterface, String externalInterface) {
892 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700893 if (DBG) Log.d(TAG, "disableNat(" + internalInterface + ", " + externalInterface + ")");
Kenny Roota80ce062010-06-01 13:23:53 -0700894 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700895 modifyNat("disable", internalInterface, externalInterface);
896 } catch (Exception e) {
897 Log.e(TAG, "disableNat got Exception " + e.toString());
Kenny Roota80ce062010-06-01 13:23:53 -0700898 throw new IllegalStateException(
899 "Unable to communicate to native daemon for disabling NAT interface");
900 }
San Mehat873f2142010-01-14 10:25:07 -0800901 }
San Mehat72759df2010-01-19 13:50:37 -0800902
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800903 @Override
904 public String[] listTtys() {
905 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700906 try {
907 return mConnector.doListCommand("list_ttys", NetdResponseCode.TtyListResult);
908 } catch (NativeDaemonConnectorException e) {
909 throw new IllegalStateException(
910 "Unable to communicate to native daemon for listing TTYs");
911 }
San Mehat72759df2010-01-19 13:50:37 -0800912 }
913
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800914 @Override
915 public void attachPppd(
916 String tty, String localAddr, String remoteAddr, String dns1Addr, String dns2Addr) {
917 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
San Mehat72759df2010-01-19 13:50:37 -0800918 try {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800919 mConnector.doCommand(String.format("pppd attach %s %s %s %s %s", tty,
Robert Greenwalte5903732011-02-22 16:00:42 -0800920 NetworkUtils.numericToInetAddress(localAddr).getHostAddress(),
921 NetworkUtils.numericToInetAddress(remoteAddr).getHostAddress(),
922 NetworkUtils.numericToInetAddress(dns1Addr).getHostAddress(),
923 NetworkUtils.numericToInetAddress(dns2Addr).getHostAddress()));
924 } catch (IllegalArgumentException e) {
San Mehat72759df2010-01-19 13:50:37 -0800925 throw new IllegalStateException("Error resolving addr", e);
Kenny Roota80ce062010-06-01 13:23:53 -0700926 } catch (NativeDaemonConnectorException e) {
927 throw new IllegalStateException("Error communicating to native daemon to attach pppd", e);
San Mehat72759df2010-01-19 13:50:37 -0800928 }
929 }
930
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800931 @Override
932 public void detachPppd(String tty) {
933 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700934 try {
935 mConnector.doCommand(String.format("pppd detach %s", tty));
936 } catch (NativeDaemonConnectorException e) {
937 throw new IllegalStateException("Error communicating to native daemon to detach pppd", e);
938 }
San Mehat72759df2010-01-19 13:50:37 -0800939 }
Robert Greenwaltce1200d2010-02-18 11:25:54 -0800940
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800941 @Override
942 public void startAccessPoint(
943 WifiConfiguration wifiConfig, String wlanIface, String softapIface) {
944 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
945 mContext.enforceCallingOrSelfPermission(CHANGE_WIFI_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700946 try {
Irfan Sheriffcb30b222011-07-29 20:54:52 -0700947 wifiFirmwareReload(wlanIface, "AP");
Kenny Roota80ce062010-06-01 13:23:53 -0700948 mConnector.doCommand(String.format("softap start " + wlanIface));
949 if (wifiConfig == null) {
950 mConnector.doCommand(String.format("softap set " + wlanIface + " " + softapIface));
951 } else {
952 /**
953 * softap set arg1 arg2 arg3 [arg4 arg5 arg6 arg7 arg8]
954 * argv1 - wlan interface
955 * argv2 - softap interface
956 * argv3 - SSID
957 * argv4 - Security
958 * argv5 - Key
959 * argv6 - Channel
960 * argv7 - Preamble
961 * argv8 - Max SCB
962 */
Irfan Sheriffec8d23a2011-02-16 17:00:33 -0800963 String str = String.format("softap set " + wlanIface + " " + softapIface +
964 " %s %s %s", convertQuotedString(wifiConfig.SSID),
965 getSecurityType(wifiConfig),
966 convertQuotedString(wifiConfig.preSharedKey));
Kenny Roota80ce062010-06-01 13:23:53 -0700967 mConnector.doCommand(str);
968 }
969 mConnector.doCommand(String.format("softap startap"));
970 } catch (NativeDaemonConnectorException e) {
971 throw new IllegalStateException("Error communicating to native daemon to start softap", e);
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800972 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800973 }
974
Irfan Sheriffa6e559e2010-05-24 14:55:42 -0700975 private String convertQuotedString(String s) {
Irfan Sheriff7baec0f2010-05-26 17:16:47 -0700976 if (s == null) {
977 return s;
978 }
979 /* Replace \ with \\, then " with \" and add quotes at end */
980 return '"' + s.replaceAll("\\\\","\\\\\\\\").replaceAll("\"","\\\\\"") + '"';
Irfan Sheriffa6e559e2010-05-24 14:55:42 -0700981 }
982
Irfan Sheriffec8d23a2011-02-16 17:00:33 -0800983 private String getSecurityType(WifiConfiguration wifiConfig) {
984 switch (wifiConfig.getAuthType()) {
985 case KeyMgmt.WPA_PSK:
986 return "wpa-psk";
987 case KeyMgmt.WPA2_PSK:
988 return "wpa2-psk";
989 default:
990 return "open";
991 }
992 }
993
Irfan Sheriffcb30b222011-07-29 20:54:52 -0700994 /* @param mode can be "AP", "STA" or "P2P" */
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800995 @Override
996 public void wifiFirmwareReload(String wlanIface, String mode) {
997 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
998 mContext.enforceCallingOrSelfPermission(CHANGE_WIFI_STATE, TAG);
Irfan Sheriffcb30b222011-07-29 20:54:52 -0700999 try {
1000 mConnector.doCommand(String.format("softap fwreload " + wlanIface + " " + mode));
1001 } catch (NativeDaemonConnectorException e) {
1002 throw new IllegalStateException("Error communicating to native daemon ", e);
1003 }
1004 }
1005
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001006 @Override
1007 public void stopAccessPoint(String wlanIface) {
1008 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
1009 mContext.enforceCallingOrSelfPermission(CHANGE_WIFI_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001010 try {
1011 mConnector.doCommand("softap stopap");
Irfan Sheriff23eb2972011-07-22 15:21:10 -07001012 mConnector.doCommand("softap stop " + wlanIface);
Irfan Sheriffcb30b222011-07-29 20:54:52 -07001013 wifiFirmwareReload(wlanIface, "STA");
Kenny Roota80ce062010-06-01 13:23:53 -07001014 } catch (NativeDaemonConnectorException e) {
1015 throw new IllegalStateException("Error communicating to native daemon to stop soft AP",
1016 e);
1017 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001018 }
1019
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001020 @Override
1021 public void setAccessPoint(WifiConfiguration wifiConfig, String wlanIface, String softapIface) {
1022 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
1023 mContext.enforceCallingOrSelfPermission(CHANGE_WIFI_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001024 try {
1025 if (wifiConfig == null) {
1026 mConnector.doCommand(String.format("softap set " + wlanIface + " " + softapIface));
1027 } else {
1028 String str = String.format("softap set " + wlanIface + " " + softapIface
1029 + " %s %s %s", convertQuotedString(wifiConfig.SSID),
Irfan Sheriffec8d23a2011-02-16 17:00:33 -08001030 getSecurityType(wifiConfig),
Kenny Roota80ce062010-06-01 13:23:53 -07001031 convertQuotedString(wifiConfig.preSharedKey));
1032 mConnector.doCommand(str);
1033 }
1034 } catch (NativeDaemonConnectorException e) {
1035 throw new IllegalStateException("Error communicating to native daemon to set soft AP",
1036 e);
Irfan Sheriffc2f54c22010-03-18 14:02:22 -07001037 }
1038 }
San Mehat91cac642010-03-31 14:31:36 -07001039
1040 private long getInterfaceCounter(String iface, boolean rx) {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001041 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
San Mehat91cac642010-03-31 14:31:36 -07001042 try {
Kenny Roota80ce062010-06-01 13:23:53 -07001043 String rsp;
1044 try {
1045 rsp = mConnector.doCommand(
1046 String.format("interface read%scounter %s", (rx ? "rx" : "tx"), iface)).get(0);
1047 } catch (NativeDaemonConnectorException e1) {
1048 Slog.e(TAG, "Error communicating with native daemon", e1);
1049 return -1;
1050 }
1051
1052 String[] tok = rsp.split(" ");
1053 if (tok.length < 2) {
1054 Slog.e(TAG, String.format("Malformed response for reading %s interface",
1055 (rx ? "rx" : "tx")));
1056 return -1;
1057 }
1058
San Mehat91cac642010-03-31 14:31:36 -07001059 int code;
1060 try {
1061 code = Integer.parseInt(tok[0]);
1062 } catch (NumberFormatException nfe) {
1063 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
1064 return -1;
1065 }
1066 if ((rx && code != NetdResponseCode.InterfaceRxCounterResult) || (
1067 !rx && code != NetdResponseCode.InterfaceTxCounterResult)) {
1068 Slog.e(TAG, String.format("Unexpected response code %d", code));
1069 return -1;
1070 }
1071 return Long.parseLong(tok[1]);
1072 } catch (Exception e) {
1073 Slog.e(TAG, String.format(
1074 "Failed to read interface %s counters", (rx ? "rx" : "tx")), e);
1075 }
1076 return -1;
1077 }
1078
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001079 @Override
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001080 public NetworkStats getNetworkStatsSummary() {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001081 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07001082 return mStatsFactory.readNetworkStatsSummary();
Jeff Sharkeyae2c1812011-10-04 13:11:40 -07001083 }
1084
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001085 @Override
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001086 public NetworkStats getNetworkStatsDetail() {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001087 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07001088 return mStatsFactory.readNetworkStatsDetail(UID_ALL);
San Mehat91cac642010-03-31 14:31:36 -07001089 }
1090
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001091 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001092 public void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001093 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1094
Jeff Sharkey350083e2011-06-29 10:45:16 -07001095 // silently discard when control disabled
1096 // TODO: eventually migrate to be always enabled
1097 if (!mBandwidthControlEnabled) return;
1098
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001099 synchronized (mQuotaLock) {
1100 if (mActiveQuotaIfaces.contains(iface)) {
1101 throw new IllegalStateException("iface " + iface + " already has quota");
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001102 }
1103
1104 final StringBuilder command = new StringBuilder();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001105 command.append("bandwidth setiquota ").append(iface).append(" ").append(quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001106
1107 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001108 // TODO: support quota shared across interfaces
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001109 mConnector.doCommand(command.toString());
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001110 mActiveQuotaIfaces.add(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001111 } catch (NativeDaemonConnectorException e) {
1112 throw new IllegalStateException("Error communicating to native daemon", e);
1113 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001114 }
1115 }
1116
1117 @Override
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001118 public void removeInterfaceQuota(String iface) {
1119 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1120
Jeff Sharkey350083e2011-06-29 10:45:16 -07001121 // silently discard when control disabled
1122 // TODO: eventually migrate to be always enabled
1123 if (!mBandwidthControlEnabled) return;
1124
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001125 synchronized (mQuotaLock) {
1126 if (!mActiveQuotaIfaces.contains(iface)) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001127 // TODO: eventually consider throwing
1128 return;
1129 }
1130
1131 final StringBuilder command = new StringBuilder();
1132 command.append("bandwidth removeiquota ").append(iface);
1133
Jeff Sharkey38ddeaa2011-11-08 13:04:22 -08001134 mActiveQuotaIfaces.remove(iface);
1135 mActiveAlertIfaces.remove(iface);
1136
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001137 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001138 // TODO: support quota shared across interfaces
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001139 mConnector.doCommand(command.toString());
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001140 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey38ddeaa2011-11-08 13:04:22 -08001141 // TODO: include current iptables state
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001142 throw new IllegalStateException("Error communicating to native daemon", e);
1143 }
1144 }
1145 }
1146
1147 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001148 public void setInterfaceAlert(String iface, long alertBytes) {
1149 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1150
1151 // silently discard when control disabled
1152 // TODO: eventually migrate to be always enabled
1153 if (!mBandwidthControlEnabled) return;
1154
1155 // quick sanity check
1156 if (!mActiveQuotaIfaces.contains(iface)) {
1157 throw new IllegalStateException("setting alert requires existing quota on iface");
1158 }
1159
1160 synchronized (mQuotaLock) {
1161 if (mActiveAlertIfaces.contains(iface)) {
1162 throw new IllegalStateException("iface " + iface + " already has alert");
1163 }
1164
1165 final StringBuilder command = new StringBuilder();
1166 command.append("bandwidth setinterfacealert ").append(iface).append(" ").append(
1167 alertBytes);
1168
1169 try {
1170 // TODO: support alert shared across interfaces
1171 mConnector.doCommand(command.toString());
1172 mActiveAlertIfaces.add(iface);
1173 } catch (NativeDaemonConnectorException e) {
1174 throw new IllegalStateException("Error communicating to native daemon", e);
1175 }
1176 }
1177 }
1178
1179 @Override
1180 public void removeInterfaceAlert(String iface) {
1181 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1182
1183 // silently discard when control disabled
1184 // TODO: eventually migrate to be always enabled
1185 if (!mBandwidthControlEnabled) return;
1186
1187 synchronized (mQuotaLock) {
1188 if (!mActiveAlertIfaces.contains(iface)) {
1189 // TODO: eventually consider throwing
1190 return;
1191 }
1192
1193 final StringBuilder command = new StringBuilder();
1194 command.append("bandwidth removeinterfacealert ").append(iface);
1195
1196 try {
1197 // TODO: support alert shared across interfaces
1198 mConnector.doCommand(command.toString());
1199 mActiveAlertIfaces.remove(iface);
1200 } catch (NativeDaemonConnectorException e) {
1201 throw new IllegalStateException("Error communicating to native daemon", e);
1202 }
1203 }
1204 }
1205
1206 @Override
1207 public void setGlobalAlert(long alertBytes) {
1208 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1209
1210 // silently discard when control disabled
1211 // TODO: eventually migrate to be always enabled
1212 if (!mBandwidthControlEnabled) return;
1213
1214 final StringBuilder command = new StringBuilder();
1215 command.append("bandwidth setglobalalert ").append(alertBytes);
1216
1217 try {
1218 mConnector.doCommand(command.toString());
1219 } catch (NativeDaemonConnectorException e) {
1220 throw new IllegalStateException("Error communicating to native daemon", e);
1221 }
1222 }
1223
1224 @Override
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001225 public void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
1226 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1227
Jeff Sharkey350083e2011-06-29 10:45:16 -07001228 // silently discard when control disabled
1229 // TODO: eventually migrate to be always enabled
1230 if (!mBandwidthControlEnabled) return;
1231
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001232 synchronized (mUidRejectOnQuota) {
1233 final boolean oldRejectOnQuota = mUidRejectOnQuota.get(uid, false);
1234 if (oldRejectOnQuota == rejectOnQuotaInterfaces) {
1235 // TODO: eventually consider throwing
1236 return;
1237 }
1238
1239 final StringBuilder command = new StringBuilder();
1240 command.append("bandwidth");
1241 if (rejectOnQuotaInterfaces) {
1242 command.append(" addnaughtyapps");
1243 } else {
1244 command.append(" removenaughtyapps");
1245 }
1246 command.append(" ").append(uid);
1247
1248 try {
1249 mConnector.doCommand(command.toString());
1250 if (rejectOnQuotaInterfaces) {
1251 mUidRejectOnQuota.put(uid, true);
1252 } else {
1253 mUidRejectOnQuota.delete(uid);
1254 }
1255 } catch (NativeDaemonConnectorException e) {
1256 throw new IllegalStateException("Error communicating to native daemon", e);
1257 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001258 }
1259 }
1260
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001261 @Override
1262 public boolean isBandwidthControlEnabled() {
1263 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1264 return mBandwidthControlEnabled;
1265 }
1266
1267 @Override
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001268 public NetworkStats getNetworkStatsUidDetail(int uid) {
1269 if (Binder.getCallingUid() != uid) {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001270 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001271 }
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07001272 return mStatsFactory.readNetworkStatsDetail(uid);
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001273 }
1274
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001275 @Override
1276 public NetworkStats getNetworkStatsTethering(String[] ifacePairs) {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001277 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001278
1279 if (ifacePairs.length % 2 != 0) {
1280 throw new IllegalArgumentException(
1281 "unexpected ifacePairs; length=" + ifacePairs.length);
1282 }
1283
1284 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 1);
1285 for (int i = 0; i < ifacePairs.length; i += 2) {
1286 final String ifaceIn = ifacePairs[i];
1287 final String ifaceOut = ifacePairs[i + 1];
1288 if (ifaceIn != null && ifaceOut != null) {
1289 stats.combineValues(getNetworkStatsTethering(ifaceIn, ifaceOut));
1290 }
1291 }
1292 return stats;
1293 }
1294
1295 private NetworkStats.Entry getNetworkStatsTethering(String ifaceIn, String ifaceOut) {
1296 final StringBuilder command = new StringBuilder();
1297 command.append("bandwidth gettetherstats ").append(ifaceIn).append(" ").append(ifaceOut);
1298
1299 final String rsp;
1300 try {
1301 rsp = mConnector.doCommand(command.toString()).get(0);
1302 } catch (NativeDaemonConnectorException e) {
1303 throw new IllegalStateException("Error communicating to native daemon", e);
1304 }
1305
1306 final String[] tok = rsp.split(" ");
1307 /* Expecting: "code ifaceIn ifaceOut rx_bytes rx_packets tx_bytes tx_packets" */
1308 if (tok.length != 7) {
1309 throw new IllegalStateException("Native daemon returned unexpected result: " + rsp);
1310 }
1311
1312 final int code;
1313 try {
1314 code = Integer.parseInt(tok[0]);
1315 } catch (NumberFormatException e) {
1316 throw new IllegalStateException(
1317 "Failed to parse native daemon return code for " + ifaceIn + " " + ifaceOut);
1318 }
1319 if (code != NetdResponseCode.TetheringStatsResult) {
1320 throw new IllegalStateException(
1321 "Unexpected return code from native daemon for " + ifaceIn + " " + ifaceOut);
1322 }
1323
1324 try {
1325 final NetworkStats.Entry entry = new NetworkStats.Entry();
1326 entry.iface = ifaceIn;
Jeff Sharkey905b5892011-09-30 15:19:49 -07001327 entry.uid = UID_TETHERING;
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001328 entry.set = SET_DEFAULT;
1329 entry.tag = TAG_NONE;
1330 entry.rxBytes = Long.parseLong(tok[3]);
1331 entry.rxPackets = Long.parseLong(tok[4]);
1332 entry.txBytes = Long.parseLong(tok[5]);
1333 entry.txPackets = Long.parseLong(tok[6]);
1334 return entry;
1335 } catch (NumberFormatException e) {
1336 throw new IllegalStateException(
1337 "problem parsing tethering stats for " + ifaceIn + " " + ifaceOut + ": " + e);
1338 }
1339 }
1340
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001341 @Override
San Mehatf0db6e12010-04-07 15:22:10 -07001342 public void setInterfaceThrottle(String iface, int rxKbps, int txKbps) {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001343 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001344 try {
1345 mConnector.doCommand(String.format(
1346 "interface setthrottle %s %d %d", iface, rxKbps, txKbps));
1347 } catch (NativeDaemonConnectorException e) {
1348 Slog.e(TAG, "Error communicating with native daemon to set throttle", e);
1349 }
San Mehat91cac642010-03-31 14:31:36 -07001350 }
1351
1352 private int getInterfaceThrottle(String iface, boolean rx) {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001353 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
San Mehat91cac642010-03-31 14:31:36 -07001354 try {
Kenny Roota80ce062010-06-01 13:23:53 -07001355 String rsp;
1356 try {
1357 rsp = mConnector.doCommand(
1358 String.format("interface getthrottle %s %s", iface,
1359 (rx ? "rx" : "tx"))).get(0);
1360 } catch (NativeDaemonConnectorException e) {
1361 Slog.e(TAG, "Error communicating with native daemon to getthrottle", e);
1362 return -1;
1363 }
1364
1365 String[] tok = rsp.split(" ");
1366 if (tok.length < 2) {
1367 Slog.e(TAG, "Malformed response to getthrottle command");
1368 return -1;
1369 }
1370
San Mehat91cac642010-03-31 14:31:36 -07001371 int code;
1372 try {
1373 code = Integer.parseInt(tok[0]);
1374 } catch (NumberFormatException nfe) {
1375 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
1376 return -1;
1377 }
1378 if ((rx && code != NetdResponseCode.InterfaceRxThrottleResult) || (
1379 !rx && code != NetdResponseCode.InterfaceTxThrottleResult)) {
1380 Slog.e(TAG, String.format("Unexpected response code %d", code));
1381 return -1;
1382 }
1383 return Integer.parseInt(tok[1]);
1384 } catch (Exception e) {
1385 Slog.e(TAG, String.format(
1386 "Failed to read interface %s throttle value", (rx ? "rx" : "tx")), e);
1387 }
1388 return -1;
1389 }
1390
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001391 @Override
San Mehat91cac642010-03-31 14:31:36 -07001392 public int getInterfaceRxThrottle(String iface) {
1393 return getInterfaceThrottle(iface, true);
1394 }
1395
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001396 @Override
San Mehat91cac642010-03-31 14:31:36 -07001397 public int getInterfaceTxThrottle(String iface) {
1398 return getInterfaceThrottle(iface, false);
1399 }
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001400
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001401 @Override
1402 public void setDefaultInterfaceForDns(String iface) {
1403 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001404 try {
1405 String cmd = "resolver setdefaultif " + iface;
1406
1407 mConnector.doCommand(cmd);
1408 } catch (NativeDaemonConnectorException e) {
1409 throw new IllegalStateException(
1410 "Error communicating with native daemon to set default interface", e);
1411 }
1412 }
1413
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001414 @Override
1415 public void setDnsServersForInterface(String iface, String[] servers) {
1416 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001417 try {
1418 String cmd = "resolver setifdns " + iface;
1419 for (String s : servers) {
Robert Greenwalt572b7042011-07-25 17:00:13 -07001420 InetAddress a = NetworkUtils.numericToInetAddress(s);
1421 if (a.isAnyLocalAddress() == false) {
1422 cmd += " " + a.getHostAddress();
Mattias Falk7475c0c2011-04-04 16:10:36 +02001423 }
1424 }
Mattias Falk7475c0c2011-04-04 16:10:36 +02001425 mConnector.doCommand(cmd);
Robert Greenwalt572b7042011-07-25 17:00:13 -07001426 } catch (IllegalArgumentException e) {
1427 throw new IllegalStateException("Error setting dnsn for interface", e);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001428 } catch (NativeDaemonConnectorException e) {
1429 throw new IllegalStateException(
Robert Greenwalt572b7042011-07-25 17:00:13 -07001430 "Error communicating with native daemon to set dns for interface", e);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001431 }
1432 }
1433
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001434 @Override
1435 public void flushDefaultDnsCache() {
1436 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001437 try {
1438 String cmd = "resolver flushdefaultif";
1439
1440 mConnector.doCommand(cmd);
1441 } catch (NativeDaemonConnectorException e) {
1442 throw new IllegalStateException(
1443 "Error communicating with native deamon to flush default interface", e);
1444 }
1445 }
1446
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001447 @Override
1448 public void flushInterfaceDnsCache(String iface) {
1449 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001450 try {
1451 String cmd = "resolver flushif " + iface;
1452
1453 mConnector.doCommand(cmd);
1454 } catch (NativeDaemonConnectorException e) {
1455 throw new IllegalStateException(
Robert Greenwalt572b7042011-07-25 17:00:13 -07001456 "Error communicating with native daemon to flush interface " + iface, e);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001457 }
1458 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07001459
1460 /** {@inheritDoc} */
1461 public void monitor() {
1462 if (mConnector != null) {
1463 mConnector.monitor();
1464 }
1465 }
Jeff Sharkey47eb1022011-08-25 17:48:52 -07001466
1467 @Override
1468 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1469 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
1470
1471 pw.print("Bandwidth control enabled: "); pw.println(mBandwidthControlEnabled);
1472
1473 synchronized (mQuotaLock) {
1474 pw.print("Active quota ifaces: "); pw.println(mActiveQuotaIfaces.toString());
1475 pw.print("Active alert ifaces: "); pw.println(mActiveAlertIfaces.toString());
1476 }
1477
1478 synchronized (mUidRejectOnQuota) {
1479 pw.print("UID reject on quota ifaces: [");
1480 final int size = mUidRejectOnQuota.size();
1481 for (int i = 0; i < size; i++) {
1482 pw.print(mUidRejectOnQuota.keyAt(i));
1483 if (i < size - 1) pw.print(",");
1484 }
1485 pw.println("]");
1486 }
1487 }
San Mehat873f2142010-01-14 10:25:07 -08001488}