1/*
2 * Copyright (C) 2010 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.wifi;
18
19import android.Manifest;
20import android.app.ActivityManager;
21import android.app.AppOpsManager;
22import android.bluetooth.BluetoothAdapter;
23import android.content.BroadcastReceiver;
24import android.content.Context;
25import android.content.Intent;
26import android.content.IntentFilter;
27import android.content.pm.PackageManager;
28import android.content.pm.UserInfo;
29import android.database.ContentObserver;
30import android.net.ConnectivityManager;
31import android.net.DhcpInfo;
32import android.net.DhcpResults;
33import android.net.IpConfiguration.ProxySettings;
34import android.net.LinkAddress;
35import android.net.NetworkUtils;
36import android.net.RouteInfo;
37import android.net.wifi.*;
38import android.net.wifi.IWifiManager;
39import android.os.AsyncTask;
40import android.os.Binder;
41import android.os.Handler;
42import android.os.HandlerThread;
43import android.os.IBinder;
44import android.os.Message;
45import android.os.Messenger;
46import android.os.RemoteException;
47import android.os.SystemProperties;
48import android.os.UserHandle;
49import android.os.UserManager;
50import android.os.WorkSource;
51import android.provider.Settings;
52import android.util.Log;
53import android.util.Slog;
54
55import java.io.FileNotFoundException;
56import java.io.BufferedReader;
57import java.io.FileDescriptor;
58import java.io.FileReader;
59import java.io.IOException;
60import java.io.PrintWriter;
61import java.lang.Override;
62import java.net.InetAddress;
63import java.net.Inet4Address;
64import java.util.ArrayList;
65import java.util.List;
66
67import com.android.internal.R;
68import com.android.internal.app.IBatteryStats;
69import com.android.internal.telephony.TelephonyIntents;
70import com.android.internal.util.AsyncChannel;
71import com.android.server.am.BatteryStatsService;
72
73import static com.android.server.wifi.WifiController.CMD_AIRPLANE_TOGGLED;
74import static com.android.server.wifi.WifiController.CMD_BATTERY_CHANGED;
75import static com.android.server.wifi.WifiController.CMD_EMERGENCY_MODE_CHANGED;
76import static com.android.server.wifi.WifiController.CMD_LOCKS_CHANGED;
77import static com.android.server.wifi.WifiController.CMD_SCAN_ALWAYS_MODE_CHANGED;
78import static com.android.server.wifi.WifiController.CMD_SCREEN_OFF;
79import static com.android.server.wifi.WifiController.CMD_SCREEN_ON;
80import static com.android.server.wifi.WifiController.CMD_SET_AP;
81import static com.android.server.wifi.WifiController.CMD_USER_PRESENT;
82import static com.android.server.wifi.WifiController.CMD_WIFI_TOGGLED;
83/**
84 * WifiService handles remote WiFi operation requests by implementing
85 * the IWifiManager interface.
86 *
87 * @hide
88 */
89public final class WifiServiceImpl extends IWifiManager.Stub {
90    private static final String TAG = "WifiService";
91    private static final boolean DBG = true;
92
93    final WifiStateMachine mWifiStateMachine;
94
95    private final Context mContext;
96
97    final LockList mLocks = new LockList();
98    // some wifi lock statistics
99    private int mFullHighPerfLocksAcquired;
100    private int mFullHighPerfLocksReleased;
101    private int mFullLocksAcquired;
102    private int mFullLocksReleased;
103    private int mScanLocksAcquired;
104    private int mScanLocksReleased;
105
106    private final List<Multicaster> mMulticasters =
107            new ArrayList<Multicaster>();
108    private int mMulticastEnabled;
109    private int mMulticastDisabled;
110
111    private final IBatteryStats mBatteryStats;
112    private final AppOpsManager mAppOps;
113
114    private String mInterfaceName;
115
116    // Debug counter tracking scan requests sent by WifiManager
117    private int scanRequestCounter = 0;
118
119    /* Tracks the open wi-fi network notification */
120    private WifiNotificationController mNotificationController;
121    /* Polls traffic stats and notifies clients */
122    private WifiTrafficPoller mTrafficPoller;
123    /* Tracks the persisted states for wi-fi & airplane mode */
124    final WifiSettingsStore mSettingsStore;
125
126    final boolean mBatchedScanSupported;
127
128    /**
129     * Asynchronous channel to WifiStateMachine
130     */
131    private AsyncChannel mWifiStateMachineChannel;
132
133    /**
134     * Handles client connections
135     */
136    private class ClientHandler extends Handler {
137
138        ClientHandler(android.os.Looper looper) {
139            super(looper);
140        }
141
142        @Override
143        public void handleMessage(Message msg) {
144            switch (msg.what) {
145                case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
146                    if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
147                        if (DBG) Slog.d(TAG, "New client listening to asynchronous messages");
148                        // We track the clients by the Messenger
149                        // since it is expected to be always available
150                        mTrafficPoller.addClient(msg.replyTo);
151                    } else {
152                        Slog.e(TAG, "Client connection failure, error=" + msg.arg1);
153                    }
154                    break;
155                }
156                case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
157                    if (msg.arg1 == AsyncChannel.STATUS_SEND_UNSUCCESSFUL) {
158                        if (DBG) Slog.d(TAG, "Send failed, client connection lost");
159                    } else {
160                        if (DBG) Slog.d(TAG, "Client connection lost with reason: " + msg.arg1);
161                    }
162                    mTrafficPoller.removeClient(msg.replyTo);
163                    break;
164                }
165                case AsyncChannel.CMD_CHANNEL_FULL_CONNECTION: {
166                    AsyncChannel ac = new AsyncChannel();
167                    ac.connect(mContext, this, msg.replyTo);
168                    break;
169                }
170                /* Client commands are forwarded to state machine */
171                case WifiManager.CONNECT_NETWORK:
172                case WifiManager.SAVE_NETWORK: {
173                    WifiConfiguration config = (WifiConfiguration) msg.obj;
174                    int networkId = msg.arg1;
175                    if (msg.what == WifiManager.SAVE_NETWORK) {
176                        if (config != null) {
177                            if (config.networkId == WifiConfiguration.INVALID_NETWORK_ID) {
178                                config.creatorUid = Binder.getCallingUid();
179                            } else {
180                                config.lastUpdateUid = Binder.getCallingUid();
181                            }
182                        }
183                        Slog.e("WiFiServiceImpl ", "SAVE"
184                                + " nid=" + Integer.toString(networkId)
185                                + " uid=" + Integer.toString(config.creatorUid)
186                                + "/" + Integer.toString(config.lastUpdateUid));
187                    }
188                    if (msg.what == WifiManager.CONNECT_NETWORK) {
189                        if (config != null) {
190                            if (config.networkId == WifiConfiguration.INVALID_NETWORK_ID) {
191                                config.creatorUid = Binder.getCallingUid();
192                            } else {
193                                config.lastUpdateUid = Binder.getCallingUid();
194                            }
195                        }
196                        Slog.e("WiFiServiceImpl ", "CONNECT "
197                                + " nid=" + Integer.toString(networkId)
198                                + " uid=" + Binder.getCallingUid());
199                    }
200                    if (config != null && config.isValid()) {
201                        if (DBG) Slog.d(TAG, "Connect with config" + config);
202                        mWifiStateMachine.sendMessage(Message.obtain(msg));
203                    } else if (config == null
204                            && networkId != WifiConfiguration.INVALID_NETWORK_ID) {
205                        if (DBG) Slog.d(TAG, "Connect with networkId" + networkId);
206                        mWifiStateMachine.sendMessage(Message.obtain(msg));
207                    } else {
208                        Slog.e(TAG, "ClientHandler.handleMessage ignoring invalid msg=" + msg);
209                        if (msg.what == WifiManager.CONNECT_NETWORK) {
210                            replyFailed(msg, WifiManager.CONNECT_NETWORK_FAILED,
211                                    WifiManager.INVALID_ARGS);
212                        } else {
213                            replyFailed(msg, WifiManager.SAVE_NETWORK_FAILED,
214                                    WifiManager.INVALID_ARGS);
215                        }
216                    }
217                    break;
218                }
219                case WifiManager.FORGET_NETWORK:
220                    if (isOwner(msg.sendingUid)) {
221                        mWifiStateMachine.sendMessage(Message.obtain(msg));
222                    } else {
223                        Slog.e(TAG, "Forget is not authorized for user");
224                        replyFailed(msg, WifiManager.FORGET_NETWORK_FAILED,
225                                WifiManager.NOT_AUTHORIZED);
226                    }
227                    break;
228                case WifiManager.START_WPS:
229                case WifiManager.CANCEL_WPS:
230                case WifiManager.DISABLE_NETWORK:
231                case WifiManager.RSSI_PKTCNT_FETCH: {
232                    mWifiStateMachine.sendMessage(Message.obtain(msg));
233                    break;
234                }
235                default: {
236                    Slog.d(TAG, "ClientHandler.handleMessage ignoring msg=" + msg);
237                    break;
238                }
239            }
240        }
241
242        private void replyFailed(Message msg, int what, int why) {
243            Message reply = msg.obtain();
244            reply.what = what;
245            reply.arg1 = why;
246            try {
247                msg.replyTo.send(reply);
248            } catch (RemoteException e) {
249                // There's not much we can do if reply can't be sent!
250            }
251        }
252    }
253    private ClientHandler mClientHandler;
254
255    /**
256     * Handles interaction with WifiStateMachine
257     */
258    private class WifiStateMachineHandler extends Handler {
259        private AsyncChannel mWsmChannel;
260
261        WifiStateMachineHandler(android.os.Looper looper) {
262            super(looper);
263            mWsmChannel = new AsyncChannel();
264            mWsmChannel.connect(mContext, this, mWifiStateMachine.getHandler());
265        }
266
267        @Override
268        public void handleMessage(Message msg) {
269            switch (msg.what) {
270                case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
271                    if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
272                        mWifiStateMachineChannel = mWsmChannel;
273                    } else {
274                        Slog.e(TAG, "WifiStateMachine connection failure, error=" + msg.arg1);
275                        mWifiStateMachineChannel = null;
276                    }
277                    break;
278                }
279                case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
280                    Slog.e(TAG, "WifiStateMachine channel lost, msg.arg1 =" + msg.arg1);
281                    mWifiStateMachineChannel = null;
282                    //Re-establish connection to state machine
283                    mWsmChannel.connect(mContext, this, mWifiStateMachine.getHandler());
284                    break;
285                }
286                default: {
287                    Slog.d(TAG, "WifiStateMachineHandler.handleMessage ignoring msg=" + msg);
288                    break;
289                }
290            }
291        }
292    }
293
294    WifiStateMachineHandler mWifiStateMachineHandler;
295
296    private WifiWatchdogStateMachine mWifiWatchdogStateMachine;
297
298    private WifiController mWifiController;
299
300    public WifiServiceImpl(Context context) {
301        mContext = context;
302
303        mInterfaceName =  SystemProperties.get("wifi.interface", "wlan0");
304
305        mTrafficPoller = new WifiTrafficPoller(mContext, mInterfaceName);
306        mWifiStateMachine = new WifiStateMachine(mContext, mInterfaceName, mTrafficPoller);
307        mWifiStateMachine.enableRssiPolling(true);
308        mBatteryStats = BatteryStatsService.getService();
309        mAppOps = (AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE);
310
311        mNotificationController = new WifiNotificationController(mContext, mWifiStateMachine);
312        mSettingsStore = new WifiSettingsStore(mContext);
313
314        HandlerThread wifiThread = new HandlerThread("WifiService");
315        wifiThread.start();
316        mClientHandler = new ClientHandler(wifiThread.getLooper());
317        mWifiStateMachineHandler = new WifiStateMachineHandler(wifiThread.getLooper());
318        mWifiController = new WifiController(mContext, this, wifiThread.getLooper());
319
320        mBatchedScanSupported = mContext.getResources().getBoolean(
321                R.bool.config_wifi_batched_scan_supported);
322    }
323
324
325    /**
326     * Check if Wi-Fi needs to be enabled and start
327     * if needed
328     *
329     * This function is used only at boot time
330     */
331    public void checkAndStartWifi() {
332        /* Check if wi-fi needs to be enabled */
333        boolean wifiEnabled = mSettingsStore.isWifiToggleEnabled();
334        Slog.i(TAG, "WifiService starting up with Wi-Fi " +
335                (wifiEnabled ? "enabled" : "disabled"));
336
337        registerForScanModeChange();
338        mContext.registerReceiver(
339                new BroadcastReceiver() {
340                    @Override
341                    public void onReceive(Context context, Intent intent) {
342                        if (mSettingsStore.handleAirplaneModeToggled()) {
343                            mWifiController.sendMessage(CMD_AIRPLANE_TOGGLED);
344                        }
345                    }
346                },
347                new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
348
349        // Adding optimizations of only receiving broadcasts when wifi is enabled
350        // can result in race conditions when apps toggle wifi in the background
351        // without active user involvement. Always receive broadcasts.
352        registerForBroadcasts();
353
354        mWifiController.start();
355
356        // If we are already disabled (could be due to airplane mode), avoid changing persist
357        // state here
358        if (wifiEnabled) setWifiEnabled(wifiEnabled);
359
360        mWifiWatchdogStateMachine = WifiWatchdogStateMachine.
361               makeWifiWatchdogStateMachine(mContext, mWifiStateMachine.getMessenger());
362    }
363
364    /**
365     * see {@link android.net.wifi.WifiManager#pingSupplicant()}
366     * @return {@code true} if the operation succeeds, {@code false} otherwise
367     */
368    public boolean pingSupplicant() {
369        enforceAccessPermission();
370        if (mWifiStateMachineChannel != null) {
371            return mWifiStateMachine.syncPingSupplicant(mWifiStateMachineChannel);
372        } else {
373            Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
374            return false;
375        }
376    }
377
378    /**
379     * see {@link android.net.wifi.WifiManager#getChannelList}
380     */
381    public List<WifiChannel> getChannelList() {
382        enforceAccessPermission();
383        if (mWifiStateMachineChannel != null) {
384            return mWifiStateMachine.syncGetChannelList(mWifiStateMachineChannel);
385        } else {
386            Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
387            return null;
388        }
389    }
390
391    // Start a location scan.
392    // L release: A location scan is implemented as a normal scan and avoids scanning DFS channels
393    public void startLocationRestrictedScan(WorkSource workSource) {
394        enforceChangePermission();
395        enforceLocationHardwarePermission();
396        List<WifiChannel> channels = getChannelList();
397        if (channels == null) {
398            Slog.e(TAG, "startLocationRestrictedScan cant get channels");
399            return;
400        }
401        ScanSettings settings = new ScanSettings();
402        for (WifiChannel channel : channels) {
403            if (!channel.isDFS) {
404                settings.channelSet.add(channel);
405            }
406        }
407        if (workSource == null) {
408            // Make sure we always have a workSource indicating the origin of the scan
409            // hence if there is none, pick an internal WifiStateMachine one
410            workSource = new WorkSource(WifiStateMachine.DFS_RESTRICTED_SCAN_REQUEST);
411        }
412        startScan(settings, workSource);
413    }
414
415    /**
416     * see {@link android.net.wifi.WifiManager#startScan}
417     * and {@link android.net.wifi.WifiManager#startCustomizedScan}
418     *
419     * @param settings If null, use default parameter, i.e. full scan.
420     * @param workSource If null, all blame is given to the calling uid.
421     */
422    public void startScan(ScanSettings settings, WorkSource workSource) {
423        enforceChangePermission();
424        if (settings != null) {
425            settings = new ScanSettings(settings);
426            if (!settings.isValid()) {
427                Slog.e(TAG, "invalid scan setting");
428                return;
429            }
430        }
431        if (workSource != null) {
432            enforceWorkSourcePermission();
433            // WifiManager currently doesn't use names, so need to clear names out of the
434            // supplied WorkSource to allow future WorkSource combining.
435            workSource.clearNames();
436        }
437        mWifiStateMachine.startScan(Binder.getCallingUid(), scanRequestCounter++,
438                settings, workSource);
439    }
440
441    private class BatchedScanRequest extends DeathRecipient {
442        final BatchedScanSettings settings;
443        final int uid;
444        final int pid;
445        final WorkSource workSource;
446
447        BatchedScanRequest(BatchedScanSettings settings, IBinder binder, WorkSource ws) {
448            super(0, null, binder, null);
449            this.settings = settings;
450            this.uid = getCallingUid();
451            this.pid = getCallingPid();
452            workSource = ws;
453        }
454        public void binderDied() {
455            stopBatchedScan(settings, uid, pid);
456        }
457        public String toString() {
458            return "BatchedScanRequest{settings=" + settings + ", binder=" + mBinder + "}";
459        }
460
461        public boolean isSameApp(int uid, int pid) {
462            return (this.uid == uid && this.pid == pid);
463        }
464    }
465
466    private final List<BatchedScanRequest> mBatchedScanners = new ArrayList<BatchedScanRequest>();
467
468    public boolean isBatchedScanSupported() {
469        return mBatchedScanSupported;
470    }
471
472    public void pollBatchedScan() {
473        enforceChangePermission();
474        if (mBatchedScanSupported == false) return;
475        mWifiStateMachine.requestBatchedScanPoll();
476    }
477
478    public String getWpsNfcConfigurationToken(int netId) {
479        enforceConnectivityInternalPermission();
480        return mWifiStateMachine.syncGetWpsNfcConfigurationToken(netId);
481    }
482
483    /**
484     * see {@link android.net.wifi.WifiManager#requestBatchedScan()}
485     */
486    public boolean requestBatchedScan(BatchedScanSettings requested, IBinder binder,
487            WorkSource workSource) {
488        enforceChangePermission();
489        if (workSource != null) {
490            enforceWorkSourcePermission();
491            // WifiManager currently doesn't use names, so need to clear names out of the
492            // supplied WorkSource to allow future WorkSource combining.
493            workSource.clearNames();
494        }
495        if (mBatchedScanSupported == false) return false;
496        requested = new BatchedScanSettings(requested);
497        if (requested.isInvalid()) return false;
498        BatchedScanRequest r = new BatchedScanRequest(requested, binder, workSource);
499        synchronized(mBatchedScanners) {
500            mBatchedScanners.add(r);
501            resolveBatchedScannersLocked();
502        }
503        return true;
504    }
505
506    public List<BatchedScanResult> getBatchedScanResults(String callingPackage) {
507        enforceAccessPermission();
508        if (mBatchedScanSupported == false) return new ArrayList<BatchedScanResult>();
509        int uid = Binder.getCallingUid();
510        int userId = UserHandle.getCallingUserId();
511        boolean hasInteractUsersFull = checkInteractAcrossUsersFull();
512        long ident = Binder.clearCallingIdentity();
513        try {
514            if (mAppOps.noteOp(AppOpsManager.OP_WIFI_SCAN, uid, callingPackage)
515                    != AppOpsManager.MODE_ALLOWED) {
516                return new ArrayList<BatchedScanResult>();
517            }
518            if (!isCurrentProfile(userId) && !hasInteractUsersFull) {
519                return new ArrayList<BatchedScanResult>();
520            }
521            return mWifiStateMachine.syncGetBatchedScanResultsList();
522        } finally {
523            Binder.restoreCallingIdentity(ident);
524        }
525    }
526
527    public void stopBatchedScan(BatchedScanSettings settings) {
528        enforceChangePermission();
529        if (mBatchedScanSupported == false) return;
530        stopBatchedScan(settings, getCallingUid(), getCallingPid());
531    }
532
533    private void stopBatchedScan(BatchedScanSettings settings, int uid, int pid) {
534        ArrayList<BatchedScanRequest> found = new ArrayList<BatchedScanRequest>();
535        synchronized(mBatchedScanners) {
536            for (BatchedScanRequest r : mBatchedScanners) {
537                if (r.isSameApp(uid, pid) && (settings == null || settings.equals(r.settings))) {
538                    found.add(r);
539                    if (settings != null) break;
540                }
541            }
542            for (BatchedScanRequest r : found) {
543                mBatchedScanners.remove(r);
544            }
545            if (found.size() != 0) {
546                resolveBatchedScannersLocked();
547            }
548        }
549    }
550
551    private void resolveBatchedScannersLocked() {
552        BatchedScanSettings setting = new BatchedScanSettings();
553        WorkSource responsibleWorkSource = null;
554        int responsibleUid = 0;
555        double responsibleCsph = 0; // Channel Scans Per Hour
556
557        if (mBatchedScanners.size() == 0) {
558            mWifiStateMachine.setBatchedScanSettings(null, 0, 0, null);
559            return;
560        }
561        for (BatchedScanRequest r : mBatchedScanners) {
562            BatchedScanSettings s = r.settings;
563
564            // evaluate responsibility
565            int currentChannelCount;
566            int currentScanInterval;
567            double currentCsph;
568
569            if (s.channelSet == null || s.channelSet.isEmpty()) {
570                // all channels - 11 B and 9 A channels roughly.
571                currentChannelCount = 9 + 11;
572            } else {
573                currentChannelCount = s.channelSet.size();
574                // these are rough est - no real need to correct for reg-domain;
575                if (s.channelSet.contains("A")) currentChannelCount += (9 - 1);
576                if (s.channelSet.contains("B")) currentChannelCount += (11 - 1);
577
578            }
579            if (s.scanIntervalSec == BatchedScanSettings.UNSPECIFIED) {
580                currentScanInterval = BatchedScanSettings.DEFAULT_INTERVAL_SEC;
581            } else {
582                currentScanInterval = s.scanIntervalSec;
583            }
584            currentCsph = 60 * 60 * currentChannelCount / currentScanInterval;
585
586            if (currentCsph > responsibleCsph) {
587                responsibleUid = r.uid;
588                responsibleWorkSource = r.workSource;
589                responsibleCsph = currentCsph;
590            }
591
592            if (s.maxScansPerBatch != BatchedScanSettings.UNSPECIFIED &&
593                    s.maxScansPerBatch < setting.maxScansPerBatch) {
594                setting.maxScansPerBatch = s.maxScansPerBatch;
595            }
596            if (s.maxApPerScan != BatchedScanSettings.UNSPECIFIED &&
597                    (setting.maxApPerScan == BatchedScanSettings.UNSPECIFIED ||
598                    s.maxApPerScan > setting.maxApPerScan)) {
599                setting.maxApPerScan = s.maxApPerScan;
600            }
601            if (s.scanIntervalSec != BatchedScanSettings.UNSPECIFIED &&
602                    s.scanIntervalSec < setting.scanIntervalSec) {
603                setting.scanIntervalSec = s.scanIntervalSec;
604            }
605            if (s.maxApForDistance != BatchedScanSettings.UNSPECIFIED &&
606                    (setting.maxApForDistance == BatchedScanSettings.UNSPECIFIED ||
607                    s.maxApForDistance > setting.maxApForDistance)) {
608                setting.maxApForDistance = s.maxApForDistance;
609            }
610            if (s.channelSet != null && s.channelSet.size() != 0) {
611                if (setting.channelSet == null || setting.channelSet.size() != 0) {
612                    if (setting.channelSet == null) setting.channelSet = new ArrayList<String>();
613                    for (String i : s.channelSet) {
614                        if (setting.channelSet.contains(i) == false) setting.channelSet.add(i);
615                    }
616                } // else, ignore the constraint - we already use all channels
617            } else {
618                if (setting.channelSet == null || setting.channelSet.size() != 0) {
619                    setting.channelSet = new ArrayList<String>();
620                }
621            }
622        }
623
624        setting.constrain();
625        mWifiStateMachine.setBatchedScanSettings(setting, responsibleUid, (int)responsibleCsph,
626                responsibleWorkSource);
627    }
628
629    private void enforceAccessPermission() {
630        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
631                "WifiService");
632    }
633
634    private void enforceChangePermission() {
635        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
636                                                "WifiService");
637    }
638
639    private void enforceLocationHardwarePermission() {
640        mContext.enforceCallingOrSelfPermission(Manifest.permission.LOCATION_HARDWARE,
641                "LocationHardware");
642    }
643
644    private void enforceReadCredentialPermission() {
645        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.READ_WIFI_CREDENTIAL,
646                                                "WifiService");
647    }
648
649    private void enforceWorkSourcePermission() {
650        mContext.enforceCallingPermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
651                "WifiService");
652
653    }
654
655    private void enforceMulticastChangePermission() {
656        mContext.enforceCallingOrSelfPermission(
657                android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
658                "WifiService");
659    }
660
661    private void enforceConnectivityInternalPermission() {
662        mContext.enforceCallingOrSelfPermission(
663                android.Manifest.permission.CONNECTIVITY_INTERNAL,
664                "ConnectivityService");
665    }
666
667    /**
668     * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
669     * @param enable {@code true} to enable, {@code false} to disable.
670     * @return {@code true} if the enable/disable operation was
671     *         started or is already in the queue.
672     */
673    public synchronized boolean setWifiEnabled(boolean enable) {
674        enforceChangePermission();
675        Slog.d(TAG, "setWifiEnabled: " + enable + " pid=" + Binder.getCallingPid()
676                    + ", uid=" + Binder.getCallingUid());
677        if (DBG) {
678            Slog.e(TAG, "Invoking mWifiStateMachine.setWifiEnabled\n");
679        }
680
681        /*
682        * Caller might not have WRITE_SECURE_SETTINGS,
683        * only CHANGE_WIFI_STATE is enforced
684        */
685
686        long ident = Binder.clearCallingIdentity();
687        try {
688            if (! mSettingsStore.handleWifiToggled(enable)) {
689                // Nothing to do if wifi cannot be toggled
690                return true;
691            }
692        } finally {
693            Binder.restoreCallingIdentity(ident);
694        }
695
696        mWifiController.sendMessage(CMD_WIFI_TOGGLED);
697        return true;
698    }
699
700    /**
701     * see {@link WifiManager#getWifiState()}
702     * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
703     *         {@link WifiManager#WIFI_STATE_DISABLING},
704     *         {@link WifiManager#WIFI_STATE_ENABLED},
705     *         {@link WifiManager#WIFI_STATE_ENABLING},
706     *         {@link WifiManager#WIFI_STATE_UNKNOWN}
707     */
708    public int getWifiEnabledState() {
709        enforceAccessPermission();
710        return mWifiStateMachine.syncGetWifiState();
711    }
712
713    /**
714     * see {@link android.net.wifi.WifiManager#setWifiApEnabled(WifiConfiguration, boolean)}
715     * @param wifiConfig SSID, security and channel details as
716     *        part of WifiConfiguration
717     * @param enabled true to enable and false to disable
718     */
719    public void setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
720        enforceChangePermission();
721        ConnectivityManager.enforceTetherChangePermission(mContext);
722        UserManager um = UserManager.get(mContext);
723        if (um.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
724            throw new SecurityException("DISALLOW_CONFIG_TETHERING is enabled for this user.");
725        }
726        // null wifiConfig is a meaningful input for CMD_SET_AP
727        if (wifiConfig == null || wifiConfig.isValid()) {
728            mWifiController.obtainMessage(CMD_SET_AP, enabled ? 1 : 0, 0, wifiConfig).sendToTarget();
729        } else {
730            Slog.e(TAG, "Invalid WifiConfiguration");
731        }
732    }
733
734    /**
735     * see {@link WifiManager#getWifiApState()}
736     * @return One of {@link WifiManager#WIFI_AP_STATE_DISABLED},
737     *         {@link WifiManager#WIFI_AP_STATE_DISABLING},
738     *         {@link WifiManager#WIFI_AP_STATE_ENABLED},
739     *         {@link WifiManager#WIFI_AP_STATE_ENABLING},
740     *         {@link WifiManager#WIFI_AP_STATE_FAILED}
741     */
742    public int getWifiApEnabledState() {
743        enforceAccessPermission();
744        return mWifiStateMachine.syncGetWifiApState();
745    }
746
747    /**
748     * see {@link WifiManager#getWifiApConfiguration()}
749     * @return soft access point configuration
750     */
751    public WifiConfiguration getWifiApConfiguration() {
752        enforceAccessPermission();
753        return mWifiStateMachine.syncGetWifiApConfiguration();
754    }
755
756    /**
757     * see {@link WifiManager#setWifiApConfiguration(WifiConfiguration)}
758     * @param wifiConfig WifiConfiguration details for soft access point
759     */
760    public void setWifiApConfiguration(WifiConfiguration wifiConfig) {
761        enforceChangePermission();
762        if (wifiConfig == null)
763            return;
764        if (wifiConfig.isValid()) {
765            mWifiStateMachine.setWifiApConfiguration(wifiConfig);
766        } else {
767            Slog.e(TAG, "Invalid WifiConfiguration");
768        }
769    }
770
771    /**
772     * @param enable {@code true} to enable, {@code false} to disable.
773     * @return {@code true} if the enable/disable operation was
774     *         started or is already in the queue.
775     */
776    public boolean isScanAlwaysAvailable() {
777        enforceAccessPermission();
778        return mSettingsStore.isScanAlwaysAvailable();
779    }
780
781    /**
782     * see {@link android.net.wifi.WifiManager#disconnect()}
783     */
784    public void disconnect() {
785        enforceChangePermission();
786        mWifiStateMachine.disconnectCommand();
787    }
788
789    /**
790     * see {@link android.net.wifi.WifiManager#reconnect()}
791     */
792    public void reconnect() {
793        enforceChangePermission();
794        mWifiStateMachine.reconnectCommand();
795    }
796
797    /**
798     * see {@link android.net.wifi.WifiManager#reassociate()}
799     */
800    public void reassociate() {
801        enforceChangePermission();
802        mWifiStateMachine.reassociateCommand();
803    }
804
805    /**
806     * see {@link android.net.wifi.WifiManager#getSupportedFeatures}
807     */
808    public int getSupportedFeatures() {
809        enforceAccessPermission();
810        if (mWifiStateMachineChannel != null) {
811            return mWifiStateMachine.syncGetSupportedFeatures(mWifiStateMachineChannel);
812        } else {
813            Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
814            return 0;
815        }
816    }
817
818    /**
819     * see {@link android.net.wifi.WifiAdapter#reportActivityInfo}
820     */
821    public WifiActivityEnergyInfo reportActivityInfo() {
822        enforceAccessPermission();
823        WifiLinkLayerStats stats;
824        WifiActivityEnergyInfo energyInfo = null;
825        if (mWifiStateMachineChannel != null) {
826            stats = mWifiStateMachine.syncGetLinkLayerStats(mWifiStateMachineChannel);
827            if (stats != null) {
828                // Convert the LinkLayerStats into EnergyActivity
829                energyInfo = new WifiActivityEnergyInfo(
830                        WifiActivityEnergyInfo.STACK_STATE_STATE_IDLE, stats.tx_time,
831                        stats.rx_time, stats.on_time - stats.tx_time - stats.rx_time,
832                        0 /* TBD */);
833            }
834            return energyInfo;
835        } else {
836            Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
837            return null;
838        }
839    }
840
841    /**
842     * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
843     * @return the list of configured networks
844     */
845    public List<WifiConfiguration> getConfiguredNetworks() {
846        enforceAccessPermission();
847        if (mWifiStateMachineChannel != null) {
848            return mWifiStateMachine.syncGetConfiguredNetworks(Binder.getCallingUid(),
849                    mWifiStateMachineChannel);
850        } else {
851            Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
852            return null;
853        }
854    }
855
856    /**
857     * see {@link android.net.wifi.WifiManager#getPrivilegedConfiguredNetworks()}
858     * @return the list of configured networks with real preSharedKey
859     */
860    public List<WifiConfiguration> getPrivilegedConfiguredNetworks() {
861        enforceReadCredentialPermission();
862        enforceAccessPermission();
863        if (mWifiStateMachineChannel != null) {
864            return mWifiStateMachine.syncGetPrivilegedConfiguredNetwork(mWifiStateMachineChannel);
865        } else {
866            Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
867            return null;
868        }
869    }
870
871    /**
872     * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
873     * @return the supplicant-assigned identifier for the new or updated
874     * network if the operation succeeds, or {@code -1} if it fails
875     */
876    public int addOrUpdateNetwork(WifiConfiguration config) {
877        enforceChangePermission();
878        if (config.isValid()) {
879            //TODO: pass the Uid the WifiStateMachine as a message parameter
880            Slog.e("addOrUpdateNetwork", " uid = " + Integer.toString(Binder.getCallingUid())
881                    + " SSID " + config.SSID
882                    + " nid=" + Integer.toString(config.networkId));
883            if (config.networkId == WifiConfiguration.INVALID_NETWORK_ID) {
884                config.creatorUid = Binder.getCallingUid();
885            } else {
886                config.lastUpdateUid = Binder.getCallingUid();
887            }
888            if (mWifiStateMachineChannel != null) {
889                return mWifiStateMachine.syncAddOrUpdateNetwork(mWifiStateMachineChannel, config);
890            } else {
891                Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
892                return -1;
893            }
894        } else {
895            Slog.e(TAG, "bad network configuration");
896            return -1;
897        }
898    }
899
900     /**
901     * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
902     * @param netId the integer that identifies the network configuration
903     * to the supplicant
904     * @return {@code true} if the operation succeeded
905     */
906    public boolean removeNetwork(int netId) {
907        enforceChangePermission();
908
909        if (!isOwner(Binder.getCallingUid())) {
910            Slog.e(TAG, "Remove is not authorized for user");
911            return false;
912        }
913
914        if (mWifiStateMachineChannel != null) {
915            return mWifiStateMachine.syncRemoveNetwork(mWifiStateMachineChannel, netId);
916        } else {
917            Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
918            return false;
919        }
920    }
921
922    /**
923     * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
924     * @param netId the integer that identifies the network configuration
925     * to the supplicant
926     * @param disableOthers if true, disable all other networks.
927     * @return {@code true} if the operation succeeded
928     */
929    public boolean enableNetwork(int netId, boolean disableOthers) {
930        enforceChangePermission();
931        if (mWifiStateMachineChannel != null) {
932            return mWifiStateMachine.syncEnableNetwork(mWifiStateMachineChannel, netId,
933                    disableOthers);
934        } else {
935            Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
936            return false;
937        }
938    }
939
940    /**
941     * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
942     * @param netId the integer that identifies the network configuration
943     * to the supplicant
944     * @return {@code true} if the operation succeeded
945     */
946    public boolean disableNetwork(int netId) {
947        enforceChangePermission();
948        if (mWifiStateMachineChannel != null) {
949            return mWifiStateMachine.syncDisableNetwork(mWifiStateMachineChannel, netId);
950        } else {
951            Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
952            return false;
953        }
954    }
955
956    /**
957     * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
958     * @return the Wi-Fi information, contained in {@link WifiInfo}.
959     */
960    public WifiInfo getConnectionInfo() {
961        enforceAccessPermission();
962        /*
963         * Make sure we have the latest information, by sending
964         * a status request to the supplicant.
965         */
966        return mWifiStateMachine.syncRequestConnectionInfo();
967    }
968
969    /**
970     * Return the results of the most recent access point scan, in the form of
971     * a list of {@link ScanResult} objects.
972     * @return the list of results
973     */
974    public List<ScanResult> getScanResults(String callingPackage) {
975        enforceAccessPermission();
976        int userId = UserHandle.getCallingUserId();
977        int uid = Binder.getCallingUid();
978        boolean hasInteractUsersFull = checkInteractAcrossUsersFull();
979        long ident = Binder.clearCallingIdentity();
980        try {
981            if (mAppOps.noteOp(AppOpsManager.OP_WIFI_SCAN, uid, callingPackage)
982                    != AppOpsManager.MODE_ALLOWED) {
983                return new ArrayList<ScanResult>();
984            }
985            if (!isCurrentProfile(userId) && !hasInteractUsersFull) {
986                return new ArrayList<ScanResult>();
987            }
988            return mWifiStateMachine.syncGetScanResultsList();
989        } finally {
990            Binder.restoreCallingIdentity(ident);
991        }
992    }
993
994    /**
995     * Returns true if the caller holds INTERACT_ACROSS_USERS_FULL.
996     */
997    private boolean checkInteractAcrossUsersFull() {
998        return mContext.checkCallingOrSelfPermission(
999                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
1000                == PackageManager.PERMISSION_GRANTED;
1001    }
1002
1003    /**
1004     * Returns true if the calling user is the current one or a profile of the
1005     * current user..
1006     */
1007    private boolean isCurrentProfile(int userId) {
1008        int currentUser = ActivityManager.getCurrentUser();
1009        if (userId == currentUser) {
1010            return true;
1011        }
1012        List<UserInfo> profiles = UserManager.get(mContext).getProfiles(currentUser);
1013        for (UserInfo user : profiles) {
1014            if (userId == user.id) {
1015                return true;
1016            }
1017        }
1018        return false;
1019    }
1020
1021    /**
1022     * Returns true if uid is an application running under the owner or a profile of the owner.
1023     *
1024     * Note: Should not be called if identity is cleared.
1025     */
1026    private boolean isOwner(int uid) {
1027        long ident = Binder.clearCallingIdentity();
1028        int userId = UserHandle.getUserId(uid);
1029        try {
1030            int ownerUser = UserHandle.USER_OWNER;
1031            if (userId == ownerUser) {
1032                return true;
1033            }
1034            List<UserInfo> profiles = UserManager.get(mContext).getProfiles(ownerUser);
1035            for (UserInfo profile : profiles) {
1036                if (userId == profile.id) {
1037                    return true;
1038                }
1039            }
1040            return false;
1041        }
1042        finally {
1043            Binder.restoreCallingIdentity(ident);
1044        }
1045    }
1046
1047
1048    /**
1049     * Tell the supplicant to persist the current list of configured networks.
1050     * @return {@code true} if the operation succeeded
1051     *
1052     * TODO: deprecate this
1053     */
1054    public boolean saveConfiguration() {
1055        boolean result = true;
1056        enforceChangePermission();
1057        if (mWifiStateMachineChannel != null) {
1058            return mWifiStateMachine.syncSaveConfig(mWifiStateMachineChannel);
1059        } else {
1060            Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
1061            return false;
1062        }
1063    }
1064
1065    /**
1066     * Set the country code
1067     * @param countryCode ISO 3166 country code.
1068     * @param persist {@code true} if the setting should be remembered.
1069     *
1070     * The persist behavior exists so that wifi can fall back to the last
1071     * persisted country code on a restart, when the locale information is
1072     * not available from telephony.
1073     */
1074    public void setCountryCode(String countryCode, boolean persist) {
1075        Slog.i(TAG, "WifiService trying to set country code to " + countryCode +
1076                " with persist set to " + persist);
1077        enforceConnectivityInternalPermission();
1078        final long token = Binder.clearCallingIdentity();
1079        try {
1080            mWifiStateMachine.setCountryCode(countryCode, persist);
1081        } finally {
1082            Binder.restoreCallingIdentity(token);
1083        }
1084    }
1085
1086    /**
1087     * Set the operational frequency band
1088     * @param band One of
1089     *     {@link WifiManager#WIFI_FREQUENCY_BAND_AUTO},
1090     *     {@link WifiManager#WIFI_FREQUENCY_BAND_5GHZ},
1091     *     {@link WifiManager#WIFI_FREQUENCY_BAND_2GHZ},
1092     * @param persist {@code true} if the setting should be remembered.
1093     *
1094     */
1095    public void setFrequencyBand(int band, boolean persist) {
1096        enforceChangePermission();
1097        if (!isDualBandSupported()) return;
1098        Slog.i(TAG, "WifiService trying to set frequency band to " + band +
1099                " with persist set to " + persist);
1100        final long token = Binder.clearCallingIdentity();
1101        try {
1102            mWifiStateMachine.setFrequencyBand(band, persist);
1103        } finally {
1104            Binder.restoreCallingIdentity(token);
1105        }
1106    }
1107
1108
1109    /**
1110     * Get the operational frequency band
1111     */
1112    public int getFrequencyBand() {
1113        enforceAccessPermission();
1114        return mWifiStateMachine.getFrequencyBand();
1115    }
1116
1117    public boolean isDualBandSupported() {
1118        //TODO: Should move towards adding a driver API that checks at runtime
1119        return mContext.getResources().getBoolean(
1120                com.android.internal.R.bool.config_wifi_dual_band_support);
1121    }
1122
1123    /**
1124     * Return the DHCP-assigned addresses from the last successful DHCP request,
1125     * if any.
1126     * @return the DHCP information
1127     * @deprecated
1128     */
1129    public DhcpInfo getDhcpInfo() {
1130        enforceAccessPermission();
1131        DhcpResults dhcpResults = mWifiStateMachine.syncGetDhcpResults();
1132
1133        DhcpInfo info = new DhcpInfo();
1134
1135        if (dhcpResults.ipAddress != null &&
1136                dhcpResults.ipAddress.getAddress() instanceof Inet4Address) {
1137            info.ipAddress = NetworkUtils.inetAddressToInt((Inet4Address) dhcpResults.ipAddress.getAddress());
1138        }
1139
1140        if (dhcpResults.gateway != null) {
1141            info.gateway = NetworkUtils.inetAddressToInt((Inet4Address) dhcpResults.gateway);
1142        }
1143
1144        int dnsFound = 0;
1145        for (InetAddress dns : dhcpResults.dnsServers) {
1146            if (dns instanceof Inet4Address) {
1147                if (dnsFound == 0) {
1148                    info.dns1 = NetworkUtils.inetAddressToInt((Inet4Address)dns);
1149                } else {
1150                    info.dns2 = NetworkUtils.inetAddressToInt((Inet4Address)dns);
1151                }
1152                if (++dnsFound > 1) break;
1153            }
1154        }
1155        InetAddress serverAddress = dhcpResults.serverAddress;
1156        if (serverAddress instanceof Inet4Address) {
1157            info.serverAddress = NetworkUtils.inetAddressToInt((Inet4Address)serverAddress);
1158        }
1159        info.leaseDuration = dhcpResults.leaseDuration;
1160
1161        return info;
1162    }
1163
1164    /**
1165     * see {@link android.net.wifi.WifiManager#startWifi}
1166     *
1167     */
1168    public void startWifi() {
1169        enforceConnectivityInternalPermission();
1170        /* TODO: may be add permissions for access only to connectivity service
1171         * TODO: if a start issued, keep wifi alive until a stop issued irrespective
1172         * of WifiLock & device idle status unless wifi enabled status is toggled
1173         */
1174
1175        mWifiStateMachine.setDriverStart(true);
1176        mWifiStateMachine.reconnectCommand();
1177    }
1178
1179    /**
1180     * see {@link android.net.wifi.WifiManager#stopWifi}
1181     *
1182     */
1183    public void stopWifi() {
1184        enforceConnectivityInternalPermission();
1185        /*
1186         * TODO: if a stop is issued, wifi is brought up only by startWifi
1187         * unless wifi enabled status is toggled
1188         */
1189        mWifiStateMachine.setDriverStart(false);
1190    }
1191
1192    /**
1193     * see {@link android.net.wifi.WifiManager#addToBlacklist}
1194     *
1195     */
1196    public void addToBlacklist(String bssid) {
1197        enforceChangePermission();
1198
1199        mWifiStateMachine.addToBlacklist(bssid);
1200    }
1201
1202    /**
1203     * see {@link android.net.wifi.WifiManager#clearBlacklist}
1204     *
1205     */
1206    public void clearBlacklist() {
1207        enforceChangePermission();
1208
1209        mWifiStateMachine.clearBlacklist();
1210    }
1211
1212    /**
1213     * enable TDLS for the local NIC to remote NIC
1214     * The APPs don't know the remote MAC address to identify NIC though,
1215     * so we need to do additional work to find it from remote IP address
1216     */
1217
1218    class TdlsTaskParams {
1219        public String remoteIpAddress;
1220        public boolean enable;
1221    }
1222
1223    class TdlsTask extends AsyncTask<TdlsTaskParams, Integer, Integer> {
1224        @Override
1225        protected Integer doInBackground(TdlsTaskParams... params) {
1226
1227            // Retrieve parameters for the call
1228            TdlsTaskParams param = params[0];
1229            String remoteIpAddress = param.remoteIpAddress.trim();
1230            boolean enable = param.enable;
1231
1232            // Get MAC address of Remote IP
1233            String macAddress = null;
1234
1235            BufferedReader reader = null;
1236
1237            try {
1238                reader = new BufferedReader(new FileReader("/proc/net/arp"));
1239
1240                // Skip over the line bearing colum titles
1241                String line = reader.readLine();
1242
1243                while ((line = reader.readLine()) != null) {
1244                    String[] tokens = line.split("[ ]+");
1245                    if (tokens.length < 6) {
1246                        continue;
1247                    }
1248
1249                    // ARP column format is
1250                    // Address HWType HWAddress Flags Mask IFace
1251                    String ip = tokens[0];
1252                    String mac = tokens[3];
1253
1254                    if (remoteIpAddress.equals(ip)) {
1255                        macAddress = mac;
1256                        break;
1257                    }
1258                }
1259
1260                if (macAddress == null) {
1261                    Slog.w(TAG, "Did not find remoteAddress {" + remoteIpAddress + "} in " +
1262                            "/proc/net/arp");
1263                } else {
1264                    enableTdlsWithMacAddress(macAddress, enable);
1265                }
1266
1267            } catch (FileNotFoundException e) {
1268                Slog.e(TAG, "Could not open /proc/net/arp to lookup mac address");
1269            } catch (IOException e) {
1270                Slog.e(TAG, "Could not read /proc/net/arp to lookup mac address");
1271            } finally {
1272                try {
1273                    if (reader != null) {
1274                        reader.close();
1275                    }
1276                }
1277                catch (IOException e) {
1278                    // Do nothing
1279                }
1280            }
1281
1282            return 0;
1283        }
1284    }
1285
1286    public void enableTdls(String remoteAddress, boolean enable) {
1287        if (remoteAddress == null) {
1288          throw new IllegalArgumentException("remoteAddress cannot be null");
1289        }
1290
1291        TdlsTaskParams params = new TdlsTaskParams();
1292        params.remoteIpAddress = remoteAddress;
1293        params.enable = enable;
1294        new TdlsTask().execute(params);
1295    }
1296
1297
1298    public void enableTdlsWithMacAddress(String remoteMacAddress, boolean enable) {
1299        if (remoteMacAddress == null) {
1300          throw new IllegalArgumentException("remoteMacAddress cannot be null");
1301        }
1302
1303        mWifiStateMachine.enableTdls(remoteMacAddress, enable);
1304    }
1305
1306    /**
1307     * Get a reference to handler. This is used by a client to establish
1308     * an AsyncChannel communication with WifiService
1309     */
1310    public Messenger getWifiServiceMessenger() {
1311        enforceAccessPermission();
1312        enforceChangePermission();
1313        return new Messenger(mClientHandler);
1314    }
1315
1316    /**
1317     * Disable an ephemeral network, i.e. network that is created thru a WiFi Scorer
1318     */
1319    public void disableEphemeralNetwork(String SSID) {
1320        enforceAccessPermission();
1321        enforceChangePermission();
1322        mWifiStateMachine.disableEphemeralNetwork(SSID);
1323    }
1324
1325    /**
1326     * Get the IP and proxy configuration file
1327     */
1328    public String getConfigFile() {
1329        enforceAccessPermission();
1330        return mWifiStateMachine.getConfigFile();
1331    }
1332
1333    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1334        @Override
1335        public void onReceive(Context context, Intent intent) {
1336            String action = intent.getAction();
1337            if (action.equals(Intent.ACTION_SCREEN_ON)) {
1338                mWifiController.sendMessage(CMD_SCREEN_ON);
1339            } else if (action.equals(Intent.ACTION_USER_PRESENT)) {
1340                mWifiController.sendMessage(CMD_USER_PRESENT);
1341            } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
1342                mWifiController.sendMessage(CMD_SCREEN_OFF);
1343            } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
1344                int pluggedType = intent.getIntExtra("plugged", 0);
1345                mWifiController.sendMessage(CMD_BATTERY_CHANGED, pluggedType, 0, null);
1346            } else if (action.equals(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED)) {
1347                int state = intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE,
1348                        BluetoothAdapter.STATE_DISCONNECTED);
1349                mWifiStateMachine.sendBluetoothAdapterStateChange(state);
1350            } else if (action.equals(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED)) {
1351                boolean emergencyMode = intent.getBooleanExtra("phoneinECMState", false);
1352                mWifiController.sendMessage(CMD_EMERGENCY_MODE_CHANGED, emergencyMode ? 1 : 0, 0);
1353            }
1354        }
1355    };
1356
1357    /**
1358     * Observes settings changes to scan always mode.
1359     */
1360    private void registerForScanModeChange() {
1361        ContentObserver contentObserver = new ContentObserver(null) {
1362            @Override
1363            public void onChange(boolean selfChange) {
1364                mSettingsStore.handleWifiScanAlwaysAvailableToggled();
1365                mWifiController.sendMessage(CMD_SCAN_ALWAYS_MODE_CHANGED);
1366            }
1367        };
1368
1369        mContext.getContentResolver().registerContentObserver(
1370                Settings.Global.getUriFor(Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE),
1371                false, contentObserver);
1372    }
1373
1374    private void registerForBroadcasts() {
1375        IntentFilter intentFilter = new IntentFilter();
1376        intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1377        intentFilter.addAction(Intent.ACTION_USER_PRESENT);
1378        intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1379        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1380        intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
1381        intentFilter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
1382        intentFilter.addAction(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED);
1383        mContext.registerReceiver(mReceiver, intentFilter);
1384    }
1385
1386    @Override
1387    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1388        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1389                != PackageManager.PERMISSION_GRANTED) {
1390            pw.println("Permission Denial: can't dump WifiService from from pid="
1391                    + Binder.getCallingPid()
1392                    + ", uid=" + Binder.getCallingUid());
1393            return;
1394        }
1395        pw.println("Wi-Fi is " + mWifiStateMachine.syncGetWifiStateByName());
1396        pw.println("Stay-awake conditions: " +
1397                Settings.Global.getInt(mContext.getContentResolver(),
1398                                       Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0));
1399        pw.println("mMulticastEnabled " + mMulticastEnabled);
1400        pw.println("mMulticastDisabled " + mMulticastDisabled);
1401        mWifiController.dump(fd, pw, args);
1402        mSettingsStore.dump(fd, pw, args);
1403        mNotificationController.dump(fd, pw, args);
1404        mTrafficPoller.dump(fd, pw, args);
1405
1406        pw.println("Latest scan results:");
1407        List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
1408        long nowMs = System.currentTimeMillis();
1409        if (scanResults != null && scanResults.size() != 0) {
1410            pw.println("    BSSID              Frequency  RSSI    Age      SSID " +
1411                    "                                Flags");
1412            for (ScanResult r : scanResults) {
1413                long ageSec = 0;
1414                long ageMilli = 0;
1415                if (nowMs > r.seen && r.seen > 0) {
1416                    ageSec = (nowMs - r.seen) / 1000;
1417                    ageMilli = (nowMs - r.seen) % 1000;
1418                }
1419                String candidate = " ";
1420                if (r.isAutoJoinCandidate > 0) candidate = "+";
1421                pw.printf("  %17s  %9d  %5d  %3d.%03d%s   %-32s  %s\n",
1422                                         r.BSSID,
1423                                         r.frequency,
1424                                         r.level,
1425                                         ageSec, ageMilli,
1426                                         candidate,
1427                                         r.SSID == null ? "" : r.SSID,
1428                                         r.capabilities);
1429            }
1430        }
1431        pw.println();
1432        pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
1433                mFullHighPerfLocksAcquired + " full high perf, " +
1434                mScanLocksAcquired + " scan");
1435        pw.println("Locks released: " + mFullLocksReleased + " full, " +
1436                mFullHighPerfLocksReleased + " full high perf, " +
1437                mScanLocksReleased + " scan");
1438        pw.println();
1439        pw.println("Locks held:");
1440        mLocks.dump(pw);
1441
1442        mWifiWatchdogStateMachine.dump(fd, pw, args);
1443        pw.println();
1444        mWifiStateMachine.dump(fd, pw, args);
1445        pw.println();
1446    }
1447
1448    private class WifiLock extends DeathRecipient {
1449        WifiLock(int lockMode, String tag, IBinder binder, WorkSource ws) {
1450            super(lockMode, tag, binder, ws);
1451        }
1452
1453        public void binderDied() {
1454            synchronized (mLocks) {
1455                releaseWifiLockLocked(mBinder);
1456            }
1457        }
1458
1459        public String toString() {
1460            return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
1461        }
1462    }
1463
1464    class LockList {
1465        private List<WifiLock> mList;
1466
1467        private LockList() {
1468            mList = new ArrayList<WifiLock>();
1469        }
1470
1471        synchronized boolean hasLocks() {
1472            return !mList.isEmpty();
1473        }
1474
1475        synchronized int getStrongestLockMode() {
1476            if (mList.isEmpty()) {
1477                return WifiManager.WIFI_MODE_FULL;
1478            }
1479
1480            if (mFullHighPerfLocksAcquired > mFullHighPerfLocksReleased) {
1481                return WifiManager.WIFI_MODE_FULL_HIGH_PERF;
1482            }
1483
1484            if (mFullLocksAcquired > mFullLocksReleased) {
1485                return WifiManager.WIFI_MODE_FULL;
1486            }
1487
1488            return WifiManager.WIFI_MODE_SCAN_ONLY;
1489        }
1490
1491        synchronized void updateWorkSource(WorkSource ws) {
1492            for (int i = 0; i < mLocks.mList.size(); i++) {
1493                ws.add(mLocks.mList.get(i).mWorkSource);
1494            }
1495        }
1496
1497        private void addLock(WifiLock lock) {
1498            if (findLockByBinder(lock.mBinder) < 0) {
1499                mList.add(lock);
1500            }
1501        }
1502
1503        private WifiLock removeLock(IBinder binder) {
1504            int index = findLockByBinder(binder);
1505            if (index >= 0) {
1506                WifiLock ret = mList.remove(index);
1507                ret.unlinkDeathRecipient();
1508                return ret;
1509            } else {
1510                return null;
1511            }
1512        }
1513
1514        private int findLockByBinder(IBinder binder) {
1515            int size = mList.size();
1516            for (int i = size - 1; i >= 0; i--) {
1517                if (mList.get(i).mBinder == binder)
1518                    return i;
1519            }
1520            return -1;
1521        }
1522
1523        private void dump(PrintWriter pw) {
1524            for (WifiLock l : mList) {
1525                pw.print("    ");
1526                pw.println(l);
1527            }
1528        }
1529    }
1530
1531    void enforceWakeSourcePermission(int uid, int pid) {
1532        if (uid == android.os.Process.myUid()) {
1533            return;
1534        }
1535        mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
1536                pid, uid, null);
1537    }
1538
1539    public boolean acquireWifiLock(IBinder binder, int lockMode, String tag, WorkSource ws) {
1540        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1541        if (lockMode != WifiManager.WIFI_MODE_FULL &&
1542                lockMode != WifiManager.WIFI_MODE_SCAN_ONLY &&
1543                lockMode != WifiManager.WIFI_MODE_FULL_HIGH_PERF) {
1544            Slog.e(TAG, "Illegal argument, lockMode= " + lockMode);
1545            if (DBG) throw new IllegalArgumentException("lockMode=" + lockMode);
1546            return false;
1547        }
1548        if (ws != null && ws.size() == 0) {
1549            ws = null;
1550        }
1551        if (ws != null) {
1552            enforceWakeSourcePermission(Binder.getCallingUid(), Binder.getCallingPid());
1553        }
1554        if (ws == null) {
1555            ws = new WorkSource(Binder.getCallingUid());
1556        }
1557        WifiLock wifiLock = new WifiLock(lockMode, tag, binder, ws);
1558        synchronized (mLocks) {
1559            return acquireWifiLockLocked(wifiLock);
1560        }
1561    }
1562
1563    private void noteAcquireWifiLock(WifiLock wifiLock) throws RemoteException {
1564        switch(wifiLock.mMode) {
1565            case WifiManager.WIFI_MODE_FULL:
1566            case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
1567            case WifiManager.WIFI_MODE_SCAN_ONLY:
1568                mBatteryStats.noteFullWifiLockAcquiredFromSource(wifiLock.mWorkSource);
1569                break;
1570        }
1571    }
1572
1573    private void noteReleaseWifiLock(WifiLock wifiLock) throws RemoteException {
1574        switch(wifiLock.mMode) {
1575            case WifiManager.WIFI_MODE_FULL:
1576            case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
1577            case WifiManager.WIFI_MODE_SCAN_ONLY:
1578                mBatteryStats.noteFullWifiLockReleasedFromSource(wifiLock.mWorkSource);
1579                break;
1580        }
1581    }
1582
1583    private boolean acquireWifiLockLocked(WifiLock wifiLock) {
1584        if (DBG) Slog.d(TAG, "acquireWifiLockLocked: " + wifiLock);
1585
1586        mLocks.addLock(wifiLock);
1587
1588        long ident = Binder.clearCallingIdentity();
1589        try {
1590            noteAcquireWifiLock(wifiLock);
1591            switch(wifiLock.mMode) {
1592            case WifiManager.WIFI_MODE_FULL:
1593                ++mFullLocksAcquired;
1594                break;
1595            case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
1596                ++mFullHighPerfLocksAcquired;
1597                break;
1598
1599            case WifiManager.WIFI_MODE_SCAN_ONLY:
1600                ++mScanLocksAcquired;
1601                break;
1602            }
1603            mWifiController.sendMessage(CMD_LOCKS_CHANGED);
1604            return true;
1605        } catch (RemoteException e) {
1606            return false;
1607        } finally {
1608            Binder.restoreCallingIdentity(ident);
1609        }
1610    }
1611
1612    public void updateWifiLockWorkSource(IBinder lock, WorkSource ws) {
1613        int uid = Binder.getCallingUid();
1614        int pid = Binder.getCallingPid();
1615        if (ws != null && ws.size() == 0) {
1616            ws = null;
1617        }
1618        if (ws != null) {
1619            enforceWakeSourcePermission(uid, pid);
1620        }
1621        long ident = Binder.clearCallingIdentity();
1622        try {
1623            synchronized (mLocks) {
1624                int index = mLocks.findLockByBinder(lock);
1625                if (index < 0) {
1626                    throw new IllegalArgumentException("Wifi lock not active");
1627                }
1628                WifiLock wl = mLocks.mList.get(index);
1629                noteReleaseWifiLock(wl);
1630                wl.mWorkSource = ws != null ? new WorkSource(ws) : new WorkSource(uid);
1631                noteAcquireWifiLock(wl);
1632            }
1633        } catch (RemoteException e) {
1634        } finally {
1635            Binder.restoreCallingIdentity(ident);
1636        }
1637    }
1638
1639    public boolean releaseWifiLock(IBinder lock) {
1640        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1641        synchronized (mLocks) {
1642            return releaseWifiLockLocked(lock);
1643        }
1644    }
1645
1646    private boolean releaseWifiLockLocked(IBinder lock) {
1647        boolean hadLock;
1648
1649        WifiLock wifiLock = mLocks.removeLock(lock);
1650
1651        if (DBG) Slog.d(TAG, "releaseWifiLockLocked: " + wifiLock);
1652
1653        hadLock = (wifiLock != null);
1654
1655        long ident = Binder.clearCallingIdentity();
1656        try {
1657            if (hadLock) {
1658                noteReleaseWifiLock(wifiLock);
1659                switch(wifiLock.mMode) {
1660                    case WifiManager.WIFI_MODE_FULL:
1661                        ++mFullLocksReleased;
1662                        break;
1663                    case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
1664                        ++mFullHighPerfLocksReleased;
1665                        break;
1666                    case WifiManager.WIFI_MODE_SCAN_ONLY:
1667                        ++mScanLocksReleased;
1668                        break;
1669                }
1670                mWifiController.sendMessage(CMD_LOCKS_CHANGED);
1671            }
1672        } catch (RemoteException e) {
1673        } finally {
1674            Binder.restoreCallingIdentity(ident);
1675        }
1676
1677        return hadLock;
1678    }
1679
1680    private abstract class DeathRecipient
1681            implements IBinder.DeathRecipient {
1682        String mTag;
1683        int mMode;
1684        IBinder mBinder;
1685        WorkSource mWorkSource;
1686
1687        DeathRecipient(int mode, String tag, IBinder binder, WorkSource ws) {
1688            super();
1689            mTag = tag;
1690            mMode = mode;
1691            mBinder = binder;
1692            mWorkSource = ws;
1693            try {
1694                mBinder.linkToDeath(this, 0);
1695            } catch (RemoteException e) {
1696                binderDied();
1697            }
1698        }
1699
1700        void unlinkDeathRecipient() {
1701            mBinder.unlinkToDeath(this, 0);
1702        }
1703    }
1704
1705    private class Multicaster extends DeathRecipient {
1706        Multicaster(String tag, IBinder binder) {
1707            super(Binder.getCallingUid(), tag, binder, null);
1708        }
1709
1710        public void binderDied() {
1711            Slog.e(TAG, "Multicaster binderDied");
1712            synchronized (mMulticasters) {
1713                int i = mMulticasters.indexOf(this);
1714                if (i != -1) {
1715                    removeMulticasterLocked(i, mMode);
1716                }
1717            }
1718        }
1719
1720        public String toString() {
1721            return "Multicaster{" + mTag + " binder=" + mBinder + "}";
1722        }
1723
1724        public int getUid() {
1725            return mMode;
1726        }
1727    }
1728
1729    public void initializeMulticastFiltering() {
1730        enforceMulticastChangePermission();
1731
1732        synchronized (mMulticasters) {
1733            // if anybody had requested filters be off, leave off
1734            if (mMulticasters.size() != 0) {
1735                return;
1736            } else {
1737                mWifiStateMachine.startFilteringMulticastV4Packets();
1738            }
1739        }
1740    }
1741
1742    public void acquireMulticastLock(IBinder binder, String tag) {
1743        enforceMulticastChangePermission();
1744
1745        synchronized (mMulticasters) {
1746            mMulticastEnabled++;
1747            mMulticasters.add(new Multicaster(tag, binder));
1748            // Note that we could call stopFilteringMulticastV4Packets only when
1749            // our new size == 1 (first call), but this function won't
1750            // be called often and by making the stopPacket call each
1751            // time we're less fragile and self-healing.
1752            mWifiStateMachine.stopFilteringMulticastV4Packets();
1753        }
1754
1755        int uid = Binder.getCallingUid();
1756        final long ident = Binder.clearCallingIdentity();
1757        try {
1758            mBatteryStats.noteWifiMulticastEnabled(uid);
1759        } catch (RemoteException e) {
1760        } finally {
1761            Binder.restoreCallingIdentity(ident);
1762        }
1763    }
1764
1765    public void releaseMulticastLock() {
1766        enforceMulticastChangePermission();
1767
1768        int uid = Binder.getCallingUid();
1769        synchronized (mMulticasters) {
1770            mMulticastDisabled++;
1771            int size = mMulticasters.size();
1772            for (int i = size - 1; i >= 0; i--) {
1773                Multicaster m = mMulticasters.get(i);
1774                if ((m != null) && (m.getUid() == uid)) {
1775                    removeMulticasterLocked(i, uid);
1776                }
1777            }
1778        }
1779    }
1780
1781    private void removeMulticasterLocked(int i, int uid)
1782    {
1783        Multicaster removed = mMulticasters.remove(i);
1784
1785        if (removed != null) {
1786            removed.unlinkDeathRecipient();
1787        }
1788        if (mMulticasters.size() == 0) {
1789            mWifiStateMachine.startFilteringMulticastV4Packets();
1790        }
1791
1792        final long ident = Binder.clearCallingIdentity();
1793        try {
1794            mBatteryStats.noteWifiMulticastDisabled(uid);
1795        } catch (RemoteException e) {
1796        } finally {
1797            Binder.restoreCallingIdentity(ident);
1798        }
1799    }
1800
1801    public boolean isMulticastEnabled() {
1802        enforceAccessPermission();
1803
1804        synchronized (mMulticasters) {
1805            return (mMulticasters.size() > 0);
1806        }
1807    }
1808
1809    public WifiMonitor getWifiMonitor() {
1810        return mWifiStateMachine.getWifiMonitor();
1811    }
1812
1813    public void enableVerboseLogging(int verbose) {
1814        enforceAccessPermission();
1815        mWifiStateMachine.enableVerboseLogging(verbose);
1816    }
1817
1818    public int getVerboseLoggingLevel() {
1819        enforceAccessPermission();
1820        return mWifiStateMachine.getVerboseLoggingLevel();
1821    }
1822
1823    public void enableAggressiveHandover(int enabled) {
1824        enforceAccessPermission();
1825        mWifiStateMachine.enableAggressiveHandover(enabled);
1826    }
1827
1828    public int getAggressiveHandover() {
1829        enforceAccessPermission();
1830        return mWifiStateMachine.getAggressiveHandover();
1831    }
1832
1833    public void setAllowScansWithTraffic(int enabled) {
1834        enforceAccessPermission();
1835        mWifiStateMachine.setAllowScansWithTraffic(enabled);
1836    }
1837
1838    public int getAllowScansWithTraffic() {
1839        enforceAccessPermission();
1840        return mWifiStateMachine.getAllowScansWithTraffic();
1841    }
1842
1843    /* Return the Wifi Connection statistics object */
1844    public WifiConnectionStatistics getConnectionStatistics() {
1845        enforceAccessPermission();
1846        enforceReadCredentialPermission();
1847        if (mWifiStateMachineChannel != null) {
1848            return mWifiStateMachine.syncGetConnectionStatistics(mWifiStateMachineChannel);
1849        } else {
1850            Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
1851            return null;
1852        }
1853    }
1854}
1855