blob: e97f71930911a2fbb57b7d13036b924776598759 [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);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800445 final InterfaceConfiguration ifcg = getInterfaceConfig(iface);
446 ifcg.interfaceFlags = ifcg.interfaceFlags.replace("up", "down");
447 setInterfaceConfig(iface, ifcg);
Irfan Sheriff7244c972011-08-05 20:40:45 -0700448 }
449
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800450 @Override
451 public void setInterfaceUp(String iface) {
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700452 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800453 final InterfaceConfiguration ifcg = getInterfaceConfig(iface);
454 ifcg.interfaceFlags = ifcg.interfaceFlags.replace("down", "up");
455 setInterfaceConfig(iface, ifcg);
Irfan Sheriff7244c972011-08-05 20:40:45 -0700456 }
457
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800458 @Override
459 public void setInterfaceIpv6PrivacyExtensions(String iface, boolean enable) {
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700460 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Irfan Sheriff73293612011-09-14 12:31:56 -0700461 String cmd = String.format("interface ipv6privacyextensions %s %s", iface,
462 enable ? "enable" : "disable");
463 try {
464 mConnector.doCommand(cmd);
465 } catch (NativeDaemonConnectorException e) {
466 throw new IllegalStateException(
467 "Unable to communicate with native daemon to set ipv6privacyextensions - " + e);
468 }
469 }
470
Irfan Sherifff5600612011-06-16 10:26:28 -0700471 /* TODO: This is right now a IPv4 only function. Works for wifi which loses its
472 IPv6 addresses on interface down, but we need to do full clean up here */
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800473 @Override
474 public void clearInterfaceAddresses(String iface) {
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700475 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
476 String cmd = String.format("interface clearaddrs %s", iface);
Irfan Sherifff5600612011-06-16 10:26:28 -0700477 try {
478 mConnector.doCommand(cmd);
479 } catch (NativeDaemonConnectorException e) {
480 throw new IllegalStateException(
481 "Unable to communicate with native daemon to interface clearallips - " + e);
482 }
483 }
484
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800485 @Override
486 public void enableIpv6(String iface) {
487 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
repo sync7960d9f2011-09-29 12:40:02 -0700488 try {
489 mConnector.doCommand(String.format("interface ipv6 %s enable", iface));
490 } catch (NativeDaemonConnectorException e) {
491 throw new IllegalStateException(
492 "Unable to communicate to native daemon for enabling ipv6");
493 }
494 }
495
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800496 @Override
497 public void disableIpv6(String iface) {
498 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
repo sync7960d9f2011-09-29 12:40:02 -0700499 try {
500 mConnector.doCommand(String.format("interface ipv6 %s disable", iface));
501 } catch (NativeDaemonConnectorException e) {
502 throw new IllegalStateException(
503 "Unable to communicate to native daemon for disabling ipv6");
504 }
505 }
506
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800507 @Override
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700508 public void addRoute(String interfaceName, RouteInfo route) {
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700509 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700510 modifyRoute(interfaceName, ADD, route, DEFAULT);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700511 }
512
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800513 @Override
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700514 public void removeRoute(String interfaceName, RouteInfo route) {
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700515 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700516 modifyRoute(interfaceName, REMOVE, route, DEFAULT);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700517 }
518
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800519 @Override
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700520 public void addSecondaryRoute(String interfaceName, RouteInfo route) {
521 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
522 modifyRoute(interfaceName, ADD, route, SECONDARY);
523 }
524
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800525 @Override
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700526 public void removeSecondaryRoute(String interfaceName, RouteInfo route) {
527 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
528 modifyRoute(interfaceName, REMOVE, route, SECONDARY);
529 }
530
531 private void modifyRoute(String interfaceName, int action, RouteInfo route, String type) {
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700532 ArrayList<String> rsp;
533
534 StringBuilder cmd;
535
536 switch (action) {
537 case ADD:
538 {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700539 cmd = new StringBuilder("interface route add " + interfaceName + " " + type);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700540 break;
541 }
542 case REMOVE:
543 {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700544 cmd = new StringBuilder("interface route remove " + interfaceName + " " + type);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700545 break;
546 }
547 default:
548 throw new IllegalStateException("Unknown action type " + action);
549 }
550
551 // create triplet: dest-ip-addr prefixlength gateway-ip-addr
552 LinkAddress la = route.getDestination();
553 cmd.append(' ');
554 cmd.append(la.getAddress().getHostAddress());
555 cmd.append(' ');
556 cmd.append(la.getNetworkPrefixLength());
557 cmd.append(' ');
558 if (route.getGateway() == null) {
559 if (la.getAddress() instanceof Inet4Address) {
560 cmd.append("0.0.0.0");
561 } else {
562 cmd.append ("::0");
563 }
564 } else {
565 cmd.append(route.getGateway().getHostAddress());
566 }
567 try {
568 rsp = mConnector.doCommand(cmd.toString());
569 } catch (NativeDaemonConnectorException e) {
570 throw new IllegalStateException(
571 "Unable to communicate with native dameon to add routes - "
572 + e);
573 }
574
Wink Savillec9acde92011-09-21 11:05:43 -0700575 if (DBG) {
576 for (String line : rsp) {
577 Log.v(TAG, "add route response is " + line);
578 }
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700579 }
580 }
581
582 private ArrayList<String> readRouteList(String filename) {
583 FileInputStream fstream = null;
584 ArrayList<String> list = new ArrayList<String>();
585
586 try {
587 fstream = new FileInputStream(filename);
588 DataInputStream in = new DataInputStream(fstream);
589 BufferedReader br = new BufferedReader(new InputStreamReader(in));
590 String s;
591
592 // throw away the title line
593
594 while (((s = br.readLine()) != null) && (s.length() != 0)) {
595 list.add(s);
596 }
597 } catch (IOException ex) {
598 // return current list, possibly empty
599 } finally {
600 if (fstream != null) {
601 try {
602 fstream.close();
603 } catch (IOException ex) {}
604 }
605 }
606
607 return list;
608 }
609
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800610 @Override
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700611 public RouteInfo[] getRoutes(String interfaceName) {
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700612 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700613 ArrayList<RouteInfo> routes = new ArrayList<RouteInfo>();
614
615 // v4 routes listed as:
616 // iface dest-addr gateway-addr flags refcnt use metric netmask mtu window IRTT
617 for (String s : readRouteList("/proc/net/route")) {
618 String[] fields = s.split("\t");
619
620 if (fields.length > 7) {
621 String iface = fields[0];
622
623 if (interfaceName.equals(iface)) {
624 String dest = fields[1];
625 String gate = fields[2];
626 String flags = fields[3]; // future use?
627 String mask = fields[7];
628 try {
629 // address stored as a hex string, ex: 0014A8C0
630 InetAddress destAddr =
631 NetworkUtils.intToInetAddress((int)Long.parseLong(dest, 16));
632 int prefixLength =
633 NetworkUtils.netmaskIntToPrefixLength(
634 (int)Long.parseLong(mask, 16));
635 LinkAddress linkAddress = new LinkAddress(destAddr, prefixLength);
636
637 // address stored as a hex string, ex 0014A8C0
638 InetAddress gatewayAddr =
639 NetworkUtils.intToInetAddress((int)Long.parseLong(gate, 16));
640
641 RouteInfo route = new RouteInfo(linkAddress, gatewayAddr);
642 routes.add(route);
643 } catch (Exception e) {
644 Log.e(TAG, "Error parsing route " + s + " : " + e);
645 continue;
646 }
647 }
648 }
649 }
650
651 // v6 routes listed as:
652 // dest-addr prefixlength ?? ?? gateway-addr ?? ?? ?? ?? iface
653 for (String s : readRouteList("/proc/net/ipv6_route")) {
654 String[]fields = s.split("\\s+");
655 if (fields.length > 9) {
656 String iface = fields[9].trim();
657 if (interfaceName.equals(iface)) {
658 String dest = fields[0];
659 String prefix = fields[1];
660 String gate = fields[4];
661
662 try {
663 // prefix length stored as a hex string, ex 40
664 int prefixLength = Integer.parseInt(prefix, 16);
665
666 // address stored as a 32 char hex string
667 // ex fe800000000000000000000000000000
668 InetAddress destAddr = NetworkUtils.hexToInet6Address(dest);
669 LinkAddress linkAddress = new LinkAddress(destAddr, prefixLength);
670
671 InetAddress gateAddr = NetworkUtils.hexToInet6Address(gate);
672
673 RouteInfo route = new RouteInfo(linkAddress, gateAddr);
674 routes.add(route);
675 } catch (Exception e) {
676 Log.e(TAG, "Error parsing route " + s + " : " + e);
677 continue;
678 }
679 }
680 }
681 }
682 return (RouteInfo[]) routes.toArray(new RouteInfo[0]);
683 }
684
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800685 @Override
San Mehat873f2142010-01-14 10:25:07 -0800686 public void shutdown() {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800687 // TODO: remove from aidl if nobody calls externally
688 mContext.enforceCallingOrSelfPermission(SHUTDOWN, TAG);
San Mehat873f2142010-01-14 10:25:07 -0800689
Joe Onorato8a9b2202010-02-26 18:56:32 -0800690 Slog.d(TAG, "Shutting down");
San Mehat873f2142010-01-14 10:25:07 -0800691 }
692
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800693 @Override
San Mehat873f2142010-01-14 10:25:07 -0800694 public boolean getIpForwardingEnabled() throws IllegalStateException{
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800695 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
San Mehat873f2142010-01-14 10:25:07 -0800696
Kenny Roota80ce062010-06-01 13:23:53 -0700697 ArrayList<String> rsp;
698 try {
699 rsp = mConnector.doCommand("ipfwd status");
700 } catch (NativeDaemonConnectorException e) {
701 throw new IllegalStateException(
702 "Unable to communicate with native daemon to ipfwd status");
703 }
San Mehat873f2142010-01-14 10:25:07 -0800704
705 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700706 String[] tok = line.split(" ");
707 if (tok.length < 3) {
708 Slog.e(TAG, "Malformed response from native daemon: " + line);
709 return false;
710 }
711
San Mehat873f2142010-01-14 10:25:07 -0800712 int code = Integer.parseInt(tok[0]);
713 if (code == NetdResponseCode.IpFwdStatusResult) {
714 // 211 Forwarding <enabled/disabled>
Kenny Roota80ce062010-06-01 13:23:53 -0700715 return "enabled".equals(tok[2]);
San Mehat873f2142010-01-14 10:25:07 -0800716 } else {
717 throw new IllegalStateException(String.format("Unexpected response code %d", code));
718 }
719 }
720 throw new IllegalStateException("Got an empty response");
721 }
722
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800723 @Override
724 public void setIpForwardingEnabled(boolean enable) {
725 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800726 try {
727 mConnector.doCommand(String.format("ipfwd %sable", (enable ? "en" : "dis")));
728 } catch (NativeDaemonConnectorException e) {
729 e.rethrowAsParcelableException();
730 }
San Mehat873f2142010-01-14 10:25:07 -0800731 }
732
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800733 @Override
734 public void startTethering(String[] dhcpRange) {
735 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -0700736 // cmd is "tether start first_start first_stop second_start second_stop ..."
737 // an odd number of addrs will fail
738 String cmd = "tether start";
739 for (String d : dhcpRange) {
740 cmd += " " + d;
741 }
Kenny Roota80ce062010-06-01 13:23:53 -0700742
743 try {
744 mConnector.doCommand(cmd);
745 } catch (NativeDaemonConnectorException e) {
746 throw new IllegalStateException("Unable to communicate to native daemon");
747 }
San Mehat873f2142010-01-14 10:25:07 -0800748 }
749
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800750 @Override
751 public void stopTethering() {
752 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700753 try {
754 mConnector.doCommand("tether stop");
755 } catch (NativeDaemonConnectorException e) {
756 throw new IllegalStateException("Unable to communicate to native daemon to stop tether");
757 }
San Mehat873f2142010-01-14 10:25:07 -0800758 }
759
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800760 @Override
761 public boolean isTetheringStarted() {
762 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
San Mehat873f2142010-01-14 10:25:07 -0800763
Kenny Roota80ce062010-06-01 13:23:53 -0700764 ArrayList<String> rsp;
765 try {
766 rsp = mConnector.doCommand("tether status");
767 } catch (NativeDaemonConnectorException e) {
768 throw new IllegalStateException(
769 "Unable to communicate to native daemon to get tether status");
770 }
San Mehat873f2142010-01-14 10:25:07 -0800771
772 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700773 String[] tok = line.split(" ");
774 if (tok.length < 3) {
775 throw new IllegalStateException("Malformed response for tether status: " + line);
776 }
San Mehat873f2142010-01-14 10:25:07 -0800777 int code = Integer.parseInt(tok[0]);
778 if (code == NetdResponseCode.TetherStatusResult) {
779 // XXX: Tethering services <started/stopped> <TBD>...
Kenny Roota80ce062010-06-01 13:23:53 -0700780 return "started".equals(tok[2]);
San Mehat873f2142010-01-14 10:25:07 -0800781 } else {
782 throw new IllegalStateException(String.format("Unexpected response code %d", code));
783 }
784 }
785 throw new IllegalStateException("Got an empty response");
786 }
787
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800788 @Override
789 public void tetherInterface(String iface) {
790 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700791 try {
792 mConnector.doCommand("tether interface add " + iface);
793 } catch (NativeDaemonConnectorException e) {
794 throw new IllegalStateException(
795 "Unable to communicate to native daemon for adding tether interface");
796 }
San Mehat873f2142010-01-14 10:25:07 -0800797 }
798
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800799 @Override
San Mehat873f2142010-01-14 10:25:07 -0800800 public void untetherInterface(String iface) {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800801 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700802 try {
803 mConnector.doCommand("tether interface remove " + iface);
804 } catch (NativeDaemonConnectorException e) {
805 throw new IllegalStateException(
806 "Unable to communicate to native daemon for removing tether interface");
807 }
San Mehat873f2142010-01-14 10:25:07 -0800808 }
809
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800810 @Override
811 public String[] listTetheredInterfaces() {
812 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700813 try {
814 return mConnector.doListCommand(
815 "tether interface list", NetdResponseCode.TetherInterfaceListResult);
816 } catch (NativeDaemonConnectorException e) {
817 throw new IllegalStateException(
818 "Unable to communicate to native daemon for listing tether interfaces");
819 }
San Mehat873f2142010-01-14 10:25:07 -0800820 }
821
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800822 @Override
823 public void setDnsForwarders(String[] dns) {
824 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
San Mehat873f2142010-01-14 10:25:07 -0800825 try {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800826 String cmd = "tether dns set";
San Mehat873f2142010-01-14 10:25:07 -0800827 for (String s : dns) {
Robert Greenwalte5903732011-02-22 16:00:42 -0800828 cmd += " " + NetworkUtils.numericToInetAddress(s).getHostAddress();
San Mehat873f2142010-01-14 10:25:07 -0800829 }
Kenny Roota80ce062010-06-01 13:23:53 -0700830 try {
831 mConnector.doCommand(cmd);
832 } catch (NativeDaemonConnectorException e) {
833 throw new IllegalStateException(
834 "Unable to communicate to native daemon for setting tether dns");
835 }
Robert Greenwalte5903732011-02-22 16:00:42 -0800836 } catch (IllegalArgumentException e) {
San Mehat873f2142010-01-14 10:25:07 -0800837 throw new IllegalStateException("Error resolving dns name", e);
838 }
839 }
840
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800841 @Override
842 public String[] getDnsForwarders() {
843 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700844 try {
845 return mConnector.doListCommand(
846 "tether dns list", NetdResponseCode.TetherDnsFwdTgtListResult);
847 } catch (NativeDaemonConnectorException e) {
848 throw new IllegalStateException(
849 "Unable to communicate to native daemon for listing tether dns");
850 }
San Mehat873f2142010-01-14 10:25:07 -0800851 }
852
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700853 private void modifyNat(String cmd, String internalInterface, String externalInterface)
854 throws SocketException {
855 cmd = String.format("nat %s %s %s", cmd, internalInterface, externalInterface);
856
857 NetworkInterface internalNetworkInterface =
858 NetworkInterface.getByName(internalInterface);
Robert Greenwalte83d1812011-11-21 14:44:39 -0800859 if (internalNetworkInterface == null) {
860 cmd += " 0";
861 } else {
862 Collection<InterfaceAddress>interfaceAddresses =
863 internalNetworkInterface.getInterfaceAddresses();
864 cmd += " " + interfaceAddresses.size();
865 for (InterfaceAddress ia : interfaceAddresses) {
866 InetAddress addr = NetworkUtils.getNetworkPart(ia.getAddress(),
867 ia.getNetworkPrefixLength());
868 cmd = cmd + " " + addr.getHostAddress() + "/" + ia.getNetworkPrefixLength();
869 }
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700870 }
871
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800872 try {
873 mConnector.doCommand(cmd);
874 } catch (NativeDaemonConnectorException e) {
875 e.rethrowAsParcelableException();
876 }
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700877 }
878
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800879 @Override
880 public void enableNat(String internalInterface, String externalInterface) {
881 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700882 if (DBG) Log.d(TAG, "enableNat(" + internalInterface + ", " + externalInterface + ")");
Kenny Roota80ce062010-06-01 13:23:53 -0700883 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700884 modifyNat("enable", internalInterface, externalInterface);
885 } catch (Exception e) {
886 Log.e(TAG, "enableNat got Exception " + e.toString());
Kenny Roota80ce062010-06-01 13:23:53 -0700887 throw new IllegalStateException(
888 "Unable to communicate to native daemon for enabling NAT interface");
889 }
San Mehat873f2142010-01-14 10:25:07 -0800890 }
891
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800892 @Override
893 public void disableNat(String internalInterface, String externalInterface) {
894 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700895 if (DBG) Log.d(TAG, "disableNat(" + internalInterface + ", " + externalInterface + ")");
Kenny Roota80ce062010-06-01 13:23:53 -0700896 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700897 modifyNat("disable", internalInterface, externalInterface);
898 } catch (Exception e) {
899 Log.e(TAG, "disableNat got Exception " + e.toString());
Kenny Roota80ce062010-06-01 13:23:53 -0700900 throw new IllegalStateException(
901 "Unable to communicate to native daemon for disabling NAT interface");
902 }
San Mehat873f2142010-01-14 10:25:07 -0800903 }
San Mehat72759df2010-01-19 13:50:37 -0800904
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800905 @Override
906 public String[] listTtys() {
907 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700908 try {
909 return mConnector.doListCommand("list_ttys", NetdResponseCode.TtyListResult);
910 } catch (NativeDaemonConnectorException e) {
911 throw new IllegalStateException(
912 "Unable to communicate to native daemon for listing TTYs");
913 }
San Mehat72759df2010-01-19 13:50:37 -0800914 }
915
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800916 @Override
917 public void attachPppd(
918 String tty, String localAddr, String remoteAddr, String dns1Addr, String dns2Addr) {
919 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
San Mehat72759df2010-01-19 13:50:37 -0800920 try {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800921 mConnector.doCommand(String.format("pppd attach %s %s %s %s %s", tty,
Robert Greenwalte5903732011-02-22 16:00:42 -0800922 NetworkUtils.numericToInetAddress(localAddr).getHostAddress(),
923 NetworkUtils.numericToInetAddress(remoteAddr).getHostAddress(),
924 NetworkUtils.numericToInetAddress(dns1Addr).getHostAddress(),
925 NetworkUtils.numericToInetAddress(dns2Addr).getHostAddress()));
926 } catch (IllegalArgumentException e) {
San Mehat72759df2010-01-19 13:50:37 -0800927 throw new IllegalStateException("Error resolving addr", e);
Kenny Roota80ce062010-06-01 13:23:53 -0700928 } catch (NativeDaemonConnectorException e) {
929 throw new IllegalStateException("Error communicating to native daemon to attach pppd", e);
San Mehat72759df2010-01-19 13:50:37 -0800930 }
931 }
932
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800933 @Override
934 public void detachPppd(String tty) {
935 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700936 try {
937 mConnector.doCommand(String.format("pppd detach %s", tty));
938 } catch (NativeDaemonConnectorException e) {
939 throw new IllegalStateException("Error communicating to native daemon to detach pppd", e);
940 }
San Mehat72759df2010-01-19 13:50:37 -0800941 }
Robert Greenwaltce1200d2010-02-18 11:25:54 -0800942
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800943 @Override
944 public void startAccessPoint(
945 WifiConfiguration wifiConfig, String wlanIface, String softapIface) {
946 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
947 mContext.enforceCallingOrSelfPermission(CHANGE_WIFI_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700948 try {
Irfan Sheriffcb30b222011-07-29 20:54:52 -0700949 wifiFirmwareReload(wlanIface, "AP");
Kenny Roota80ce062010-06-01 13:23:53 -0700950 mConnector.doCommand(String.format("softap start " + wlanIface));
951 if (wifiConfig == null) {
952 mConnector.doCommand(String.format("softap set " + wlanIface + " " + softapIface));
953 } else {
954 /**
955 * softap set arg1 arg2 arg3 [arg4 arg5 arg6 arg7 arg8]
956 * argv1 - wlan interface
957 * argv2 - softap interface
958 * argv3 - SSID
959 * argv4 - Security
960 * argv5 - Key
961 * argv6 - Channel
962 * argv7 - Preamble
963 * argv8 - Max SCB
964 */
Irfan Sheriffec8d23a2011-02-16 17:00:33 -0800965 String str = String.format("softap set " + wlanIface + " " + softapIface +
966 " %s %s %s", convertQuotedString(wifiConfig.SSID),
967 getSecurityType(wifiConfig),
968 convertQuotedString(wifiConfig.preSharedKey));
Kenny Roota80ce062010-06-01 13:23:53 -0700969 mConnector.doCommand(str);
970 }
971 mConnector.doCommand(String.format("softap startap"));
972 } catch (NativeDaemonConnectorException e) {
973 throw new IllegalStateException("Error communicating to native daemon to start softap", e);
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800974 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800975 }
976
Irfan Sheriffa6e559e2010-05-24 14:55:42 -0700977 private String convertQuotedString(String s) {
Irfan Sheriff7baec0f2010-05-26 17:16:47 -0700978 if (s == null) {
979 return s;
980 }
981 /* Replace \ with \\, then " with \" and add quotes at end */
982 return '"' + s.replaceAll("\\\\","\\\\\\\\").replaceAll("\"","\\\\\"") + '"';
Irfan Sheriffa6e559e2010-05-24 14:55:42 -0700983 }
984
Irfan Sheriffec8d23a2011-02-16 17:00:33 -0800985 private String getSecurityType(WifiConfiguration wifiConfig) {
986 switch (wifiConfig.getAuthType()) {
987 case KeyMgmt.WPA_PSK:
988 return "wpa-psk";
989 case KeyMgmt.WPA2_PSK:
990 return "wpa2-psk";
991 default:
992 return "open";
993 }
994 }
995
Irfan Sheriffcb30b222011-07-29 20:54:52 -0700996 /* @param mode can be "AP", "STA" or "P2P" */
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800997 @Override
998 public void wifiFirmwareReload(String wlanIface, String mode) {
999 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
1000 mContext.enforceCallingOrSelfPermission(CHANGE_WIFI_STATE, TAG);
Irfan Sheriffcb30b222011-07-29 20:54:52 -07001001 try {
1002 mConnector.doCommand(String.format("softap fwreload " + wlanIface + " " + mode));
1003 } catch (NativeDaemonConnectorException e) {
1004 throw new IllegalStateException("Error communicating to native daemon ", e);
1005 }
1006 }
1007
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001008 @Override
1009 public void stopAccessPoint(String wlanIface) {
1010 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
1011 mContext.enforceCallingOrSelfPermission(CHANGE_WIFI_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001012 try {
1013 mConnector.doCommand("softap stopap");
Irfan Sheriff23eb2972011-07-22 15:21:10 -07001014 mConnector.doCommand("softap stop " + wlanIface);
Irfan Sheriffcb30b222011-07-29 20:54:52 -07001015 wifiFirmwareReload(wlanIface, "STA");
Kenny Roota80ce062010-06-01 13:23:53 -07001016 } catch (NativeDaemonConnectorException e) {
1017 throw new IllegalStateException("Error communicating to native daemon to stop soft AP",
1018 e);
1019 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001020 }
1021
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001022 @Override
1023 public void setAccessPoint(WifiConfiguration wifiConfig, String wlanIface, String softapIface) {
1024 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
1025 mContext.enforceCallingOrSelfPermission(CHANGE_WIFI_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001026 try {
1027 if (wifiConfig == null) {
1028 mConnector.doCommand(String.format("softap set " + wlanIface + " " + softapIface));
1029 } else {
1030 String str = String.format("softap set " + wlanIface + " " + softapIface
1031 + " %s %s %s", convertQuotedString(wifiConfig.SSID),
Irfan Sheriffec8d23a2011-02-16 17:00:33 -08001032 getSecurityType(wifiConfig),
Kenny Roota80ce062010-06-01 13:23:53 -07001033 convertQuotedString(wifiConfig.preSharedKey));
1034 mConnector.doCommand(str);
1035 }
1036 } catch (NativeDaemonConnectorException e) {
1037 throw new IllegalStateException("Error communicating to native daemon to set soft AP",
1038 e);
Irfan Sheriffc2f54c22010-03-18 14:02:22 -07001039 }
1040 }
San Mehat91cac642010-03-31 14:31:36 -07001041
1042 private long getInterfaceCounter(String iface, boolean rx) {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001043 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
San Mehat91cac642010-03-31 14:31:36 -07001044 try {
Kenny Roota80ce062010-06-01 13:23:53 -07001045 String rsp;
1046 try {
1047 rsp = mConnector.doCommand(
1048 String.format("interface read%scounter %s", (rx ? "rx" : "tx"), iface)).get(0);
1049 } catch (NativeDaemonConnectorException e1) {
1050 Slog.e(TAG, "Error communicating with native daemon", e1);
1051 return -1;
1052 }
1053
1054 String[] tok = rsp.split(" ");
1055 if (tok.length < 2) {
1056 Slog.e(TAG, String.format("Malformed response for reading %s interface",
1057 (rx ? "rx" : "tx")));
1058 return -1;
1059 }
1060
San Mehat91cac642010-03-31 14:31:36 -07001061 int code;
1062 try {
1063 code = Integer.parseInt(tok[0]);
1064 } catch (NumberFormatException nfe) {
1065 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
1066 return -1;
1067 }
1068 if ((rx && code != NetdResponseCode.InterfaceRxCounterResult) || (
1069 !rx && code != NetdResponseCode.InterfaceTxCounterResult)) {
1070 Slog.e(TAG, String.format("Unexpected response code %d", code));
1071 return -1;
1072 }
1073 return Long.parseLong(tok[1]);
1074 } catch (Exception e) {
1075 Slog.e(TAG, String.format(
1076 "Failed to read interface %s counters", (rx ? "rx" : "tx")), e);
1077 }
1078 return -1;
1079 }
1080
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001081 @Override
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001082 public NetworkStats getNetworkStatsSummary() {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001083 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07001084 return mStatsFactory.readNetworkStatsSummary();
Jeff Sharkeyae2c1812011-10-04 13:11:40 -07001085 }
1086
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001087 @Override
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001088 public NetworkStats getNetworkStatsDetail() {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001089 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07001090 return mStatsFactory.readNetworkStatsDetail(UID_ALL);
San Mehat91cac642010-03-31 14:31:36 -07001091 }
1092
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001093 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001094 public void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001095 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1096
Jeff Sharkey350083e2011-06-29 10:45:16 -07001097 // silently discard when control disabled
1098 // TODO: eventually migrate to be always enabled
1099 if (!mBandwidthControlEnabled) return;
1100
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001101 synchronized (mQuotaLock) {
1102 if (mActiveQuotaIfaces.contains(iface)) {
1103 throw new IllegalStateException("iface " + iface + " already has quota");
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001104 }
1105
1106 final StringBuilder command = new StringBuilder();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001107 command.append("bandwidth setiquota ").append(iface).append(" ").append(quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001108
1109 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001110 // TODO: support quota shared across interfaces
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001111 mConnector.doCommand(command.toString());
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001112 mActiveQuotaIfaces.add(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001113 } catch (NativeDaemonConnectorException e) {
1114 throw new IllegalStateException("Error communicating to native daemon", e);
1115 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001116 }
1117 }
1118
1119 @Override
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001120 public void removeInterfaceQuota(String iface) {
1121 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1122
Jeff Sharkey350083e2011-06-29 10:45:16 -07001123 // silently discard when control disabled
1124 // TODO: eventually migrate to be always enabled
1125 if (!mBandwidthControlEnabled) return;
1126
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001127 synchronized (mQuotaLock) {
1128 if (!mActiveQuotaIfaces.contains(iface)) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001129 // TODO: eventually consider throwing
1130 return;
1131 }
1132
1133 final StringBuilder command = new StringBuilder();
1134 command.append("bandwidth removeiquota ").append(iface);
1135
Jeff Sharkey38ddeaa2011-11-08 13:04:22 -08001136 mActiveQuotaIfaces.remove(iface);
1137 mActiveAlertIfaces.remove(iface);
1138
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001139 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001140 // TODO: support quota shared across interfaces
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001141 mConnector.doCommand(command.toString());
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001142 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey38ddeaa2011-11-08 13:04:22 -08001143 // TODO: include current iptables state
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001144 throw new IllegalStateException("Error communicating to native daemon", e);
1145 }
1146 }
1147 }
1148
1149 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001150 public void setInterfaceAlert(String iface, long alertBytes) {
1151 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1152
1153 // silently discard when control disabled
1154 // TODO: eventually migrate to be always enabled
1155 if (!mBandwidthControlEnabled) return;
1156
1157 // quick sanity check
1158 if (!mActiveQuotaIfaces.contains(iface)) {
1159 throw new IllegalStateException("setting alert requires existing quota on iface");
1160 }
1161
1162 synchronized (mQuotaLock) {
1163 if (mActiveAlertIfaces.contains(iface)) {
1164 throw new IllegalStateException("iface " + iface + " already has alert");
1165 }
1166
1167 final StringBuilder command = new StringBuilder();
1168 command.append("bandwidth setinterfacealert ").append(iface).append(" ").append(
1169 alertBytes);
1170
1171 try {
1172 // TODO: support alert shared across interfaces
1173 mConnector.doCommand(command.toString());
1174 mActiveAlertIfaces.add(iface);
1175 } catch (NativeDaemonConnectorException e) {
1176 throw new IllegalStateException("Error communicating to native daemon", e);
1177 }
1178 }
1179 }
1180
1181 @Override
1182 public void removeInterfaceAlert(String iface) {
1183 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1184
1185 // silently discard when control disabled
1186 // TODO: eventually migrate to be always enabled
1187 if (!mBandwidthControlEnabled) return;
1188
1189 synchronized (mQuotaLock) {
1190 if (!mActiveAlertIfaces.contains(iface)) {
1191 // TODO: eventually consider throwing
1192 return;
1193 }
1194
1195 final StringBuilder command = new StringBuilder();
1196 command.append("bandwidth removeinterfacealert ").append(iface);
1197
1198 try {
1199 // TODO: support alert shared across interfaces
1200 mConnector.doCommand(command.toString());
1201 mActiveAlertIfaces.remove(iface);
1202 } catch (NativeDaemonConnectorException e) {
1203 throw new IllegalStateException("Error communicating to native daemon", e);
1204 }
1205 }
1206 }
1207
1208 @Override
1209 public void setGlobalAlert(long alertBytes) {
1210 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1211
1212 // silently discard when control disabled
1213 // TODO: eventually migrate to be always enabled
1214 if (!mBandwidthControlEnabled) return;
1215
1216 final StringBuilder command = new StringBuilder();
1217 command.append("bandwidth setglobalalert ").append(alertBytes);
1218
1219 try {
1220 mConnector.doCommand(command.toString());
1221 } catch (NativeDaemonConnectorException e) {
1222 throw new IllegalStateException("Error communicating to native daemon", e);
1223 }
1224 }
1225
1226 @Override
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001227 public void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
1228 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1229
Jeff Sharkey350083e2011-06-29 10:45:16 -07001230 // silently discard when control disabled
1231 // TODO: eventually migrate to be always enabled
1232 if (!mBandwidthControlEnabled) return;
1233
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001234 synchronized (mUidRejectOnQuota) {
1235 final boolean oldRejectOnQuota = mUidRejectOnQuota.get(uid, false);
1236 if (oldRejectOnQuota == rejectOnQuotaInterfaces) {
1237 // TODO: eventually consider throwing
1238 return;
1239 }
1240
1241 final StringBuilder command = new StringBuilder();
1242 command.append("bandwidth");
1243 if (rejectOnQuotaInterfaces) {
1244 command.append(" addnaughtyapps");
1245 } else {
1246 command.append(" removenaughtyapps");
1247 }
1248 command.append(" ").append(uid);
1249
1250 try {
1251 mConnector.doCommand(command.toString());
1252 if (rejectOnQuotaInterfaces) {
1253 mUidRejectOnQuota.put(uid, true);
1254 } else {
1255 mUidRejectOnQuota.delete(uid);
1256 }
1257 } catch (NativeDaemonConnectorException e) {
1258 throw new IllegalStateException("Error communicating to native daemon", e);
1259 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001260 }
1261 }
1262
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001263 @Override
1264 public boolean isBandwidthControlEnabled() {
1265 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1266 return mBandwidthControlEnabled;
1267 }
1268
1269 @Override
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001270 public NetworkStats getNetworkStatsUidDetail(int uid) {
1271 if (Binder.getCallingUid() != uid) {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001272 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001273 }
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07001274 return mStatsFactory.readNetworkStatsDetail(uid);
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001275 }
1276
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001277 @Override
1278 public NetworkStats getNetworkStatsTethering(String[] ifacePairs) {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001279 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001280
1281 if (ifacePairs.length % 2 != 0) {
1282 throw new IllegalArgumentException(
1283 "unexpected ifacePairs; length=" + ifacePairs.length);
1284 }
1285
1286 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 1);
1287 for (int i = 0; i < ifacePairs.length; i += 2) {
1288 final String ifaceIn = ifacePairs[i];
1289 final String ifaceOut = ifacePairs[i + 1];
1290 if (ifaceIn != null && ifaceOut != null) {
1291 stats.combineValues(getNetworkStatsTethering(ifaceIn, ifaceOut));
1292 }
1293 }
1294 return stats;
1295 }
1296
1297 private NetworkStats.Entry getNetworkStatsTethering(String ifaceIn, String ifaceOut) {
1298 final StringBuilder command = new StringBuilder();
1299 command.append("bandwidth gettetherstats ").append(ifaceIn).append(" ").append(ifaceOut);
1300
1301 final String rsp;
1302 try {
1303 rsp = mConnector.doCommand(command.toString()).get(0);
1304 } catch (NativeDaemonConnectorException e) {
1305 throw new IllegalStateException("Error communicating to native daemon", e);
1306 }
1307
1308 final String[] tok = rsp.split(" ");
1309 /* Expecting: "code ifaceIn ifaceOut rx_bytes rx_packets tx_bytes tx_packets" */
1310 if (tok.length != 7) {
1311 throw new IllegalStateException("Native daemon returned unexpected result: " + rsp);
1312 }
1313
1314 final int code;
1315 try {
1316 code = Integer.parseInt(tok[0]);
1317 } catch (NumberFormatException e) {
1318 throw new IllegalStateException(
1319 "Failed to parse native daemon return code for " + ifaceIn + " " + ifaceOut);
1320 }
1321 if (code != NetdResponseCode.TetheringStatsResult) {
1322 throw new IllegalStateException(
1323 "Unexpected return code from native daemon for " + ifaceIn + " " + ifaceOut);
1324 }
1325
1326 try {
1327 final NetworkStats.Entry entry = new NetworkStats.Entry();
1328 entry.iface = ifaceIn;
Jeff Sharkey905b5892011-09-30 15:19:49 -07001329 entry.uid = UID_TETHERING;
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001330 entry.set = SET_DEFAULT;
1331 entry.tag = TAG_NONE;
1332 entry.rxBytes = Long.parseLong(tok[3]);
1333 entry.rxPackets = Long.parseLong(tok[4]);
1334 entry.txBytes = Long.parseLong(tok[5]);
1335 entry.txPackets = Long.parseLong(tok[6]);
1336 return entry;
1337 } catch (NumberFormatException e) {
1338 throw new IllegalStateException(
1339 "problem parsing tethering stats for " + ifaceIn + " " + ifaceOut + ": " + e);
1340 }
1341 }
1342
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001343 @Override
San Mehatf0db6e12010-04-07 15:22:10 -07001344 public void setInterfaceThrottle(String iface, int rxKbps, int txKbps) {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001345 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001346 try {
1347 mConnector.doCommand(String.format(
1348 "interface setthrottle %s %d %d", iface, rxKbps, txKbps));
1349 } catch (NativeDaemonConnectorException e) {
1350 Slog.e(TAG, "Error communicating with native daemon to set throttle", e);
1351 }
San Mehat91cac642010-03-31 14:31:36 -07001352 }
1353
1354 private int getInterfaceThrottle(String iface, boolean rx) {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001355 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
San Mehat91cac642010-03-31 14:31:36 -07001356 try {
Kenny Roota80ce062010-06-01 13:23:53 -07001357 String rsp;
1358 try {
1359 rsp = mConnector.doCommand(
1360 String.format("interface getthrottle %s %s", iface,
1361 (rx ? "rx" : "tx"))).get(0);
1362 } catch (NativeDaemonConnectorException e) {
1363 Slog.e(TAG, "Error communicating with native daemon to getthrottle", e);
1364 return -1;
1365 }
1366
1367 String[] tok = rsp.split(" ");
1368 if (tok.length < 2) {
1369 Slog.e(TAG, "Malformed response to getthrottle command");
1370 return -1;
1371 }
1372
San Mehat91cac642010-03-31 14:31:36 -07001373 int code;
1374 try {
1375 code = Integer.parseInt(tok[0]);
1376 } catch (NumberFormatException nfe) {
1377 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
1378 return -1;
1379 }
1380 if ((rx && code != NetdResponseCode.InterfaceRxThrottleResult) || (
1381 !rx && code != NetdResponseCode.InterfaceTxThrottleResult)) {
1382 Slog.e(TAG, String.format("Unexpected response code %d", code));
1383 return -1;
1384 }
1385 return Integer.parseInt(tok[1]);
1386 } catch (Exception e) {
1387 Slog.e(TAG, String.format(
1388 "Failed to read interface %s throttle value", (rx ? "rx" : "tx")), e);
1389 }
1390 return -1;
1391 }
1392
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001393 @Override
San Mehat91cac642010-03-31 14:31:36 -07001394 public int getInterfaceRxThrottle(String iface) {
1395 return getInterfaceThrottle(iface, true);
1396 }
1397
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001398 @Override
San Mehat91cac642010-03-31 14:31:36 -07001399 public int getInterfaceTxThrottle(String iface) {
1400 return getInterfaceThrottle(iface, false);
1401 }
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001402
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001403 @Override
1404 public void setDefaultInterfaceForDns(String iface) {
1405 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001406 try {
1407 String cmd = "resolver setdefaultif " + iface;
1408
1409 mConnector.doCommand(cmd);
1410 } catch (NativeDaemonConnectorException e) {
1411 throw new IllegalStateException(
1412 "Error communicating with native daemon to set default interface", e);
1413 }
1414 }
1415
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001416 @Override
1417 public void setDnsServersForInterface(String iface, String[] servers) {
1418 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001419 try {
1420 String cmd = "resolver setifdns " + iface;
1421 for (String s : servers) {
Robert Greenwalt572b7042011-07-25 17:00:13 -07001422 InetAddress a = NetworkUtils.numericToInetAddress(s);
1423 if (a.isAnyLocalAddress() == false) {
1424 cmd += " " + a.getHostAddress();
Mattias Falk7475c0c2011-04-04 16:10:36 +02001425 }
1426 }
Mattias Falk7475c0c2011-04-04 16:10:36 +02001427 mConnector.doCommand(cmd);
Robert Greenwalt572b7042011-07-25 17:00:13 -07001428 } catch (IllegalArgumentException e) {
1429 throw new IllegalStateException("Error setting dnsn for interface", e);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001430 } catch (NativeDaemonConnectorException e) {
1431 throw new IllegalStateException(
Robert Greenwalt572b7042011-07-25 17:00:13 -07001432 "Error communicating with native daemon to set dns for interface", e);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001433 }
1434 }
1435
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001436 @Override
1437 public void flushDefaultDnsCache() {
1438 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001439 try {
1440 String cmd = "resolver flushdefaultif";
1441
1442 mConnector.doCommand(cmd);
1443 } catch (NativeDaemonConnectorException e) {
1444 throw new IllegalStateException(
1445 "Error communicating with native deamon to flush default interface", e);
1446 }
1447 }
1448
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001449 @Override
1450 public void flushInterfaceDnsCache(String iface) {
1451 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001452 try {
1453 String cmd = "resolver flushif " + iface;
1454
1455 mConnector.doCommand(cmd);
1456 } catch (NativeDaemonConnectorException e) {
1457 throw new IllegalStateException(
Robert Greenwalt572b7042011-07-25 17:00:13 -07001458 "Error communicating with native daemon to flush interface " + iface, e);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001459 }
1460 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07001461
1462 /** {@inheritDoc} */
1463 public void monitor() {
1464 if (mConnector != null) {
1465 mConnector.monitor();
1466 }
1467 }
Jeff Sharkey47eb1022011-08-25 17:48:52 -07001468
1469 @Override
1470 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1471 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
1472
1473 pw.print("Bandwidth control enabled: "); pw.println(mBandwidthControlEnabled);
1474
1475 synchronized (mQuotaLock) {
1476 pw.print("Active quota ifaces: "); pw.println(mActiveQuotaIfaces.toString());
1477 pw.print("Active alert ifaces: "); pw.println(mActiveAlertIfaces.toString());
1478 }
1479
1480 synchronized (mUidRejectOnQuota) {
1481 pw.print("UID reject on quota ifaces: [");
1482 final int size = mUidRejectOnQuota.size();
1483 for (int i = 0; i < size; i++) {
1484 pw.print(mUidRejectOnQuota.keyAt(i));
1485 if (i < size - 1) pw.print(",");
1486 }
1487 pw.println("]");
1488 }
1489 }
San Mehat873f2142010-01-14 10:25:07 -08001490}