NetworkManagementService.java revision db3c8678e5cbdfec011afaf25bde2091152c30ad
1/* 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 19import static android.Manifest.permission.CONNECTIVITY_INTERNAL; 20import static android.Manifest.permission.DUMP; 21import static android.Manifest.permission.SHUTDOWN; 22import static android.net.NetworkStats.SET_DEFAULT; 23import static android.net.NetworkStats.TAG_NONE; 24import static android.net.NetworkStats.UID_ALL; 25import static android.net.TrafficStats.UID_TETHERING; 26import static com.android.server.NetworkManagementService.NetdResponseCode.InterfaceGetCfgResult; 27import static com.android.server.NetworkManagementService.NetdResponseCode.InterfaceListResult; 28import static com.android.server.NetworkManagementService.NetdResponseCode.InterfaceRxThrottleResult; 29import static com.android.server.NetworkManagementService.NetdResponseCode.InterfaceTxThrottleResult; 30import static com.android.server.NetworkManagementService.NetdResponseCode.IpFwdStatusResult; 31import static com.android.server.NetworkManagementService.NetdResponseCode.TetherDnsFwdTgtListResult; 32import static com.android.server.NetworkManagementService.NetdResponseCode.TetherInterfaceListResult; 33import static com.android.server.NetworkManagementService.NetdResponseCode.TetherStatusResult; 34import static com.android.server.NetworkManagementService.NetdResponseCode.TetheringStatsResult; 35import static com.android.server.NetworkManagementService.NetdResponseCode.TtyListResult; 36import static com.android.server.NetworkManagementSocketTagger.PROP_QTAGUID_ENABLED; 37 38import android.content.Context; 39import android.net.INetworkManagementEventObserver; 40import android.net.InterfaceConfiguration; 41import android.net.LinkAddress; 42import android.net.NetworkStats; 43import android.net.NetworkUtils; 44import android.net.RouteInfo; 45import android.net.wifi.WifiConfiguration; 46import android.net.wifi.WifiConfiguration.KeyMgmt; 47import android.os.Handler; 48import android.os.INetworkManagementService; 49import android.os.RemoteCallbackList; 50import android.os.RemoteException; 51import android.os.SystemClock; 52import android.os.SystemProperties; 53import android.util.Log; 54import android.util.Slog; 55import android.util.SparseBooleanArray; 56 57import com.android.internal.net.NetworkStatsFactory; 58import com.android.server.NativeDaemonConnector.Command; 59import com.google.android.collect.Maps; 60 61import java.io.BufferedReader; 62import java.io.DataInputStream; 63import java.io.File; 64import java.io.FileDescriptor; 65import java.io.FileInputStream; 66import java.io.IOException; 67import java.io.InputStreamReader; 68import java.io.PrintWriter; 69import java.net.Inet4Address; 70import java.net.InetAddress; 71import java.net.InterfaceAddress; 72import java.net.NetworkInterface; 73import java.net.SocketException; 74import java.util.ArrayList; 75import java.util.Collection; 76import java.util.HashMap; 77import java.util.Map; 78import java.util.NoSuchElementException; 79import java.util.StringTokenizer; 80import java.util.concurrent.CountDownLatch; 81import android.bluetooth.BluetoothTetheringDataTracker; 82 83/** 84 * @hide 85 */ 86public class NetworkManagementService extends INetworkManagementService.Stub 87 implements Watchdog.Monitor { 88 private static final String TAG = "NetworkManagementService"; 89 private static final boolean DBG = false; 90 private static final String NETD_TAG = "NetdConnector"; 91 92 private static final String ADD = "add"; 93 private static final String REMOVE = "remove"; 94 95 private static final String DEFAULT = "default"; 96 private static final String SECONDARY = "secondary"; 97 98 /** 99 * Name representing {@link #setGlobalAlert(long)} limit when delivered to 100 * {@link INetworkManagementEventObserver#limitReached(String, String)}. 101 */ 102 public static final String LIMIT_GLOBAL_ALERT = "globalAlert"; 103 104 class NetdResponseCode { 105 /* Keep in sync with system/netd/ResponseCode.h */ 106 public static final int InterfaceListResult = 110; 107 public static final int TetherInterfaceListResult = 111; 108 public static final int TetherDnsFwdTgtListResult = 112; 109 public static final int TtyListResult = 113; 110 111 public static final int TetherStatusResult = 210; 112 public static final int IpFwdStatusResult = 211; 113 public static final int InterfaceGetCfgResult = 213; 114 public static final int SoftapStatusResult = 214; 115 public static final int InterfaceRxCounterResult = 216; 116 public static final int InterfaceTxCounterResult = 217; 117 public static final int InterfaceRxThrottleResult = 218; 118 public static final int InterfaceTxThrottleResult = 219; 119 public static final int QuotaCounterResult = 220; 120 public static final int TetheringStatsResult = 221; 121 public static final int DnsProxyQueryResult = 222; 122 123 public static final int InterfaceChange = 600; 124 public static final int BandwidthControl = 601; 125 public static final int InterfaceClassActivity = 613; 126 } 127 128 /** 129 * Binder context for this service 130 */ 131 private Context mContext; 132 133 /** 134 * connector object for communicating with netd 135 */ 136 private NativeDaemonConnector mConnector; 137 138 private final Handler mMainHandler = new Handler(); 139 140 private Thread mThread; 141 private CountDownLatch mConnectedSignal = new CountDownLatch(1); 142 143 private final RemoteCallbackList<INetworkManagementEventObserver> mObservers = 144 new RemoteCallbackList<INetworkManagementEventObserver>(); 145 146 private final NetworkStatsFactory mStatsFactory = new NetworkStatsFactory(); 147 148 private Object mQuotaLock = new Object(); 149 /** Set of interfaces with active quotas. */ 150 private HashMap<String, Long> mActiveQuotas = Maps.newHashMap(); 151 /** Set of interfaces with active alerts. */ 152 private HashMap<String, Long> mActiveAlerts = Maps.newHashMap(); 153 /** Set of UIDs with active reject rules. */ 154 private SparseBooleanArray mUidRejectOnQuota = new SparseBooleanArray(); 155 156 private volatile boolean mBandwidthControlEnabled; 157 158 /** 159 * Constructs a new NetworkManagementService instance 160 * 161 * @param context Binder context for this service 162 */ 163 private NetworkManagementService(Context context) { 164 mContext = context; 165 166 if ("simulator".equals(SystemProperties.get("ro.product.device"))) { 167 return; 168 } 169 170 mConnector = new NativeDaemonConnector( 171 new NetdCallbackReceiver(), "netd", 10, NETD_TAG, 160); 172 mThread = new Thread(mConnector, NETD_TAG); 173 174 // Add ourself to the Watchdog monitors. 175 Watchdog.getInstance().addMonitor(this); 176 } 177 178 public static NetworkManagementService create(Context context) throws InterruptedException { 179 final NetworkManagementService service = new NetworkManagementService(context); 180 final CountDownLatch connectedSignal = service.mConnectedSignal; 181 if (DBG) Slog.d(TAG, "Creating NetworkManagementService"); 182 service.mThread.start(); 183 if (DBG) Slog.d(TAG, "Awaiting socket connection"); 184 connectedSignal.await(); 185 if (DBG) Slog.d(TAG, "Connected"); 186 return service; 187 } 188 189 public void systemReady() { 190 prepareNativeDaemon(); 191 if (DBG) Slog.d(TAG, "Prepared"); 192 } 193 194 @Override 195 public void registerObserver(INetworkManagementEventObserver observer) { 196 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 197 mObservers.register(observer); 198 } 199 200 @Override 201 public void unregisterObserver(INetworkManagementEventObserver observer) { 202 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 203 mObservers.unregister(observer); 204 } 205 206 /** 207 * Notify our observers of an interface status change 208 */ 209 private void notifyInterfaceStatusChanged(String iface, boolean up) { 210 final int length = mObservers.beginBroadcast(); 211 for (int i = 0; i < length; i++) { 212 try { 213 mObservers.getBroadcastItem(i).interfaceStatusChanged(iface, up); 214 } catch (RemoteException e) { 215 } 216 } 217 mObservers.finishBroadcast(); 218 } 219 220 /** 221 * Notify our observers of an interface link state change 222 * (typically, an Ethernet cable has been plugged-in or unplugged). 223 */ 224 private void notifyInterfaceLinkStateChanged(String iface, boolean up) { 225 final int length = mObservers.beginBroadcast(); 226 for (int i = 0; i < length; i++) { 227 try { 228 mObservers.getBroadcastItem(i).interfaceLinkStateChanged(iface, up); 229 } catch (RemoteException e) { 230 } 231 } 232 mObservers.finishBroadcast(); 233 } 234 235 /** 236 * Notify our observers of an interface addition. 237 */ 238 private void notifyInterfaceAdded(String iface) { 239 final int length = mObservers.beginBroadcast(); 240 for (int i = 0; i < length; i++) { 241 try { 242 mObservers.getBroadcastItem(i).interfaceAdded(iface); 243 } catch (RemoteException e) { 244 } 245 } 246 mObservers.finishBroadcast(); 247 } 248 249 /** 250 * Notify our observers of an interface removal. 251 */ 252 private void notifyInterfaceRemoved(String iface) { 253 // netd already clears out quota and alerts for removed ifaces; update 254 // our sanity-checking state. 255 mActiveAlerts.remove(iface); 256 mActiveQuotas.remove(iface); 257 258 final int length = mObservers.beginBroadcast(); 259 for (int i = 0; i < length; i++) { 260 try { 261 mObservers.getBroadcastItem(i).interfaceRemoved(iface); 262 } catch (RemoteException e) { 263 } 264 } 265 mObservers.finishBroadcast(); 266 } 267 268 /** 269 * Notify our observers of a limit reached. 270 */ 271 private void notifyLimitReached(String limitName, String iface) { 272 final int length = mObservers.beginBroadcast(); 273 for (int i = 0; i < length; i++) { 274 try { 275 mObservers.getBroadcastItem(i).limitReached(limitName, iface); 276 } catch (RemoteException e) { 277 } 278 } 279 mObservers.finishBroadcast(); 280 } 281 282 /** 283 * Notify our observers of a change in the data activity state of the interface 284 */ 285 private void notifyInterfaceClassActivity(String label, boolean active) { 286 final int length = mObservers.beginBroadcast(); 287 for (int i = 0; i < length; i++) { 288 try { 289 mObservers.getBroadcastItem(i).interfaceClassDataActivityChanged(label, active); 290 } catch (RemoteException e) { 291 } 292 } 293 mObservers.finishBroadcast(); 294 } 295 296 /** 297 * Prepare native daemon once connected, enabling modules and pushing any 298 * existing in-memory rules. 299 */ 300 private void prepareNativeDaemon() { 301 mBandwidthControlEnabled = false; 302 303 // only enable bandwidth control when support exists 304 final boolean hasKernelSupport = new File("/proc/net/xt_qtaguid/ctrl").exists(); 305 if (hasKernelSupport) { 306 Slog.d(TAG, "enabling bandwidth control"); 307 try { 308 mConnector.execute("bandwidth", "enable"); 309 mBandwidthControlEnabled = true; 310 } catch (NativeDaemonConnectorException e) { 311 Log.wtf(TAG, "problem enabling bandwidth controls", e); 312 } 313 } else { 314 Slog.d(TAG, "not enabling bandwidth control"); 315 } 316 317 SystemProperties.set(PROP_QTAGUID_ENABLED, mBandwidthControlEnabled ? "1" : "0"); 318 319 // push any existing quota or UID rules 320 synchronized (mQuotaLock) { 321 int size = mActiveQuotas.size(); 322 if (size > 0) { 323 Slog.d(TAG, "pushing " + size + " active quota rules"); 324 final HashMap<String, Long> activeQuotas = mActiveQuotas; 325 mActiveQuotas = Maps.newHashMap(); 326 for (Map.Entry<String, Long> entry : activeQuotas.entrySet()) { 327 setInterfaceQuota(entry.getKey(), entry.getValue()); 328 } 329 } 330 331 size = mActiveAlerts.size(); 332 if (size > 0) { 333 Slog.d(TAG, "pushing " + size + " active alert rules"); 334 final HashMap<String, Long> activeAlerts = mActiveAlerts; 335 mActiveAlerts = Maps.newHashMap(); 336 for (Map.Entry<String, Long> entry : activeAlerts.entrySet()) { 337 setInterfaceAlert(entry.getKey(), entry.getValue()); 338 } 339 } 340 341 size = mUidRejectOnQuota.size(); 342 if (size > 0) { 343 Slog.d(TAG, "pushing " + size + " active uid rules"); 344 final SparseBooleanArray uidRejectOnQuota = mUidRejectOnQuota; 345 mUidRejectOnQuota = new SparseBooleanArray(); 346 for (int i = 0; i < uidRejectOnQuota.size(); i++) { 347 setUidNetworkRules(uidRejectOnQuota.keyAt(i), uidRejectOnQuota.valueAt(i)); 348 } 349 } 350 } 351 } 352 353 // 354 // Netd Callback handling 355 // 356 357 private class NetdCallbackReceiver implements INativeDaemonConnectorCallbacks { 358 @Override 359 public void onDaemonConnected() { 360 // event is dispatched from internal NDC thread, so we prepare the 361 // daemon back on main thread. 362 if (mConnectedSignal != null) { 363 mConnectedSignal.countDown(); 364 mConnectedSignal = null; 365 } else { 366 mMainHandler.post(new Runnable() { 367 @Override 368 public void run() { 369 prepareNativeDaemon(); 370 } 371 }); 372 } 373 } 374 375 @Override 376 public boolean onEvent(int code, String raw, String[] cooked) { 377 switch (code) { 378 case NetdResponseCode.InterfaceChange: 379 /* 380 * a network interface change occured 381 * Format: "NNN Iface added <name>" 382 * "NNN Iface removed <name>" 383 * "NNN Iface changed <name> <up/down>" 384 * "NNN Iface linkstatus <name> <up/down>" 385 */ 386 if (cooked.length < 4 || !cooked[1].equals("Iface")) { 387 throw new IllegalStateException( 388 String.format("Invalid event from daemon (%s)", raw)); 389 } 390 if (cooked[2].equals("added")) { 391 notifyInterfaceAdded(cooked[3]); 392 return true; 393 } else if (cooked[2].equals("removed")) { 394 notifyInterfaceRemoved(cooked[3]); 395 return true; 396 } else if (cooked[2].equals("changed") && cooked.length == 5) { 397 notifyInterfaceStatusChanged(cooked[3], cooked[4].equals("up")); 398 return true; 399 } else if (cooked[2].equals("linkstate") && cooked.length == 5) { 400 notifyInterfaceLinkStateChanged(cooked[3], cooked[4].equals("up")); 401 return true; 402 } 403 throw new IllegalStateException( 404 String.format("Invalid event from daemon (%s)", raw)); 405 // break; 406 case NetdResponseCode.BandwidthControl: 407 /* 408 * Bandwidth control needs some attention 409 * Format: "NNN limit alert <alertName> <ifaceName>" 410 */ 411 if (cooked.length < 5 || !cooked[1].equals("limit")) { 412 throw new IllegalStateException( 413 String.format("Invalid event from daemon (%s)", raw)); 414 } 415 if (cooked[2].equals("alert")) { 416 notifyLimitReached(cooked[3], cooked[4]); 417 return true; 418 } 419 throw new IllegalStateException( 420 String.format("Invalid event from daemon (%s)", raw)); 421 // break; 422 case NetdResponseCode.InterfaceClassActivity: 423 /* 424 * An network interface class state changed (active/idle) 425 * Format: "NNN IfaceClass <active/idle> <label>" 426 */ 427 if (cooked.length < 4 || !cooked[1].equals("IfaceClass")) { 428 throw new IllegalStateException( 429 String.format("Invalid event from daemon (%s)", raw)); 430 } 431 boolean isActive = cooked[2].equals("active"); 432 notifyInterfaceClassActivity(cooked[3], isActive); 433 return true; 434 // break; 435 default: break; 436 } 437 return false; 438 } 439 } 440 441 442 // 443 // INetworkManagementService members 444 // 445 446 @Override 447 public String[] listInterfaces() { 448 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 449 try { 450 return NativeDaemonEvent.filterMessageList( 451 mConnector.executeForList("interface", "list"), InterfaceListResult); 452 } catch (NativeDaemonConnectorException e) { 453 throw e.rethrowAsParcelableException(); 454 } 455 } 456 457 @Override 458 public InterfaceConfiguration getInterfaceConfig(String iface) { 459 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 460 461 final NativeDaemonEvent event; 462 try { 463 event = mConnector.execute("interface", "getcfg", iface); 464 } catch (NativeDaemonConnectorException e) { 465 throw e.rethrowAsParcelableException(); 466 } 467 468 event.checkCode(InterfaceGetCfgResult); 469 470 // Rsp: 213 xx:xx:xx:xx:xx:xx yyy.yyy.yyy.yyy zzz flag1 flag2 flag3 471 final StringTokenizer st = new StringTokenizer(event.getMessage()); 472 473 InterfaceConfiguration cfg; 474 try { 475 cfg = new InterfaceConfiguration(); 476 cfg.setHardwareAddress(st.nextToken(" ")); 477 InetAddress addr = null; 478 int prefixLength = 0; 479 try { 480 addr = NetworkUtils.numericToInetAddress(st.nextToken()); 481 } catch (IllegalArgumentException iae) { 482 Slog.e(TAG, "Failed to parse ipaddr", iae); 483 } 484 485 try { 486 prefixLength = Integer.parseInt(st.nextToken()); 487 } catch (NumberFormatException nfe) { 488 Slog.e(TAG, "Failed to parse prefixLength", nfe); 489 } 490 491 cfg.setLinkAddress(new LinkAddress(addr, prefixLength)); 492 while (st.hasMoreTokens()) { 493 cfg.setFlag(st.nextToken()); 494 } 495 } catch (NoSuchElementException nsee) { 496 throw new IllegalStateException("Invalid response from daemon: " + event); 497 } 498 return cfg; 499 } 500 501 @Override 502 public void setInterfaceConfig(String iface, InterfaceConfiguration cfg) { 503 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 504 LinkAddress linkAddr = cfg.getLinkAddress(); 505 if (linkAddr == null || linkAddr.getAddress() == null) { 506 throw new IllegalStateException("Null LinkAddress given"); 507 } 508 509 final Command cmd = new Command("interface", "setcfg", iface, 510 linkAddr.getAddress().getHostAddress(), 511 linkAddr.getNetworkPrefixLength()); 512 for (String flag : cfg.getFlags()) { 513 cmd.appendArg(flag); 514 } 515 516 try { 517 mConnector.execute(cmd); 518 } catch (NativeDaemonConnectorException e) { 519 throw e.rethrowAsParcelableException(); 520 } 521 } 522 523 @Override 524 public void setInterfaceDown(String iface) { 525 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 526 final InterfaceConfiguration ifcg = getInterfaceConfig(iface); 527 ifcg.setInterfaceDown(); 528 setInterfaceConfig(iface, ifcg); 529 } 530 531 @Override 532 public void setInterfaceUp(String iface) { 533 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 534 final InterfaceConfiguration ifcg = getInterfaceConfig(iface); 535 ifcg.setInterfaceUp(); 536 setInterfaceConfig(iface, ifcg); 537 } 538 539 @Override 540 public void setInterfaceIpv6PrivacyExtensions(String iface, boolean enable) { 541 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 542 try { 543 mConnector.execute( 544 "interface", "ipv6privacyextensions", iface, enable ? "enable" : "disable"); 545 } catch (NativeDaemonConnectorException e) { 546 throw e.rethrowAsParcelableException(); 547 } 548 } 549 550 /* TODO: This is right now a IPv4 only function. Works for wifi which loses its 551 IPv6 addresses on interface down, but we need to do full clean up here */ 552 @Override 553 public void clearInterfaceAddresses(String iface) { 554 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 555 try { 556 mConnector.execute("interface", "clearaddrs", iface); 557 } catch (NativeDaemonConnectorException e) { 558 throw e.rethrowAsParcelableException(); 559 } 560 } 561 562 @Override 563 public void enableIpv6(String iface) { 564 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 565 try { 566 mConnector.execute("interface", "ipv6", iface, "enable"); 567 } catch (NativeDaemonConnectorException e) { 568 throw e.rethrowAsParcelableException(); 569 } 570 } 571 572 @Override 573 public void disableIpv6(String iface) { 574 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 575 try { 576 mConnector.execute("interface", "ipv6", iface, "disable"); 577 } catch (NativeDaemonConnectorException e) { 578 throw e.rethrowAsParcelableException(); 579 } 580 } 581 582 @Override 583 public void addRoute(String interfaceName, RouteInfo route) { 584 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 585 modifyRoute(interfaceName, ADD, route, DEFAULT); 586 } 587 588 @Override 589 public void removeRoute(String interfaceName, RouteInfo route) { 590 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 591 modifyRoute(interfaceName, REMOVE, route, DEFAULT); 592 } 593 594 @Override 595 public void addSecondaryRoute(String interfaceName, RouteInfo route) { 596 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 597 modifyRoute(interfaceName, ADD, route, SECONDARY); 598 } 599 600 @Override 601 public void removeSecondaryRoute(String interfaceName, RouteInfo route) { 602 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 603 modifyRoute(interfaceName, REMOVE, route, SECONDARY); 604 } 605 606 private void modifyRoute(String interfaceName, String action, RouteInfo route, String type) { 607 final Command cmd = new Command("interface", "route", action, interfaceName, type); 608 609 // create triplet: dest-ip-addr prefixlength gateway-ip-addr 610 final LinkAddress la = route.getDestination(); 611 cmd.appendArg(la.getAddress().getHostAddress()); 612 cmd.appendArg(la.getNetworkPrefixLength()); 613 614 if (route.getGateway() == null) { 615 if (la.getAddress() instanceof Inet4Address) { 616 cmd.appendArg("0.0.0.0"); 617 } else { 618 cmd.appendArg("::0"); 619 } 620 } else { 621 cmd.appendArg(route.getGateway().getHostAddress()); 622 } 623 624 try { 625 mConnector.execute(cmd); 626 } catch (NativeDaemonConnectorException e) { 627 throw e.rethrowAsParcelableException(); 628 } 629 } 630 631 private ArrayList<String> readRouteList(String filename) { 632 FileInputStream fstream = null; 633 ArrayList<String> list = new ArrayList<String>(); 634 635 try { 636 fstream = new FileInputStream(filename); 637 DataInputStream in = new DataInputStream(fstream); 638 BufferedReader br = new BufferedReader(new InputStreamReader(in)); 639 String s; 640 641 // throw away the title line 642 643 while (((s = br.readLine()) != null) && (s.length() != 0)) { 644 list.add(s); 645 } 646 } catch (IOException ex) { 647 // return current list, possibly empty 648 } finally { 649 if (fstream != null) { 650 try { 651 fstream.close(); 652 } catch (IOException ex) {} 653 } 654 } 655 656 return list; 657 } 658 659 @Override 660 public RouteInfo[] getRoutes(String interfaceName) { 661 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 662 ArrayList<RouteInfo> routes = new ArrayList<RouteInfo>(); 663 664 // v4 routes listed as: 665 // iface dest-addr gateway-addr flags refcnt use metric netmask mtu window IRTT 666 for (String s : readRouteList("/proc/net/route")) { 667 String[] fields = s.split("\t"); 668 669 if (fields.length > 7) { 670 String iface = fields[0]; 671 672 if (interfaceName.equals(iface)) { 673 String dest = fields[1]; 674 String gate = fields[2]; 675 String flags = fields[3]; // future use? 676 String mask = fields[7]; 677 try { 678 // address stored as a hex string, ex: 0014A8C0 679 InetAddress destAddr = 680 NetworkUtils.intToInetAddress((int)Long.parseLong(dest, 16)); 681 int prefixLength = 682 NetworkUtils.netmaskIntToPrefixLength( 683 (int)Long.parseLong(mask, 16)); 684 LinkAddress linkAddress = new LinkAddress(destAddr, prefixLength); 685 686 // address stored as a hex string, ex 0014A8C0 687 InetAddress gatewayAddr = 688 NetworkUtils.intToInetAddress((int)Long.parseLong(gate, 16)); 689 690 RouteInfo route = new RouteInfo(linkAddress, gatewayAddr); 691 routes.add(route); 692 } catch (Exception e) { 693 Log.e(TAG, "Error parsing route " + s + " : " + e); 694 continue; 695 } 696 } 697 } 698 } 699 700 // v6 routes listed as: 701 // dest-addr prefixlength ?? ?? gateway-addr ?? ?? ?? ?? iface 702 for (String s : readRouteList("/proc/net/ipv6_route")) { 703 String[]fields = s.split("\\s+"); 704 if (fields.length > 9) { 705 String iface = fields[9].trim(); 706 if (interfaceName.equals(iface)) { 707 String dest = fields[0]; 708 String prefix = fields[1]; 709 String gate = fields[4]; 710 711 try { 712 // prefix length stored as a hex string, ex 40 713 int prefixLength = Integer.parseInt(prefix, 16); 714 715 // address stored as a 32 char hex string 716 // ex fe800000000000000000000000000000 717 InetAddress destAddr = NetworkUtils.hexToInet6Address(dest); 718 LinkAddress linkAddress = new LinkAddress(destAddr, prefixLength); 719 720 InetAddress gateAddr = NetworkUtils.hexToInet6Address(gate); 721 722 RouteInfo route = new RouteInfo(linkAddress, gateAddr); 723 routes.add(route); 724 } catch (Exception e) { 725 Log.e(TAG, "Error parsing route " + s + " : " + e); 726 continue; 727 } 728 } 729 } 730 } 731 return routes.toArray(new RouteInfo[routes.size()]); 732 } 733 734 @Override 735 public void shutdown() { 736 // TODO: remove from aidl if nobody calls externally 737 mContext.enforceCallingOrSelfPermission(SHUTDOWN, TAG); 738 739 Slog.d(TAG, "Shutting down"); 740 } 741 742 @Override 743 public boolean getIpForwardingEnabled() throws IllegalStateException{ 744 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 745 746 final NativeDaemonEvent event; 747 try { 748 event = mConnector.execute("ipfwd", "status"); 749 } catch (NativeDaemonConnectorException e) { 750 throw e.rethrowAsParcelableException(); 751 } 752 753 // 211 Forwarding enabled 754 event.checkCode(IpFwdStatusResult); 755 return event.getMessage().endsWith("enabled"); 756 } 757 758 @Override 759 public void setIpForwardingEnabled(boolean enable) { 760 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 761 try { 762 mConnector.execute("ipfwd", enable ? "enable" : "disable"); 763 } catch (NativeDaemonConnectorException e) { 764 throw e.rethrowAsParcelableException(); 765 } 766 } 767 768 @Override 769 public void startTethering(String[] dhcpRange) { 770 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 771 // cmd is "tether start first_start first_stop second_start second_stop ..." 772 // an odd number of addrs will fail 773 774 final Command cmd = new Command("tether", "start"); 775 for (String d : dhcpRange) { 776 cmd.appendArg(d); 777 } 778 779 try { 780 mConnector.execute(cmd); 781 } catch (NativeDaemonConnectorException e) { 782 throw e.rethrowAsParcelableException(); 783 } 784 } 785 786 @Override 787 public void stopTethering() { 788 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 789 try { 790 mConnector.execute("tether", "stop"); 791 } catch (NativeDaemonConnectorException e) { 792 throw e.rethrowAsParcelableException(); 793 } 794 } 795 796 @Override 797 public boolean isTetheringStarted() { 798 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 799 800 final NativeDaemonEvent event; 801 try { 802 event = mConnector.execute("tether", "status"); 803 } catch (NativeDaemonConnectorException e) { 804 throw e.rethrowAsParcelableException(); 805 } 806 807 // 210 Tethering services started 808 event.checkCode(TetherStatusResult); 809 return event.getMessage().endsWith("started"); 810 } 811 812 // TODO(BT) Remove 813 public void startReverseTethering(String iface) 814 throws IllegalStateException { 815 if (DBG) Slog.d(TAG, "startReverseTethering in"); 816 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 817 // cmd is "tether start first_start first_stop second_start second_stop ..." 818 // an odd number of addrs will fail 819 String cmd = "tether start-reverse"; 820 cmd += " " + iface; 821 if (DBG) Slog.d(TAG, "startReverseTethering cmd: " + cmd); 822 try { 823 mConnector.doCommand(cmd); 824 } catch (NativeDaemonConnectorException e) { 825 throw new IllegalStateException("Unable to communicate to native daemon"); 826 } 827 BluetoothTetheringDataTracker.getInstance().startReverseTether(iface); 828 829 } 830 831 // TODO(BT) Remove 832 public void stopReverseTethering() throws IllegalStateException { 833 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 834 try { 835 mConnector.doCommand("tether stop-reverse"); 836 } catch (NativeDaemonConnectorException e) { 837 throw new IllegalStateException("Unable to communicate to native daemon to stop tether"); 838 } 839 BluetoothTetheringDataTracker.getInstance().stopReverseTether(); 840 } 841 842 @Override 843 public void tetherInterface(String iface) { 844 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 845 try { 846 mConnector.execute("tether", "interface", "add", iface); 847 } catch (NativeDaemonConnectorException e) { 848 throw e.rethrowAsParcelableException(); 849 } 850 } 851 852 @Override 853 public void untetherInterface(String iface) { 854 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 855 try { 856 mConnector.execute("tether", "interface", "remove", iface); 857 } catch (NativeDaemonConnectorException e) { 858 throw e.rethrowAsParcelableException(); 859 } 860 } 861 862 @Override 863 public String[] listTetheredInterfaces() { 864 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 865 try { 866 return NativeDaemonEvent.filterMessageList( 867 mConnector.executeForList("tether", "interface", "list"), 868 TetherInterfaceListResult); 869 } catch (NativeDaemonConnectorException e) { 870 throw e.rethrowAsParcelableException(); 871 } 872 } 873 874 @Override 875 public void setDnsForwarders(String[] dns) { 876 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 877 878 final Command cmd = new Command("tether", "dns", "set"); 879 for (String s : dns) { 880 cmd.appendArg(NetworkUtils.numericToInetAddress(s).getHostAddress()); 881 } 882 883 try { 884 mConnector.execute(cmd); 885 } catch (NativeDaemonConnectorException e) { 886 throw e.rethrowAsParcelableException(); 887 } 888 } 889 890 @Override 891 public String[] getDnsForwarders() { 892 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 893 try { 894 return NativeDaemonEvent.filterMessageList( 895 mConnector.executeForList("tether", "dns", "list"), TetherDnsFwdTgtListResult); 896 } catch (NativeDaemonConnectorException e) { 897 throw e.rethrowAsParcelableException(); 898 } 899 } 900 901 private void modifyNat(String action, String internalInterface, String externalInterface) 902 throws SocketException { 903 final Command cmd = new Command("nat", action, internalInterface, externalInterface); 904 905 final NetworkInterface internalNetworkInterface = NetworkInterface.getByName( 906 internalInterface); 907 if (internalNetworkInterface == null) { 908 cmd.appendArg("0"); 909 } else { 910 Collection<InterfaceAddress> interfaceAddresses = internalNetworkInterface 911 .getInterfaceAddresses(); 912 cmd.appendArg(interfaceAddresses.size()); 913 for (InterfaceAddress ia : interfaceAddresses) { 914 InetAddress addr = NetworkUtils.getNetworkPart( 915 ia.getAddress(), ia.getNetworkPrefixLength()); 916 cmd.appendArg(addr.getHostAddress() + "/" + ia.getNetworkPrefixLength()); 917 } 918 } 919 920 try { 921 mConnector.execute(cmd); 922 } catch (NativeDaemonConnectorException e) { 923 throw e.rethrowAsParcelableException(); 924 } 925 } 926 927 @Override 928 public void enableNat(String internalInterface, String externalInterface) { 929 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 930 try { 931 modifyNat("enable", internalInterface, externalInterface); 932 } catch (SocketException e) { 933 throw new IllegalStateException(e); 934 } 935 } 936 937 @Override 938 public void disableNat(String internalInterface, String externalInterface) { 939 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 940 try { 941 modifyNat("disable", internalInterface, externalInterface); 942 } catch (SocketException e) { 943 throw new IllegalStateException(e); 944 } 945 } 946 947 @Override 948 public String[] listTtys() { 949 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 950 try { 951 return NativeDaemonEvent.filterMessageList( 952 mConnector.executeForList("list_ttys"), TtyListResult); 953 } catch (NativeDaemonConnectorException e) { 954 throw e.rethrowAsParcelableException(); 955 } 956 } 957 958 @Override 959 public void attachPppd( 960 String tty, String localAddr, String remoteAddr, String dns1Addr, String dns2Addr) { 961 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 962 try { 963 mConnector.execute("pppd", "attach", tty, 964 NetworkUtils.numericToInetAddress(localAddr).getHostAddress(), 965 NetworkUtils.numericToInetAddress(remoteAddr).getHostAddress(), 966 NetworkUtils.numericToInetAddress(dns1Addr).getHostAddress(), 967 NetworkUtils.numericToInetAddress(dns2Addr).getHostAddress()); 968 } catch (NativeDaemonConnectorException e) { 969 throw e.rethrowAsParcelableException(); 970 } 971 } 972 973 @Override 974 public void detachPppd(String tty) { 975 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 976 try { 977 mConnector.execute("pppd", "detach", tty); 978 } catch (NativeDaemonConnectorException e) { 979 throw e.rethrowAsParcelableException(); 980 } 981 } 982 983 @Override 984 public void startAccessPoint( 985 WifiConfiguration wifiConfig, String wlanIface) { 986 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 987 try { 988 wifiFirmwareReload(wlanIface, "AP"); 989 if (wifiConfig == null) { 990 mConnector.execute("softap", "set", wlanIface); 991 } else { 992 mConnector.execute("softap", "set", wlanIface, wifiConfig.SSID, 993 getSecurityType(wifiConfig), wifiConfig.preSharedKey); 994 } 995 mConnector.execute("softap", "startap"); 996 } catch (NativeDaemonConnectorException e) { 997 throw e.rethrowAsParcelableException(); 998 } 999 } 1000 1001 private static String getSecurityType(WifiConfiguration wifiConfig) { 1002 switch (wifiConfig.getAuthType()) { 1003 case KeyMgmt.WPA_PSK: 1004 return "wpa-psk"; 1005 case KeyMgmt.WPA2_PSK: 1006 return "wpa2-psk"; 1007 default: 1008 return "open"; 1009 } 1010 } 1011 1012 /* @param mode can be "AP", "STA" or "P2P" */ 1013 @Override 1014 public void wifiFirmwareReload(String wlanIface, String mode) { 1015 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 1016 try { 1017 mConnector.execute("softap", "fwreload", wlanIface, mode); 1018 } catch (NativeDaemonConnectorException e) { 1019 throw e.rethrowAsParcelableException(); 1020 } 1021 } 1022 1023 @Override 1024 public void stopAccessPoint(String wlanIface) { 1025 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 1026 try { 1027 mConnector.execute("softap", "stopap"); 1028 wifiFirmwareReload(wlanIface, "STA"); 1029 } catch (NativeDaemonConnectorException e) { 1030 throw e.rethrowAsParcelableException(); 1031 } 1032 } 1033 1034 @Override 1035 public void setAccessPoint(WifiConfiguration wifiConfig, String wlanIface) { 1036 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 1037 try { 1038 if (wifiConfig == null) { 1039 mConnector.execute("softap", "set", wlanIface); 1040 } else { 1041 mConnector.execute("softap", "set", wlanIface, wifiConfig.SSID, 1042 getSecurityType(wifiConfig), wifiConfig.preSharedKey); 1043 } 1044 } catch (NativeDaemonConnectorException e) { 1045 throw e.rethrowAsParcelableException(); 1046 } 1047 } 1048 1049 @Override 1050 public NetworkStats getNetworkStatsSummaryDev() { 1051 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 1052 return mStatsFactory.readNetworkStatsSummaryDev(); 1053 } 1054 1055 @Override 1056 public NetworkStats getNetworkStatsSummaryXt() { 1057 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 1058 return mStatsFactory.readNetworkStatsSummaryXt(); 1059 } 1060 1061 @Override 1062 public NetworkStats getNetworkStatsDetail() { 1063 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 1064 return mStatsFactory.readNetworkStatsDetail(UID_ALL); 1065 } 1066 1067 @Override 1068 public void setInterfaceQuota(String iface, long quotaBytes) { 1069 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 1070 1071 // silently discard when control disabled 1072 // TODO: eventually migrate to be always enabled 1073 if (!mBandwidthControlEnabled) return; 1074 1075 synchronized (mQuotaLock) { 1076 if (mActiveQuotas.containsKey(iface)) { 1077 throw new IllegalStateException("iface " + iface + " already has quota"); 1078 } 1079 1080 try { 1081 // TODO: support quota shared across interfaces 1082 mConnector.execute("bandwidth", "setiquota", iface, quotaBytes); 1083 mActiveQuotas.put(iface, quotaBytes); 1084 } catch (NativeDaemonConnectorException e) { 1085 throw e.rethrowAsParcelableException(); 1086 } 1087 } 1088 } 1089 1090 @Override 1091 public void removeInterfaceQuota(String iface) { 1092 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 1093 1094 // silently discard when control disabled 1095 // TODO: eventually migrate to be always enabled 1096 if (!mBandwidthControlEnabled) return; 1097 1098 synchronized (mQuotaLock) { 1099 if (!mActiveQuotas.containsKey(iface)) { 1100 // TODO: eventually consider throwing 1101 return; 1102 } 1103 1104 mActiveQuotas.remove(iface); 1105 mActiveAlerts.remove(iface); 1106 1107 try { 1108 // TODO: support quota shared across interfaces 1109 mConnector.execute("bandwidth", "removeiquota", iface); 1110 } catch (NativeDaemonConnectorException e) { 1111 throw e.rethrowAsParcelableException(); 1112 } 1113 } 1114 } 1115 1116 @Override 1117 public void setInterfaceAlert(String iface, long alertBytes) { 1118 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 1119 1120 // silently discard when control disabled 1121 // TODO: eventually migrate to be always enabled 1122 if (!mBandwidthControlEnabled) return; 1123 1124 // quick sanity check 1125 if (!mActiveQuotas.containsKey(iface)) { 1126 throw new IllegalStateException("setting alert requires existing quota on iface"); 1127 } 1128 1129 synchronized (mQuotaLock) { 1130 if (mActiveAlerts.containsKey(iface)) { 1131 throw new IllegalStateException("iface " + iface + " already has alert"); 1132 } 1133 1134 try { 1135 // TODO: support alert shared across interfaces 1136 mConnector.execute("bandwidth", "setinterfacealert", iface, alertBytes); 1137 mActiveAlerts.put(iface, alertBytes); 1138 } catch (NativeDaemonConnectorException e) { 1139 throw e.rethrowAsParcelableException(); 1140 } 1141 } 1142 } 1143 1144 @Override 1145 public void removeInterfaceAlert(String iface) { 1146 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 1147 1148 // silently discard when control disabled 1149 // TODO: eventually migrate to be always enabled 1150 if (!mBandwidthControlEnabled) return; 1151 1152 synchronized (mQuotaLock) { 1153 if (!mActiveAlerts.containsKey(iface)) { 1154 // TODO: eventually consider throwing 1155 return; 1156 } 1157 1158 try { 1159 // TODO: support alert shared across interfaces 1160 mConnector.execute("bandwidth", "removeinterfacealert", iface); 1161 mActiveAlerts.remove(iface); 1162 } catch (NativeDaemonConnectorException e) { 1163 throw e.rethrowAsParcelableException(); 1164 } 1165 } 1166 } 1167 1168 @Override 1169 public void setGlobalAlert(long alertBytes) { 1170 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 1171 1172 // silently discard when control disabled 1173 // TODO: eventually migrate to be always enabled 1174 if (!mBandwidthControlEnabled) return; 1175 1176 try { 1177 mConnector.execute("bandwidth", "setglobalalert", alertBytes); 1178 } catch (NativeDaemonConnectorException e) { 1179 throw e.rethrowAsParcelableException(); 1180 } 1181 } 1182 1183 @Override 1184 public void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) { 1185 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, 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 final boolean oldRejectOnQuota = mUidRejectOnQuota.get(uid, false); 1193 if (oldRejectOnQuota == rejectOnQuotaInterfaces) { 1194 // TODO: eventually consider throwing 1195 return; 1196 } 1197 1198 try { 1199 mConnector.execute("bandwidth", 1200 rejectOnQuotaInterfaces ? "addnaughtyapps" : "removenaughtyapps", uid); 1201 if (rejectOnQuotaInterfaces) { 1202 mUidRejectOnQuota.put(uid, true); 1203 } else { 1204 mUidRejectOnQuota.delete(uid); 1205 } 1206 } catch (NativeDaemonConnectorException e) { 1207 throw e.rethrowAsParcelableException(); 1208 } 1209 } 1210 } 1211 1212 @Override 1213 public boolean isBandwidthControlEnabled() { 1214 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 1215 return mBandwidthControlEnabled; 1216 } 1217 1218 @Override 1219 public NetworkStats getNetworkStatsUidDetail(int uid) { 1220 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 1221 return mStatsFactory.readNetworkStatsDetail(uid); 1222 } 1223 1224 @Override 1225 public NetworkStats getNetworkStatsTethering(String[] ifacePairs) { 1226 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 1227 1228 if (ifacePairs.length % 2 != 0) { 1229 throw new IllegalArgumentException( 1230 "unexpected ifacePairs; length=" + ifacePairs.length); 1231 } 1232 1233 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 1); 1234 for (int i = 0; i < ifacePairs.length; i += 2) { 1235 final String ifaceIn = ifacePairs[i]; 1236 final String ifaceOut = ifacePairs[i + 1]; 1237 if (ifaceIn != null && ifaceOut != null) { 1238 stats.combineValues(getNetworkStatsTethering(ifaceIn, ifaceOut)); 1239 } 1240 } 1241 return stats; 1242 } 1243 1244 private NetworkStats.Entry getNetworkStatsTethering(String ifaceIn, String ifaceOut) { 1245 final NativeDaemonEvent event; 1246 try { 1247 event = mConnector.execute("bandwidth", "gettetherstats", ifaceIn, ifaceOut); 1248 } catch (NativeDaemonConnectorException e) { 1249 throw e.rethrowAsParcelableException(); 1250 } 1251 1252 event.checkCode(TetheringStatsResult); 1253 1254 // 221 ifaceIn ifaceOut rx_bytes rx_packets tx_bytes tx_packets 1255 final StringTokenizer tok = new StringTokenizer(event.getMessage()); 1256 tok.nextToken(); 1257 tok.nextToken(); 1258 1259 try { 1260 final NetworkStats.Entry entry = new NetworkStats.Entry(); 1261 entry.iface = ifaceIn; 1262 entry.uid = UID_TETHERING; 1263 entry.set = SET_DEFAULT; 1264 entry.tag = TAG_NONE; 1265 entry.rxBytes = Long.parseLong(tok.nextToken()); 1266 entry.rxPackets = Long.parseLong(tok.nextToken()); 1267 entry.txBytes = Long.parseLong(tok.nextToken()); 1268 entry.txPackets = Long.parseLong(tok.nextToken()); 1269 return entry; 1270 } catch (NumberFormatException e) { 1271 throw new IllegalStateException( 1272 "problem parsing tethering stats for " + ifaceIn + " " + ifaceOut + ": " + e); 1273 } 1274 } 1275 1276 @Override 1277 public void setInterfaceThrottle(String iface, int rxKbps, int txKbps) { 1278 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 1279 try { 1280 mConnector.execute("interface", "setthrottle", iface, rxKbps, txKbps); 1281 } catch (NativeDaemonConnectorException e) { 1282 throw e.rethrowAsParcelableException(); 1283 } 1284 } 1285 1286 private int getInterfaceThrottle(String iface, boolean rx) { 1287 final NativeDaemonEvent event; 1288 try { 1289 event = mConnector.execute("interface", "getthrottle", iface, rx ? "rx" : "tx"); 1290 } catch (NativeDaemonConnectorException e) { 1291 throw e.rethrowAsParcelableException(); 1292 } 1293 1294 if (rx) { 1295 event.checkCode(InterfaceRxThrottleResult); 1296 } else { 1297 event.checkCode(InterfaceTxThrottleResult); 1298 } 1299 1300 try { 1301 return Integer.parseInt(event.getMessage()); 1302 } catch (NumberFormatException e) { 1303 throw new IllegalStateException("unexpected response:" + event); 1304 } 1305 } 1306 1307 @Override 1308 public int getInterfaceRxThrottle(String iface) { 1309 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 1310 return getInterfaceThrottle(iface, true); 1311 } 1312 1313 @Override 1314 public int getInterfaceTxThrottle(String iface) { 1315 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 1316 return getInterfaceThrottle(iface, false); 1317 } 1318 1319 @Override 1320 public void setDefaultInterfaceForDns(String iface) { 1321 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 1322 try { 1323 mConnector.execute("resolver", "setdefaultif", iface); 1324 } catch (NativeDaemonConnectorException e) { 1325 throw e.rethrowAsParcelableException(); 1326 } 1327 } 1328 1329 @Override 1330 public void setDnsServersForInterface(String iface, String[] servers) { 1331 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 1332 1333 final Command cmd = new Command("resolver", "setifdns", iface); 1334 for (String s : servers) { 1335 InetAddress a = NetworkUtils.numericToInetAddress(s); 1336 if (a.isAnyLocalAddress() == false) { 1337 cmd.appendArg(a.getHostAddress()); 1338 } 1339 } 1340 1341 try { 1342 mConnector.execute(cmd); 1343 } catch (NativeDaemonConnectorException e) { 1344 throw e.rethrowAsParcelableException(); 1345 } 1346 } 1347 1348 @Override 1349 public void flushDefaultDnsCache() { 1350 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 1351 try { 1352 mConnector.execute("resolver", "flushdefaultif"); 1353 } catch (NativeDaemonConnectorException e) { 1354 throw e.rethrowAsParcelableException(); 1355 } 1356 } 1357 1358 @Override 1359 public void flushInterfaceDnsCache(String iface) { 1360 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); 1361 try { 1362 mConnector.execute("resolver", "flushif", iface); 1363 } catch (NativeDaemonConnectorException e) { 1364 throw e.rethrowAsParcelableException(); 1365 } 1366 } 1367 1368 /** {@inheritDoc} */ 1369 public void monitor() { 1370 if (mConnector != null) { 1371 mConnector.monitor(); 1372 } 1373 } 1374 1375 @Override 1376 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 1377 mContext.enforceCallingOrSelfPermission(DUMP, TAG); 1378 1379 pw.println("NetworkManagementService NativeDaemonConnector Log:"); 1380 mConnector.dump(fd, pw, args); 1381 pw.println(); 1382 1383 pw.print("Bandwidth control enabled: "); pw.println(mBandwidthControlEnabled); 1384 1385 synchronized (mQuotaLock) { 1386 pw.print("Active quota ifaces: "); pw.println(mActiveQuotas.toString()); 1387 pw.print("Active alert ifaces: "); pw.println(mActiveAlerts.toString()); 1388 } 1389 1390 synchronized (mUidRejectOnQuota) { 1391 pw.print("UID reject on quota ifaces: ["); 1392 final int size = mUidRejectOnQuota.size(); 1393 for (int i = 0; i < size; i++) { 1394 pw.print(mUidRejectOnQuota.keyAt(i)); 1395 if (i < size - 1) pw.print(","); 1396 } 1397 pw.println("]"); 1398 } 1399 } 1400} 1401