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