WifiMonitor.java revision 1d5cd3938f9191184cd9aea3059a3b62bf3a0372
1ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann/*
2ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann * Copyright (C) 2008 The Android Open Source Project
3ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann *
4ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann * Licensed under the Apache License, Version 2.0 (the "License");
5ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann * you may not use this file except in compliance with the License.
6ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann * You may obtain a copy of the License at
7ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann *
8ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann *      http://www.apache.org/licenses/LICENSE-2.0
9ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann *
104d3acf4ec42bf6e838f9060103aff98fbf170794Philip P. Moltmann * Unless required by applicable law or agreed to in writing, software
11ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann * distributed under the License is distributed on an "AS IS" BASIS,
12ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann * See the License for the specific language governing permissions and
14ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann * limitations under the License.
15ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann */
16ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann
17ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmannpackage com.android.server.wifi;
18ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann
19ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmannimport android.net.NetworkInfo;
20ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmannimport android.net.wifi.SupplicantState;
21ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmannimport android.net.wifi.WifiEnterpriseConfig;
22ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmannimport android.net.wifi.WifiManager;
23ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmannimport android.net.wifi.WifiSsid;
24ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmannimport android.net.wifi.p2p.WifiP2pConfig;
25ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmannimport android.net.wifi.p2p.WifiP2pDevice;
26ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmannimport android.net.wifi.p2p.WifiP2pGroup;
27ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmannimport android.net.wifi.p2p.WifiP2pProvDiscEvent;
28ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmannimport android.net.wifi.p2p.nsd.WifiP2pServiceResponse;
29ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmannimport android.os.Message;
30ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmannimport android.text.TextUtils;
31ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmannimport android.util.Base64;
32ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmannimport android.util.LocalLog;
33ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmannimport android.util.Log;
34ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann
35ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmannimport com.android.server.wifi.hotspot2.Utils;
36ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmannimport com.android.server.wifi.p2p.WifiP2pServiceImpl.P2pStatus;
37ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann
38ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmannimport com.android.internal.util.Protocol;
39ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmannimport com.android.internal.util.StateMachine;
40ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann
41ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmannimport java.util.HashMap;
424d3acf4ec42bf6e838f9060103aff98fbf170794Philip P. Moltmannimport java.util.LinkedHashMap;
434d3acf4ec42bf6e838f9060103aff98fbf170794Philip P. Moltmannimport java.util.List;
444d3acf4ec42bf6e838f9060103aff98fbf170794Philip P. Moltmannimport java.util.Map;
454d3acf4ec42bf6e838f9060103aff98fbf170794Philip P. Moltmannimport java.util.regex.Matcher;
464d3acf4ec42bf6e838f9060103aff98fbf170794Philip P. Moltmannimport java.util.regex.Pattern;
47ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann
48ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann/**
49ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann * Listens for events from the wpa_supplicant server, and passes them on
50ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann * to the {@link StateMachine} for handling. Runs in its own thread.
51ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann *
52ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann * @hide
53ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann */
54ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmannpublic class WifiMonitor {
55ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann
56ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static boolean DBG = false;
57ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final boolean VDBG = false;
58ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final String TAG = "WifiMonitor";
59ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann
60ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    /** Events we receive from the supplicant daemon */
61ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann
62ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final int CONNECTED    = 1;
63ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final int DISCONNECTED = 2;
64ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final int STATE_CHANGE = 3;
65ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final int SCAN_RESULTS = 4;
66ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final int LINK_SPEED   = 5;
67ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final int TERMINATING  = 6;
68ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final int DRIVER_STATE = 7;
69ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final int EAP_FAILURE  = 8;
70ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final int ASSOC_REJECT = 9;
71ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final int SSID_TEMP_DISABLE = 10;
72ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final int SSID_REENABLE = 11;
73ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final int BSS_ADDED    = 12;
74ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final int BSS_REMOVED  = 13;
75ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final int UNKNOWN      = 14;
76ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final int SCAN_FAILED  = 15;
77ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann
78ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    /** All events coming from the supplicant start with this prefix */
79ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final String EVENT_PREFIX_STR = "CTRL-EVENT-";
80ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final int EVENT_PREFIX_LEN_STR = EVENT_PREFIX_STR.length();
81ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann
82ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    /** All events coming from the supplicant start with this prefix */
83ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final String REQUEST_PREFIX_STR = "CTRL-REQ-";
84ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final int REQUEST_PREFIX_LEN_STR = REQUEST_PREFIX_STR.length();
85ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann
86ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann
87ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    /** All WPA events coming from the supplicant start with this prefix */
88ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final String WPA_EVENT_PREFIX_STR = "WPA:";
89ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final String PASSWORD_MAY_BE_INCORRECT_STR =
90ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann       "pre-shared key may be incorrect";
91ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann
92ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    /* WPS events */
93ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final String WPS_SUCCESS_STR = "WPS-SUCCESS";
94ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann
95ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    /* Format: WPS-FAIL msg=%d [config_error=%d] [reason=%d (%s)] */
96ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final String WPS_FAIL_STR    = "WPS-FAIL";
97ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final String WPS_FAIL_PATTERN =
98ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann            "WPS-FAIL msg=\\d+(?: config_error=(\\d+))?(?: reason=(\\d+))?";
99ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann
100ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    /* config error code values for config_error=%d */
101ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final int CONFIG_MULTIPLE_PBC_DETECTED = 12;
102ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final int CONFIG_AUTH_FAILURE = 18;
103ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann
104ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    /* reason code values for reason=%d */
105ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final int REASON_TKIP_ONLY_PROHIBITED = 1;
106ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final int REASON_WEP_PROHIBITED = 2;
107ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann
108ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final String WPS_OVERLAP_STR = "WPS-OVERLAP-DETECTED";
109ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final String WPS_TIMEOUT_STR = "WPS-TIMEOUT";
110ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann
111ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    /* Hotspot 2.0 ANQP query events */
112ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final String GAS_QUERY_PREFIX_STR = "GAS-QUERY-";
113ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final String GAS_QUERY_START_STR = "GAS-QUERY-START";
114ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final String GAS_QUERY_DONE_STR = "GAS-QUERY-DONE";
115ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final String RX_HS20_ANQP_ICON_STR = "RX-HS20-ANQP-ICON";
116ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final int RX_HS20_ANQP_ICON_STR_LEN = RX_HS20_ANQP_ICON_STR.length();
117ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann
118ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    /* Hotspot 2.0 events */
119ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final String HS20_PREFIX_STR = "HS20-";
120ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    public static final String HS20_SUB_REM_STR = "HS20-SUBSCRIPTION-REMEDIATION";
121ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    public static final String HS20_DEAUTH_STR = "HS20-DEAUTH-IMMINENT-NOTICE";
122ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann
123ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final String IDENTITY_STR = "IDENTITY";
124ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann
125ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final String SIM_STR = "SIM";
126ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann
127ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann
128ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    //used to debug and detect if we miss an event
129ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static int eventLogCounter = 0;
130ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann
131ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    /**
132ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * Names of events from wpa_supplicant (minus the prefix). In the
133ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * format descriptions, * &quot;<code>x</code>&quot;
134ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * designates a dynamic value that needs to be parsed out from the event
135ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * string
136ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     */
137ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    /**
138ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * <pre>
139ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * CTRL-EVENT-CONNECTED - Connection to xx:xx:xx:xx:xx:xx completed
140ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * </pre>
141ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * <code>xx:xx:xx:xx:xx:xx</code> is the BSSID of the associated access point
142ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     */
143ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final String CONNECTED_STR =    "CONNECTED";
144ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final String ConnectPrefix = "Connection to ";
145ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final String ConnectSuffix = " completed";
146ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann
147ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    /**
148ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * <pre>
149ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * CTRL-EVENT-DISCONNECTED - Disconnect event - remove keys
150ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * </pre>
151ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     */
152ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final String DISCONNECTED_STR = "DISCONNECTED";
153ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    /**
154ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * <pre>
155ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * CTRL-EVENT-STATE-CHANGE x
156ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * </pre>
157ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * <code>x</code> is the numerical value of the new state.
158ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     */
159ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final String STATE_CHANGE_STR =  "STATE-CHANGE";
160ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    /**
161ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * <pre>
162ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * CTRL-EVENT-SCAN-RESULTS ready
163ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * </pre>
164ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     */
165ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final String SCAN_RESULTS_STR =  "SCAN-RESULTS";
166ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann
167ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    /**
168ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * <pre>
169ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * CTRL-EVENT-SCAN-FAILED ret=code[ retry=1]
170ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * </pre>
171ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     */
172ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final String SCAN_FAILED_STR =  "SCAN-FAILED";
173ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann
174ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    /**
175ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * <pre>
176ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * CTRL-EVENT-LINK-SPEED x Mb/s
177ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * </pre>
178ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * {@code x} is the link speed in Mb/sec.
179ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     */
180ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final String LINK_SPEED_STR = "LINK-SPEED";
181ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    /**
182ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * <pre>
183ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * CTRL-EVENT-TERMINATING - signal x
184ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * </pre>
185ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * <code>x</code> is the signal that caused termination.
186ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     */
187ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final String TERMINATING_STR =  "TERMINATING";
188ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    /**
189ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * <pre>
190ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * CTRL-EVENT-DRIVER-STATE state
191ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * </pre>
192ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * <code>state</code> can be HANGED
193ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     */
194ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final String DRIVER_STATE_STR = "DRIVER-STATE";
195ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    /**
196ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * <pre>
197ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * CTRL-EVENT-EAP-FAILURE EAP authentication failed
198ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * </pre>
199ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     */
200ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final String EAP_FAILURE_STR = "EAP-FAILURE";
201ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann
202ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    /**
203ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * This indicates an authentication failure on EAP FAILURE event
204ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     */
205ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final String EAP_AUTH_FAILURE_STR = "EAP authentication failed";
206ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann
207ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    /* EAP authentication timeout events */
208ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final String AUTH_EVENT_PREFIX_STR = "Authentication with";
209ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final String AUTH_TIMEOUT_STR = "timed out.";
210ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann
211ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    /**
212ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * This indicates an assoc reject event
213ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     */
214ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final String ASSOC_REJECT_STR = "ASSOC-REJECT";
215ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann
216ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    /**
217ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * This indicates auth or association failure bad enough so as network got disabled
218ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * - WPA_PSK auth failure suspecting shared key mismatch
219ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * - failed multiple Associations
220ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     */
221ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final String TEMP_DISABLED_STR = "SSID-TEMP-DISABLED";
222ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann
223ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    /**
224ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * This indicates a previously disabled SSID was reenabled by supplicant
225ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     */
226ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final String REENABLED_STR = "SSID-REENABLED";
227ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann
228ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    /**
229ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * This indicates supplicant found a given BSS
230ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     */
231ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final String BSS_ADDED_STR = "BSS-ADDED";
232ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann
233ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    /**
234ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * This indicates supplicant removed a given BSS
235ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     */
236ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static final String BSS_REMOVED_STR = "BSS-REMOVED";
237ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann
238ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    /**
239ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * Regex pattern for extracting an Ethernet-style MAC address from a string.
240ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * Matches a strings like the following:<pre>
241ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * CTRL-EVENT-CONNECTED - Connection to 00:1e:58:ec:d5:6d completed (reauth) [id=1 id_str=]</pre>
242ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     */
243ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static Pattern mConnectedEventPattern =
244ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann        Pattern.compile("((?:[0-9a-f]{2}:){5}[0-9a-f]{2}) .* \\[id=([0-9]+) ");
245ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann
246ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    /**
247ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * Regex pattern for extracting an Ethernet-style MAC address from a string.
248ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * Matches a strings like the following:<pre>
249ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     * CTRL-EVENT-DISCONNECTED - bssid=ac:22:0b:24:70:74 reason=3 locally_generated=1
250ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann     */
251ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann    private static Pattern mDisconnectedEventPattern =
252ac3d58cff7c80b0ef56bf55130d91da17cbaa3c4Philip P. Moltmann            Pattern.compile("((?:[0-9a-f]{2}:){5}[0-9a-f]{2}) +" +
253                    "reason=([0-9]+) +locally_generated=([0-1])");
254
255    /**
256     * Regex pattern for extracting an Ethernet-style MAC address from a string.
257     * Matches a strings like the following:<pre>
258     * CTRL-EVENT-ASSOC-REJECT - bssid=ac:22:0b:24:70:74 status_code=1
259     */
260    private static Pattern mAssocRejectEventPattern =
261            Pattern.compile("((?:[0-9a-f]{2}:){5}[0-9a-f]{2}) +" +
262                    "status_code=([0-9]+)");
263
264    /**
265     * Regex pattern for extracting an Ethernet-style MAC address from a string.
266     * Matches a strings like the following:<pre>
267     * IFNAME=wlan0 Trying to associate with 6c:f3:7f:ae:87:71
268     */
269    private static final String TARGET_BSSID_STR =  "Trying to associate with ";
270
271    private static Pattern mTargetBSSIDPattern =
272            Pattern.compile("Trying to associate with ((?:[0-9a-f]{2}:){5}[0-9a-f]{2}).*");
273
274    /**
275     * Regex pattern for extracting an Ethernet-style MAC address from a string.
276     * Matches a strings like the following:<pre>
277     * IFNAME=wlan0 Associated with 6c:f3:7f:ae:87:71
278     */
279    private static final String ASSOCIATED_WITH_STR =  "Associated with ";
280
281    private static Pattern mAssociatedPattern =
282            Pattern.compile("Associated with ((?:[0-9a-f]{2}:){5}[0-9a-f]{2}).*");
283
284    /**
285     * Regex pattern for extracting an external GSM sim authentication request from a string.
286     * Matches a strings like the following:<pre>
287     * CTRL-REQ-SIM-<network id>:GSM-AUTH:<RAND1>:<RAND2>[:<RAND3>] needed for SSID <SSID>
288     * This pattern should find
289     *    0 - id
290     *    1 - Rand1
291     *    2 - Rand2
292     *    3 - Rand3
293     *    4 - SSID
294     */
295    private static Pattern mRequestGsmAuthPattern =
296            Pattern.compile("SIM-([0-9]*):GSM-AUTH((:[0-9a-f]+)+) needed for SSID (.+)");
297
298    /**
299     * Regex pattern for extracting an external 3G sim authentication request from a string.
300     * Matches a strings like the following:<pre>
301     * CTRL-REQ-SIM-<network id>:UMTS-AUTH:<RAND>:<AUTN> needed for SSID <SSID>
302     * This pattern should find
303     *    1 - id
304     *    2 - Rand
305     *    3 - Autn
306     *    4 - SSID
307     */
308    private static Pattern mRequestUmtsAuthPattern =
309            Pattern.compile("SIM-([0-9]*):UMTS-AUTH:([0-9a-f]+):([0-9a-f]+) needed for SSID (.+)");
310
311    /**
312     * Regex pattern for extracting SSIDs from request identity string.
313     * Matches a strings like the following:<pre>
314     * CTRL-REQ-IDENTITY-xx:Identity needed for SSID XXXX</pre>
315     */
316    private static Pattern mRequestIdentityPattern =
317            Pattern.compile("IDENTITY-([0-9]+):Identity needed for SSID (.+)");
318
319    /** P2P events */
320    private static final String P2P_EVENT_PREFIX_STR = "P2P";
321
322    /* P2P-DEVICE-FOUND fa:7b:7a:42:02:13 p2p_dev_addr=fa:7b:7a:42:02:13 pri_dev_type=1-0050F204-1
323       name='p2p-TEST1' config_methods=0x188 dev_capab=0x27 group_capab=0x0 */
324    private static final String P2P_DEVICE_FOUND_STR = "P2P-DEVICE-FOUND";
325
326    /* P2P-DEVICE-LOST p2p_dev_addr=42:fc:89:e1:e2:27 */
327    private static final String P2P_DEVICE_LOST_STR = "P2P-DEVICE-LOST";
328
329    /* P2P-FIND-STOPPED */
330    private static final String P2P_FIND_STOPPED_STR = "P2P-FIND-STOPPED";
331
332    /* P2P-GO-NEG-REQUEST 42:fc:89:a8:96:09 dev_passwd_id=4 */
333    private static final String P2P_GO_NEG_REQUEST_STR = "P2P-GO-NEG-REQUEST";
334
335    private static final String P2P_GO_NEG_SUCCESS_STR = "P2P-GO-NEG-SUCCESS";
336
337    /* P2P-GO-NEG-FAILURE status=x */
338    private static final String P2P_GO_NEG_FAILURE_STR = "P2P-GO-NEG-FAILURE";
339
340    private static final String P2P_GROUP_FORMATION_SUCCESS_STR =
341            "P2P-GROUP-FORMATION-SUCCESS";
342
343    private static final String P2P_GROUP_FORMATION_FAILURE_STR =
344            "P2P-GROUP-FORMATION-FAILURE";
345
346    /* P2P-GROUP-STARTED p2p-wlan0-0 [client|GO] ssid="DIRECT-W8" freq=2437
347       [psk=2182b2e50e53f260d04f3c7b25ef33c965a3291b9b36b455a82d77fd82ca15bc|passphrase="fKG4jMe3"]
348       go_dev_addr=fa:7b:7a:42:02:13 [PERSISTENT] */
349    private static final String P2P_GROUP_STARTED_STR = "P2P-GROUP-STARTED";
350
351    /* P2P-GROUP-REMOVED p2p-wlan0-0 [client|GO] reason=REQUESTED */
352    private static final String P2P_GROUP_REMOVED_STR = "P2P-GROUP-REMOVED";
353
354    /* P2P-INVITATION-RECEIVED sa=fa:7b:7a:42:02:13 go_dev_addr=f8:7b:7a:42:02:13
355        bssid=fa:7b:7a:42:82:13 unknown-network */
356    private static final String P2P_INVITATION_RECEIVED_STR = "P2P-INVITATION-RECEIVED";
357
358    /* P2P-INVITATION-RESULT status=1 */
359    private static final String P2P_INVITATION_RESULT_STR = "P2P-INVITATION-RESULT";
360
361    /* P2P-PROV-DISC-PBC-REQ 42:fc:89:e1:e2:27 p2p_dev_addr=42:fc:89:e1:e2:27
362       pri_dev_type=1-0050F204-1 name='p2p-TEST2' config_methods=0x188 dev_capab=0x27
363       group_capab=0x0 */
364    private static final String P2P_PROV_DISC_PBC_REQ_STR = "P2P-PROV-DISC-PBC-REQ";
365
366    /* P2P-PROV-DISC-PBC-RESP 02:12:47:f2:5a:36 */
367    private static final String P2P_PROV_DISC_PBC_RSP_STR = "P2P-PROV-DISC-PBC-RESP";
368
369    /* P2P-PROV-DISC-ENTER-PIN 42:fc:89:e1:e2:27 p2p_dev_addr=42:fc:89:e1:e2:27
370       pri_dev_type=1-0050F204-1 name='p2p-TEST2' config_methods=0x188 dev_capab=0x27
371       group_capab=0x0 */
372    private static final String P2P_PROV_DISC_ENTER_PIN_STR = "P2P-PROV-DISC-ENTER-PIN";
373    /* P2P-PROV-DISC-SHOW-PIN 42:fc:89:e1:e2:27 44490607 p2p_dev_addr=42:fc:89:e1:e2:27
374       pri_dev_type=1-0050F204-1 name='p2p-TEST2' config_methods=0x188 dev_capab=0x27
375       group_capab=0x0 */
376    private static final String P2P_PROV_DISC_SHOW_PIN_STR = "P2P-PROV-DISC-SHOW-PIN";
377    /* P2P-PROV-DISC-FAILURE p2p_dev_addr=42:fc:89:e1:e2:27 */
378    private static final String P2P_PROV_DISC_FAILURE_STR = "P2P-PROV-DISC-FAILURE";
379
380    /*
381     * Protocol format is as follows.<br>
382     * See the Table.62 in the WiFi Direct specification for the detail.
383     * ______________________________________________________________
384     * |           Length(2byte)     | Type(1byte) | TransId(1byte)}|
385     * ______________________________________________________________
386     * | status(1byte)  |            vendor specific(variable)      |
387     *
388     * P2P-SERV-DISC-RESP 42:fc:89:e1:e2:27 1 0300000101
389     * length=3, service type=0(ALL Service), transaction id=1,
390     * status=1(service protocol type not available)<br>
391     *
392     * P2P-SERV-DISC-RESP 42:fc:89:e1:e2:27 1 0300020201
393     * length=3, service type=2(UPnP), transaction id=2,
394     * status=1(service protocol type not available)
395     *
396     * P2P-SERV-DISC-RESP 42:fc:89:e1:e2:27 1 990002030010757569643a3131323
397     * 2646534652d383537342d353961622d393332322d3333333435363738393034343a3
398     * a75726e3a736368656d61732d75706e702d6f72673a736572766963653a436f6e746
399     * 56e744469726563746f72793a322c757569643a36383539646564652d383537342d3
400     * 53961622d393333322d3132333435363738393031323a3a75706e703a726f6f74646
401     * 576696365
402     * length=153,type=2(UPnP),transaction id=3,status=0
403     *
404     * UPnP Protocol format is as follows.
405     * ______________________________________________________
406     * |  Version (1)  |          USN (Variable)            |
407     *
408     * version=0x10(UPnP1.0) data=usn:uuid:1122de4e-8574-59ab-9322-33345678
409     * 9044::urn:schemas-upnp-org:service:ContentDirectory:2,usn:uuid:6859d
410     * ede-8574-59ab-9332-123456789012::upnp:rootdevice
411     *
412     * P2P-SERV-DISC-RESP 58:17:0c:bc:dd:ca 21 1900010200045f6970
413     * 70c00c000c01094d795072696e746572c027
414     * length=25, type=1(Bonjour),transaction id=2,status=0
415     *
416     * Bonjour Protocol format is as follows.
417     * __________________________________________________________
418     * |DNS Name(Variable)|DNS Type(1)|Version(1)|RDATA(Variable)|
419     *
420     * DNS Name=_ipp._tcp.local.,DNS type=12(PTR), Version=1,
421     * RDATA=MyPrinter._ipp._tcp.local.
422     *
423     */
424    private static final String P2P_SERV_DISC_RESP_STR = "P2P-SERV-DISC-RESP";
425
426    private static final String HOST_AP_EVENT_PREFIX_STR = "AP";
427    /* AP-STA-CONNECTED 42:fc:89:a8:96:09 dev_addr=02:90:4c:a0:92:54 */
428    private static final String AP_STA_CONNECTED_STR = "AP-STA-CONNECTED";
429    /* AP-STA-DISCONNECTED 42:fc:89:a8:96:09 */
430    private static final String AP_STA_DISCONNECTED_STR = "AP-STA-DISCONNECTED";
431    private static final String ANQP_DONE_STR = "ANQP-QUERY-DONE";
432    private static final String HS20_ICON_STR = "RX-HS20-ICON";
433
434    /* Supplicant events reported to a state machine */
435    private static final int BASE = Protocol.BASE_WIFI_MONITOR;
436
437    /* Connection to supplicant established */
438    public static final int SUP_CONNECTION_EVENT                 = BASE + 1;
439    /* Connection to supplicant lost */
440    public static final int SUP_DISCONNECTION_EVENT              = BASE + 2;
441   /* Network connection completed */
442    public static final int NETWORK_CONNECTION_EVENT             = BASE + 3;
443    /* Network disconnection completed */
444    public static final int NETWORK_DISCONNECTION_EVENT          = BASE + 4;
445    /* Scan results are available */
446    public static final int SCAN_RESULTS_EVENT                   = BASE + 5;
447    /* Supplicate state changed */
448    public static final int SUPPLICANT_STATE_CHANGE_EVENT        = BASE + 6;
449    /* Password failure and EAP authentication failure */
450    public static final int AUTHENTICATION_FAILURE_EVENT         = BASE + 7;
451    /* WPS success detected */
452    public static final int WPS_SUCCESS_EVENT                    = BASE + 8;
453    /* WPS failure detected */
454    public static final int WPS_FAIL_EVENT                       = BASE + 9;
455     /* WPS overlap detected */
456    public static final int WPS_OVERLAP_EVENT                    = BASE + 10;
457     /* WPS timeout detected */
458    public static final int WPS_TIMEOUT_EVENT                    = BASE + 11;
459    /* Driver was hung */
460    public static final int DRIVER_HUNG_EVENT                    = BASE + 12;
461    /* SSID was disabled due to auth failure or excessive
462     * connection failures */
463    public static final int SSID_TEMP_DISABLED                   = BASE + 13;
464    /* SSID reenabled by supplicant */
465    public static final int SSID_REENABLED                       = BASE + 14;
466
467    /* Request Identity */
468    public static final int SUP_REQUEST_IDENTITY                 = BASE + 15;
469
470    /* Request SIM Auth */
471    public static final int SUP_REQUEST_SIM_AUTH                 = BASE + 16;
472
473    public static final int SCAN_FAILED_EVENT                    = BASE + 17;
474
475    /* P2P events */
476    public static final int P2P_DEVICE_FOUND_EVENT               = BASE + 21;
477    public static final int P2P_DEVICE_LOST_EVENT                = BASE + 22;
478    public static final int P2P_GO_NEGOTIATION_REQUEST_EVENT     = BASE + 23;
479    public static final int P2P_GO_NEGOTIATION_SUCCESS_EVENT     = BASE + 25;
480    public static final int P2P_GO_NEGOTIATION_FAILURE_EVENT     = BASE + 26;
481    public static final int P2P_GROUP_FORMATION_SUCCESS_EVENT    = BASE + 27;
482    public static final int P2P_GROUP_FORMATION_FAILURE_EVENT    = BASE + 28;
483    public static final int P2P_GROUP_STARTED_EVENT              = BASE + 29;
484    public static final int P2P_GROUP_REMOVED_EVENT              = BASE + 30;
485    public static final int P2P_INVITATION_RECEIVED_EVENT        = BASE + 31;
486    public static final int P2P_INVITATION_RESULT_EVENT          = BASE + 32;
487    public static final int P2P_PROV_DISC_PBC_REQ_EVENT          = BASE + 33;
488    public static final int P2P_PROV_DISC_PBC_RSP_EVENT          = BASE + 34;
489    public static final int P2P_PROV_DISC_ENTER_PIN_EVENT        = BASE + 35;
490    public static final int P2P_PROV_DISC_SHOW_PIN_EVENT         = BASE + 36;
491    public static final int P2P_FIND_STOPPED_EVENT               = BASE + 37;
492    public static final int P2P_SERV_DISC_RESP_EVENT             = BASE + 38;
493    public static final int P2P_PROV_DISC_FAILURE_EVENT          = BASE + 39;
494
495    /* hostap events */
496    public static final int AP_STA_DISCONNECTED_EVENT            = BASE + 41;
497    public static final int AP_STA_CONNECTED_EVENT               = BASE + 42;
498
499    /* Indicates assoc reject event */
500    public static final int ASSOCIATION_REJECTION_EVENT          = BASE + 43;
501    public static final int ANQP_DONE_EVENT                      = BASE + 44;
502
503    /* hotspot 2.0 ANQP events */
504    public static final int GAS_QUERY_START_EVENT                = BASE + 51;
505    public static final int GAS_QUERY_DONE_EVENT                 = BASE + 52;
506    public static final int RX_HS20_ANQP_ICON_EVENT              = BASE + 53;
507
508    /* hotspot 2.0 events */
509    public static final int HS20_REMEDIATION_EVENT               = BASE + 61;
510    public static final int HS20_DEAUTH_EVENT                    = BASE + 62;
511
512    /**
513     * This indicates a read error on the monitor socket conenction
514     */
515    private static final String WPA_RECV_ERROR_STR = "recv error";
516
517    /**
518     * Max errors before we close supplicant connection
519     */
520    private static final int MAX_RECV_ERRORS    = 10;
521
522    private final String mInterfaceName;
523    private final WifiNative mWifiNative;
524    private final StateMachine mStateMachine;
525    private boolean mMonitoring;
526
527    // This is a global counter, since it's not monitor specific. However, the existing
528    // implementation forwards all "global" control events like CTRL-EVENT-TERMINATING
529    // to the p2p0 monitor. Is that expected ? It seems a bit surprising.
530    //
531    // TODO: If the p2p0 monitor isn't registered, the behaviour is even more surprising.
532    // The event will be dispatched to all monitors, and each of them will end up incrementing
533    // it in their dispatchXXX method. If we have 5 registered monitors (say), 2 consecutive
534    // recv errors will cause us to disconnect from the supplicant (instead of the intended 10).
535    //
536    // This variable is always accessed and modified under a WifiMonitorSingleton lock.
537    private static int sRecvErrors;
538
539    public WifiMonitor(StateMachine stateMachine, WifiNative wifiNative) {
540        if (DBG) Log.d(TAG, "Creating WifiMonitor");
541        mWifiNative = wifiNative;
542        mInterfaceName = wifiNative.mInterfaceName;
543        mStateMachine = stateMachine;
544        mMonitoring = false;
545
546        WifiMonitorSingleton.sInstance.registerInterfaceMonitor(mInterfaceName, this);
547    }
548
549    void enableVerboseLogging(int verbose) {
550        if (verbose > 0) {
551            DBG = true;
552        } else {
553            DBG = false;
554        }
555    }
556
557    public void startMonitoring() {
558        WifiMonitorSingleton.sInstance.startMonitoring(mInterfaceName);
559    }
560
561    public void stopMonitoring() {
562        WifiMonitorSingleton.sInstance.stopMonitoring(mInterfaceName);
563    }
564
565    public void stopSupplicant() {
566        WifiMonitorSingleton.sInstance.stopSupplicant();
567    }
568
569    public void killSupplicant(boolean p2pSupported) {
570        WifiMonitorSingleton.sInstance.killSupplicant(p2pSupported);
571    }
572
573    private static class WifiMonitorSingleton {
574        private static final WifiMonitorSingleton sInstance = new WifiMonitorSingleton();
575
576        private final HashMap<String, WifiMonitor> mIfaceMap = new HashMap<String, WifiMonitor>();
577        private boolean mConnected = false;
578        private WifiNative mWifiNative;
579
580        private WifiMonitorSingleton() {
581        }
582
583        public synchronized void startMonitoring(String iface) {
584            WifiMonitor m = mIfaceMap.get(iface);
585            if (m == null) {
586                Log.e(TAG, "startMonitor called with unknown iface=" + iface);
587                return;
588            }
589
590            Log.d(TAG, "startMonitoring(" + iface + ") with mConnected = " + mConnected);
591
592            if (mConnected) {
593                m.mMonitoring = true;
594                m.mStateMachine.sendMessage(SUP_CONNECTION_EVENT);
595            } else {
596                if (DBG) Log.d(TAG, "connecting to supplicant");
597                int connectTries = 0;
598                while (true) {
599                    if (mWifiNative.connectToSupplicant()) {
600                        m.mMonitoring = true;
601                        m.mStateMachine.sendMessage(SUP_CONNECTION_EVENT);
602                        mConnected = true;
603                        new MonitorThread(mWifiNative, this).start();
604                        break;
605                    }
606                    if (connectTries++ < 5) {
607                        try {
608                            Thread.sleep(1000);
609                        } catch (InterruptedException ignore) {
610                        }
611                    } else {
612                        m.mStateMachine.sendMessage(SUP_DISCONNECTION_EVENT);
613                        Log.e(TAG, "startMonitoring(" + iface + ") failed!");
614                        break;
615                    }
616                }
617            }
618        }
619
620        public synchronized void stopMonitoring(String iface) {
621            WifiMonitor m = mIfaceMap.get(iface);
622            if (DBG) Log.d(TAG, "stopMonitoring(" + iface + ") = " + m.mStateMachine);
623            m.mMonitoring = false;
624            m.mStateMachine.sendMessage(SUP_DISCONNECTION_EVENT);
625        }
626
627        public synchronized void registerInterfaceMonitor(String iface, WifiMonitor m) {
628            if (DBG) Log.d(TAG, "registerInterface(" + iface + "+" + m.mStateMachine + ")");
629            mIfaceMap.put(iface, m);
630            if (mWifiNative == null) {
631                mWifiNative = m.mWifiNative;
632            }
633        }
634
635        public synchronized void unregisterInterfaceMonitor(String iface) {
636            // REVIEW: When should we call this? If this isn't called, then WifiMonitor
637            // objects will remain in the mIfaceMap; and won't ever get deleted
638
639            WifiMonitor m = mIfaceMap.remove(iface);
640            if (DBG) Log.d(TAG, "unregisterInterface(" + iface + "+" + m.mStateMachine + ")");
641        }
642
643        public synchronized void stopSupplicant() {
644            mWifiNative.stopSupplicant();
645        }
646
647        public synchronized void killSupplicant(boolean p2pSupported) {
648            String suppState = System.getProperty("init.svc.wpa_supplicant");
649            if (suppState == null) suppState = "unknown";
650            String p2pSuppState = System.getProperty("init.svc.p2p_supplicant");
651            if (p2pSuppState == null) p2pSuppState = "unknown";
652
653            Log.e(TAG, "killSupplicant p2p" + p2pSupported
654                    + " init.svc.wpa_supplicant=" + suppState
655                    + " init.svc.p2p_supplicant=" + p2pSuppState);
656            WifiNative.killSupplicant(p2pSupported);
657            mConnected = false;
658            for (WifiMonitor m : mIfaceMap.values()) {
659                m.mMonitoring = false;
660            }
661        }
662
663        private synchronized boolean dispatchEvent(String eventStr) {
664            String iface;
665            // IFNAME=wlan0 ANQP-QUERY-DONE addr=18:cf:5e:26:a4:88 result=SUCCESS
666            if (eventStr.startsWith("IFNAME=")) {
667                int space = eventStr.indexOf(' ');
668                if (space != -1) {
669                    iface = eventStr.substring(7, space);
670                    if (!mIfaceMap.containsKey(iface) && iface.startsWith("p2p-")) {
671                        // p2p interfaces are created dynamically, but we have
672                        // only one P2p state machine monitoring all of them; look
673                        // for it explicitly, and send messages there ..
674                        iface = "p2p0";
675                    }
676                    eventStr = eventStr.substring(space + 1);
677                } else {
678                    // No point dispatching this event to any interface, the dispatched
679                    // event string will begin with "IFNAME=" which dispatchEvent can't really
680                    // do anything about.
681                    Log.e(TAG, "Dropping malformed event (unparsable iface): " + eventStr);
682                    return false;
683                }
684            } else {
685                // events without prefix belong to p2p0 monitor
686                iface = "p2p0";
687            }
688
689            if (VDBG) Log.d(TAG, "Dispatching event to interface: " + iface);
690
691            WifiMonitor m = mIfaceMap.get(iface);
692            if (m != null) {
693                if (m.mMonitoring) {
694                    if (m.dispatchEvent(eventStr, iface)) {
695                        mConnected = false;
696                        return true;
697                    }
698
699                    return false;
700                } else {
701                    if (DBG) Log.d(TAG, "Dropping event because (" + iface + ") is stopped");
702                    return false;
703                }
704            } else {
705                if (DBG) Log.d(TAG, "Sending to all monitors because there's no matching iface");
706                boolean done = false;
707                boolean isMonitoring = false;
708                boolean isTerminating = false;
709                if (eventStr.startsWith(EVENT_PREFIX_STR)
710                        && eventStr.contains(TERMINATING_STR)) {
711                    isTerminating = true;
712                }
713                for (WifiMonitor monitor : mIfaceMap.values()) {
714                    if (monitor.mMonitoring) {
715                        isMonitoring = true;
716                        if (monitor.dispatchEvent(eventStr, iface)) {
717                            done = true;
718                        }
719                    }
720                }
721
722                if (!isMonitoring && isTerminating) {
723                    done = true;
724                }
725
726                if (done) {
727                    mConnected = false;
728                }
729
730                return done;
731            }
732        }
733    }
734
735    private static class MonitorThread extends Thread {
736        private final WifiNative mWifiNative;
737        private final WifiMonitorSingleton mWifiMonitorSingleton;
738        private final LocalLog mLocalLog = WifiNative.getLocalLog();
739
740        public MonitorThread(WifiNative wifiNative, WifiMonitorSingleton wifiMonitorSingleton) {
741            super("WifiMonitor");
742            mWifiNative = wifiNative;
743            mWifiMonitorSingleton = wifiMonitorSingleton;
744        }
745
746        public void run() {
747            if (DBG) {
748                Log.d(TAG, "MonitorThread start with mConnected=" +
749                     mWifiMonitorSingleton.mConnected);
750            }
751            //noinspection InfiniteLoopStatement
752            for (;;) {
753                if (!mWifiMonitorSingleton.mConnected) {
754                    if (DBG) Log.d(TAG, "MonitorThread exit because mConnected is false");
755                    break;
756                }
757                String eventStr = mWifiNative.waitForEvent();
758
759                // Skip logging the common but mostly uninteresting events
760                if (eventStr.indexOf(BSS_ADDED_STR) == -1
761                        && eventStr.indexOf(BSS_REMOVED_STR) == -1) {
762                    if (DBG) Log.d(TAG, "Event [" + eventStr + "]");
763                    mLocalLog.log("Event [" + eventStr + "]");
764                }
765
766                if (mWifiMonitorSingleton.dispatchEvent(eventStr)) {
767                    if (DBG) Log.d(TAG, "Disconnecting from the supplicant, no more events");
768                    break;
769                }
770            }
771        }
772    }
773
774    private void logDbg(String debug) {
775        Log.e(TAG, debug/*+ " stack:" + Thread.currentThread().getStackTrace()[2].getMethodName()
776                +" - "+ Thread.currentThread().getStackTrace()[3].getMethodName()
777                +" - "+ Thread.currentThread().getStackTrace()[4].getMethodName()
778                +" - "+ Thread.currentThread().getStackTrace()[5].getMethodName()*/);
779    }
780
781    private volatile long mLastConnectBSSID;
782
783    /* @return true if the event was supplicant disconnection */
784    private boolean dispatchEvent(String eventStr, String iface) {
785
786        if (DBG) {
787            // Dont log CTRL-EVENT-BSS-ADDED which are too verbose and not handled
788            if (eventStr != null && !eventStr.contains("CTRL-EVENT-BSS-ADDED")) {
789                logDbg("WifiMonitor:" + iface + " cnt=" + Integer.toString(eventLogCounter)
790                        + " dispatchEvent: " + eventStr);
791            }
792        }
793
794        if (!eventStr.startsWith(EVENT_PREFIX_STR)) {
795            if (eventStr.startsWith(WPA_EVENT_PREFIX_STR) &&
796                    0 < eventStr.indexOf(PASSWORD_MAY_BE_INCORRECT_STR)) {
797               mStateMachine.sendMessage(AUTHENTICATION_FAILURE_EVENT, eventLogCounter);
798            } else if (eventStr.startsWith(WPS_SUCCESS_STR)) {
799                mStateMachine.sendMessage(WPS_SUCCESS_EVENT);
800            } else if (eventStr.startsWith(WPS_FAIL_STR)) {
801                handleWpsFailEvent(eventStr);
802            } else if (eventStr.startsWith(WPS_OVERLAP_STR)) {
803                mStateMachine.sendMessage(WPS_OVERLAP_EVENT);
804            } else if (eventStr.startsWith(WPS_TIMEOUT_STR)) {
805                mStateMachine.sendMessage(WPS_TIMEOUT_EVENT);
806            } else if (eventStr.startsWith(P2P_EVENT_PREFIX_STR)) {
807                handleP2pEvents(eventStr);
808            } else if (eventStr.startsWith(HOST_AP_EVENT_PREFIX_STR)) {
809                handleHostApEvents(eventStr);
810            } else if (eventStr.startsWith(ANQP_DONE_STR)) {
811                try {
812                    handleAnqpResult(eventStr);
813                }
814                catch (IllegalArgumentException iae) {
815                    Log.e(TAG, "Bad ANQP event string: '" + eventStr + "': " + iae);
816                }
817            } else if (eventStr.startsWith(HS20_ICON_STR)) {
818                try {
819                    handleIconResult(eventStr);
820                }
821                catch (IllegalArgumentException iae) {
822                    Log.e(TAG, "Bad Icon event string: '" + eventStr + "': " + iae);
823                }
824            }
825            else if (eventStr.startsWith(HS20_SUB_REM_STR)) {
826                // Tack on the last connected BSSID so we have some idea what AP the WNM pertains to
827                handleWnmRemediationFrame(String.format("%012x %s", mLastConnectBSSID, eventStr));
828            } else if (eventStr.startsWith(HS20_DEAUTH_STR)) {
829                handleWnmDeauthFrame(String.format("%012x %s", mLastConnectBSSID, eventStr));
830            } else if (eventStr.startsWith(REQUEST_PREFIX_STR)) {
831                handleRequests(eventStr);
832            } else if (eventStr.startsWith(TARGET_BSSID_STR)) {
833                handleTargetBSSIDEvent(eventStr);
834            } else if (eventStr.startsWith(ASSOCIATED_WITH_STR)) {
835                handleAssociatedBSSIDEvent(eventStr);
836            } else if (eventStr.startsWith(AUTH_EVENT_PREFIX_STR) &&
837                    eventStr.endsWith(AUTH_TIMEOUT_STR)) {
838                mStateMachine.sendMessage(AUTHENTICATION_FAILURE_EVENT);
839            } else {
840                if (DBG) Log.w(TAG, "couldn't identify event type - " + eventStr);
841            }
842            eventLogCounter++;
843            return false;
844        }
845
846        String eventName = eventStr.substring(EVENT_PREFIX_LEN_STR);
847        int nameEnd = eventName.indexOf(' ');
848        if (nameEnd != -1)
849            eventName = eventName.substring(0, nameEnd);
850        if (eventName.length() == 0) {
851            if (DBG) Log.i(TAG, "Received wpa_supplicant event with empty event name");
852            eventLogCounter++;
853            return false;
854        }
855        /*
856        * Map event name into event enum
857        */
858        int event;
859        if (eventName.equals(CONNECTED_STR)) {
860            event = CONNECTED;
861            long bssid = -1L;
862            int prefix = eventStr.indexOf(ConnectPrefix);
863            if (prefix >= 0) {
864                int suffix = eventStr.indexOf(ConnectSuffix);
865                if (suffix > prefix) {
866                    try {
867                        bssid = Utils.parseMac(
868                                eventStr.substring(prefix + ConnectPrefix.length(), suffix));
869                    } catch (IllegalArgumentException iae) {
870                        bssid = -1L;
871                    }
872                }
873            }
874            mLastConnectBSSID = bssid;
875            if (bssid == -1L) {
876                Log.w(TAG, "Failed to parse out BSSID from '" + eventStr + "'");
877            }
878        }
879        else if (eventName.equals(DISCONNECTED_STR))
880            event = DISCONNECTED;
881        else if (eventName.equals(STATE_CHANGE_STR))
882            event = STATE_CHANGE;
883        else if (eventName.equals(SCAN_RESULTS_STR))
884            event = SCAN_RESULTS;
885        else if (eventName.equals(SCAN_FAILED_STR))
886            event = SCAN_FAILED;
887        else if (eventName.equals(LINK_SPEED_STR))
888            event = LINK_SPEED;
889        else if (eventName.equals(TERMINATING_STR))
890            event = TERMINATING;
891        else if (eventName.equals(DRIVER_STATE_STR))
892            event = DRIVER_STATE;
893        else if (eventName.equals(EAP_FAILURE_STR))
894            event = EAP_FAILURE;
895        else if (eventName.equals(ASSOC_REJECT_STR))
896            event = ASSOC_REJECT;
897        else if (eventName.equals(TEMP_DISABLED_STR)) {
898            event = SSID_TEMP_DISABLE;
899        } else if (eventName.equals(REENABLED_STR)) {
900            event = SSID_REENABLE;
901        } else if (eventName.equals(BSS_ADDED_STR)) {
902            event = BSS_ADDED;
903        } else if (eventName.equals(BSS_REMOVED_STR)) {
904            event = BSS_REMOVED;
905        } else
906            event = UNKNOWN;
907
908        String eventData = eventStr;
909        if (event == DRIVER_STATE || event == LINK_SPEED)
910            eventData = eventData.split(" ")[1];
911        else if (event == STATE_CHANGE || event == EAP_FAILURE) {
912            int ind = eventStr.indexOf(" ");
913            if (ind != -1) {
914                eventData = eventStr.substring(ind + 1);
915            }
916        } else {
917            int ind = eventStr.indexOf(" - ");
918            if (ind != -1) {
919                eventData = eventStr.substring(ind + 3);
920            }
921        }
922
923        if ((event == SSID_TEMP_DISABLE)||(event == SSID_REENABLE)) {
924            String substr = null;
925            int netId = -1;
926            int ind = eventStr.indexOf(" ");
927            if (ind != -1) {
928                substr = eventStr.substring(ind + 1);
929            }
930            if (substr != null) {
931                String status[] = substr.split(" ");
932                for (String key : status) {
933                    if (key.regionMatches(0, "id=", 0, 3)) {
934                        int idx = 3;
935                        netId = 0;
936                        while (idx < key.length()) {
937                            char c = key.charAt(idx);
938                            if ((c >= 0x30) && (c <= 0x39)) {
939                                netId *= 10;
940                                netId += c - 0x30;
941                                idx++;
942                            } else {
943                                break;
944                            }
945                        }
946                    }
947                }
948            }
949            mStateMachine.sendMessage((event == SSID_TEMP_DISABLE)?
950                    SSID_TEMP_DISABLED:SSID_REENABLED, netId, 0, substr);
951        } else if (event == STATE_CHANGE) {
952            handleSupplicantStateChange(eventData);
953        } else if (event == DRIVER_STATE) {
954            handleDriverEvent(eventData);
955        } else if (event == TERMINATING) {
956            /**
957             * Close the supplicant connection if we see
958             * too many recv errors
959             */
960            if (eventData.startsWith(WPA_RECV_ERROR_STR)) {
961                if (++sRecvErrors > MAX_RECV_ERRORS) {
962                    if (DBG) {
963                        Log.d(TAG, "too many recv errors, closing connection");
964                    }
965                } else {
966                    eventLogCounter++;
967                    return false;
968                }
969            }
970
971            // Notify and exit
972            mStateMachine.sendMessage(SUP_DISCONNECTION_EVENT, eventLogCounter);
973            return true;
974        } else if (event == EAP_FAILURE) {
975            if (eventData.startsWith(EAP_AUTH_FAILURE_STR)) {
976                logDbg("WifiMonitor send auth failure (EAP_AUTH_FAILURE) ");
977                mStateMachine.sendMessage(AUTHENTICATION_FAILURE_EVENT, eventLogCounter);
978            }
979        } else if (event == ASSOC_REJECT) {
980            Matcher match = mAssocRejectEventPattern.matcher(eventData);
981            String BSSID = "";
982            int status = -1;
983            if (!match.find()) {
984                if (DBG) Log.d(TAG, "Assoc Reject: Could not parse assoc reject string");
985            } else {
986                BSSID = match.group(1);
987                try {
988                    status = Integer.parseInt(match.group(2));
989                } catch (NumberFormatException e) {
990                    status = -1;
991                }
992            }
993            mStateMachine.sendMessage(ASSOCIATION_REJECTION_EVENT, eventLogCounter, status, BSSID);
994        } else if (event == BSS_ADDED && !VDBG) {
995            // Ignore that event - it is not handled, and dont log it as it is too verbose
996        } else if (event == BSS_REMOVED && !VDBG) {
997            // Ignore that event - it is not handled, and dont log it as it is too verbose
998        }  else {
999                handleEvent(event, eventData);
1000        }
1001        sRecvErrors = 0;
1002        eventLogCounter++;
1003        return false;
1004    }
1005
1006    private void handleDriverEvent(String state) {
1007        if (state == null) {
1008            return;
1009        }
1010        if (state.equals("HANGED")) {
1011            mStateMachine.sendMessage(DRIVER_HUNG_EVENT);
1012        }
1013    }
1014
1015    /**
1016     * Handle all supplicant events except STATE-CHANGE
1017     * @param event the event type
1018     * @param remainder the rest of the string following the
1019     * event name and &quot;&#8195;&#8212;&#8195;&quot;
1020     */
1021    void handleEvent(int event, String remainder) {
1022        if (DBG) {
1023            logDbg("handleEvent " + Integer.toString(event) + "  " + remainder);
1024        }
1025        switch (event) {
1026            case DISCONNECTED:
1027                handleNetworkStateChange(NetworkInfo.DetailedState.DISCONNECTED, remainder);
1028                break;
1029
1030            case CONNECTED:
1031                handleNetworkStateChange(NetworkInfo.DetailedState.CONNECTED, remainder);
1032                break;
1033
1034            case SCAN_RESULTS:
1035                mStateMachine.sendMessage(SCAN_RESULTS_EVENT);
1036                break;
1037
1038            case SCAN_FAILED:
1039                mStateMachine.sendMessage(SCAN_FAILED_EVENT);
1040                break;
1041
1042            case UNKNOWN:
1043                if (DBG) {
1044                    logDbg("handleEvent unknown: " + Integer.toString(event) + "  " + remainder);
1045                }
1046                break;
1047            default:
1048                break;
1049        }
1050    }
1051
1052    private void handleTargetBSSIDEvent(String eventStr) {
1053        String BSSID = null;
1054        Matcher match = mTargetBSSIDPattern.matcher(eventStr);
1055        if (match.find()) {
1056            BSSID = match.group(1);
1057        }
1058        mStateMachine.sendMessage(WifiStateMachine.CMD_TARGET_BSSID, eventLogCounter, 0, BSSID);
1059    }
1060
1061    private void handleAssociatedBSSIDEvent(String eventStr) {
1062        String BSSID = null;
1063        Matcher match = mAssociatedPattern.matcher(eventStr);
1064        if (match.find()) {
1065            BSSID = match.group(1);
1066        }
1067        mStateMachine.sendMessage(WifiStateMachine.CMD_ASSOCIATED_BSSID, eventLogCounter, 0, BSSID);
1068    }
1069
1070
1071    private void handleWpsFailEvent(String dataString) {
1072        final Pattern p = Pattern.compile(WPS_FAIL_PATTERN);
1073        Matcher match = p.matcher(dataString);
1074        int reason = 0;
1075        if (match.find()) {
1076            String cfgErrStr = match.group(1);
1077            String reasonStr = match.group(2);
1078
1079            if (reasonStr != null) {
1080                int reasonInt = Integer.parseInt(reasonStr);
1081                switch(reasonInt) {
1082                    case REASON_TKIP_ONLY_PROHIBITED:
1083                        mStateMachine.sendMessage(mStateMachine.obtainMessage(WPS_FAIL_EVENT,
1084                                WifiManager.WPS_TKIP_ONLY_PROHIBITED, 0));
1085                        return;
1086                    case REASON_WEP_PROHIBITED:
1087                        mStateMachine.sendMessage(mStateMachine.obtainMessage(WPS_FAIL_EVENT,
1088                                WifiManager.WPS_WEP_PROHIBITED, 0));
1089                        return;
1090                    default:
1091                        reason = reasonInt;
1092                        break;
1093                }
1094            }
1095            if (cfgErrStr != null) {
1096                int cfgErrInt = Integer.parseInt(cfgErrStr);
1097                switch(cfgErrInt) {
1098                    case CONFIG_AUTH_FAILURE:
1099                        mStateMachine.sendMessage(mStateMachine.obtainMessage(WPS_FAIL_EVENT,
1100                                WifiManager.WPS_AUTH_FAILURE, 0));
1101                        return;
1102                    case CONFIG_MULTIPLE_PBC_DETECTED:
1103                        mStateMachine.sendMessage(mStateMachine.obtainMessage(WPS_FAIL_EVENT,
1104                                WifiManager.WPS_OVERLAP_ERROR, 0));
1105                        return;
1106                    default:
1107                        if (reason == 0) reason = cfgErrInt;
1108                        break;
1109                }
1110            }
1111        }
1112        //For all other errors, return a generic internal error
1113        mStateMachine.sendMessage(mStateMachine.obtainMessage(WPS_FAIL_EVENT,
1114                WifiManager.ERROR, reason));
1115    }
1116
1117    /* <event> status=<err> and the special case of <event> reason=FREQ_CONFLICT */
1118    private P2pStatus p2pError(String dataString) {
1119        P2pStatus err = P2pStatus.UNKNOWN;
1120        String[] tokens = dataString.split(" ");
1121        if (tokens.length < 2) return err;
1122        String[] nameValue = tokens[1].split("=");
1123        if (nameValue.length != 2) return err;
1124
1125        /* Handle the special case of reason=FREQ+CONFLICT */
1126        if (nameValue[1].equals("FREQ_CONFLICT")) {
1127            return P2pStatus.NO_COMMON_CHANNEL;
1128        }
1129        try {
1130            err = P2pStatus.valueOf(Integer.parseInt(nameValue[1]));
1131        } catch (NumberFormatException e) {
1132            e.printStackTrace();
1133        }
1134        return err;
1135    }
1136
1137    WifiP2pDevice getWifiP2pDevice(String dataString) {
1138        try {
1139            WifiP2pDevice device = new WifiP2pDevice(dataString);
1140            return device;
1141        } catch (IllegalArgumentException e) {
1142            return null;
1143        }
1144    }
1145
1146    WifiP2pGroup getWifiP2pGroup(String dataString) {
1147        try {
1148            WifiP2pGroup group = new WifiP2pGroup(dataString);
1149            return group;
1150        } catch (IllegalArgumentException e) {
1151            return null;
1152        }
1153    }
1154
1155    /**
1156     * Handle p2p events
1157     */
1158    private void handleP2pEvents(String dataString) {
1159        if (dataString.startsWith(P2P_DEVICE_FOUND_STR)) {
1160            WifiP2pDevice device = getWifiP2pDevice(dataString);
1161            if (device != null) mStateMachine.sendMessage(P2P_DEVICE_FOUND_EVENT, device);
1162        } else if (dataString.startsWith(P2P_DEVICE_LOST_STR)) {
1163            WifiP2pDevice device = getWifiP2pDevice(dataString);
1164            if (device != null) mStateMachine.sendMessage(P2P_DEVICE_LOST_EVENT, device);
1165        } else if (dataString.startsWith(P2P_FIND_STOPPED_STR)) {
1166            mStateMachine.sendMessage(P2P_FIND_STOPPED_EVENT);
1167        } else if (dataString.startsWith(P2P_GO_NEG_REQUEST_STR)) {
1168            mStateMachine.sendMessage(P2P_GO_NEGOTIATION_REQUEST_EVENT,
1169                    new WifiP2pConfig(dataString));
1170        } else if (dataString.startsWith(P2P_GO_NEG_SUCCESS_STR)) {
1171            mStateMachine.sendMessage(P2P_GO_NEGOTIATION_SUCCESS_EVENT);
1172        } else if (dataString.startsWith(P2P_GO_NEG_FAILURE_STR)) {
1173            mStateMachine.sendMessage(P2P_GO_NEGOTIATION_FAILURE_EVENT, p2pError(dataString));
1174        } else if (dataString.startsWith(P2P_GROUP_FORMATION_SUCCESS_STR)) {
1175            mStateMachine.sendMessage(P2P_GROUP_FORMATION_SUCCESS_EVENT);
1176        } else if (dataString.startsWith(P2P_GROUP_FORMATION_FAILURE_STR)) {
1177            mStateMachine.sendMessage(P2P_GROUP_FORMATION_FAILURE_EVENT, p2pError(dataString));
1178        } else if (dataString.startsWith(P2P_GROUP_STARTED_STR)) {
1179            WifiP2pGroup group = getWifiP2pGroup(dataString);
1180            if (group != null) mStateMachine.sendMessage(P2P_GROUP_STARTED_EVENT, group);
1181        } else if (dataString.startsWith(P2P_GROUP_REMOVED_STR)) {
1182            WifiP2pGroup group = getWifiP2pGroup(dataString);
1183            if (group != null) mStateMachine.sendMessage(P2P_GROUP_REMOVED_EVENT, group);
1184        } else if (dataString.startsWith(P2P_INVITATION_RECEIVED_STR)) {
1185            mStateMachine.sendMessage(P2P_INVITATION_RECEIVED_EVENT,
1186                    new WifiP2pGroup(dataString));
1187        } else if (dataString.startsWith(P2P_INVITATION_RESULT_STR)) {
1188            mStateMachine.sendMessage(P2P_INVITATION_RESULT_EVENT, p2pError(dataString));
1189        } else if (dataString.startsWith(P2P_PROV_DISC_PBC_REQ_STR)) {
1190            mStateMachine.sendMessage(P2P_PROV_DISC_PBC_REQ_EVENT,
1191                    new WifiP2pProvDiscEvent(dataString));
1192        } else if (dataString.startsWith(P2P_PROV_DISC_PBC_RSP_STR)) {
1193            mStateMachine.sendMessage(P2P_PROV_DISC_PBC_RSP_EVENT,
1194                    new WifiP2pProvDiscEvent(dataString));
1195        } else if (dataString.startsWith(P2P_PROV_DISC_ENTER_PIN_STR)) {
1196            mStateMachine.sendMessage(P2P_PROV_DISC_ENTER_PIN_EVENT,
1197                    new WifiP2pProvDiscEvent(dataString));
1198        } else if (dataString.startsWith(P2P_PROV_DISC_SHOW_PIN_STR)) {
1199            mStateMachine.sendMessage(P2P_PROV_DISC_SHOW_PIN_EVENT,
1200                    new WifiP2pProvDiscEvent(dataString));
1201        } else if (dataString.startsWith(P2P_PROV_DISC_FAILURE_STR)) {
1202            mStateMachine.sendMessage(P2P_PROV_DISC_FAILURE_EVENT);
1203        } else if (dataString.startsWith(P2P_SERV_DISC_RESP_STR)) {
1204            List<WifiP2pServiceResponse> list = WifiP2pServiceResponse.newInstance(dataString);
1205            if (list != null) {
1206                mStateMachine.sendMessage(P2P_SERV_DISC_RESP_EVENT, list);
1207            } else {
1208                Log.e(TAG, "Null service resp " + dataString);
1209            }
1210        }
1211    }
1212
1213    /**
1214     * Handle hostap events
1215     */
1216    private void handleHostApEvents(String dataString) {
1217        String[] tokens = dataString.split(" ");
1218        /* AP-STA-CONNECTED 42:fc:89:a8:96:09 p2p_dev_addr=02:90:4c:a0:92:54 */
1219        if (tokens[0].equals(AP_STA_CONNECTED_STR)) {
1220            mStateMachine.sendMessage(AP_STA_CONNECTED_EVENT, new WifiP2pDevice(dataString));
1221            /* AP-STA-DISCONNECTED 42:fc:89:a8:96:09 p2p_dev_addr=02:90:4c:a0:92:54 */
1222        } else if (tokens[0].equals(AP_STA_DISCONNECTED_STR)) {
1223            mStateMachine.sendMessage(AP_STA_DISCONNECTED_EVENT, new WifiP2pDevice(dataString));
1224        }
1225    }
1226
1227    private static final String ADDR_STRING = "addr=";
1228    private static final String RESULT_STRING = "result=";
1229
1230    // ANQP-QUERY-DONE addr=18:cf:5e:26:a4:88 result=SUCCESS
1231
1232    private void handleAnqpResult(String eventStr) {
1233        int addrPos = eventStr.indexOf(ADDR_STRING);
1234        int resPos = eventStr.indexOf(RESULT_STRING);
1235        if (addrPos < 0 || resPos < 0) {
1236            throw new IllegalArgumentException("Unexpected ANQP result notification");
1237        }
1238        int eoaddr = eventStr.indexOf(' ', addrPos + ADDR_STRING.length());
1239        if (eoaddr < 0) {
1240            eoaddr = eventStr.length();
1241        }
1242        int eoresult = eventStr.indexOf(' ', resPos + RESULT_STRING.length());
1243        if (eoresult < 0) {
1244            eoresult = eventStr.length();
1245        }
1246
1247        try {
1248            long bssid = Utils.parseMac(eventStr.substring(addrPos + ADDR_STRING.length(), eoaddr));
1249            int result = eventStr.substring(
1250                    resPos + RESULT_STRING.length(), eoresult).equalsIgnoreCase("success") ? 1 : 0;
1251
1252            mStateMachine.sendMessage(ANQP_DONE_EVENT, result, 0, bssid);
1253        }
1254        catch (IllegalArgumentException iae) {
1255            Log.e(TAG, "Bad MAC address in ANQP response: " + iae.getMessage());
1256        }
1257    }
1258
1259    private final Map<String, String[]> mIconFragmentMap = new LinkedHashMap<String, String[]>() {
1260        @Override
1261        protected boolean removeEldestEntry(Entry eldest) {
1262            return size() > 3;
1263        }
1264    };
1265
1266    private void handleIconResult(String eventStr) {
1267        // RX-HS20-ICON c0:c5:20:27:d1:e8 9 10 OMJjkpWlDpC+UC...
1268        String[] segments = eventStr.split(" ");
1269        if (segments.length != 5) {
1270            throw new IllegalArgumentException("Incorrect number of segments");
1271        }
1272        try {
1273            String bssid = segments[1];
1274            int fragmentIndex = Integer.parseInt(segments[2]);
1275            int fragmentEnd = Integer.parseInt(segments[3]);
1276
1277            String[] fragments = mIconFragmentMap.get(bssid);
1278            if (fragments == null) {
1279                fragments = new String[fragmentEnd+1];
1280                mIconFragmentMap.put(bssid, fragments);
1281            }
1282            if (fragmentEnd >= fragments.length) {
1283                fragments = new String[fragmentEnd+1];
1284                mIconFragmentMap.put(bssid, fragments);
1285                Log.w(TAG, String.format("Icon fragment %d out of %d exceeds %d",
1286                        fragmentIndex, fragmentEnd, fragments.length));
1287            }
1288            fragments[fragmentIndex] = segments[4];
1289
1290            boolean incomplete = false;
1291            for (String fragment : fragments) {
1292                if (fragment == null) {
1293                    incomplete = true;
1294                    break;
1295                }
1296            }
1297            if (!incomplete) {
1298                StringBuilder b64 = new StringBuilder();
1299                for (String fragment : fragments) {
1300                    b64.append(fragment);
1301                }
1302                mIconFragmentMap.remove(bssid);
1303                long mac = Utils.parseMac(bssid);
1304                byte[] octets = Base64.decode(b64.toString(), Base64.DEFAULT);
1305                mStateMachine.sendMessage(
1306                        RX_HS20_ANQP_ICON_EVENT, (int)(mac >>> 32), (int)mac, octets);
1307            }
1308        }
1309        catch (NumberFormatException nfe) {
1310            throw new IllegalArgumentException("Bad numeral");
1311        }
1312    }
1313
1314    private void handleWnmRemediationFrame(String eventStr) {
1315        Log.d("ZXZ", "WNM frame: " + eventStr);
1316        mStateMachine.sendMessage(HS20_REMEDIATION_EVENT, eventStr);
1317    }
1318
1319    private void handleWnmDeauthFrame(String eventStr) {
1320        mStateMachine.sendMessage(HS20_DEAUTH_EVENT, eventStr);
1321    }
1322
1323    /**
1324     * Handle Supplicant Requests
1325     */
1326    private void handleRequests(String dataString) {
1327        String SSID = null;
1328        int reason = -2;
1329        String requestName = dataString.substring(REQUEST_PREFIX_LEN_STR);
1330        if (TextUtils.isEmpty(requestName)) {
1331            return;
1332        }
1333        if (requestName.startsWith(IDENTITY_STR)) {
1334            Matcher match = mRequestIdentityPattern.matcher(requestName);
1335            if (match.find()) {
1336                SSID = match.group(2);
1337                try {
1338                    reason = Integer.parseInt(match.group(1));
1339                } catch (NumberFormatException e) {
1340                    reason = -1;
1341                }
1342            } else {
1343                Log.e(TAG, "didn't find SSID " + requestName);
1344            }
1345            mStateMachine.sendMessage(SUP_REQUEST_IDENTITY, eventLogCounter, reason, SSID);
1346        } else if (requestName.startsWith(SIM_STR)) {
1347            Matcher matchGsm = mRequestGsmAuthPattern.matcher(requestName);
1348            Matcher matchUmts = mRequestUmtsAuthPattern.matcher(requestName);
1349            WifiStateMachine.SimAuthRequestData data =
1350                    new WifiStateMachine.SimAuthRequestData();
1351            if (matchGsm.find()) {
1352                data.networkId = Integer.parseInt(matchGsm.group(1));
1353                data.protocol = WifiEnterpriseConfig.Eap.SIM;
1354                data.ssid = matchGsm.group(4);
1355                data.data = matchGsm.group(2).split(":");
1356                mStateMachine.sendMessage(SUP_REQUEST_SIM_AUTH, data);
1357            } else if (matchUmts.find()) {
1358                data.networkId = Integer.parseInt(matchUmts.group(1));
1359                data.protocol = WifiEnterpriseConfig.Eap.AKA;
1360                data.ssid = matchUmts.group(4);
1361                data.data = new String[2];
1362                data.data[0] = matchUmts.group(2);
1363                data.data[1] = matchUmts.group(3);
1364                mStateMachine.sendMessage(SUP_REQUEST_SIM_AUTH, data);
1365            } else {
1366                Log.e(TAG, "couldn't parse SIM auth request - " + requestName);
1367            }
1368
1369        } else {
1370            if (DBG) Log.w(TAG, "couldn't identify request type - " + dataString);
1371        }
1372    }
1373
1374    /**
1375     * Handle the supplicant STATE-CHANGE event
1376     * @param dataString New supplicant state string in the format:
1377     * id=network-id state=new-state
1378     */
1379    private void handleSupplicantStateChange(String dataString) {
1380        WifiSsid wifiSsid = null;
1381        int index = dataString.lastIndexOf("SSID=");
1382        if (index != -1) {
1383            wifiSsid = WifiSsid.createFromAsciiEncoded(
1384                    dataString.substring(index + 5));
1385        }
1386        String[] dataTokens = dataString.split(" ");
1387
1388        String BSSID = null;
1389        int networkId = -1;
1390        int newState  = -1;
1391        for (String token : dataTokens) {
1392            String[] nameValue = token.split("=");
1393            if (nameValue.length != 2) {
1394                continue;
1395            }
1396
1397            if (nameValue[0].equals("BSSID")) {
1398                BSSID = nameValue[1];
1399                continue;
1400            }
1401
1402            int value;
1403            try {
1404                value = Integer.parseInt(nameValue[1]);
1405            } catch (NumberFormatException e) {
1406                continue;
1407            }
1408
1409            if (nameValue[0].equals("id")) {
1410                networkId = value;
1411            } else if (nameValue[0].equals("state")) {
1412                newState = value;
1413            }
1414        }
1415
1416        if (newState == -1) return;
1417
1418        SupplicantState newSupplicantState = SupplicantState.INVALID;
1419        for (SupplicantState state : SupplicantState.values()) {
1420            if (state.ordinal() == newState) {
1421                newSupplicantState = state;
1422                break;
1423            }
1424        }
1425        if (newSupplicantState == SupplicantState.INVALID) {
1426            Log.w(TAG, "Invalid supplicant state: " + newState);
1427        }
1428        notifySupplicantStateChange(networkId, wifiSsid, BSSID, newSupplicantState);
1429    }
1430
1431    private void handleNetworkStateChange(NetworkInfo.DetailedState newState, String data) {
1432        String BSSID = null;
1433        int networkId = -1;
1434        int reason = 0;
1435        int ind = -1;
1436        int local = 0;
1437        Matcher match;
1438        if (newState == NetworkInfo.DetailedState.CONNECTED) {
1439            match = mConnectedEventPattern.matcher(data);
1440            if (!match.find()) {
1441               if (DBG) Log.d(TAG, "handleNetworkStateChange: Couldnt find BSSID in event string");
1442            } else {
1443                BSSID = match.group(1);
1444                try {
1445                    networkId = Integer.parseInt(match.group(2));
1446                } catch (NumberFormatException e) {
1447                    networkId = -1;
1448                }
1449            }
1450            notifyNetworkStateChange(newState, BSSID, networkId, reason);
1451        } else if (newState == NetworkInfo.DetailedState.DISCONNECTED) {
1452            match = mDisconnectedEventPattern.matcher(data);
1453            if (!match.find()) {
1454               if (DBG) Log.d(TAG, "handleNetworkStateChange: Could not parse disconnect string");
1455            } else {
1456                BSSID = match.group(1);
1457                try {
1458                    reason = Integer.parseInt(match.group(2));
1459                } catch (NumberFormatException e) {
1460                    reason = -1;
1461                }
1462                try {
1463                    local = Integer.parseInt(match.group(3));
1464                } catch (NumberFormatException e) {
1465                    local = -1;
1466                }
1467            }
1468            notifyNetworkStateChange(newState, BSSID, local, reason);
1469        }
1470    }
1471
1472    /**
1473     * Send the state machine a notification that the state of Wifi connectivity
1474     * has changed.
1475     * @param newState the new network state
1476     * @param BSSID when the new state is {@link NetworkInfo.DetailedState#CONNECTED},
1477     * this is the MAC address of the access point. Otherwise, it
1478     * is {@code null}.
1479     * @param netId the configured network on which the state change occurred
1480     */
1481    void notifyNetworkStateChange(NetworkInfo.DetailedState newState,
1482                                  String BSSID, int netId, int reason) {
1483        if (newState == NetworkInfo.DetailedState.CONNECTED) {
1484            Message m = mStateMachine.obtainMessage(NETWORK_CONNECTION_EVENT,
1485                    netId, reason, BSSID);
1486            mStateMachine.sendMessage(m);
1487        } else {
1488
1489            Message m = mStateMachine.obtainMessage(NETWORK_DISCONNECTION_EVENT,
1490                    netId, reason, BSSID);
1491            if (DBG) logDbg("WifiMonitor notify network disconnect: "
1492                    + BSSID
1493                    + " reason=" + Integer.toString(reason));
1494            mStateMachine.sendMessage(m);
1495        }
1496    }
1497
1498    /**
1499     * Send the state machine a notification that the state of the supplicant
1500     * has changed.
1501     * @param networkId the configured network on which the state change occurred
1502     * @param wifiSsid network name
1503     * @param BSSID network address
1504     * @param newState the new {@code SupplicantState}
1505     */
1506    void notifySupplicantStateChange(int networkId, WifiSsid wifiSsid, String BSSID,
1507            SupplicantState newState) {
1508        mStateMachine.sendMessage(mStateMachine.obtainMessage(SUPPLICANT_STATE_CHANGE_EVENT,
1509                eventLogCounter, 0,
1510                new StateChangeResult(networkId, wifiSsid, BSSID, newState)));
1511    }
1512}
1513