aboutsummaryrefslogtreecommitdiffstats
path: root/app/src/fil/libre/repwifiapp/network/Engine6p0.java
blob: c6475e24eca8651c0ac9d507083d59c612013454 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
//
// Copyright 2017, 2018 Filippo "Fil" Bergamo <fil.bergamo@riseup.net>
// 
// This file is part of RepWifiApp.
//
// RepWifiApp is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// RepWifiApp is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with RepWifiApp.  If not, see <http://www.gnu.org/licenses/>.
// 
// ********************************************************************

package fil.libre.repwifiapp.network;

import fil.libre.repwifiapp.Commons;
import fil.libre.repwifiapp.helpers.Logger;
import fil.libre.repwifiapp.helpers.RootCommand;
import fil.libre.repwifiapp.helpers.ShellCommand;
import org.apache.http.conn.util.InetAddressUtils;

public class Engine6p0 extends Engine {

    private Object abortFlagSync = new Object();
    private boolean abortConnectionSignaled = false;

    @Override
    public int connect(AccessPointInfo info) {

        WpaSupplicant.kill();
        

        if (info == null) {
            Logger.logDebug("Engine's connect() received a null AccessPointInfo");
            return ConnectionResult.CONN_FAILED;
        }

        if (!checkAbortSignal())
            return ConnectionResult.CONN_ABORTED;

        // clear any previously set network
        if (!destroyNetwork()) {
            Logger.logDebug("Unable to ndc destroy network");
            return ConnectionResult.CONN_FAILED;
        }

        if (!checkAbortSignal())
            return ConnectionResult.CONN_ABORTED;

        // clear interface's ip
        if (!clearAddrs()) {
            Logger.logDebug("Unable to ndc clearaddrs");
            return ConnectionResult.CONN_FAILED;
        }

        if (!checkAbortSignal())
            return ConnectionResult.CONN_ABORTED;

        // bring up interface
        if (!interfaceUp()) {
            Logger.logDebug("Unable to bring up interface.");
            return ConnectionResult.CONN_FAILED;
        }

        if (!checkAbortSignal())
            return ConnectionResult.CONN_ABORTED;

        // launch wpa_supplicant specifying our custom configuration and the
        // socket file
        if (!WpaSupplicant.start()) {
            Logger.logDebug("Unable to run wpa start");
            return ConnectionResult.CONN_FAILED;
        }

        if (!checkAbortSignal())
            return ConnectionResult.CONN_ABORTED;

        // create new network and get network id
        String netID = WpaCli.createNetworkGetId();
        if (netID == null) {
            Logger.logDebug("Unable to fetch network id");
            return ConnectionResult.CONN_FAILED;
        }

        if (!checkAbortSignal())
            return ConnectionResult.CONN_ABORTED;

        // set network SSID
        if (!WpaCli.setNetworkSSID(info.getSsid(), netID)) {
            Logger.logDebug("Failed to set network ssid");
            return ConnectionResult.CONN_FAILED;
        }

        if (!checkAbortSignal())
            return ConnectionResult.CONN_ABORTED;

        if (info.isHidden() && !WpaCli.setNetworkScanSSID(netID)) {
            Logger.logDebug("Failed to set scan_ssid 1 for hidden network.");
            return ConnectionResult.CONN_FAILED;
        }

        if (!checkAbortSignal())
            return ConnectionResult.CONN_ABORTED;

        // set password (if any)
        if (!WpaCli.setNetworkPSK(info, netID)) {
            Logger.logDebug("Failed to set network psk");
            return ConnectionResult.CONN_FAILED;
        }

        if (!checkAbortSignal())
            return ConnectionResult.CONN_ABORTED;

        // select the network we just created
        if (!WpaCli.selectNetwork(netID)) {
            Logger.logDebug("Unable to wpa_cli select network");
            return ConnectionResult.CONN_FAILED;
        }

        if (!checkAbortSignal())
            return ConnectionResult.CONN_ABORTED;

        // enable the newtork
        if (!WpaCli.enableNetwork(netID)) {
            Logger.logDebug("Unable to wpa_cli enable_newtork");
            return ConnectionResult.CONN_FAILED;
        }

        if (!checkAbortSignal())
            return ConnectionResult.CONN_ABORTED;

        // kill previous dhchcd instances
        if (!killDhcpcd()) {
            Logger.logError("Unable to kill previous instances of dhcpcd");
        }

        if (!checkAbortSignal())
            return ConnectionResult.CONN_ABORTED;

        // get DHCP
        Logger.logDebug("Attempt to run dhcpcd..");
        try {

            int retcode = runDhcpcd(info.getDhcpConfiguration());
            if (retcode == 1) {
                Logger.logDebug("Dhcpcd exited on timeout exceeded.");
                return ConnectionResult.CONN_TIMEOUT;

            } else if (retcode != 0) {
                Logger.logDebug("Dhcpcd exited with unknown code: " + retcode);
                return ConnectionResult.CONN_FAILED;

            }
        } catch (Exception e) {
            Logger.logError("Exception while executing dhcpcd: ", e);
            return ConnectionResult.CONN_FAILED;
        }

        if (!checkAbortSignal())
            return ConnectionResult.CONN_ABORTED;

        // try to fetch gateway
        String gw = getGateWayTimeout(Commons.WAIT_FOR_GATEWAY);
        if (gw == null || !InetAddressUtils.isIPv4Address(gw)) {
            // failed to get gateway
            Logger.logDebug("Failed to get gateway");
            return ConnectionResult.CONN_GW_FAIL;
        }

        /*
         * Calls to ndc to set gateway and dns were removed 2018-04-09
         * Starting from 2018-04-20, RepWifi registers itself as a NetworkAgent.
         * When we register, all the following steps are performed by
         * ConnectivityService itself:
         * - creating a new network
         * - setting the gateway
         * - setting DNS
         * There is no reason to perform those actions on our side via the command line;
         * it would conflict with ConnectivityService's calls to "ndc"
         */

        return ConnectionResult.CONN_OK;

    }

    public void abortConnection() {
        synchronized (abortFlagSync) {
            this.abortConnectionSignaled = true;
        }
    }

    @Override
    public ConnectionStatus getConnectionStatus() {
        ConnectionStatus s = super.getConnectionStatus();
        if (s == null) {
            return null;
        }

        s.gateway = this.getGateway();

        return s;
    }

    private boolean checkAbortSignal() {

        synchronized (abortFlagSync) {
            if (abortConnectionSignaled) {
                abortConnectionSignaled = false;
                Logger.logDebug("Engine received abort connection signal. Aborting connection...");
                killDhcpcd();
                disconnect();
                return false;
            } else {
                return true;
            }
        }
    }

    private boolean destroyNetwork() {

        // needs root (tested)
        return RootCommand.executeRootCmd("ndc network destroy 1");
    }

    private String getGateWayTimeout(int timeoutMillis) {

        String gw = getGateway();
        if (gw != null && !gw.trim().isEmpty()) {
            return gw;
        }

        Logger.logDebug("Gateway not available.. going into wait loop..");

        // gateway not (yet) available
        // waits for a maximum of timeoutMillis milliseconds
        // to let the interface being registered.
        int msWaited = 0;
        while (msWaited < timeoutMillis) {

            try {
                Thread.sleep(100);
            } catch (Exception e) {
                return null;
            }
            msWaited += 100;

            gw = getGateway();
            if (gw != null && !gw.trim().isEmpty()) {
                Logger.logDebug("Gateway found after wait loop!");
                return gw;
            }
        }

        // unable to get gateway
        Logger.logError("Gateway not found after wait loop.");
        return null;

    }

    private String getGateway() {

        try {

            // doesn't need root (tested)
            ShellCommand cmd = new ShellCommand("ip route show dev " + WpaSupplicant.INTERFACE_NAME);
            if (cmd.execute() != 0) {
                Logger.logDebug("command failed show route");
                return null;
            }

            // read command output
            String out = cmd.getOutput();
            if (out == null) {
                return null;
            }

            String[] lines = out.split("\n");

            for (String l : lines) {

                if (l.contains("default via")) {

                    String[] f = l.split(" ");
                    if (f.length > 2) {

                        // found route's address:
                        return f[2];

                    }
                }
            }

            return null;

        } catch (Exception e) {
            Logger.logError("Error while trying to fetch route", e);
            return null;
        }

    }

    private boolean clearAddrs() {
        // needs root (tested)
        return RootCommand.executeRootCmd("ndc interface clearaddrs "
                        + WpaSupplicant.INTERFACE_NAME);
    }

}