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