blob: 70e3c1fa22e96bf24f15b657a8d4bc664e996ed6 [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();
Jeff Sharkeyddba1062011-11-29 18:37:04 -0800398 cfg.setHardwareAddress(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
Jeff Sharkeyddba1062011-11-29 18:37:04 -0800413 cfg.setLinkAddress(new LinkAddress(addr, prefixLength));
414 while (st.hasMoreTokens()) {
415 cfg.setFlag(st.nextToken());
416 }
Kenny Roota80ce062010-06-01 13:23:53 -0700417 } catch (NoSuchElementException nsee) {
San Mehated4fc8a2010-01-22 12:28:36 -0800418 throw new IllegalStateException(
419 String.format("Invalid response from daemon (%s)", rsp));
420 }
Jeff Sharkeyddba1062011-11-29 18:37:04 -0800421 Slog.d(TAG, String.format("flags <%s>", cfg.getFlags()));
San Mehated4fc8a2010-01-22 12:28:36 -0800422 return cfg;
423 }
424
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800425 @Override
426 public void setInterfaceConfig(String iface, InterfaceConfiguration cfg) {
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700427 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Jeff Sharkeyddba1062011-11-29 18:37:04 -0800428 LinkAddress linkAddr = cfg.getLinkAddress();
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800429 if (linkAddr == null || linkAddr.getAddress() == null) {
430 throw new IllegalStateException("Null LinkAddress given");
Robert Greenwalted126402011-01-28 15:34:55 -0800431 }
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800432 String cmd = String.format("interface setcfg %s %s %d %s", iface,
433 linkAddr.getAddress().getHostAddress(),
434 linkAddr.getNetworkPrefixLength(),
Jeff Sharkeyddba1062011-11-29 18:37:04 -0800435 cfg.getFlags());
Kenny Roota80ce062010-06-01 13:23:53 -0700436 try {
437 mConnector.doCommand(cmd);
438 } catch (NativeDaemonConnectorException e) {
439 throw new IllegalStateException(
Robert Greenwalt81d5ad52010-12-16 11:27:38 -0800440 "Unable to communicate with native daemon to interface setcfg - " + e);
Kenny Roota80ce062010-06-01 13:23:53 -0700441 }
San Mehat873f2142010-01-14 10:25:07 -0800442 }
443
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800444 @Override
445 public void setInterfaceDown(String iface) {
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700446 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800447 final InterfaceConfiguration ifcg = getInterfaceConfig(iface);
Jeff Sharkeyddba1062011-11-29 18:37:04 -0800448 ifcg.setInterfaceDown();
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800449 setInterfaceConfig(iface, ifcg);
Irfan Sheriff7244c972011-08-05 20:40:45 -0700450 }
451
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800452 @Override
453 public void setInterfaceUp(String iface) {
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700454 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800455 final InterfaceConfiguration ifcg = getInterfaceConfig(iface);
Jeff Sharkeyddba1062011-11-29 18:37:04 -0800456 ifcg.setInterfaceUp();
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800457 setInterfaceConfig(iface, ifcg);
Irfan Sheriff7244c972011-08-05 20:40:45 -0700458 }
459
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800460 @Override
461 public void setInterfaceIpv6PrivacyExtensions(String iface, boolean enable) {
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700462 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Irfan Sheriff73293612011-09-14 12:31:56 -0700463 String cmd = String.format("interface ipv6privacyextensions %s %s", iface,
464 enable ? "enable" : "disable");
465 try {
466 mConnector.doCommand(cmd);
467 } catch (NativeDaemonConnectorException e) {
468 throw new IllegalStateException(
469 "Unable to communicate with native daemon to set ipv6privacyextensions - " + e);
470 }
471 }
472
Irfan Sherifff5600612011-06-16 10:26:28 -0700473 /* TODO: This is right now a IPv4 only function. Works for wifi which loses its
474 IPv6 addresses on interface down, but we need to do full clean up here */
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800475 @Override
476 public void clearInterfaceAddresses(String iface) {
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700477 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
478 String cmd = String.format("interface clearaddrs %s", iface);
Irfan Sherifff5600612011-06-16 10:26:28 -0700479 try {
480 mConnector.doCommand(cmd);
481 } catch (NativeDaemonConnectorException e) {
482 throw new IllegalStateException(
483 "Unable to communicate with native daemon to interface clearallips - " + e);
484 }
485 }
486
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800487 @Override
488 public void enableIpv6(String iface) {
489 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
repo sync7960d9f2011-09-29 12:40:02 -0700490 try {
491 mConnector.doCommand(String.format("interface ipv6 %s enable", iface));
492 } catch (NativeDaemonConnectorException e) {
493 throw new IllegalStateException(
494 "Unable to communicate to native daemon for enabling ipv6");
495 }
496 }
497
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800498 @Override
499 public void disableIpv6(String iface) {
500 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
repo sync7960d9f2011-09-29 12:40:02 -0700501 try {
502 mConnector.doCommand(String.format("interface ipv6 %s disable", iface));
503 } catch (NativeDaemonConnectorException e) {
504 throw new IllegalStateException(
505 "Unable to communicate to native daemon for disabling ipv6");
506 }
507 }
508
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800509 @Override
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700510 public void addRoute(String interfaceName, RouteInfo route) {
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700511 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700512 modifyRoute(interfaceName, ADD, route, DEFAULT);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700513 }
514
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800515 @Override
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700516 public void removeRoute(String interfaceName, RouteInfo route) {
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700517 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700518 modifyRoute(interfaceName, REMOVE, route, DEFAULT);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700519 }
520
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800521 @Override
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700522 public void addSecondaryRoute(String interfaceName, RouteInfo route) {
523 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
524 modifyRoute(interfaceName, ADD, route, SECONDARY);
525 }
526
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800527 @Override
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700528 public void removeSecondaryRoute(String interfaceName, RouteInfo route) {
529 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
530 modifyRoute(interfaceName, REMOVE, route, SECONDARY);
531 }
532
533 private void modifyRoute(String interfaceName, int action, RouteInfo route, String type) {
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700534 ArrayList<String> rsp;
535
536 StringBuilder cmd;
537
538 switch (action) {
539 case ADD:
540 {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700541 cmd = new StringBuilder("interface route add " + interfaceName + " " + type);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700542 break;
543 }
544 case REMOVE:
545 {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700546 cmd = new StringBuilder("interface route remove " + interfaceName + " " + type);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700547 break;
548 }
549 default:
550 throw new IllegalStateException("Unknown action type " + action);
551 }
552
553 // create triplet: dest-ip-addr prefixlength gateway-ip-addr
554 LinkAddress la = route.getDestination();
555 cmd.append(' ');
556 cmd.append(la.getAddress().getHostAddress());
557 cmd.append(' ');
558 cmd.append(la.getNetworkPrefixLength());
559 cmd.append(' ');
560 if (route.getGateway() == null) {
561 if (la.getAddress() instanceof Inet4Address) {
562 cmd.append("0.0.0.0");
563 } else {
564 cmd.append ("::0");
565 }
566 } else {
567 cmd.append(route.getGateway().getHostAddress());
568 }
569 try {
570 rsp = mConnector.doCommand(cmd.toString());
571 } catch (NativeDaemonConnectorException e) {
572 throw new IllegalStateException(
573 "Unable to communicate with native dameon to add routes - "
574 + e);
575 }
576
Wink Savillec9acde92011-09-21 11:05:43 -0700577 if (DBG) {
578 for (String line : rsp) {
579 Log.v(TAG, "add route response is " + line);
580 }
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700581 }
582 }
583
584 private ArrayList<String> readRouteList(String filename) {
585 FileInputStream fstream = null;
586 ArrayList<String> list = new ArrayList<String>();
587
588 try {
589 fstream = new FileInputStream(filename);
590 DataInputStream in = new DataInputStream(fstream);
591 BufferedReader br = new BufferedReader(new InputStreamReader(in));
592 String s;
593
594 // throw away the title line
595
596 while (((s = br.readLine()) != null) && (s.length() != 0)) {
597 list.add(s);
598 }
599 } catch (IOException ex) {
600 // return current list, possibly empty
601 } finally {
602 if (fstream != null) {
603 try {
604 fstream.close();
605 } catch (IOException ex) {}
606 }
607 }
608
609 return list;
610 }
611
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800612 @Override
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700613 public RouteInfo[] getRoutes(String interfaceName) {
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700614 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700615 ArrayList<RouteInfo> routes = new ArrayList<RouteInfo>();
616
617 // v4 routes listed as:
618 // iface dest-addr gateway-addr flags refcnt use metric netmask mtu window IRTT
619 for (String s : readRouteList("/proc/net/route")) {
620 String[] fields = s.split("\t");
621
622 if (fields.length > 7) {
623 String iface = fields[0];
624
625 if (interfaceName.equals(iface)) {
626 String dest = fields[1];
627 String gate = fields[2];
628 String flags = fields[3]; // future use?
629 String mask = fields[7];
630 try {
631 // address stored as a hex string, ex: 0014A8C0
632 InetAddress destAddr =
633 NetworkUtils.intToInetAddress((int)Long.parseLong(dest, 16));
634 int prefixLength =
635 NetworkUtils.netmaskIntToPrefixLength(
636 (int)Long.parseLong(mask, 16));
637 LinkAddress linkAddress = new LinkAddress(destAddr, prefixLength);
638
639 // address stored as a hex string, ex 0014A8C0
640 InetAddress gatewayAddr =
641 NetworkUtils.intToInetAddress((int)Long.parseLong(gate, 16));
642
643 RouteInfo route = new RouteInfo(linkAddress, gatewayAddr);
644 routes.add(route);
645 } catch (Exception e) {
646 Log.e(TAG, "Error parsing route " + s + " : " + e);
647 continue;
648 }
649 }
650 }
651 }
652
653 // v6 routes listed as:
654 // dest-addr prefixlength ?? ?? gateway-addr ?? ?? ?? ?? iface
655 for (String s : readRouteList("/proc/net/ipv6_route")) {
656 String[]fields = s.split("\\s+");
657 if (fields.length > 9) {
658 String iface = fields[9].trim();
659 if (interfaceName.equals(iface)) {
660 String dest = fields[0];
661 String prefix = fields[1];
662 String gate = fields[4];
663
664 try {
665 // prefix length stored as a hex string, ex 40
666 int prefixLength = Integer.parseInt(prefix, 16);
667
668 // address stored as a 32 char hex string
669 // ex fe800000000000000000000000000000
670 InetAddress destAddr = NetworkUtils.hexToInet6Address(dest);
671 LinkAddress linkAddress = new LinkAddress(destAddr, prefixLength);
672
673 InetAddress gateAddr = NetworkUtils.hexToInet6Address(gate);
674
675 RouteInfo route = new RouteInfo(linkAddress, gateAddr);
676 routes.add(route);
677 } catch (Exception e) {
678 Log.e(TAG, "Error parsing route " + s + " : " + e);
679 continue;
680 }
681 }
682 }
683 }
684 return (RouteInfo[]) routes.toArray(new RouteInfo[0]);
685 }
686
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800687 @Override
San Mehat873f2142010-01-14 10:25:07 -0800688 public void shutdown() {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800689 // TODO: remove from aidl if nobody calls externally
690 mContext.enforceCallingOrSelfPermission(SHUTDOWN, TAG);
San Mehat873f2142010-01-14 10:25:07 -0800691
Joe Onorato8a9b2202010-02-26 18:56:32 -0800692 Slog.d(TAG, "Shutting down");
San Mehat873f2142010-01-14 10:25:07 -0800693 }
694
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800695 @Override
San Mehat873f2142010-01-14 10:25:07 -0800696 public boolean getIpForwardingEnabled() throws IllegalStateException{
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800697 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
San Mehat873f2142010-01-14 10:25:07 -0800698
Kenny Roota80ce062010-06-01 13:23:53 -0700699 ArrayList<String> rsp;
700 try {
701 rsp = mConnector.doCommand("ipfwd status");
702 } catch (NativeDaemonConnectorException e) {
703 throw new IllegalStateException(
704 "Unable to communicate with native daemon to ipfwd status");
705 }
San Mehat873f2142010-01-14 10:25:07 -0800706
707 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700708 String[] tok = line.split(" ");
709 if (tok.length < 3) {
710 Slog.e(TAG, "Malformed response from native daemon: " + line);
711 return false;
712 }
713
San Mehat873f2142010-01-14 10:25:07 -0800714 int code = Integer.parseInt(tok[0]);
715 if (code == NetdResponseCode.IpFwdStatusResult) {
716 // 211 Forwarding <enabled/disabled>
Kenny Roota80ce062010-06-01 13:23:53 -0700717 return "enabled".equals(tok[2]);
San Mehat873f2142010-01-14 10:25:07 -0800718 } else {
719 throw new IllegalStateException(String.format("Unexpected response code %d", code));
720 }
721 }
722 throw new IllegalStateException("Got an empty response");
723 }
724
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800725 @Override
726 public void setIpForwardingEnabled(boolean enable) {
727 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800728 try {
729 mConnector.doCommand(String.format("ipfwd %sable", (enable ? "en" : "dis")));
730 } catch (NativeDaemonConnectorException e) {
731 e.rethrowAsParcelableException();
732 }
San Mehat873f2142010-01-14 10:25:07 -0800733 }
734
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800735 @Override
736 public void startTethering(String[] dhcpRange) {
737 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -0700738 // cmd is "tether start first_start first_stop second_start second_stop ..."
739 // an odd number of addrs will fail
740 String cmd = "tether start";
741 for (String d : dhcpRange) {
742 cmd += " " + d;
743 }
Kenny Roota80ce062010-06-01 13:23:53 -0700744
745 try {
746 mConnector.doCommand(cmd);
747 } catch (NativeDaemonConnectorException e) {
748 throw new IllegalStateException("Unable to communicate to native daemon");
749 }
San Mehat873f2142010-01-14 10:25:07 -0800750 }
751
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800752 @Override
753 public void stopTethering() {
754 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700755 try {
756 mConnector.doCommand("tether stop");
757 } catch (NativeDaemonConnectorException e) {
758 throw new IllegalStateException("Unable to communicate to native daemon to stop tether");
759 }
San Mehat873f2142010-01-14 10:25:07 -0800760 }
761
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800762 @Override
763 public boolean isTetheringStarted() {
764 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
San Mehat873f2142010-01-14 10:25:07 -0800765
Kenny Roota80ce062010-06-01 13:23:53 -0700766 ArrayList<String> rsp;
767 try {
768 rsp = mConnector.doCommand("tether status");
769 } catch (NativeDaemonConnectorException e) {
770 throw new IllegalStateException(
771 "Unable to communicate to native daemon to get tether status");
772 }
San Mehat873f2142010-01-14 10:25:07 -0800773
774 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700775 String[] tok = line.split(" ");
776 if (tok.length < 3) {
777 throw new IllegalStateException("Malformed response for tether status: " + line);
778 }
San Mehat873f2142010-01-14 10:25:07 -0800779 int code = Integer.parseInt(tok[0]);
780 if (code == NetdResponseCode.TetherStatusResult) {
781 // XXX: Tethering services <started/stopped> <TBD>...
Kenny Roota80ce062010-06-01 13:23:53 -0700782 return "started".equals(tok[2]);
San Mehat873f2142010-01-14 10:25:07 -0800783 } else {
784 throw new IllegalStateException(String.format("Unexpected response code %d", code));
785 }
786 }
787 throw new IllegalStateException("Got an empty response");
788 }
789
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800790 @Override
791 public void tetherInterface(String iface) {
792 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700793 try {
794 mConnector.doCommand("tether interface add " + iface);
795 } catch (NativeDaemonConnectorException e) {
796 throw new IllegalStateException(
797 "Unable to communicate to native daemon for adding tether interface");
798 }
San Mehat873f2142010-01-14 10:25:07 -0800799 }
800
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800801 @Override
San Mehat873f2142010-01-14 10:25:07 -0800802 public void untetherInterface(String iface) {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800803 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700804 try {
805 mConnector.doCommand("tether interface remove " + iface);
806 } catch (NativeDaemonConnectorException e) {
807 throw new IllegalStateException(
808 "Unable to communicate to native daemon for removing tether interface");
809 }
San Mehat873f2142010-01-14 10:25:07 -0800810 }
811
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800812 @Override
813 public String[] listTetheredInterfaces() {
814 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700815 try {
816 return mConnector.doListCommand(
817 "tether interface list", NetdResponseCode.TetherInterfaceListResult);
818 } catch (NativeDaemonConnectorException e) {
819 throw new IllegalStateException(
820 "Unable to communicate to native daemon for listing tether interfaces");
821 }
San Mehat873f2142010-01-14 10:25:07 -0800822 }
823
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800824 @Override
825 public void setDnsForwarders(String[] dns) {
826 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
San Mehat873f2142010-01-14 10:25:07 -0800827 try {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800828 String cmd = "tether dns set";
San Mehat873f2142010-01-14 10:25:07 -0800829 for (String s : dns) {
Robert Greenwalte5903732011-02-22 16:00:42 -0800830 cmd += " " + NetworkUtils.numericToInetAddress(s).getHostAddress();
San Mehat873f2142010-01-14 10:25:07 -0800831 }
Kenny Roota80ce062010-06-01 13:23:53 -0700832 try {
833 mConnector.doCommand(cmd);
834 } catch (NativeDaemonConnectorException e) {
835 throw new IllegalStateException(
836 "Unable to communicate to native daemon for setting tether dns");
837 }
Robert Greenwalte5903732011-02-22 16:00:42 -0800838 } catch (IllegalArgumentException e) {
San Mehat873f2142010-01-14 10:25:07 -0800839 throw new IllegalStateException("Error resolving dns name", e);
840 }
841 }
842
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800843 @Override
844 public String[] getDnsForwarders() {
845 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700846 try {
847 return mConnector.doListCommand(
848 "tether dns list", NetdResponseCode.TetherDnsFwdTgtListResult);
849 } catch (NativeDaemonConnectorException e) {
850 throw new IllegalStateException(
851 "Unable to communicate to native daemon for listing tether dns");
852 }
San Mehat873f2142010-01-14 10:25:07 -0800853 }
854
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700855 private void modifyNat(String cmd, String internalInterface, String externalInterface)
856 throws SocketException {
857 cmd = String.format("nat %s %s %s", cmd, internalInterface, externalInterface);
858
859 NetworkInterface internalNetworkInterface =
860 NetworkInterface.getByName(internalInterface);
Robert Greenwalte83d1812011-11-21 14:44:39 -0800861 if (internalNetworkInterface == null) {
862 cmd += " 0";
863 } else {
864 Collection<InterfaceAddress>interfaceAddresses =
865 internalNetworkInterface.getInterfaceAddresses();
866 cmd += " " + interfaceAddresses.size();
867 for (InterfaceAddress ia : interfaceAddresses) {
868 InetAddress addr = NetworkUtils.getNetworkPart(ia.getAddress(),
869 ia.getNetworkPrefixLength());
870 cmd = cmd + " " + addr.getHostAddress() + "/" + ia.getNetworkPrefixLength();
871 }
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700872 }
873
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800874 try {
875 mConnector.doCommand(cmd);
876 } catch (NativeDaemonConnectorException e) {
877 e.rethrowAsParcelableException();
878 }
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700879 }
880
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800881 @Override
882 public void enableNat(String internalInterface, String externalInterface) {
883 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700884 if (DBG) Log.d(TAG, "enableNat(" + internalInterface + ", " + externalInterface + ")");
Kenny Roota80ce062010-06-01 13:23:53 -0700885 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700886 modifyNat("enable", internalInterface, externalInterface);
887 } catch (Exception e) {
888 Log.e(TAG, "enableNat got Exception " + e.toString());
Kenny Roota80ce062010-06-01 13:23:53 -0700889 throw new IllegalStateException(
890 "Unable to communicate to native daemon for enabling NAT interface");
891 }
San Mehat873f2142010-01-14 10:25:07 -0800892 }
893
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800894 @Override
895 public void disableNat(String internalInterface, String externalInterface) {
896 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700897 if (DBG) Log.d(TAG, "disableNat(" + internalInterface + ", " + externalInterface + ")");
Kenny Roota80ce062010-06-01 13:23:53 -0700898 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700899 modifyNat("disable", internalInterface, externalInterface);
900 } catch (Exception e) {
901 Log.e(TAG, "disableNat got Exception " + e.toString());
Kenny Roota80ce062010-06-01 13:23:53 -0700902 throw new IllegalStateException(
903 "Unable to communicate to native daemon for disabling NAT interface");
904 }
San Mehat873f2142010-01-14 10:25:07 -0800905 }
San Mehat72759df2010-01-19 13:50:37 -0800906
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800907 @Override
908 public String[] listTtys() {
909 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700910 try {
911 return mConnector.doListCommand("list_ttys", NetdResponseCode.TtyListResult);
912 } catch (NativeDaemonConnectorException e) {
913 throw new IllegalStateException(
914 "Unable to communicate to native daemon for listing TTYs");
915 }
San Mehat72759df2010-01-19 13:50:37 -0800916 }
917
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800918 @Override
919 public void attachPppd(
920 String tty, String localAddr, String remoteAddr, String dns1Addr, String dns2Addr) {
921 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
San Mehat72759df2010-01-19 13:50:37 -0800922 try {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800923 mConnector.doCommand(String.format("pppd attach %s %s %s %s %s", tty,
Robert Greenwalte5903732011-02-22 16:00:42 -0800924 NetworkUtils.numericToInetAddress(localAddr).getHostAddress(),
925 NetworkUtils.numericToInetAddress(remoteAddr).getHostAddress(),
926 NetworkUtils.numericToInetAddress(dns1Addr).getHostAddress(),
927 NetworkUtils.numericToInetAddress(dns2Addr).getHostAddress()));
928 } catch (IllegalArgumentException e) {
San Mehat72759df2010-01-19 13:50:37 -0800929 throw new IllegalStateException("Error resolving addr", e);
Kenny Roota80ce062010-06-01 13:23:53 -0700930 } catch (NativeDaemonConnectorException e) {
931 throw new IllegalStateException("Error communicating to native daemon to attach pppd", e);
San Mehat72759df2010-01-19 13:50:37 -0800932 }
933 }
934
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800935 @Override
936 public void detachPppd(String tty) {
937 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700938 try {
939 mConnector.doCommand(String.format("pppd detach %s", tty));
940 } catch (NativeDaemonConnectorException e) {
941 throw new IllegalStateException("Error communicating to native daemon to detach pppd", e);
942 }
San Mehat72759df2010-01-19 13:50:37 -0800943 }
Robert Greenwaltce1200d2010-02-18 11:25:54 -0800944
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800945 @Override
946 public void startAccessPoint(
947 WifiConfiguration wifiConfig, String wlanIface, String softapIface) {
948 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
949 mContext.enforceCallingOrSelfPermission(CHANGE_WIFI_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700950 try {
Irfan Sheriffcb30b222011-07-29 20:54:52 -0700951 wifiFirmwareReload(wlanIface, "AP");
Kenny Roota80ce062010-06-01 13:23:53 -0700952 mConnector.doCommand(String.format("softap start " + wlanIface));
953 if (wifiConfig == null) {
954 mConnector.doCommand(String.format("softap set " + wlanIface + " " + softapIface));
955 } else {
956 /**
957 * softap set arg1 arg2 arg3 [arg4 arg5 arg6 arg7 arg8]
958 * argv1 - wlan interface
959 * argv2 - softap interface
960 * argv3 - SSID
961 * argv4 - Security
962 * argv5 - Key
963 * argv6 - Channel
964 * argv7 - Preamble
965 * argv8 - Max SCB
966 */
Irfan Sheriffec8d23a2011-02-16 17:00:33 -0800967 String str = String.format("softap set " + wlanIface + " " + softapIface +
968 " %s %s %s", convertQuotedString(wifiConfig.SSID),
969 getSecurityType(wifiConfig),
970 convertQuotedString(wifiConfig.preSharedKey));
Kenny Roota80ce062010-06-01 13:23:53 -0700971 mConnector.doCommand(str);
972 }
973 mConnector.doCommand(String.format("softap startap"));
974 } catch (NativeDaemonConnectorException e) {
975 throw new IllegalStateException("Error communicating to native daemon to start softap", e);
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800976 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800977 }
978
Irfan Sheriffa6e559e2010-05-24 14:55:42 -0700979 private String convertQuotedString(String s) {
Irfan Sheriff7baec0f2010-05-26 17:16:47 -0700980 if (s == null) {
981 return s;
982 }
983 /* Replace \ with \\, then " with \" and add quotes at end */
984 return '"' + s.replaceAll("\\\\","\\\\\\\\").replaceAll("\"","\\\\\"") + '"';
Irfan Sheriffa6e559e2010-05-24 14:55:42 -0700985 }
986
Irfan Sheriffec8d23a2011-02-16 17:00:33 -0800987 private String getSecurityType(WifiConfiguration wifiConfig) {
988 switch (wifiConfig.getAuthType()) {
989 case KeyMgmt.WPA_PSK:
990 return "wpa-psk";
991 case KeyMgmt.WPA2_PSK:
992 return "wpa2-psk";
993 default:
994 return "open";
995 }
996 }
997
Irfan Sheriffcb30b222011-07-29 20:54:52 -0700998 /* @param mode can be "AP", "STA" or "P2P" */
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800999 @Override
1000 public void wifiFirmwareReload(String wlanIface, String mode) {
1001 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
1002 mContext.enforceCallingOrSelfPermission(CHANGE_WIFI_STATE, TAG);
Irfan Sheriffcb30b222011-07-29 20:54:52 -07001003 try {
1004 mConnector.doCommand(String.format("softap fwreload " + wlanIface + " " + mode));
1005 } catch (NativeDaemonConnectorException e) {
1006 throw new IllegalStateException("Error communicating to native daemon ", e);
1007 }
1008 }
1009
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001010 @Override
1011 public void stopAccessPoint(String wlanIface) {
1012 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
1013 mContext.enforceCallingOrSelfPermission(CHANGE_WIFI_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001014 try {
1015 mConnector.doCommand("softap stopap");
Irfan Sheriff23eb2972011-07-22 15:21:10 -07001016 mConnector.doCommand("softap stop " + wlanIface);
Irfan Sheriffcb30b222011-07-29 20:54:52 -07001017 wifiFirmwareReload(wlanIface, "STA");
Kenny Roota80ce062010-06-01 13:23:53 -07001018 } catch (NativeDaemonConnectorException e) {
1019 throw new IllegalStateException("Error communicating to native daemon to stop soft AP",
1020 e);
1021 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001022 }
1023
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001024 @Override
1025 public void setAccessPoint(WifiConfiguration wifiConfig, String wlanIface, String softapIface) {
1026 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
1027 mContext.enforceCallingOrSelfPermission(CHANGE_WIFI_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001028 try {
1029 if (wifiConfig == null) {
1030 mConnector.doCommand(String.format("softap set " + wlanIface + " " + softapIface));
1031 } else {
1032 String str = String.format("softap set " + wlanIface + " " + softapIface
1033 + " %s %s %s", convertQuotedString(wifiConfig.SSID),
Irfan Sheriffec8d23a2011-02-16 17:00:33 -08001034 getSecurityType(wifiConfig),
Kenny Roota80ce062010-06-01 13:23:53 -07001035 convertQuotedString(wifiConfig.preSharedKey));
1036 mConnector.doCommand(str);
1037 }
1038 } catch (NativeDaemonConnectorException e) {
1039 throw new IllegalStateException("Error communicating to native daemon to set soft AP",
1040 e);
Irfan Sheriffc2f54c22010-03-18 14:02:22 -07001041 }
1042 }
San Mehat91cac642010-03-31 14:31:36 -07001043
1044 private long getInterfaceCounter(String iface, boolean rx) {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001045 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
San Mehat91cac642010-03-31 14:31:36 -07001046 try {
Kenny Roota80ce062010-06-01 13:23:53 -07001047 String rsp;
1048 try {
1049 rsp = mConnector.doCommand(
1050 String.format("interface read%scounter %s", (rx ? "rx" : "tx"), iface)).get(0);
1051 } catch (NativeDaemonConnectorException e1) {
1052 Slog.e(TAG, "Error communicating with native daemon", e1);
1053 return -1;
1054 }
1055
1056 String[] tok = rsp.split(" ");
1057 if (tok.length < 2) {
1058 Slog.e(TAG, String.format("Malformed response for reading %s interface",
1059 (rx ? "rx" : "tx")));
1060 return -1;
1061 }
1062
San Mehat91cac642010-03-31 14:31:36 -07001063 int code;
1064 try {
1065 code = Integer.parseInt(tok[0]);
1066 } catch (NumberFormatException nfe) {
1067 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
1068 return -1;
1069 }
1070 if ((rx && code != NetdResponseCode.InterfaceRxCounterResult) || (
1071 !rx && code != NetdResponseCode.InterfaceTxCounterResult)) {
1072 Slog.e(TAG, String.format("Unexpected response code %d", code));
1073 return -1;
1074 }
1075 return Long.parseLong(tok[1]);
1076 } catch (Exception e) {
1077 Slog.e(TAG, String.format(
1078 "Failed to read interface %s counters", (rx ? "rx" : "tx")), e);
1079 }
1080 return -1;
1081 }
1082
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001083 @Override
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001084 public NetworkStats getNetworkStatsSummary() {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001085 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07001086 return mStatsFactory.readNetworkStatsSummary();
Jeff Sharkeyae2c1812011-10-04 13:11:40 -07001087 }
1088
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001089 @Override
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001090 public NetworkStats getNetworkStatsDetail() {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001091 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07001092 return mStatsFactory.readNetworkStatsDetail(UID_ALL);
San Mehat91cac642010-03-31 14:31:36 -07001093 }
1094
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001095 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001096 public void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001097 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1098
Jeff Sharkey350083e2011-06-29 10:45:16 -07001099 // silently discard when control disabled
1100 // TODO: eventually migrate to be always enabled
1101 if (!mBandwidthControlEnabled) return;
1102
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001103 synchronized (mQuotaLock) {
1104 if (mActiveQuotaIfaces.contains(iface)) {
1105 throw new IllegalStateException("iface " + iface + " already has quota");
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001106 }
1107
1108 final StringBuilder command = new StringBuilder();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001109 command.append("bandwidth setiquota ").append(iface).append(" ").append(quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001110
1111 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001112 // TODO: support quota shared across interfaces
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001113 mConnector.doCommand(command.toString());
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001114 mActiveQuotaIfaces.add(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001115 } catch (NativeDaemonConnectorException e) {
1116 throw new IllegalStateException("Error communicating to native daemon", e);
1117 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001118 }
1119 }
1120
1121 @Override
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001122 public void removeInterfaceQuota(String iface) {
1123 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1124
Jeff Sharkey350083e2011-06-29 10:45:16 -07001125 // silently discard when control disabled
1126 // TODO: eventually migrate to be always enabled
1127 if (!mBandwidthControlEnabled) return;
1128
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001129 synchronized (mQuotaLock) {
1130 if (!mActiveQuotaIfaces.contains(iface)) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001131 // TODO: eventually consider throwing
1132 return;
1133 }
1134
1135 final StringBuilder command = new StringBuilder();
1136 command.append("bandwidth removeiquota ").append(iface);
1137
Jeff Sharkey38ddeaa2011-11-08 13:04:22 -08001138 mActiveQuotaIfaces.remove(iface);
1139 mActiveAlertIfaces.remove(iface);
1140
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001141 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001142 // TODO: support quota shared across interfaces
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001143 mConnector.doCommand(command.toString());
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001144 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey38ddeaa2011-11-08 13:04:22 -08001145 // TODO: include current iptables state
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001146 throw new IllegalStateException("Error communicating to native daemon", e);
1147 }
1148 }
1149 }
1150
1151 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001152 public void setInterfaceAlert(String iface, long alertBytes) {
1153 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1154
1155 // silently discard when control disabled
1156 // TODO: eventually migrate to be always enabled
1157 if (!mBandwidthControlEnabled) return;
1158
1159 // quick sanity check
1160 if (!mActiveQuotaIfaces.contains(iface)) {
1161 throw new IllegalStateException("setting alert requires existing quota on iface");
1162 }
1163
1164 synchronized (mQuotaLock) {
1165 if (mActiveAlertIfaces.contains(iface)) {
1166 throw new IllegalStateException("iface " + iface + " already has alert");
1167 }
1168
1169 final StringBuilder command = new StringBuilder();
1170 command.append("bandwidth setinterfacealert ").append(iface).append(" ").append(
1171 alertBytes);
1172
1173 try {
1174 // TODO: support alert shared across interfaces
1175 mConnector.doCommand(command.toString());
1176 mActiveAlertIfaces.add(iface);
1177 } catch (NativeDaemonConnectorException e) {
1178 throw new IllegalStateException("Error communicating to native daemon", e);
1179 }
1180 }
1181 }
1182
1183 @Override
1184 public void removeInterfaceAlert(String iface) {
1185 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1186
1187 // silently discard when control disabled
1188 // TODO: eventually migrate to be always enabled
1189 if (!mBandwidthControlEnabled) return;
1190
1191 synchronized (mQuotaLock) {
1192 if (!mActiveAlertIfaces.contains(iface)) {
1193 // TODO: eventually consider throwing
1194 return;
1195 }
1196
1197 final StringBuilder command = new StringBuilder();
1198 command.append("bandwidth removeinterfacealert ").append(iface);
1199
1200 try {
1201 // TODO: support alert shared across interfaces
1202 mConnector.doCommand(command.toString());
1203 mActiveAlertIfaces.remove(iface);
1204 } catch (NativeDaemonConnectorException e) {
1205 throw new IllegalStateException("Error communicating to native daemon", e);
1206 }
1207 }
1208 }
1209
1210 @Override
1211 public void setGlobalAlert(long alertBytes) {
1212 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1213
1214 // silently discard when control disabled
1215 // TODO: eventually migrate to be always enabled
1216 if (!mBandwidthControlEnabled) return;
1217
1218 final StringBuilder command = new StringBuilder();
1219 command.append("bandwidth setglobalalert ").append(alertBytes);
1220
1221 try {
1222 mConnector.doCommand(command.toString());
1223 } catch (NativeDaemonConnectorException e) {
1224 throw new IllegalStateException("Error communicating to native daemon", e);
1225 }
1226 }
1227
1228 @Override
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001229 public void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
1230 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1231
Jeff Sharkey350083e2011-06-29 10:45:16 -07001232 // silently discard when control disabled
1233 // TODO: eventually migrate to be always enabled
1234 if (!mBandwidthControlEnabled) return;
1235
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001236 synchronized (mUidRejectOnQuota) {
1237 final boolean oldRejectOnQuota = mUidRejectOnQuota.get(uid, false);
1238 if (oldRejectOnQuota == rejectOnQuotaInterfaces) {
1239 // TODO: eventually consider throwing
1240 return;
1241 }
1242
1243 final StringBuilder command = new StringBuilder();
1244 command.append("bandwidth");
1245 if (rejectOnQuotaInterfaces) {
1246 command.append(" addnaughtyapps");
1247 } else {
1248 command.append(" removenaughtyapps");
1249 }
1250 command.append(" ").append(uid);
1251
1252 try {
1253 mConnector.doCommand(command.toString());
1254 if (rejectOnQuotaInterfaces) {
1255 mUidRejectOnQuota.put(uid, true);
1256 } else {
1257 mUidRejectOnQuota.delete(uid);
1258 }
1259 } catch (NativeDaemonConnectorException e) {
1260 throw new IllegalStateException("Error communicating to native daemon", e);
1261 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001262 }
1263 }
1264
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001265 @Override
1266 public boolean isBandwidthControlEnabled() {
1267 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1268 return mBandwidthControlEnabled;
1269 }
1270
1271 @Override
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001272 public NetworkStats getNetworkStatsUidDetail(int uid) {
1273 if (Binder.getCallingUid() != uid) {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001274 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001275 }
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07001276 return mStatsFactory.readNetworkStatsDetail(uid);
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001277 }
1278
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001279 @Override
1280 public NetworkStats getNetworkStatsTethering(String[] ifacePairs) {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001281 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001282
1283 if (ifacePairs.length % 2 != 0) {
1284 throw new IllegalArgumentException(
1285 "unexpected ifacePairs; length=" + ifacePairs.length);
1286 }
1287
1288 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 1);
1289 for (int i = 0; i < ifacePairs.length; i += 2) {
1290 final String ifaceIn = ifacePairs[i];
1291 final String ifaceOut = ifacePairs[i + 1];
1292 if (ifaceIn != null && ifaceOut != null) {
1293 stats.combineValues(getNetworkStatsTethering(ifaceIn, ifaceOut));
1294 }
1295 }
1296 return stats;
1297 }
1298
1299 private NetworkStats.Entry getNetworkStatsTethering(String ifaceIn, String ifaceOut) {
1300 final StringBuilder command = new StringBuilder();
1301 command.append("bandwidth gettetherstats ").append(ifaceIn).append(" ").append(ifaceOut);
1302
1303 final String rsp;
1304 try {
1305 rsp = mConnector.doCommand(command.toString()).get(0);
1306 } catch (NativeDaemonConnectorException e) {
1307 throw new IllegalStateException("Error communicating to native daemon", e);
1308 }
1309
1310 final String[] tok = rsp.split(" ");
1311 /* Expecting: "code ifaceIn ifaceOut rx_bytes rx_packets tx_bytes tx_packets" */
1312 if (tok.length != 7) {
1313 throw new IllegalStateException("Native daemon returned unexpected result: " + rsp);
1314 }
1315
1316 final int code;
1317 try {
1318 code = Integer.parseInt(tok[0]);
1319 } catch (NumberFormatException e) {
1320 throw new IllegalStateException(
1321 "Failed to parse native daemon return code for " + ifaceIn + " " + ifaceOut);
1322 }
1323 if (code != NetdResponseCode.TetheringStatsResult) {
1324 throw new IllegalStateException(
1325 "Unexpected return code from native daemon for " + ifaceIn + " " + ifaceOut);
1326 }
1327
1328 try {
1329 final NetworkStats.Entry entry = new NetworkStats.Entry();
1330 entry.iface = ifaceIn;
Jeff Sharkey905b5892011-09-30 15:19:49 -07001331 entry.uid = UID_TETHERING;
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001332 entry.set = SET_DEFAULT;
1333 entry.tag = TAG_NONE;
1334 entry.rxBytes = Long.parseLong(tok[3]);
1335 entry.rxPackets = Long.parseLong(tok[4]);
1336 entry.txBytes = Long.parseLong(tok[5]);
1337 entry.txPackets = Long.parseLong(tok[6]);
1338 return entry;
1339 } catch (NumberFormatException e) {
1340 throw new IllegalStateException(
1341 "problem parsing tethering stats for " + ifaceIn + " " + ifaceOut + ": " + e);
1342 }
1343 }
1344
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001345 @Override
San Mehatf0db6e12010-04-07 15:22:10 -07001346 public void setInterfaceThrottle(String iface, int rxKbps, int txKbps) {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001347 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001348 try {
1349 mConnector.doCommand(String.format(
1350 "interface setthrottle %s %d %d", iface, rxKbps, txKbps));
1351 } catch (NativeDaemonConnectorException e) {
1352 Slog.e(TAG, "Error communicating with native daemon to set throttle", e);
1353 }
San Mehat91cac642010-03-31 14:31:36 -07001354 }
1355
1356 private int getInterfaceThrottle(String iface, boolean rx) {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001357 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
San Mehat91cac642010-03-31 14:31:36 -07001358 try {
Kenny Roota80ce062010-06-01 13:23:53 -07001359 String rsp;
1360 try {
1361 rsp = mConnector.doCommand(
1362 String.format("interface getthrottle %s %s", iface,
1363 (rx ? "rx" : "tx"))).get(0);
1364 } catch (NativeDaemonConnectorException e) {
1365 Slog.e(TAG, "Error communicating with native daemon to getthrottle", e);
1366 return -1;
1367 }
1368
1369 String[] tok = rsp.split(" ");
1370 if (tok.length < 2) {
1371 Slog.e(TAG, "Malformed response to getthrottle command");
1372 return -1;
1373 }
1374
San Mehat91cac642010-03-31 14:31:36 -07001375 int code;
1376 try {
1377 code = Integer.parseInt(tok[0]);
1378 } catch (NumberFormatException nfe) {
1379 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
1380 return -1;
1381 }
1382 if ((rx && code != NetdResponseCode.InterfaceRxThrottleResult) || (
1383 !rx && code != NetdResponseCode.InterfaceTxThrottleResult)) {
1384 Slog.e(TAG, String.format("Unexpected response code %d", code));
1385 return -1;
1386 }
1387 return Integer.parseInt(tok[1]);
1388 } catch (Exception e) {
1389 Slog.e(TAG, String.format(
1390 "Failed to read interface %s throttle value", (rx ? "rx" : "tx")), e);
1391 }
1392 return -1;
1393 }
1394
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001395 @Override
San Mehat91cac642010-03-31 14:31:36 -07001396 public int getInterfaceRxThrottle(String iface) {
1397 return getInterfaceThrottle(iface, true);
1398 }
1399
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001400 @Override
San Mehat91cac642010-03-31 14:31:36 -07001401 public int getInterfaceTxThrottle(String iface) {
1402 return getInterfaceThrottle(iface, false);
1403 }
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001404
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001405 @Override
1406 public void setDefaultInterfaceForDns(String iface) {
1407 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001408 try {
1409 String cmd = "resolver setdefaultif " + iface;
1410
1411 mConnector.doCommand(cmd);
1412 } catch (NativeDaemonConnectorException e) {
1413 throw new IllegalStateException(
1414 "Error communicating with native daemon to set default interface", e);
1415 }
1416 }
1417
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001418 @Override
1419 public void setDnsServersForInterface(String iface, String[] servers) {
1420 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001421 try {
1422 String cmd = "resolver setifdns " + iface;
1423 for (String s : servers) {
Robert Greenwalt572b7042011-07-25 17:00:13 -07001424 InetAddress a = NetworkUtils.numericToInetAddress(s);
1425 if (a.isAnyLocalAddress() == false) {
1426 cmd += " " + a.getHostAddress();
Mattias Falk7475c0c2011-04-04 16:10:36 +02001427 }
1428 }
Mattias Falk7475c0c2011-04-04 16:10:36 +02001429 mConnector.doCommand(cmd);
Robert Greenwalt572b7042011-07-25 17:00:13 -07001430 } catch (IllegalArgumentException e) {
1431 throw new IllegalStateException("Error setting dnsn for interface", e);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001432 } catch (NativeDaemonConnectorException e) {
1433 throw new IllegalStateException(
Robert Greenwalt572b7042011-07-25 17:00:13 -07001434 "Error communicating with native daemon to set dns for interface", e);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001435 }
1436 }
1437
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001438 @Override
1439 public void flushDefaultDnsCache() {
1440 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001441 try {
1442 String cmd = "resolver flushdefaultif";
1443
1444 mConnector.doCommand(cmd);
1445 } catch (NativeDaemonConnectorException e) {
1446 throw new IllegalStateException(
1447 "Error communicating with native deamon to flush default interface", e);
1448 }
1449 }
1450
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001451 @Override
1452 public void flushInterfaceDnsCache(String iface) {
1453 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001454 try {
1455 String cmd = "resolver flushif " + iface;
1456
1457 mConnector.doCommand(cmd);
1458 } catch (NativeDaemonConnectorException e) {
1459 throw new IllegalStateException(
Robert Greenwalt572b7042011-07-25 17:00:13 -07001460 "Error communicating with native daemon to flush interface " + iface, e);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001461 }
1462 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07001463
1464 /** {@inheritDoc} */
1465 public void monitor() {
1466 if (mConnector != null) {
1467 mConnector.monitor();
1468 }
1469 }
Jeff Sharkey47eb1022011-08-25 17:48:52 -07001470
1471 @Override
1472 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1473 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
1474
1475 pw.print("Bandwidth control enabled: "); pw.println(mBandwidthControlEnabled);
1476
1477 synchronized (mQuotaLock) {
1478 pw.print("Active quota ifaces: "); pw.println(mActiveQuotaIfaces.toString());
1479 pw.print("Active alert ifaces: "); pw.println(mActiveAlertIfaces.toString());
1480 }
1481
1482 synchronized (mUidRejectOnQuota) {
1483 pw.print("UID reject on quota ifaces: [");
1484 final int size = mUidRejectOnQuota.size();
1485 for (int i = 0; i < size; i++) {
1486 pw.print(mUidRejectOnQuota.keyAt(i));
1487 if (i < size - 1) pw.print(",");
1488 }
1489 pw.println("]");
1490 }
1491 }
San Mehat873f2142010-01-14 10:25:07 -08001492}