WifiMonitor.java revision e57857d829f670c62e8d53ffed580681271a272b
1/*
2 * Copyright (C) 2008 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.net.NetworkInfo;
20import android.net.wifi.SupplicantState;
21import android.net.wifi.WifiManager;
22import android.net.wifi.WifiSsid;
23import android.net.wifi.p2p.WifiP2pConfig;
24import android.net.wifi.p2p.WifiP2pDevice;
25import android.net.wifi.p2p.WifiP2pGroup;
26import android.net.wifi.p2p.WifiP2pProvDiscEvent;
27import android.net.wifi.p2p.nsd.WifiP2pServiceResponse;
28import android.os.Message;
29import android.os.SystemClock;
30import android.util.Log;
31
32import com.android.server.wifi.p2p.WifiP2pServiceImpl.P2pStatus;
33
34import com.android.internal.util.Protocol;
35import com.android.internal.util.StateMachine;
36
37import java.util.HashMap;
38import java.util.List;
39import java.util.regex.Matcher;
40import java.util.regex.Pattern;
41
42/**
43 * Listens for events from the wpa_supplicant server, and passes them on
44 * to the {@link StateMachine} for handling. Runs in its own thread.
45 *
46 * @hide
47 */
48public class WifiMonitor {
49
50    private static final boolean DBG = false;
51    private static final String TAG = "WifiMonitor";
52
53    /** Events we receive from the supplicant daemon */
54
55    private static final int CONNECTED    = 1;
56    private static final int DISCONNECTED = 2;
57    private static final int STATE_CHANGE = 3;
58    private static final int SCAN_RESULTS = 4;
59    private static final int LINK_SPEED   = 5;
60    private static final int TERMINATING  = 6;
61    private static final int DRIVER_STATE = 7;
62    private static final int EAP_FAILURE  = 8;
63    private static final int ASSOC_REJECT = 9;
64    private static final int SSID_TEMP_DISABLED = 10;
65    private static final int UNKNOWN      = 11;
66
67    /** All events coming from the supplicant start with this prefix */
68    private static final String EVENT_PREFIX_STR = "CTRL-EVENT-";
69    private static final int EVENT_PREFIX_LEN_STR = EVENT_PREFIX_STR.length();
70
71    /** All WPA events coming from the supplicant start with this prefix */
72    private static final String WPA_EVENT_PREFIX_STR = "WPA:";
73    private static final String PASSWORD_MAY_BE_INCORRECT_STR =
74       "pre-shared key may be incorrect";
75
76    /* WPS events */
77    private static final String WPS_SUCCESS_STR = "WPS-SUCCESS";
78
79    /* Format: WPS-FAIL msg=%d [config_error=%d] [reason=%d (%s)] */
80    private static final String WPS_FAIL_STR    = "WPS-FAIL";
81    private static final String WPS_FAIL_PATTERN =
82            "WPS-FAIL msg=\\d+(?: config_error=(\\d+))?(?: reason=(\\d+))?";
83
84    /* config error code values for config_error=%d */
85    private static final int CONFIG_MULTIPLE_PBC_DETECTED = 12;
86    private static final int CONFIG_AUTH_FAILURE = 18;
87
88    /* reason code values for reason=%d */
89    private static final int REASON_TKIP_ONLY_PROHIBITED = 1;
90    private static final int REASON_WEP_PROHIBITED = 2;
91
92    private static final String WPS_OVERLAP_STR = "WPS-OVERLAP-DETECTED";
93    private static final String WPS_TIMEOUT_STR = "WPS-TIMEOUT";
94
95    /**
96     * Names of events from wpa_supplicant (minus the prefix). In the
97     * format descriptions, * &quot;<code>x</code>&quot;
98     * designates a dynamic value that needs to be parsed out from the event
99     * string
100     */
101    /**
102     * <pre>
103     * CTRL-EVENT-CONNECTED - Connection to xx:xx:xx:xx:xx:xx completed
104     * </pre>
105     * <code>xx:xx:xx:xx:xx:xx</code> is the BSSID of the associated access point
106     */
107    private static final String CONNECTED_STR =    "CONNECTED";
108    /**
109     * <pre>
110     * CTRL-EVENT-DISCONNECTED - Disconnect event - remove keys
111     * </pre>
112     */
113    private static final String DISCONNECTED_STR = "DISCONNECTED";
114    /**
115     * <pre>
116     * CTRL-EVENT-STATE-CHANGE x
117     * </pre>
118     * <code>x</code> is the numerical value of the new state.
119     */
120    private static final String STATE_CHANGE_STR =  "STATE-CHANGE";
121    /**
122     * <pre>
123     * CTRL-EVENT-SCAN-RESULTS ready
124     * </pre>
125     */
126    private static final String SCAN_RESULTS_STR =  "SCAN-RESULTS";
127
128    /**
129     * <pre>
130     * CTRL-EVENT-LINK-SPEED x Mb/s
131     * </pre>
132     * {@code x} is the link speed in Mb/sec.
133     */
134    private static final String LINK_SPEED_STR = "LINK-SPEED";
135    /**
136     * <pre>
137     * CTRL-EVENT-TERMINATING - signal x
138     * </pre>
139     * <code>x</code> is the signal that caused termination.
140     */
141    private static final String TERMINATING_STR =  "TERMINATING";
142    /**
143     * <pre>
144     * CTRL-EVENT-DRIVER-STATE state
145     * </pre>
146     * <code>state</code> can be HANGED
147     */
148    private static final String DRIVER_STATE_STR = "DRIVER-STATE";
149    /**
150     * <pre>
151     * CTRL-EVENT-EAP-FAILURE EAP authentication failed
152     * </pre>
153     */
154    private static final String EAP_FAILURE_STR = "EAP-FAILURE";
155
156    /**
157     * This indicates an authentication failure on EAP FAILURE event
158     */
159    private static final String EAP_AUTH_FAILURE_STR = "EAP authentication failed";
160
161    /**
162     * This indicates an assoc reject event
163     */
164    private static final String ASSOC_REJECT_STR = "ASSOC-REJECT";
165
166    /**
167     * This indicates auth or association failure bad enough so as network got disabled
168     * - WPA_PSK auth failure suspecting shared key mismatch
169     * - failed 3 Association
170     */
171    private static final String TEMP_DISABLED_STR = "SSID-TEMP-DISABLED";
172
173
174    /**
175     * Regex pattern for extracting an Ethernet-style MAC address from a string.
176     * Matches a strings like the following:<pre>
177     * CTRL-EVENT-CONNECTED - Connection to 00:1e:58:ec:d5:6d completed (reauth) [id=1 id_str=]</pre>
178     */
179    private static Pattern mConnectedEventPattern =
180        Pattern.compile("((?:[0-9a-f]{2}:){5}[0-9a-f]{2}) .* \\[id=([0-9]+) ");
181
182    /** P2P events */
183    private static final String P2P_EVENT_PREFIX_STR = "P2P";
184
185    /* P2P-DEVICE-FOUND fa:7b:7a:42:02:13 p2p_dev_addr=fa:7b:7a:42:02:13 pri_dev_type=1-0050F204-1
186       name='p2p-TEST1' config_methods=0x188 dev_capab=0x27 group_capab=0x0 */
187    private static final String P2P_DEVICE_FOUND_STR = "P2P-DEVICE-FOUND";
188
189    /* P2P-DEVICE-LOST p2p_dev_addr=42:fc:89:e1:e2:27 */
190    private static final String P2P_DEVICE_LOST_STR = "P2P-DEVICE-LOST";
191
192    /* P2P-FIND-STOPPED */
193    private static final String P2P_FIND_STOPPED_STR = "P2P-FIND-STOPPED";
194
195    /* P2P-GO-NEG-REQUEST 42:fc:89:a8:96:09 dev_passwd_id=4 */
196    private static final String P2P_GO_NEG_REQUEST_STR = "P2P-GO-NEG-REQUEST";
197
198    private static final String P2P_GO_NEG_SUCCESS_STR = "P2P-GO-NEG-SUCCESS";
199
200    /* P2P-GO-NEG-FAILURE status=x */
201    private static final String P2P_GO_NEG_FAILURE_STR = "P2P-GO-NEG-FAILURE";
202
203    private static final String P2P_GROUP_FORMATION_SUCCESS_STR =
204            "P2P-GROUP-FORMATION-SUCCESS";
205
206    private static final String P2P_GROUP_FORMATION_FAILURE_STR =
207            "P2P-GROUP-FORMATION-FAILURE";
208
209    /* P2P-GROUP-STARTED p2p-wlan0-0 [client|GO] ssid="DIRECT-W8" freq=2437
210       [psk=2182b2e50e53f260d04f3c7b25ef33c965a3291b9b36b455a82d77fd82ca15bc|passphrase="fKG4jMe3"]
211       go_dev_addr=fa:7b:7a:42:02:13 [PERSISTENT] */
212    private static final String P2P_GROUP_STARTED_STR = "P2P-GROUP-STARTED";
213
214    /* P2P-GROUP-REMOVED p2p-wlan0-0 [client|GO] reason=REQUESTED */
215    private static final String P2P_GROUP_REMOVED_STR = "P2P-GROUP-REMOVED";
216
217    /* P2P-INVITATION-RECEIVED sa=fa:7b:7a:42:02:13 go_dev_addr=f8:7b:7a:42:02:13
218        bssid=fa:7b:7a:42:82:13 unknown-network */
219    private static final String P2P_INVITATION_RECEIVED_STR = "P2P-INVITATION-RECEIVED";
220
221    /* P2P-INVITATION-RESULT status=1 */
222    private static final String P2P_INVITATION_RESULT_STR = "P2P-INVITATION-RESULT";
223
224    /* P2P-PROV-DISC-PBC-REQ 42:fc:89:e1:e2:27 p2p_dev_addr=42:fc:89:e1:e2:27
225       pri_dev_type=1-0050F204-1 name='p2p-TEST2' config_methods=0x188 dev_capab=0x27
226       group_capab=0x0 */
227    private static final String P2P_PROV_DISC_PBC_REQ_STR = "P2P-PROV-DISC-PBC-REQ";
228
229    /* P2P-PROV-DISC-PBC-RESP 02:12:47:f2:5a:36 */
230    private static final String P2P_PROV_DISC_PBC_RSP_STR = "P2P-PROV-DISC-PBC-RESP";
231
232    /* P2P-PROV-DISC-ENTER-PIN 42:fc:89:e1:e2:27 p2p_dev_addr=42:fc:89:e1:e2:27
233       pri_dev_type=1-0050F204-1 name='p2p-TEST2' config_methods=0x188 dev_capab=0x27
234       group_capab=0x0 */
235    private static final String P2P_PROV_DISC_ENTER_PIN_STR = "P2P-PROV-DISC-ENTER-PIN";
236    /* P2P-PROV-DISC-SHOW-PIN 42:fc:89:e1:e2:27 44490607 p2p_dev_addr=42:fc:89:e1:e2:27
237       pri_dev_type=1-0050F204-1 name='p2p-TEST2' config_methods=0x188 dev_capab=0x27
238       group_capab=0x0 */
239    private static final String P2P_PROV_DISC_SHOW_PIN_STR = "P2P-PROV-DISC-SHOW-PIN";
240    /* P2P-PROV-DISC-FAILURE p2p_dev_addr=42:fc:89:e1:e2:27 */
241    private static final String P2P_PROV_DISC_FAILURE_STR = "P2P-PROV-DISC-FAILURE";
242
243    /*
244     * Protocol format is as follows.<br>
245     * See the Table.62 in the WiFi Direct specification for the detail.
246     * ______________________________________________________________
247     * |           Length(2byte)     | Type(1byte) | TransId(1byte)}|
248     * ______________________________________________________________
249     * | status(1byte)  |            vendor specific(variable)      |
250     *
251     * P2P-SERV-DISC-RESP 42:fc:89:e1:e2:27 1 0300000101
252     * length=3, service type=0(ALL Service), transaction id=1,
253     * status=1(service protocol type not available)<br>
254     *
255     * P2P-SERV-DISC-RESP 42:fc:89:e1:e2:27 1 0300020201
256     * length=3, service type=2(UPnP), transaction id=2,
257     * status=1(service protocol type not available)
258     *
259     * P2P-SERV-DISC-RESP 42:fc:89:e1:e2:27 1 990002030010757569643a3131323
260     * 2646534652d383537342d353961622d393332322d3333333435363738393034343a3
261     * a75726e3a736368656d61732d75706e702d6f72673a736572766963653a436f6e746
262     * 56e744469726563746f72793a322c757569643a36383539646564652d383537342d3
263     * 53961622d393333322d3132333435363738393031323a3a75706e703a726f6f74646
264     * 576696365
265     * length=153,type=2(UPnP),transaction id=3,status=0
266     *
267     * UPnP Protocol format is as follows.
268     * ______________________________________________________
269     * |  Version (1)  |          USN (Variable)            |
270     *
271     * version=0x10(UPnP1.0) data=usn:uuid:1122de4e-8574-59ab-9322-33345678
272     * 9044::urn:schemas-upnp-org:service:ContentDirectory:2,usn:uuid:6859d
273     * ede-8574-59ab-9332-123456789012::upnp:rootdevice
274     *
275     * P2P-SERV-DISC-RESP 58:17:0c:bc:dd:ca 21 1900010200045f6970
276     * 70c00c000c01094d795072696e746572c027
277     * length=25, type=1(Bonjour),transaction id=2,status=0
278     *
279     * Bonjour Protocol format is as follows.
280     * __________________________________________________________
281     * |DNS Name(Variable)|DNS Type(1)|Version(1)|RDATA(Variable)|
282     *
283     * DNS Name=_ipp._tcp.local.,DNS type=12(PTR), Version=1,
284     * RDATA=MyPrinter._ipp._tcp.local.
285     *
286     */
287    private static final String P2P_SERV_DISC_RESP_STR = "P2P-SERV-DISC-RESP";
288
289    private static final String HOST_AP_EVENT_PREFIX_STR = "AP";
290    /* AP-STA-CONNECTED 42:fc:89:a8:96:09 dev_addr=02:90:4c:a0:92:54 */
291    private static final String AP_STA_CONNECTED_STR = "AP-STA-CONNECTED";
292    /* AP-STA-DISCONNECTED 42:fc:89:a8:96:09 */
293    private static final String AP_STA_DISCONNECTED_STR = "AP-STA-DISCONNECTED";
294
295    /* Supplicant events reported to a state machine */
296    private static final int BASE = Protocol.BASE_WIFI_MONITOR;
297
298    /* Connection to supplicant established */
299    public static final int SUP_CONNECTION_EVENT                 = BASE + 1;
300    /* Connection to supplicant lost */
301    public static final int SUP_DISCONNECTION_EVENT              = BASE + 2;
302   /* Network connection completed */
303    public static final int NETWORK_CONNECTION_EVENT             = BASE + 3;
304    /* Network disconnection completed */
305    public static final int NETWORK_DISCONNECTION_EVENT          = BASE + 4;
306    /* Scan results are available */
307    public static final int SCAN_RESULTS_EVENT                   = BASE + 5;
308    /* Supplicate state changed */
309    public static final int SUPPLICANT_STATE_CHANGE_EVENT        = BASE + 6;
310    /* Password failure and EAP authentication failure */
311    public static final int AUTHENTICATION_FAILURE_EVENT         = BASE + 7;
312    /* WPS success detected */
313    public static final int WPS_SUCCESS_EVENT                    = BASE + 8;
314    /* WPS failure detected */
315    public static final int WPS_FAIL_EVENT                       = BASE + 9;
316     /* WPS overlap detected */
317    public static final int WPS_OVERLAP_EVENT                    = BASE + 10;
318     /* WPS timeout detected */
319    public static final int WPS_TIMEOUT_EVENT                    = BASE + 11;
320    /* Driver was hung */
321    public static final int DRIVER_HUNG_EVENT                    = BASE + 12;
322
323    /* P2P events */
324    public static final int P2P_DEVICE_FOUND_EVENT               = BASE + 21;
325    public static final int P2P_DEVICE_LOST_EVENT                = BASE + 22;
326    public static final int P2P_GO_NEGOTIATION_REQUEST_EVENT     = BASE + 23;
327    public static final int P2P_GO_NEGOTIATION_SUCCESS_EVENT     = BASE + 25;
328    public static final int P2P_GO_NEGOTIATION_FAILURE_EVENT     = BASE + 26;
329    public static final int P2P_GROUP_FORMATION_SUCCESS_EVENT    = BASE + 27;
330    public static final int P2P_GROUP_FORMATION_FAILURE_EVENT    = BASE + 28;
331    public static final int P2P_GROUP_STARTED_EVENT              = BASE + 29;
332    public static final int P2P_GROUP_REMOVED_EVENT              = BASE + 30;
333    public static final int P2P_INVITATION_RECEIVED_EVENT        = BASE + 31;
334    public static final int P2P_INVITATION_RESULT_EVENT          = BASE + 32;
335    public static final int P2P_PROV_DISC_PBC_REQ_EVENT          = BASE + 33;
336    public static final int P2P_PROV_DISC_PBC_RSP_EVENT          = BASE + 34;
337    public static final int P2P_PROV_DISC_ENTER_PIN_EVENT        = BASE + 35;
338    public static final int P2P_PROV_DISC_SHOW_PIN_EVENT         = BASE + 36;
339    public static final int P2P_FIND_STOPPED_EVENT               = BASE + 37;
340    public static final int P2P_SERV_DISC_RESP_EVENT             = BASE + 38;
341    public static final int P2P_PROV_DISC_FAILURE_EVENT          = BASE + 39;
342
343    /* hostap events */
344    public static final int AP_STA_DISCONNECTED_EVENT            = BASE + 41;
345    public static final int AP_STA_CONNECTED_EVENT               = BASE + 42;
346
347    /* Indicates assoc reject event */
348    public static final int ASSOCIATION_REJECTION_EVENT          = BASE + 43;
349
350    /**
351     * This indicates a read error on the monitor socket conenction
352     */
353    private static final String WPA_RECV_ERROR_STR = "recv error";
354
355    /**
356     * Max errors before we close supplicant connection
357     */
358    private static final int MAX_RECV_ERRORS    = 10;
359
360    private final String mInterfaceName;
361    private final WifiNative mWifiNative;
362    private final StateMachine mStateMachine;
363    private boolean mMonitoring;
364
365    // This is a global counter, since it's not monitor specific. However, the existing
366    // implementation forwards all "global" control events like CTRL-EVENT-TERMINATING
367    // to the p2p0 monitor. Is that expected ? It seems a bit surprising.
368    //
369    // TODO: If the p2p0 monitor isn't registered, the behaviour is even more surprising.
370    // The event will be dispatched to all monitors, and each of them will end up incrementing
371    // it in their dispatchXXX method. If we have 5 registered monitors (say), 2 consecutive
372    // recv errors will cause us to disconnect from the supplicant (instead of the intended 10).
373    //
374    // This variable is always accessed and modified under a WifiMonitorSingleton lock.
375    private static int sRecvErrors;
376
377    public WifiMonitor(StateMachine wifiStateMachine, WifiNative wifiNative) {
378        if (DBG) Log.d(TAG, "Creating WifiMonitor");
379        mWifiNative = wifiNative;
380        mInterfaceName = wifiNative.mInterfaceName;
381        mStateMachine = wifiStateMachine;
382        mMonitoring = false;
383
384        WifiMonitorSingleton.sInstance.registerInterfaceMonitor(mInterfaceName, this);
385    }
386
387    public void startMonitoring() {
388        WifiMonitorSingleton.sInstance.startMonitoring(mInterfaceName);
389    }
390
391    public void stopMonitoring() {
392        WifiMonitorSingleton.sInstance.stopMonitoring(mInterfaceName);
393    }
394
395    public void stopSupplicant() {
396        WifiMonitorSingleton.sInstance.stopSupplicant();
397    }
398
399    public void killSupplicant(boolean p2pSupported) {
400        WifiMonitorSingleton.sInstance.killSupplicant(p2pSupported);
401    }
402
403    private static class WifiMonitorSingleton {
404        private static final WifiMonitorSingleton sInstance = new WifiMonitorSingleton();
405
406        private final HashMap<String, WifiMonitor> mIfaceMap = new HashMap<String, WifiMonitor>();
407        private boolean mConnected = false;
408        private WifiNative mWifiNative;
409
410        private WifiMonitorSingleton() {
411        }
412
413        public synchronized void startMonitoring(String iface) {
414            WifiMonitor m = mIfaceMap.get(iface);
415            if (m == null) {
416                Log.e(TAG, "startMonitor called with unknown iface=" + iface);
417                return;
418            }
419
420            Log.d(TAG, "startMonitoring(" + iface + ") with mConnected = " + mConnected);
421
422            if (mConnected) {
423                m.mMonitoring = true;
424                m.mStateMachine.sendMessage(SUP_CONNECTION_EVENT);
425            } else {
426                if (DBG) Log.d(TAG, "connecting to supplicant");
427                int connectTries = 0;
428                while (true) {
429                    if (mWifiNative.connectToSupplicant()) {
430                        m.mMonitoring = true;
431                        m.mStateMachine.sendMessage(SUP_CONNECTION_EVENT);
432                        new MonitorThread(mWifiNative, this).start();
433                        mConnected = true;
434                        break;
435                    }
436                    if (connectTries++ < 5) {
437                        try {
438                            Thread.sleep(1000);
439                        } catch (InterruptedException ignore) {
440                        }
441                    } else {
442                        mIfaceMap.remove(iface);
443                        m.mStateMachine.sendMessage(SUP_DISCONNECTION_EVENT);
444                        Log.e(TAG, "startMonitoring(" + iface + ") failed!");
445                        break;
446                    }
447                }
448            }
449        }
450
451        public synchronized void stopMonitoring(String iface) {
452            WifiMonitor m = mIfaceMap.get(iface);
453            if (DBG) Log.d(TAG, "stopMonitoring(" + iface + ") = " + m.mStateMachine);
454            m.mMonitoring = false;
455            m.mStateMachine.sendMessage(SUP_DISCONNECTION_EVENT);
456        }
457
458        public synchronized void registerInterfaceMonitor(String iface, WifiMonitor m) {
459            if (DBG) Log.d(TAG, "registerInterface(" + iface + "+" + m.mStateMachine + ")");
460            mIfaceMap.put(iface, m);
461            if (mWifiNative == null) {
462                mWifiNative = m.mWifiNative;
463            }
464        }
465
466        public synchronized void unregisterInterfaceMonitor(String iface) {
467            // REVIEW: When should we call this? If this isn't called, then WifiMonitor
468            // objects will remain in the mIfaceMap; and won't ever get deleted
469
470            WifiMonitor m = mIfaceMap.remove(iface);
471            if (DBG) Log.d(TAG, "unregisterInterface(" + iface + "+" + m.mStateMachine + ")");
472        }
473
474        public synchronized void stopSupplicant() {
475            mWifiNative.stopSupplicant();
476        }
477
478        public synchronized void killSupplicant(boolean p2pSupported) {
479            WifiNative.killSupplicant(p2pSupported);
480            mConnected = false;
481            for (WifiMonitor m : mIfaceMap.values()) {
482                m.mMonitoring = false;
483            }
484        }
485
486        private synchronized boolean dispatchEvent(String eventStr) {
487            String iface;
488            if (eventStr.startsWith("IFNAME=")) {
489                int space = eventStr.indexOf(' ');
490                if (space != -1) {
491                    iface = eventStr.substring(7, space);
492                    if (!mIfaceMap.containsKey(iface) && iface.startsWith("p2p-")) {
493                        // p2p interfaces are created dynamically, but we have
494                        // only one P2p state machine monitoring all of them; look
495                        // for it explicitly, and send messages there ..
496                        iface = "p2p0";
497                    }
498                    eventStr = eventStr.substring(space + 1);
499                } else {
500                    // No point dispatching this event to any interface, the dispatched
501                    // event string will begin with "IFNAME=" which dispatchEvent can't really
502                    // do anything about.
503                    Log.e(TAG, "Dropping malformed event (unparsable iface): " + eventStr);
504                    return false;
505                }
506            } else {
507                // events without prefix belong to p2p0 monitor
508                iface = "p2p0";
509            }
510
511            if (DBG) Log.d(TAG, "Dispatching event to interface: " + iface);
512
513            WifiMonitor m = mIfaceMap.get(iface);
514            if (m != null) {
515                if (m.mMonitoring) {
516                    if (m.dispatchEvent(eventStr)) {
517                        mConnected = false;
518                        return true;
519                    }
520
521                    return false;
522                } else {
523                    if (DBG) Log.d(TAG, "Dropping event because (" + iface + ") is stopped");
524                    return false;
525                }
526            } else {
527                if (DBG) Log.d(TAG, "Sending to all monitors because there's no matching iface");
528                boolean done = false;
529                for (WifiMonitor monitor : mIfaceMap.values()) {
530                    if (monitor.mMonitoring && monitor.dispatchEvent(eventStr)) {
531                        done = true;
532                    }
533                }
534
535                if (done) {
536                    mConnected = false;
537                }
538
539                return done;
540            }
541        }
542    }
543
544    private static class MonitorThread extends Thread {
545        private final WifiNative mWifiNative;
546        private final WifiMonitorSingleton mWifiMonitorSingleton;
547
548        public MonitorThread(WifiNative wifiNative, WifiMonitorSingleton wifiMonitorSingleton) {
549            super("WifiMonitor");
550            mWifiNative = wifiNative;
551            mWifiMonitorSingleton = wifiMonitorSingleton;
552        }
553
554        public void run() {
555            //noinspection InfiniteLoopStatement
556            for (;;) {
557                String eventStr = mWifiNative.waitForEvent();
558
559                // Skip logging the common but mostly uninteresting scan-results event
560                if (DBG && eventStr.indexOf(SCAN_RESULTS_STR) == -1) {
561                    Log.d(TAG, "Event [" + eventStr + "]");
562                }
563
564                if (mWifiMonitorSingleton.dispatchEvent(eventStr)) {
565                    if (DBG) Log.d(TAG, "Disconnecting from the supplicant, no more events");
566                    break;
567                }
568            }
569        }
570    }
571
572    private void logDbg(String debug) {
573        long now = SystemClock.elapsedRealtimeNanos();
574        String ts = String.format("[%,d us] ", now/1000);
575        Log.e(TAG, ts+debug+ " stack:" + Thread.currentThread().getStackTrace()[2].getMethodName() +" - "+ Thread.currentThread().getStackTrace()[3].getMethodName() +" - "+ Thread.currentThread().getStackTrace()[4].getMethodName() +" - "+ Thread.currentThread().getStackTrace()[5].getMethodName());
576
577    }
578
579    /* @return true if the event was supplicant disconnection */
580    private boolean dispatchEvent(String eventStr) {
581
582        if (DBG) logDbg("WifiMonitor dispatchEvent " + eventStr);
583
584        if (!eventStr.startsWith(EVENT_PREFIX_STR)) {
585            if (eventStr.startsWith(WPA_EVENT_PREFIX_STR) &&
586                    0 < eventStr.indexOf(PASSWORD_MAY_BE_INCORRECT_STR)) {
587               // AUTHENTICATION_FAILURE_EVENT is sent thru SSID_TEMP_DISABLED message, this CTRL message contains the netId and ssid
588               // and sohuld be used instead of the wpa_supplicant log
589               // mStateMachine.sendMessage(AUTHENTICATION_FAILURE_EVENT);
590            } else if (eventStr.startsWith(WPS_SUCCESS_STR)) {
591                mStateMachine.sendMessage(WPS_SUCCESS_EVENT);
592            } else if (eventStr.startsWith(WPS_FAIL_STR)) {
593                handleWpsFailEvent(eventStr);
594            } else if (eventStr.startsWith(WPS_OVERLAP_STR)) {
595                mStateMachine.sendMessage(WPS_OVERLAP_EVENT);
596            } else if (eventStr.startsWith(WPS_TIMEOUT_STR)) {
597                mStateMachine.sendMessage(WPS_TIMEOUT_EVENT);
598            } else if (eventStr.startsWith(P2P_EVENT_PREFIX_STR)) {
599                handleP2pEvents(eventStr);
600            } else if (eventStr.startsWith(HOST_AP_EVENT_PREFIX_STR)) {
601                handleHostApEvents(eventStr);
602            }
603            else {
604                if (DBG) Log.w(TAG, "couldn't identify event type - " + eventStr);
605            }
606            return false;
607        }
608
609        String eventName = eventStr.substring(EVENT_PREFIX_LEN_STR);
610        int nameEnd = eventName.indexOf(' ');
611        if (nameEnd != -1)
612            eventName = eventName.substring(0, nameEnd);
613        if (eventName.length() == 0) {
614            if (DBG) Log.i(TAG, "Received wpa_supplicant event with empty event name");
615            return false;
616        }
617        /*
618        * Map event name into event enum
619        */
620        int event;
621        if (eventName.equals(CONNECTED_STR))
622            event = CONNECTED;
623        else if (eventName.equals(DISCONNECTED_STR))
624            event = DISCONNECTED;
625        else if (eventName.equals(STATE_CHANGE_STR))
626            event = STATE_CHANGE;
627        else if (eventName.equals(SCAN_RESULTS_STR))
628            event = SCAN_RESULTS;
629        else if (eventName.equals(LINK_SPEED_STR))
630            event = LINK_SPEED;
631        else if (eventName.equals(TERMINATING_STR))
632            event = TERMINATING;
633        else if (eventName.equals(DRIVER_STATE_STR))
634            event = DRIVER_STATE;
635        else if (eventName.equals(EAP_FAILURE_STR))
636            event = EAP_FAILURE;
637        else if (eventName.equals(ASSOC_REJECT_STR))
638            event = ASSOC_REJECT;
639        else if (eventName.equals(TEMP_DISABLED_STR)) {
640            event = SSID_TEMP_DISABLED;
641        }
642        else
643            event = UNKNOWN;
644
645        String eventData = eventStr;
646        if (event == DRIVER_STATE || event == LINK_SPEED)
647            eventData = eventData.split(" ")[1];
648        else if (event == STATE_CHANGE || event == EAP_FAILURE) {
649            int ind = eventStr.indexOf(" ");
650            if (ind != -1) {
651                eventData = eventStr.substring(ind + 1);
652            }
653        } else {
654            int ind = eventStr.indexOf(" - ");
655            if (ind != -1) {
656                eventData = eventStr.substring(ind + 3);
657            }
658        }
659
660        if (event == SSID_TEMP_DISABLED) {
661            String substr = null;
662            int ind = eventStr.indexOf(" ");
663            if (ind != -1) {
664                substr = eventStr.substring(ind + 1);
665            }
666            mStateMachine.sendMessage(AUTHENTICATION_FAILURE_EVENT, substr);
667        } else if (event == STATE_CHANGE) {
668            handleSupplicantStateChange(eventData);
669        } else if (event == DRIVER_STATE) {
670            handleDriverEvent(eventData);
671        } else if (event == TERMINATING) {
672            /**
673             * Close the supplicant connection if we see
674             * too many recv errors
675             */
676            if (eventData.startsWith(WPA_RECV_ERROR_STR)) {
677                if (++sRecvErrors > MAX_RECV_ERRORS) {
678                    if (DBG) {
679                        Log.d(TAG, "too many recv errors, closing connection");
680                    }
681                } else {
682                    return false;
683                }
684            }
685
686            // notify and exit
687            mStateMachine.sendMessage(SUP_DISCONNECTION_EVENT);
688            return true;
689        } else if (event == EAP_FAILURE) {
690            if (eventData.startsWith(EAP_AUTH_FAILURE_STR)) {
691                logDbg("WifiMonitor send auth failure (EAP_AUTH_FAILURE) ");
692                mStateMachine.sendMessage(AUTHENTICATION_FAILURE_EVENT);
693            }
694        } else if (event == ASSOC_REJECT) {
695            mStateMachine.sendMessage(ASSOCIATION_REJECTION_EVENT);
696        } else {
697            handleEvent(event, eventData);
698        }
699        sRecvErrors = 0;
700        return false;
701    }
702
703    private void handleDriverEvent(String state) {
704        if (state == null) {
705            return;
706        }
707        if (state.equals("HANGED")) {
708            mStateMachine.sendMessage(DRIVER_HUNG_EVENT);
709        }
710    }
711
712    /**
713     * Handle all supplicant events except STATE-CHANGE
714     * @param event the event type
715     * @param remainder the rest of the string following the
716     * event name and &quot;&#8195;&#8212;&#8195;&quot;
717     */
718    void handleEvent(int event, String remainder) {
719        switch (event) {
720            case DISCONNECTED:
721                handleNetworkStateChange(NetworkInfo.DetailedState.DISCONNECTED, remainder);
722                break;
723
724            case CONNECTED:
725                handleNetworkStateChange(NetworkInfo.DetailedState.CONNECTED, remainder);
726                break;
727
728            case SCAN_RESULTS:
729                mStateMachine.sendMessage(SCAN_RESULTS_EVENT);
730                break;
731
732            case UNKNOWN:
733                break;
734        }
735    }
736
737    private void handleWpsFailEvent(String dataString) {
738        final Pattern p = Pattern.compile(WPS_FAIL_PATTERN);
739        Matcher match = p.matcher(dataString);
740        if (match.find()) {
741            String cfgErr = match.group(1);
742            String reason = match.group(2);
743
744            if (reason != null) {
745                switch(Integer.parseInt(reason)) {
746                    case REASON_TKIP_ONLY_PROHIBITED:
747                        mStateMachine.sendMessage(mStateMachine.obtainMessage(WPS_FAIL_EVENT,
748                                WifiManager.WPS_TKIP_ONLY_PROHIBITED, 0));
749                        return;
750                    case REASON_WEP_PROHIBITED:
751                        mStateMachine.sendMessage(mStateMachine.obtainMessage(WPS_FAIL_EVENT,
752                                WifiManager.WPS_WEP_PROHIBITED, 0));
753                        return;
754                }
755            }
756            if (cfgErr != null) {
757                switch(Integer.parseInt(cfgErr)) {
758                    case CONFIG_AUTH_FAILURE:
759                        mStateMachine.sendMessage(mStateMachine.obtainMessage(WPS_FAIL_EVENT,
760                                WifiManager.WPS_AUTH_FAILURE, 0));
761                        return;
762                    case CONFIG_MULTIPLE_PBC_DETECTED:
763                        mStateMachine.sendMessage(mStateMachine.obtainMessage(WPS_FAIL_EVENT,
764                                WifiManager.WPS_OVERLAP_ERROR, 0));
765                        return;
766                }
767            }
768        }
769        //For all other errors, return a generic internal error
770        mStateMachine.sendMessage(mStateMachine.obtainMessage(WPS_FAIL_EVENT,
771                WifiManager.ERROR, 0));
772    }
773
774    /* <event> status=<err> and the special case of <event> reason=FREQ_CONFLICT */
775    private P2pStatus p2pError(String dataString) {
776        P2pStatus err = P2pStatus.UNKNOWN;
777        String[] tokens = dataString.split(" ");
778        if (tokens.length < 2) return err;
779        String[] nameValue = tokens[1].split("=");
780        if (nameValue.length != 2) return err;
781
782        /* Handle the special case of reason=FREQ+CONFLICT */
783        if (nameValue[1].equals("FREQ_CONFLICT")) {
784            return P2pStatus.NO_COMMON_CHANNEL;
785        }
786        try {
787            err = P2pStatus.valueOf(Integer.parseInt(nameValue[1]));
788        } catch (NumberFormatException e) {
789            e.printStackTrace();
790        }
791        return err;
792    }
793
794    /**
795     * Handle p2p events
796     */
797    private void handleP2pEvents(String dataString) {
798        if (dataString.startsWith(P2P_DEVICE_FOUND_STR)) {
799            mStateMachine.sendMessage(P2P_DEVICE_FOUND_EVENT, new WifiP2pDevice(dataString));
800        } else if (dataString.startsWith(P2P_DEVICE_LOST_STR)) {
801            mStateMachine.sendMessage(P2P_DEVICE_LOST_EVENT, new WifiP2pDevice(dataString));
802        } else if (dataString.startsWith(P2P_FIND_STOPPED_STR)) {
803            mStateMachine.sendMessage(P2P_FIND_STOPPED_EVENT);
804        } else if (dataString.startsWith(P2P_GO_NEG_REQUEST_STR)) {
805            mStateMachine.sendMessage(P2P_GO_NEGOTIATION_REQUEST_EVENT,
806                    new WifiP2pConfig(dataString));
807        } else if (dataString.startsWith(P2P_GO_NEG_SUCCESS_STR)) {
808            mStateMachine.sendMessage(P2P_GO_NEGOTIATION_SUCCESS_EVENT);
809        } else if (dataString.startsWith(P2P_GO_NEG_FAILURE_STR)) {
810            mStateMachine.sendMessage(P2P_GO_NEGOTIATION_FAILURE_EVENT, p2pError(dataString));
811        } else if (dataString.startsWith(P2P_GROUP_FORMATION_SUCCESS_STR)) {
812            mStateMachine.sendMessage(P2P_GROUP_FORMATION_SUCCESS_EVENT);
813        } else if (dataString.startsWith(P2P_GROUP_FORMATION_FAILURE_STR)) {
814            mStateMachine.sendMessage(P2P_GROUP_FORMATION_FAILURE_EVENT, p2pError(dataString));
815        } else if (dataString.startsWith(P2P_GROUP_STARTED_STR)) {
816            mStateMachine.sendMessage(P2P_GROUP_STARTED_EVENT, new WifiP2pGroup(dataString));
817        } else if (dataString.startsWith(P2P_GROUP_REMOVED_STR)) {
818            mStateMachine.sendMessage(P2P_GROUP_REMOVED_EVENT, new WifiP2pGroup(dataString));
819        } else if (dataString.startsWith(P2P_INVITATION_RECEIVED_STR)) {
820            mStateMachine.sendMessage(P2P_INVITATION_RECEIVED_EVENT,
821                    new WifiP2pGroup(dataString));
822        } else if (dataString.startsWith(P2P_INVITATION_RESULT_STR)) {
823            mStateMachine.sendMessage(P2P_INVITATION_RESULT_EVENT, p2pError(dataString));
824        } else if (dataString.startsWith(P2P_PROV_DISC_PBC_REQ_STR)) {
825            mStateMachine.sendMessage(P2P_PROV_DISC_PBC_REQ_EVENT,
826                    new WifiP2pProvDiscEvent(dataString));
827        } else if (dataString.startsWith(P2P_PROV_DISC_PBC_RSP_STR)) {
828            mStateMachine.sendMessage(P2P_PROV_DISC_PBC_RSP_EVENT,
829                    new WifiP2pProvDiscEvent(dataString));
830        } else if (dataString.startsWith(P2P_PROV_DISC_ENTER_PIN_STR)) {
831            mStateMachine.sendMessage(P2P_PROV_DISC_ENTER_PIN_EVENT,
832                    new WifiP2pProvDiscEvent(dataString));
833        } else if (dataString.startsWith(P2P_PROV_DISC_SHOW_PIN_STR)) {
834            mStateMachine.sendMessage(P2P_PROV_DISC_SHOW_PIN_EVENT,
835                    new WifiP2pProvDiscEvent(dataString));
836        } else if (dataString.startsWith(P2P_PROV_DISC_FAILURE_STR)) {
837            mStateMachine.sendMessage(P2P_PROV_DISC_FAILURE_EVENT);
838        } else if (dataString.startsWith(P2P_SERV_DISC_RESP_STR)) {
839            List<WifiP2pServiceResponse> list = WifiP2pServiceResponse.newInstance(dataString);
840            if (list != null) {
841                mStateMachine.sendMessage(P2P_SERV_DISC_RESP_EVENT, list);
842            } else {
843                Log.e(TAG, "Null service resp " + dataString);
844            }
845        }
846    }
847
848    /**
849     * Handle hostap events
850     */
851    private void handleHostApEvents(String dataString) {
852        String[] tokens = dataString.split(" ");
853        /* AP-STA-CONNECTED 42:fc:89:a8:96:09 p2p_dev_addr=02:90:4c:a0:92:54 */
854        if (tokens[0].equals(AP_STA_CONNECTED_STR)) {
855            mStateMachine.sendMessage(AP_STA_CONNECTED_EVENT, new WifiP2pDevice(dataString));
856            /* AP-STA-DISCONNECTED 42:fc:89:a8:96:09 p2p_dev_addr=02:90:4c:a0:92:54 */
857        } else if (tokens[0].equals(AP_STA_DISCONNECTED_STR)) {
858            mStateMachine.sendMessage(AP_STA_DISCONNECTED_EVENT, new WifiP2pDevice(dataString));
859        }
860    }
861
862    /**
863     * Handle the supplicant STATE-CHANGE event
864     * @param dataString New supplicant state string in the format:
865     * id=network-id state=new-state
866     */
867    private void handleSupplicantStateChange(String dataString) {
868        WifiSsid wifiSsid = null;
869        int index = dataString.lastIndexOf("SSID=");
870        if (index != -1) {
871            wifiSsid = WifiSsid.createFromAsciiEncoded(
872                    dataString.substring(index + 5));
873        }
874        String[] dataTokens = dataString.split(" ");
875
876        String BSSID = null;
877        int networkId = -1;
878        int newState  = -1;
879        for (String token : dataTokens) {
880            String[] nameValue = token.split("=");
881            if (nameValue.length != 2) {
882                continue;
883            }
884
885            if (nameValue[0].equals("BSSID")) {
886                BSSID = nameValue[1];
887                continue;
888            }
889
890            int value;
891            try {
892                value = Integer.parseInt(nameValue[1]);
893            } catch (NumberFormatException e) {
894                continue;
895            }
896
897            if (nameValue[0].equals("id")) {
898                networkId = value;
899            } else if (nameValue[0].equals("state")) {
900                newState = value;
901            }
902        }
903
904        if (newState == -1) return;
905
906        SupplicantState newSupplicantState = SupplicantState.INVALID;
907        for (SupplicantState state : SupplicantState.values()) {
908            if (state.ordinal() == newState) {
909                newSupplicantState = state;
910                break;
911            }
912        }
913        if (newSupplicantState == SupplicantState.INVALID) {
914            Log.w(TAG, "Invalid supplicant state: " + newState);
915        }
916        notifySupplicantStateChange(networkId, wifiSsid, BSSID, newSupplicantState);
917    }
918
919    private void handleNetworkStateChange(NetworkInfo.DetailedState newState, String data) {
920        String BSSID = null;
921        int networkId = -1;
922        if (newState == NetworkInfo.DetailedState.CONNECTED) {
923            Matcher match = mConnectedEventPattern.matcher(data);
924            if (!match.find()) {
925                if (DBG) Log.d(TAG, "Could not find BSSID in CONNECTED event string");
926            } else {
927                BSSID = match.group(1);
928                try {
929                    networkId = Integer.parseInt(match.group(2));
930                } catch (NumberFormatException e) {
931                    networkId = -1;
932                }
933            }
934            notifyNetworkStateChange(newState, BSSID, networkId);
935        }
936    }
937
938    /**
939     * Send the state machine a notification that the state of Wifi connectivity
940     * has changed.
941     * @param newState the new network state
942     * @param BSSID when the new state is {@link NetworkInfo.DetailedState#CONNECTED},
943     * this is the MAC address of the access point. Otherwise, it
944     * is {@code null}.
945     * @param netId the configured network on which the state change occurred
946     */
947    void notifyNetworkStateChange(NetworkInfo.DetailedState newState, String BSSID, int netId) {
948        if (newState == NetworkInfo.DetailedState.CONNECTED) {
949            Message m = mStateMachine.obtainMessage(NETWORK_CONNECTION_EVENT,
950                    netId, 0, BSSID);
951            mStateMachine.sendMessage(m);
952        } else {
953            Message m = mStateMachine.obtainMessage(NETWORK_DISCONNECTION_EVENT,
954                    netId, 0, BSSID);
955            mStateMachine.sendMessage(m);
956        }
957    }
958
959    /**
960     * Send the state machine a notification that the state of the supplicant
961     * has changed.
962     * @param networkId the configured network on which the state change occurred
963     * @param wifiSsid network name
964     * @param BSSID network address
965     * @param newState the new {@code SupplicantState}
966     */
967    void notifySupplicantStateChange(int networkId, WifiSsid wifiSsid, String BSSID,
968            SupplicantState newState) {
969        mStateMachine.sendMessage(mStateMachine.obtainMessage(SUPPLICANT_STATE_CHANGE_EVENT,
970                new StateChangeResult(networkId, wifiSsid, BSSID, newState)));
971    }
972}
973