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