blob: 0da60b7b1e9bd9028c6dd2f982bb409fba36114b [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) {
Jeff Sharkey276642b2011-12-01 11:24:24 -0800363 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -0700364 }
San Mehated4fc8a2010-01-22 12:28:36 -0800365 }
366
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800367 @Override
368 public InterfaceConfiguration getInterfaceConfig(String iface) {
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700369 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700370 String rsp;
371 try {
372 rsp = mConnector.doCommand("interface getcfg " + iface).get(0);
373 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -0800374 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -0700375 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800376 Slog.d(TAG, String.format("rsp <%s>", rsp));
San Mehated4fc8a2010-01-22 12:28:36 -0800377
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800378 // Rsp: 213 xx:xx:xx:xx:xx:xx yyy.yyy.yyy.yyy zzz [flag1 flag2 flag3]
San Mehated4fc8a2010-01-22 12:28:36 -0800379 StringTokenizer st = new StringTokenizer(rsp);
380
Kenny Roota80ce062010-06-01 13:23:53 -0700381 InterfaceConfiguration cfg;
San Mehated4fc8a2010-01-22 12:28:36 -0800382 try {
Kenny Roota80ce062010-06-01 13:23:53 -0700383 try {
384 int code = Integer.parseInt(st.nextToken(" "));
385 if (code != NetdResponseCode.InterfaceGetCfgResult) {
386 throw new IllegalStateException(
387 String.format("Expected code %d, but got %d",
388 NetdResponseCode.InterfaceGetCfgResult, code));
389 }
390 } catch (NumberFormatException nfe) {
San Mehated4fc8a2010-01-22 12:28:36 -0800391 throw new IllegalStateException(
Kenny Roota80ce062010-06-01 13:23:53 -0700392 String.format("Invalid response from daemon (%s)", rsp));
San Mehated4fc8a2010-01-22 12:28:36 -0800393 }
Kenny Roota80ce062010-06-01 13:23:53 -0700394
395 cfg = new InterfaceConfiguration();
Jeff Sharkeyddba1062011-11-29 18:37:04 -0800396 cfg.setHardwareAddress(st.nextToken(" "));
Robert Greenwalted126402011-01-28 15:34:55 -0800397 InetAddress addr = null;
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800398 int prefixLength = 0;
Kenny Roota80ce062010-06-01 13:23:53 -0700399 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800400 addr = NetworkUtils.numericToInetAddress(st.nextToken(" "));
401 } catch (IllegalArgumentException iae) {
402 Slog.e(TAG, "Failed to parse ipaddr", iae);
Kenny Roota80ce062010-06-01 13:23:53 -0700403 }
404
405 try {
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800406 prefixLength = Integer.parseInt(st.nextToken(" "));
407 } catch (NumberFormatException nfe) {
408 Slog.e(TAG, "Failed to parse prefixLength", nfe);
Kenny Roota80ce062010-06-01 13:23:53 -0700409 }
Robert Greenwalt04808c22010-12-13 17:01:41 -0800410
Jeff Sharkeyddba1062011-11-29 18:37:04 -0800411 cfg.setLinkAddress(new LinkAddress(addr, prefixLength));
412 while (st.hasMoreTokens()) {
413 cfg.setFlag(st.nextToken());
414 }
Kenny Roota80ce062010-06-01 13:23:53 -0700415 } catch (NoSuchElementException nsee) {
San Mehated4fc8a2010-01-22 12:28:36 -0800416 throw new IllegalStateException(
417 String.format("Invalid response from daemon (%s)", rsp));
418 }
Jeff Sharkeyddba1062011-11-29 18:37:04 -0800419 Slog.d(TAG, String.format("flags <%s>", cfg.getFlags()));
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);
Jeff Sharkeyddba1062011-11-29 18:37:04 -0800426 LinkAddress linkAddr = cfg.getLinkAddress();
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(),
Jeff Sharkeyddba1062011-11-29 18:37:04 -0800433 cfg.getFlags());
Kenny Roota80ce062010-06-01 13:23:53 -0700434 try {
435 mConnector.doCommand(cmd);
436 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -0800437 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -0700438 }
San Mehat873f2142010-01-14 10:25:07 -0800439 }
440
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800441 @Override
442 public void setInterfaceDown(String iface) {
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700443 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800444 final InterfaceConfiguration ifcg = getInterfaceConfig(iface);
Jeff Sharkeyddba1062011-11-29 18:37:04 -0800445 ifcg.setInterfaceDown();
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800446 setInterfaceConfig(iface, ifcg);
Irfan Sheriff7244c972011-08-05 20:40:45 -0700447 }
448
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800449 @Override
450 public void setInterfaceUp(String iface) {
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700451 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800452 final InterfaceConfiguration ifcg = getInterfaceConfig(iface);
Jeff Sharkeyddba1062011-11-29 18:37:04 -0800453 ifcg.setInterfaceUp();
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800454 setInterfaceConfig(iface, ifcg);
Irfan Sheriff7244c972011-08-05 20:40:45 -0700455 }
456
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800457 @Override
458 public void setInterfaceIpv6PrivacyExtensions(String iface, boolean enable) {
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700459 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Irfan Sheriff73293612011-09-14 12:31:56 -0700460 String cmd = String.format("interface ipv6privacyextensions %s %s", iface,
461 enable ? "enable" : "disable");
462 try {
463 mConnector.doCommand(cmd);
464 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -0800465 throw e.rethrowAsParcelableException();
Irfan Sheriff73293612011-09-14 12:31:56 -0700466 }
467 }
468
Irfan Sherifff5600612011-06-16 10:26:28 -0700469 /* TODO: This is right now a IPv4 only function. Works for wifi which loses its
470 IPv6 addresses on interface down, but we need to do full clean up here */
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800471 @Override
472 public void clearInterfaceAddresses(String iface) {
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700473 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
474 String cmd = String.format("interface clearaddrs %s", iface);
Irfan Sherifff5600612011-06-16 10:26:28 -0700475 try {
476 mConnector.doCommand(cmd);
477 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -0800478 throw e.rethrowAsParcelableException();
Irfan Sherifff5600612011-06-16 10:26:28 -0700479 }
480 }
481
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800482 @Override
483 public void enableIpv6(String iface) {
484 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
repo sync7960d9f2011-09-29 12:40:02 -0700485 try {
486 mConnector.doCommand(String.format("interface ipv6 %s enable", iface));
487 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -0800488 throw e.rethrowAsParcelableException();
repo sync7960d9f2011-09-29 12:40:02 -0700489 }
490 }
491
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800492 @Override
493 public void disableIpv6(String iface) {
494 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
repo sync7960d9f2011-09-29 12:40:02 -0700495 try {
496 mConnector.doCommand(String.format("interface ipv6 %s disable", iface));
497 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -0800498 throw e.rethrowAsParcelableException();
repo sync7960d9f2011-09-29 12:40:02 -0700499 }
500 }
501
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800502 @Override
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700503 public void addRoute(String interfaceName, RouteInfo route) {
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700504 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700505 modifyRoute(interfaceName, ADD, route, DEFAULT);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700506 }
507
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800508 @Override
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700509 public void removeRoute(String interfaceName, RouteInfo route) {
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700510 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700511 modifyRoute(interfaceName, REMOVE, route, DEFAULT);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700512 }
513
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800514 @Override
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700515 public void addSecondaryRoute(String interfaceName, RouteInfo route) {
516 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
517 modifyRoute(interfaceName, ADD, route, SECONDARY);
518 }
519
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800520 @Override
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700521 public void removeSecondaryRoute(String interfaceName, RouteInfo route) {
522 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
523 modifyRoute(interfaceName, REMOVE, route, SECONDARY);
524 }
525
526 private void modifyRoute(String interfaceName, int action, RouteInfo route, String type) {
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700527 ArrayList<String> rsp;
528
529 StringBuilder cmd;
530
531 switch (action) {
532 case ADD:
533 {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700534 cmd = new StringBuilder("interface route add " + interfaceName + " " + type);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700535 break;
536 }
537 case REMOVE:
538 {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700539 cmd = new StringBuilder("interface route remove " + interfaceName + " " + type);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700540 break;
541 }
542 default:
543 throw new IllegalStateException("Unknown action type " + action);
544 }
545
546 // create triplet: dest-ip-addr prefixlength gateway-ip-addr
547 LinkAddress la = route.getDestination();
548 cmd.append(' ');
549 cmd.append(la.getAddress().getHostAddress());
550 cmd.append(' ');
551 cmd.append(la.getNetworkPrefixLength());
552 cmd.append(' ');
553 if (route.getGateway() == null) {
554 if (la.getAddress() instanceof Inet4Address) {
555 cmd.append("0.0.0.0");
556 } else {
557 cmd.append ("::0");
558 }
559 } else {
560 cmd.append(route.getGateway().getHostAddress());
561 }
562 try {
563 rsp = mConnector.doCommand(cmd.toString());
564 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -0800565 throw e.rethrowAsParcelableException();
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700566 }
567
Wink Savillec9acde92011-09-21 11:05:43 -0700568 if (DBG) {
569 for (String line : rsp) {
570 Log.v(TAG, "add route response is " + line);
571 }
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700572 }
573 }
574
575 private ArrayList<String> readRouteList(String filename) {
576 FileInputStream fstream = null;
577 ArrayList<String> list = new ArrayList<String>();
578
579 try {
580 fstream = new FileInputStream(filename);
581 DataInputStream in = new DataInputStream(fstream);
582 BufferedReader br = new BufferedReader(new InputStreamReader(in));
583 String s;
584
585 // throw away the title line
586
587 while (((s = br.readLine()) != null) && (s.length() != 0)) {
588 list.add(s);
589 }
590 } catch (IOException ex) {
591 // return current list, possibly empty
592 } finally {
593 if (fstream != null) {
594 try {
595 fstream.close();
596 } catch (IOException ex) {}
597 }
598 }
599
600 return list;
601 }
602
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800603 @Override
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700604 public RouteInfo[] getRoutes(String interfaceName) {
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700605 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700606 ArrayList<RouteInfo> routes = new ArrayList<RouteInfo>();
607
608 // v4 routes listed as:
609 // iface dest-addr gateway-addr flags refcnt use metric netmask mtu window IRTT
610 for (String s : readRouteList("/proc/net/route")) {
611 String[] fields = s.split("\t");
612
613 if (fields.length > 7) {
614 String iface = fields[0];
615
616 if (interfaceName.equals(iface)) {
617 String dest = fields[1];
618 String gate = fields[2];
619 String flags = fields[3]; // future use?
620 String mask = fields[7];
621 try {
622 // address stored as a hex string, ex: 0014A8C0
623 InetAddress destAddr =
624 NetworkUtils.intToInetAddress((int)Long.parseLong(dest, 16));
625 int prefixLength =
626 NetworkUtils.netmaskIntToPrefixLength(
627 (int)Long.parseLong(mask, 16));
628 LinkAddress linkAddress = new LinkAddress(destAddr, prefixLength);
629
630 // address stored as a hex string, ex 0014A8C0
631 InetAddress gatewayAddr =
632 NetworkUtils.intToInetAddress((int)Long.parseLong(gate, 16));
633
634 RouteInfo route = new RouteInfo(linkAddress, gatewayAddr);
635 routes.add(route);
636 } catch (Exception e) {
637 Log.e(TAG, "Error parsing route " + s + " : " + e);
638 continue;
639 }
640 }
641 }
642 }
643
644 // v6 routes listed as:
645 // dest-addr prefixlength ?? ?? gateway-addr ?? ?? ?? ?? iface
646 for (String s : readRouteList("/proc/net/ipv6_route")) {
647 String[]fields = s.split("\\s+");
648 if (fields.length > 9) {
649 String iface = fields[9].trim();
650 if (interfaceName.equals(iface)) {
651 String dest = fields[0];
652 String prefix = fields[1];
653 String gate = fields[4];
654
655 try {
656 // prefix length stored as a hex string, ex 40
657 int prefixLength = Integer.parseInt(prefix, 16);
658
659 // address stored as a 32 char hex string
660 // ex fe800000000000000000000000000000
661 InetAddress destAddr = NetworkUtils.hexToInet6Address(dest);
662 LinkAddress linkAddress = new LinkAddress(destAddr, prefixLength);
663
664 InetAddress gateAddr = NetworkUtils.hexToInet6Address(gate);
665
666 RouteInfo route = new RouteInfo(linkAddress, gateAddr);
667 routes.add(route);
668 } catch (Exception e) {
669 Log.e(TAG, "Error parsing route " + s + " : " + e);
670 continue;
671 }
672 }
673 }
674 }
675 return (RouteInfo[]) routes.toArray(new RouteInfo[0]);
676 }
677
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800678 @Override
San Mehat873f2142010-01-14 10:25:07 -0800679 public void shutdown() {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800680 // TODO: remove from aidl if nobody calls externally
681 mContext.enforceCallingOrSelfPermission(SHUTDOWN, TAG);
San Mehat873f2142010-01-14 10:25:07 -0800682
Joe Onorato8a9b2202010-02-26 18:56:32 -0800683 Slog.d(TAG, "Shutting down");
San Mehat873f2142010-01-14 10:25:07 -0800684 }
685
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800686 @Override
San Mehat873f2142010-01-14 10:25:07 -0800687 public boolean getIpForwardingEnabled() throws IllegalStateException{
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800688 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
San Mehat873f2142010-01-14 10:25:07 -0800689
Kenny Roota80ce062010-06-01 13:23:53 -0700690 ArrayList<String> rsp;
691 try {
692 rsp = mConnector.doCommand("ipfwd status");
693 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -0800694 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -0700695 }
San Mehat873f2142010-01-14 10:25:07 -0800696
697 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700698 String[] tok = line.split(" ");
699 if (tok.length < 3) {
700 Slog.e(TAG, "Malformed response from native daemon: " + line);
701 return false;
702 }
703
San Mehat873f2142010-01-14 10:25:07 -0800704 int code = Integer.parseInt(tok[0]);
705 if (code == NetdResponseCode.IpFwdStatusResult) {
706 // 211 Forwarding <enabled/disabled>
Kenny Roota80ce062010-06-01 13:23:53 -0700707 return "enabled".equals(tok[2]);
San Mehat873f2142010-01-14 10:25:07 -0800708 } else {
709 throw new IllegalStateException(String.format("Unexpected response code %d", code));
710 }
711 }
712 throw new IllegalStateException("Got an empty response");
713 }
714
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800715 @Override
716 public void setIpForwardingEnabled(boolean enable) {
717 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800718 try {
719 mConnector.doCommand(String.format("ipfwd %sable", (enable ? "en" : "dis")));
720 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -0800721 throw e.rethrowAsParcelableException();
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800722 }
San Mehat873f2142010-01-14 10:25:07 -0800723 }
724
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800725 @Override
726 public void startTethering(String[] dhcpRange) {
727 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -0700728 // cmd is "tether start first_start first_stop second_start second_stop ..."
729 // an odd number of addrs will fail
730 String cmd = "tether start";
731 for (String d : dhcpRange) {
732 cmd += " " + d;
733 }
Kenny Roota80ce062010-06-01 13:23:53 -0700734
735 try {
736 mConnector.doCommand(cmd);
737 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -0800738 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -0700739 }
San Mehat873f2142010-01-14 10:25:07 -0800740 }
741
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800742 @Override
743 public void stopTethering() {
744 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700745 try {
746 mConnector.doCommand("tether stop");
747 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -0800748 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -0700749 }
San Mehat873f2142010-01-14 10:25:07 -0800750 }
751
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800752 @Override
753 public boolean isTetheringStarted() {
754 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
San Mehat873f2142010-01-14 10:25:07 -0800755
Kenny Roota80ce062010-06-01 13:23:53 -0700756 ArrayList<String> rsp;
757 try {
758 rsp = mConnector.doCommand("tether status");
759 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -0800760 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -0700761 }
San Mehat873f2142010-01-14 10:25:07 -0800762
763 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700764 String[] tok = line.split(" ");
765 if (tok.length < 3) {
766 throw new IllegalStateException("Malformed response for tether status: " + line);
767 }
San Mehat873f2142010-01-14 10:25:07 -0800768 int code = Integer.parseInt(tok[0]);
769 if (code == NetdResponseCode.TetherStatusResult) {
770 // XXX: Tethering services <started/stopped> <TBD>...
Kenny Roota80ce062010-06-01 13:23:53 -0700771 return "started".equals(tok[2]);
San Mehat873f2142010-01-14 10:25:07 -0800772 } else {
773 throw new IllegalStateException(String.format("Unexpected response code %d", code));
774 }
775 }
776 throw new IllegalStateException("Got an empty response");
777 }
778
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800779 @Override
780 public void tetherInterface(String iface) {
781 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700782 try {
783 mConnector.doCommand("tether interface add " + iface);
784 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -0800785 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -0700786 }
San Mehat873f2142010-01-14 10:25:07 -0800787 }
788
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800789 @Override
San Mehat873f2142010-01-14 10:25:07 -0800790 public void untetherInterface(String iface) {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800791 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700792 try {
793 mConnector.doCommand("tether interface remove " + iface);
794 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -0800795 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -0700796 }
San Mehat873f2142010-01-14 10:25:07 -0800797 }
798
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800799 @Override
800 public String[] listTetheredInterfaces() {
801 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700802 try {
803 return mConnector.doListCommand(
804 "tether interface list", NetdResponseCode.TetherInterfaceListResult);
805 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -0800806 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -0700807 }
San Mehat873f2142010-01-14 10:25:07 -0800808 }
809
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800810 @Override
811 public void setDnsForwarders(String[] dns) {
812 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
San Mehat873f2142010-01-14 10:25:07 -0800813 try {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800814 String cmd = "tether dns set";
San Mehat873f2142010-01-14 10:25:07 -0800815 for (String s : dns) {
Robert Greenwalte5903732011-02-22 16:00:42 -0800816 cmd += " " + NetworkUtils.numericToInetAddress(s).getHostAddress();
San Mehat873f2142010-01-14 10:25:07 -0800817 }
Kenny Roota80ce062010-06-01 13:23:53 -0700818 try {
819 mConnector.doCommand(cmd);
820 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -0800821 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -0700822 }
Robert Greenwalte5903732011-02-22 16:00:42 -0800823 } catch (IllegalArgumentException e) {
San Mehat873f2142010-01-14 10:25:07 -0800824 throw new IllegalStateException("Error resolving dns name", e);
825 }
826 }
827
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800828 @Override
829 public String[] getDnsForwarders() {
830 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700831 try {
832 return mConnector.doListCommand(
833 "tether dns list", NetdResponseCode.TetherDnsFwdTgtListResult);
834 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -0800835 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -0700836 }
San Mehat873f2142010-01-14 10:25:07 -0800837 }
838
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700839 private void modifyNat(String cmd, String internalInterface, String externalInterface)
840 throws SocketException {
841 cmd = String.format("nat %s %s %s", cmd, internalInterface, externalInterface);
842
843 NetworkInterface internalNetworkInterface =
844 NetworkInterface.getByName(internalInterface);
Robert Greenwalte83d1812011-11-21 14:44:39 -0800845 if (internalNetworkInterface == null) {
846 cmd += " 0";
847 } else {
848 Collection<InterfaceAddress>interfaceAddresses =
849 internalNetworkInterface.getInterfaceAddresses();
850 cmd += " " + interfaceAddresses.size();
851 for (InterfaceAddress ia : interfaceAddresses) {
852 InetAddress addr = NetworkUtils.getNetworkPart(ia.getAddress(),
853 ia.getNetworkPrefixLength());
854 cmd = cmd + " " + addr.getHostAddress() + "/" + ia.getNetworkPrefixLength();
855 }
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700856 }
857
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800858 try {
859 mConnector.doCommand(cmd);
860 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -0800861 throw e.rethrowAsParcelableException();
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800862 }
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700863 }
864
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800865 @Override
866 public void enableNat(String internalInterface, String externalInterface) {
867 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700868 if (DBG) Log.d(TAG, "enableNat(" + internalInterface + ", " + externalInterface + ")");
Kenny Roota80ce062010-06-01 13:23:53 -0700869 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700870 modifyNat("enable", internalInterface, externalInterface);
871 } catch (Exception e) {
872 Log.e(TAG, "enableNat got Exception " + e.toString());
Kenny Roota80ce062010-06-01 13:23:53 -0700873 throw new IllegalStateException(
874 "Unable to communicate to native daemon for enabling NAT interface");
875 }
San Mehat873f2142010-01-14 10:25:07 -0800876 }
877
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800878 @Override
879 public void disableNat(String internalInterface, String externalInterface) {
880 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700881 if (DBG) Log.d(TAG, "disableNat(" + internalInterface + ", " + externalInterface + ")");
Kenny Roota80ce062010-06-01 13:23:53 -0700882 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700883 modifyNat("disable", internalInterface, externalInterface);
884 } catch (Exception e) {
885 Log.e(TAG, "disableNat got Exception " + e.toString());
Kenny Roota80ce062010-06-01 13:23:53 -0700886 throw new IllegalStateException(
887 "Unable to communicate to native daemon for disabling NAT interface");
888 }
San Mehat873f2142010-01-14 10:25:07 -0800889 }
San Mehat72759df2010-01-19 13:50:37 -0800890
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800891 @Override
892 public String[] listTtys() {
893 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700894 try {
895 return mConnector.doListCommand("list_ttys", NetdResponseCode.TtyListResult);
896 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -0800897 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -0700898 }
San Mehat72759df2010-01-19 13:50:37 -0800899 }
900
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800901 @Override
902 public void attachPppd(
903 String tty, String localAddr, String remoteAddr, String dns1Addr, String dns2Addr) {
904 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
San Mehat72759df2010-01-19 13:50:37 -0800905 try {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800906 mConnector.doCommand(String.format("pppd attach %s %s %s %s %s", tty,
Robert Greenwalte5903732011-02-22 16:00:42 -0800907 NetworkUtils.numericToInetAddress(localAddr).getHostAddress(),
908 NetworkUtils.numericToInetAddress(remoteAddr).getHostAddress(),
909 NetworkUtils.numericToInetAddress(dns1Addr).getHostAddress(),
910 NetworkUtils.numericToInetAddress(dns2Addr).getHostAddress()));
911 } catch (IllegalArgumentException e) {
San Mehat72759df2010-01-19 13:50:37 -0800912 throw new IllegalStateException("Error resolving addr", e);
Kenny Roota80ce062010-06-01 13:23:53 -0700913 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -0800914 throw e.rethrowAsParcelableException();
San Mehat72759df2010-01-19 13:50:37 -0800915 }
916 }
917
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800918 @Override
919 public void detachPppd(String tty) {
920 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700921 try {
922 mConnector.doCommand(String.format("pppd detach %s", tty));
923 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -0800924 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -0700925 }
San Mehat72759df2010-01-19 13:50:37 -0800926 }
Robert Greenwaltce1200d2010-02-18 11:25:54 -0800927
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800928 @Override
929 public void startAccessPoint(
930 WifiConfiguration wifiConfig, String wlanIface, String softapIface) {
931 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
932 mContext.enforceCallingOrSelfPermission(CHANGE_WIFI_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700933 try {
Irfan Sheriffcb30b222011-07-29 20:54:52 -0700934 wifiFirmwareReload(wlanIface, "AP");
Kenny Roota80ce062010-06-01 13:23:53 -0700935 mConnector.doCommand(String.format("softap start " + wlanIface));
936 if (wifiConfig == null) {
937 mConnector.doCommand(String.format("softap set " + wlanIface + " " + softapIface));
938 } else {
939 /**
940 * softap set arg1 arg2 arg3 [arg4 arg5 arg6 arg7 arg8]
941 * argv1 - wlan interface
942 * argv2 - softap interface
943 * argv3 - SSID
944 * argv4 - Security
945 * argv5 - Key
946 * argv6 - Channel
947 * argv7 - Preamble
948 * argv8 - Max SCB
949 */
Irfan Sheriffec8d23a2011-02-16 17:00:33 -0800950 String str = String.format("softap set " + wlanIface + " " + softapIface +
951 " %s %s %s", convertQuotedString(wifiConfig.SSID),
952 getSecurityType(wifiConfig),
953 convertQuotedString(wifiConfig.preSharedKey));
Kenny Roota80ce062010-06-01 13:23:53 -0700954 mConnector.doCommand(str);
955 }
956 mConnector.doCommand(String.format("softap startap"));
957 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -0800958 throw e.rethrowAsParcelableException();
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800959 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800960 }
961
Irfan Sheriffa6e559e2010-05-24 14:55:42 -0700962 private String convertQuotedString(String s) {
Irfan Sheriff7baec0f2010-05-26 17:16:47 -0700963 if (s == null) {
964 return s;
965 }
966 /* Replace \ with \\, then " with \" and add quotes at end */
967 return '"' + s.replaceAll("\\\\","\\\\\\\\").replaceAll("\"","\\\\\"") + '"';
Irfan Sheriffa6e559e2010-05-24 14:55:42 -0700968 }
969
Irfan Sheriffec8d23a2011-02-16 17:00:33 -0800970 private String getSecurityType(WifiConfiguration wifiConfig) {
971 switch (wifiConfig.getAuthType()) {
972 case KeyMgmt.WPA_PSK:
973 return "wpa-psk";
974 case KeyMgmt.WPA2_PSK:
975 return "wpa2-psk";
976 default:
977 return "open";
978 }
979 }
980
Irfan Sheriffcb30b222011-07-29 20:54:52 -0700981 /* @param mode can be "AP", "STA" or "P2P" */
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800982 @Override
983 public void wifiFirmwareReload(String wlanIface, String mode) {
984 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
985 mContext.enforceCallingOrSelfPermission(CHANGE_WIFI_STATE, TAG);
Irfan Sheriffcb30b222011-07-29 20:54:52 -0700986 try {
987 mConnector.doCommand(String.format("softap fwreload " + wlanIface + " " + mode));
988 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -0800989 throw e.rethrowAsParcelableException();
Irfan Sheriffcb30b222011-07-29 20:54:52 -0700990 }
991 }
992
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800993 @Override
994 public void stopAccessPoint(String wlanIface) {
995 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
996 mContext.enforceCallingOrSelfPermission(CHANGE_WIFI_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700997 try {
998 mConnector.doCommand("softap stopap");
Irfan Sheriff23eb2972011-07-22 15:21:10 -0700999 mConnector.doCommand("softap stop " + wlanIface);
Irfan Sheriffcb30b222011-07-29 20:54:52 -07001000 wifiFirmwareReload(wlanIface, "STA");
Kenny Roota80ce062010-06-01 13:23:53 -07001001 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001002 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -07001003 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -08001004 }
1005
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001006 @Override
1007 public void setAccessPoint(WifiConfiguration wifiConfig, String wlanIface, String softapIface) {
1008 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
1009 mContext.enforceCallingOrSelfPermission(CHANGE_WIFI_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001010 try {
1011 if (wifiConfig == null) {
1012 mConnector.doCommand(String.format("softap set " + wlanIface + " " + softapIface));
1013 } else {
1014 String str = String.format("softap set " + wlanIface + " " + softapIface
1015 + " %s %s %s", convertQuotedString(wifiConfig.SSID),
Irfan Sheriffec8d23a2011-02-16 17:00:33 -08001016 getSecurityType(wifiConfig),
Kenny Roota80ce062010-06-01 13:23:53 -07001017 convertQuotedString(wifiConfig.preSharedKey));
1018 mConnector.doCommand(str);
1019 }
1020 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001021 throw e.rethrowAsParcelableException();
Irfan Sheriffc2f54c22010-03-18 14:02:22 -07001022 }
1023 }
San Mehat91cac642010-03-31 14:31:36 -07001024
1025 private long getInterfaceCounter(String iface, boolean rx) {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001026 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
San Mehat91cac642010-03-31 14:31:36 -07001027 try {
Kenny Roota80ce062010-06-01 13:23:53 -07001028 String rsp;
1029 try {
1030 rsp = mConnector.doCommand(
1031 String.format("interface read%scounter %s", (rx ? "rx" : "tx"), iface)).get(0);
1032 } catch (NativeDaemonConnectorException e1) {
1033 Slog.e(TAG, "Error communicating with native daemon", e1);
1034 return -1;
1035 }
1036
1037 String[] tok = rsp.split(" ");
1038 if (tok.length < 2) {
1039 Slog.e(TAG, String.format("Malformed response for reading %s interface",
1040 (rx ? "rx" : "tx")));
1041 return -1;
1042 }
1043
San Mehat91cac642010-03-31 14:31:36 -07001044 int code;
1045 try {
1046 code = Integer.parseInt(tok[0]);
1047 } catch (NumberFormatException nfe) {
1048 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
1049 return -1;
1050 }
1051 if ((rx && code != NetdResponseCode.InterfaceRxCounterResult) || (
1052 !rx && code != NetdResponseCode.InterfaceTxCounterResult)) {
1053 Slog.e(TAG, String.format("Unexpected response code %d", code));
1054 return -1;
1055 }
1056 return Long.parseLong(tok[1]);
1057 } catch (Exception e) {
1058 Slog.e(TAG, String.format(
1059 "Failed to read interface %s counters", (rx ? "rx" : "tx")), e);
1060 }
1061 return -1;
1062 }
1063
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001064 @Override
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001065 public NetworkStats getNetworkStatsSummary() {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001066 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07001067 return mStatsFactory.readNetworkStatsSummary();
Jeff Sharkeyae2c1812011-10-04 13:11:40 -07001068 }
1069
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001070 @Override
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001071 public NetworkStats getNetworkStatsDetail() {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001072 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07001073 return mStatsFactory.readNetworkStatsDetail(UID_ALL);
San Mehat91cac642010-03-31 14:31:36 -07001074 }
1075
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001076 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001077 public void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001078 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1079
Jeff Sharkey350083e2011-06-29 10:45:16 -07001080 // silently discard when control disabled
1081 // TODO: eventually migrate to be always enabled
1082 if (!mBandwidthControlEnabled) return;
1083
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001084 synchronized (mQuotaLock) {
1085 if (mActiveQuotaIfaces.contains(iface)) {
1086 throw new IllegalStateException("iface " + iface + " already has quota");
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001087 }
1088
1089 final StringBuilder command = new StringBuilder();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001090 command.append("bandwidth setiquota ").append(iface).append(" ").append(quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001091
1092 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001093 // TODO: support quota shared across interfaces
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001094 mConnector.doCommand(command.toString());
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001095 mActiveQuotaIfaces.add(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001096 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001097 throw e.rethrowAsParcelableException();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001098 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001099 }
1100 }
1101
1102 @Override
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001103 public void removeInterfaceQuota(String iface) {
1104 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1105
Jeff Sharkey350083e2011-06-29 10:45:16 -07001106 // silently discard when control disabled
1107 // TODO: eventually migrate to be always enabled
1108 if (!mBandwidthControlEnabled) return;
1109
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001110 synchronized (mQuotaLock) {
1111 if (!mActiveQuotaIfaces.contains(iface)) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001112 // TODO: eventually consider throwing
1113 return;
1114 }
1115
1116 final StringBuilder command = new StringBuilder();
1117 command.append("bandwidth removeiquota ").append(iface);
1118
Jeff Sharkey38ddeaa2011-11-08 13:04:22 -08001119 mActiveQuotaIfaces.remove(iface);
1120 mActiveAlertIfaces.remove(iface);
1121
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001122 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001123 // TODO: support quota shared across interfaces
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001124 mConnector.doCommand(command.toString());
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001125 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001126 throw e.rethrowAsParcelableException();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001127 }
1128 }
1129 }
1130
1131 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001132 public void setInterfaceAlert(String iface, long alertBytes) {
1133 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1134
1135 // silently discard when control disabled
1136 // TODO: eventually migrate to be always enabled
1137 if (!mBandwidthControlEnabled) return;
1138
1139 // quick sanity check
1140 if (!mActiveQuotaIfaces.contains(iface)) {
1141 throw new IllegalStateException("setting alert requires existing quota on iface");
1142 }
1143
1144 synchronized (mQuotaLock) {
1145 if (mActiveAlertIfaces.contains(iface)) {
1146 throw new IllegalStateException("iface " + iface + " already has alert");
1147 }
1148
1149 final StringBuilder command = new StringBuilder();
1150 command.append("bandwidth setinterfacealert ").append(iface).append(" ").append(
1151 alertBytes);
1152
1153 try {
1154 // TODO: support alert shared across interfaces
1155 mConnector.doCommand(command.toString());
1156 mActiveAlertIfaces.add(iface);
1157 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001158 throw e.rethrowAsParcelableException();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001159 }
1160 }
1161 }
1162
1163 @Override
1164 public void removeInterfaceAlert(String iface) {
1165 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1166
1167 // silently discard when control disabled
1168 // TODO: eventually migrate to be always enabled
1169 if (!mBandwidthControlEnabled) return;
1170
1171 synchronized (mQuotaLock) {
1172 if (!mActiveAlertIfaces.contains(iface)) {
1173 // TODO: eventually consider throwing
1174 return;
1175 }
1176
1177 final StringBuilder command = new StringBuilder();
1178 command.append("bandwidth removeinterfacealert ").append(iface);
1179
1180 try {
1181 // TODO: support alert shared across interfaces
1182 mConnector.doCommand(command.toString());
1183 mActiveAlertIfaces.remove(iface);
1184 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001185 throw e.rethrowAsParcelableException();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001186 }
1187 }
1188 }
1189
1190 @Override
1191 public void setGlobalAlert(long alertBytes) {
1192 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1193
1194 // silently discard when control disabled
1195 // TODO: eventually migrate to be always enabled
1196 if (!mBandwidthControlEnabled) return;
1197
1198 final StringBuilder command = new StringBuilder();
1199 command.append("bandwidth setglobalalert ").append(alertBytes);
1200
1201 try {
1202 mConnector.doCommand(command.toString());
1203 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001204 throw e.rethrowAsParcelableException();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001205 }
1206 }
1207
1208 @Override
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001209 public void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
1210 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1211
Jeff Sharkey350083e2011-06-29 10:45:16 -07001212 // silently discard when control disabled
1213 // TODO: eventually migrate to be always enabled
1214 if (!mBandwidthControlEnabled) return;
1215
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001216 synchronized (mUidRejectOnQuota) {
1217 final boolean oldRejectOnQuota = mUidRejectOnQuota.get(uid, false);
1218 if (oldRejectOnQuota == rejectOnQuotaInterfaces) {
1219 // TODO: eventually consider throwing
1220 return;
1221 }
1222
1223 final StringBuilder command = new StringBuilder();
1224 command.append("bandwidth");
1225 if (rejectOnQuotaInterfaces) {
1226 command.append(" addnaughtyapps");
1227 } else {
1228 command.append(" removenaughtyapps");
1229 }
1230 command.append(" ").append(uid);
1231
1232 try {
1233 mConnector.doCommand(command.toString());
1234 if (rejectOnQuotaInterfaces) {
1235 mUidRejectOnQuota.put(uid, true);
1236 } else {
1237 mUidRejectOnQuota.delete(uid);
1238 }
1239 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001240 throw e.rethrowAsParcelableException();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001241 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001242 }
1243 }
1244
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001245 @Override
1246 public boolean isBandwidthControlEnabled() {
1247 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1248 return mBandwidthControlEnabled;
1249 }
1250
1251 @Override
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001252 public NetworkStats getNetworkStatsUidDetail(int uid) {
1253 if (Binder.getCallingUid() != uid) {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001254 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001255 }
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07001256 return mStatsFactory.readNetworkStatsDetail(uid);
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001257 }
1258
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001259 @Override
1260 public NetworkStats getNetworkStatsTethering(String[] ifacePairs) {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001261 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001262
1263 if (ifacePairs.length % 2 != 0) {
1264 throw new IllegalArgumentException(
1265 "unexpected ifacePairs; length=" + ifacePairs.length);
1266 }
1267
1268 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 1);
1269 for (int i = 0; i < ifacePairs.length; i += 2) {
1270 final String ifaceIn = ifacePairs[i];
1271 final String ifaceOut = ifacePairs[i + 1];
1272 if (ifaceIn != null && ifaceOut != null) {
1273 stats.combineValues(getNetworkStatsTethering(ifaceIn, ifaceOut));
1274 }
1275 }
1276 return stats;
1277 }
1278
1279 private NetworkStats.Entry getNetworkStatsTethering(String ifaceIn, String ifaceOut) {
1280 final StringBuilder command = new StringBuilder();
1281 command.append("bandwidth gettetherstats ").append(ifaceIn).append(" ").append(ifaceOut);
1282
1283 final String rsp;
1284 try {
1285 rsp = mConnector.doCommand(command.toString()).get(0);
1286 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001287 throw e.rethrowAsParcelableException();
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001288 }
1289
1290 final String[] tok = rsp.split(" ");
1291 /* Expecting: "code ifaceIn ifaceOut rx_bytes rx_packets tx_bytes tx_packets" */
1292 if (tok.length != 7) {
1293 throw new IllegalStateException("Native daemon returned unexpected result: " + rsp);
1294 }
1295
1296 final int code;
1297 try {
1298 code = Integer.parseInt(tok[0]);
1299 } catch (NumberFormatException e) {
1300 throw new IllegalStateException(
1301 "Failed to parse native daemon return code for " + ifaceIn + " " + ifaceOut);
1302 }
1303 if (code != NetdResponseCode.TetheringStatsResult) {
1304 throw new IllegalStateException(
1305 "Unexpected return code from native daemon for " + ifaceIn + " " + ifaceOut);
1306 }
1307
1308 try {
1309 final NetworkStats.Entry entry = new NetworkStats.Entry();
1310 entry.iface = ifaceIn;
Jeff Sharkey905b5892011-09-30 15:19:49 -07001311 entry.uid = UID_TETHERING;
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001312 entry.set = SET_DEFAULT;
1313 entry.tag = TAG_NONE;
1314 entry.rxBytes = Long.parseLong(tok[3]);
1315 entry.rxPackets = Long.parseLong(tok[4]);
1316 entry.txBytes = Long.parseLong(tok[5]);
1317 entry.txPackets = Long.parseLong(tok[6]);
1318 return entry;
1319 } catch (NumberFormatException e) {
1320 throw new IllegalStateException(
1321 "problem parsing tethering stats for " + ifaceIn + " " + ifaceOut + ": " + e);
1322 }
1323 }
1324
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001325 @Override
San Mehatf0db6e12010-04-07 15:22:10 -07001326 public void setInterfaceThrottle(String iface, int rxKbps, int txKbps) {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001327 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001328 try {
1329 mConnector.doCommand(String.format(
1330 "interface setthrottle %s %d %d", iface, rxKbps, txKbps));
1331 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001332 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -07001333 }
San Mehat91cac642010-03-31 14:31:36 -07001334 }
1335
1336 private int getInterfaceThrottle(String iface, boolean rx) {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001337 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
San Mehat91cac642010-03-31 14:31:36 -07001338 try {
Kenny Roota80ce062010-06-01 13:23:53 -07001339 String rsp;
1340 try {
1341 rsp = mConnector.doCommand(
1342 String.format("interface getthrottle %s %s", iface,
1343 (rx ? "rx" : "tx"))).get(0);
1344 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001345 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -07001346 }
1347
1348 String[] tok = rsp.split(" ");
1349 if (tok.length < 2) {
1350 Slog.e(TAG, "Malformed response to getthrottle command");
1351 return -1;
1352 }
1353
San Mehat91cac642010-03-31 14:31:36 -07001354 int code;
1355 try {
1356 code = Integer.parseInt(tok[0]);
1357 } catch (NumberFormatException nfe) {
1358 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
1359 return -1;
1360 }
1361 if ((rx && code != NetdResponseCode.InterfaceRxThrottleResult) || (
1362 !rx && code != NetdResponseCode.InterfaceTxThrottleResult)) {
1363 Slog.e(TAG, String.format("Unexpected response code %d", code));
1364 return -1;
1365 }
1366 return Integer.parseInt(tok[1]);
1367 } catch (Exception e) {
1368 Slog.e(TAG, String.format(
1369 "Failed to read interface %s throttle value", (rx ? "rx" : "tx")), e);
1370 }
1371 return -1;
1372 }
1373
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001374 @Override
San Mehat91cac642010-03-31 14:31:36 -07001375 public int getInterfaceRxThrottle(String iface) {
1376 return getInterfaceThrottle(iface, true);
1377 }
1378
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001379 @Override
San Mehat91cac642010-03-31 14:31:36 -07001380 public int getInterfaceTxThrottle(String iface) {
1381 return getInterfaceThrottle(iface, false);
1382 }
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001383
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001384 @Override
1385 public void setDefaultInterfaceForDns(String iface) {
1386 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001387 try {
1388 String cmd = "resolver setdefaultif " + iface;
1389
1390 mConnector.doCommand(cmd);
1391 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001392 throw e.rethrowAsParcelableException();
Mattias Falk7475c0c2011-04-04 16:10:36 +02001393 }
1394 }
1395
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001396 @Override
1397 public void setDnsServersForInterface(String iface, String[] servers) {
1398 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001399 try {
1400 String cmd = "resolver setifdns " + iface;
1401 for (String s : servers) {
Robert Greenwalt572b7042011-07-25 17:00:13 -07001402 InetAddress a = NetworkUtils.numericToInetAddress(s);
1403 if (a.isAnyLocalAddress() == false) {
1404 cmd += " " + a.getHostAddress();
Mattias Falk7475c0c2011-04-04 16:10:36 +02001405 }
1406 }
Mattias Falk7475c0c2011-04-04 16:10:36 +02001407 mConnector.doCommand(cmd);
Robert Greenwalt572b7042011-07-25 17:00:13 -07001408 } catch (IllegalArgumentException e) {
1409 throw new IllegalStateException("Error setting dnsn for interface", e);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001410 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001411 throw e.rethrowAsParcelableException();
Mattias Falk7475c0c2011-04-04 16:10:36 +02001412 }
1413 }
1414
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001415 @Override
1416 public void flushDefaultDnsCache() {
1417 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001418 try {
1419 String cmd = "resolver flushdefaultif";
1420
1421 mConnector.doCommand(cmd);
1422 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001423 throw e.rethrowAsParcelableException();
Mattias Falk7475c0c2011-04-04 16:10:36 +02001424 }
1425 }
1426
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001427 @Override
1428 public void flushInterfaceDnsCache(String iface) {
1429 mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
Mattias Falk7475c0c2011-04-04 16:10:36 +02001430 try {
1431 String cmd = "resolver flushif " + iface;
1432
1433 mConnector.doCommand(cmd);
1434 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001435 throw e.rethrowAsParcelableException();
Mattias Falk7475c0c2011-04-04 16:10:36 +02001436 }
1437 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07001438
1439 /** {@inheritDoc} */
1440 public void monitor() {
1441 if (mConnector != null) {
1442 mConnector.monitor();
1443 }
1444 }
Jeff Sharkey47eb1022011-08-25 17:48:52 -07001445
1446 @Override
1447 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1448 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
1449
1450 pw.print("Bandwidth control enabled: "); pw.println(mBandwidthControlEnabled);
1451
1452 synchronized (mQuotaLock) {
1453 pw.print("Active quota ifaces: "); pw.println(mActiveQuotaIfaces.toString());
1454 pw.print("Active alert ifaces: "); pw.println(mActiveAlertIfaces.toString());
1455 }
1456
1457 synchronized (mUidRejectOnQuota) {
1458 pw.print("UID reject on quota ifaces: [");
1459 final int size = mUidRejectOnQuota.size();
1460 for (int i = 0; i < size; i++) {
1461 pw.print(mUidRejectOnQuota.keyAt(i));
1462 if (i < size - 1) pw.print(",");
1463 }
1464 pw.println("]");
1465 }
1466 }
San Mehat873f2142010-01-14 10:25:07 -08001467}