This repository has been archived by the owner on Apr 10, 2024. It is now read-only.
/
WifiWorker.js
2927 lines (2543 loc) · 92.3 KB
/
WifiWorker.js
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm");
var DEBUG = false; // set to true to show debug messages
const WIFIWORKER_CONTRACTID = "@mozilla.org/wifi/worker;1";
const WIFIWORKER_CID = Components.ID("{a14e8977-d259-433a-a88d-58dd44657e5b}");
const WIFIWORKER_WORKER = "resource://gre/modules/wifi_worker.js";
const kNetworkInterfaceStateChangedTopic = "network-interface-state-changed";
const kMozSettingsChangedObserverTopic = "mozsettings-changed";
const MAX_RETRIES_ON_AUTHENTICATION_FAILURE = 2;
const MAX_SUPPLICANT_LOOP_ITERATIONS = 4;
XPCOMUtils.defineLazyServiceGetter(this, "gNetworkManager",
"@mozilla.org/network/manager;1",
"nsINetworkManager");
XPCOMUtils.defineLazyServiceGetter(this, "gSettingsService",
"@mozilla.org/settingsService;1",
"nsISettingsService");
// A note about errors and error handling in this file:
// The libraries that we use in this file are intended for C code. For
// C code, it is natural to return -1 for errors and 0 for success.
// Therefore, the code that interacts directly with the worker uses this
// convention (note: command functions do get boolean results since the
// command always succeeds and we do a string/boolean check for the
// expected results).
var WifiManager = (function() {
function getStartupPrefs() {
Cu.import("resource://gre/modules/systemlibs.js");
return {
sdkVersion: parseInt(libcutils.property_get("ro.build.version.sdk"), 10),
schedScanRecovery: libcutils.property_get("ro.moz.wifi.sched_scan_recover") === "false" ? false : true
};
}
let {sdkVersion, schedScanRecovery} = getStartupPrefs();
var controlWorker = new ChromeWorker(WIFIWORKER_WORKER);
var eventWorker = new ChromeWorker(WIFIWORKER_WORKER);
var manager = {};
manager.schedScanRecovery = schedScanRecovery;
// Callbacks to invoke when a reply arrives from the controlWorker.
var controlCallbacks = Object.create(null);
var idgen = 0;
function controlMessage(obj, callback) {
var id = idgen++;
obj.id = id;
if (callback)
controlCallbacks[id] = callback;
controlWorker.postMessage(obj);
}
function onerror(e) {
// It is very important to call preventDefault on the event here.
// If an exception is thrown on the worker, it bubbles out to the
// component that created it. If that component doesn't have an
// onerror handler, the worker will try to call the error reporter
// on the context it was created on. However, That doesn't work
// for component contexts and can result in crashes. This onerror
// handler has to make sure that it calls preventDefault on the
// incoming event.
e.preventDefault();
var worker = (this === controlWorker) ? "control" : "event";
debug("Got an error from the " + worker + " worker: " + e.filename +
":" + e.lineno + ": " + e.message + "\n");
}
controlWorker.onerror = onerror;
eventWorker.onerror = onerror;
controlWorker.onmessage = function(e) {
var data = e.data;
var id = data.id;
var callback = controlCallbacks[id];
if (callback) {
callback(data);
delete controlCallbacks[id];
}
};
// Polling the status worker
var recvErrors = 0;
eventWorker.onmessage = function(e) {
// process the event and tell the event worker to listen for more events
if (handleEvent(e.data.event))
waitForEvent();
};
function waitForEvent() {
eventWorker.postMessage({ cmd: "wait_for_event" });
}
// Commands to the control worker
function voidControlMessage(cmd, callback) {
controlMessage({ cmd: cmd }, function (data) {
callback(data.status);
});
}
var driverLoaded = false;
function loadDriver(callback) {
if (driverLoaded) {
callback(0);
return;
}
voidControlMessage("load_driver", function(status) {
driverLoaded = (status >= 0);
callback(status)
});
}
function unloadDriver(callback) {
// Unloading drivers is generally unnecessary and
// can trigger bugs in some drivers.
// On properly written drivers, bringing the interface
// down powers down the interface.
callback(0);
return;
voidControlMessage("unload_driver", function(status) {
driverLoaded = (status < 0);
callback(status);
});
}
function startSupplicant(callback) {
voidControlMessage("start_supplicant", callback);
}
function terminateSupplicant(callback) {
doBooleanCommand("TERMINATE", "OK", callback);
}
function stopSupplicant(callback) {
voidControlMessage("stop_supplicant", callback);
}
function connectToSupplicant(callback) {
voidControlMessage("connect_to_supplicant", callback);
}
function closeSupplicantConnection(callback) {
voidControlMessage("close_supplicant_connection", callback);
}
function doCommand(request, callback) {
controlMessage({ cmd: "command", request: request }, callback);
}
function doIntCommand(request, callback) {
doCommand(request, function(data) {
callback(data.status ? -1 : (data.reply|0));
});
}
function doBooleanCommand(request, expected, callback) {
doCommand(request, function(data) {
callback(data.status ? false : (data.reply == expected));
});
}
function doStringCommand(request, callback) {
doCommand(request, function(data) {
callback(data.status ? null : data.reply);
});
}
function listNetworksCommand(callback) {
doStringCommand("LIST_NETWORKS", callback);
}
function addNetworkCommand(callback) {
doIntCommand("ADD_NETWORK", callback);
}
function setNetworkVariableCommand(netId, name, value, callback) {
doBooleanCommand("SET_NETWORK " + netId + " " + name + " " + value, "OK", callback);
}
function getNetworkVariableCommand(netId, name, callback) {
doStringCommand("GET_NETWORK " + netId + " " + name, callback);
}
function removeNetworkCommand(netId, callback) {
doBooleanCommand("REMOVE_NETWORK " + netId, "OK", callback);
}
function enableNetworkCommand(netId, disableOthers, callback) {
doBooleanCommand((disableOthers ? "SELECT_NETWORK " : "ENABLE_NETWORK ") + netId, "OK", callback);
}
function disableNetworkCommand(netId, callback) {
doBooleanCommand("DISABLE_NETWORK " + netId, "OK", callback);
}
function statusCommand(callback) {
doStringCommand("STATUS", callback);
}
function pingCommand(callback) {
doBooleanCommand("PING", "PONG", callback);
}
function scanResultsCommand(callback) {
doStringCommand("SCAN_RESULTS", callback);
}
function disconnectCommand(callback) {
doBooleanCommand("DISCONNECT", "OK", callback);
}
function reconnectCommand(callback) {
doBooleanCommand("RECONNECT", "OK", callback);
}
function reassociateCommand(callback) {
doBooleanCommand("REASSOCIATE", "OK", callback);
}
// A note about background scanning:
// Normally, background scanning shouldn't be necessary as wpa_supplicant
// has the capability to automatically schedule its own scans at appropriate
// intervals. However, with some drivers, this appears to get stuck after
// three scans, so we enable the driver's background scanning to work around
// that when we're not connected to any network. This ensures that we'll
// automatically reconnect to networks if one falls out of range.
var reEnableBackgroundScan = false;
// NB: This is part of the internal API.
manager.backgroundScanEnabled = false;
function setBackgroundScan(enable, callback) {
var doEnable = (enable === "ON");
if (doEnable === manager.backgroundScanEnabled) {
callback(false, true);
return;
}
manager.backgroundScanEnabled = doEnable;
doBooleanCommand("SET pno " + (manager.backgroundScanEnabled ? "1" : "0"),
"OK",
function(ok) {
callback(true, ok);
});
}
var scanModeActive = false;
function doSetScanModeCommand(setActive, callback) {
doBooleanCommand(setActive ? "DRIVER SCAN-ACTIVE" : "DRIVER SCAN-PASSIVE", "OK", callback);
}
function scanCommand(forceActive, callback) {
if (forceActive && !scanModeActive) {
// Note: we ignore errors from doSetScanMode.
doSetScanModeCommand(true, function(ignore) {
setBackgroundScan("OFF", function(turned, ignore) {
reEnableBackgroundScan = turned;
doBooleanCommand("SCAN", "OK", function(ok) {
doSetScanModeCommand(false, function(ignore) {
// The result of scanCommand is the result of the actual SCAN
// request.
callback(ok);
});
});
});
});
return;
}
doBooleanCommand("SCAN", "OK", callback);
}
var debugEnabled = false;
function setLogLevel(level, callback) {
doBooleanCommand("LOG_LEVEL " + level, "OK", callback);
}
function syncDebug() {
if (debugEnabled !== DEBUG) {
let wanted = DEBUG;
setLogLevel(wanted ? "DEBUG" : "INFO", function(ok) {
if (ok)
debugEnabled = wanted;
});
}
}
function getLogLevel(callback) {
doStringCommand("LOG_LEVEL", callback);
}
function getDebugEnabled(callback) {
getLogLevel(function(level) {
if (level === null) {
debug("Unable to get wpa_supplicant's log level");
callback(false);
return;
}
var lines = level.split("\n");
for (let i = 0; i < lines.length; ++i) {
let match = /Current level: (.*)/.exec(lines[i]);
if (match) {
debugEnabled = match[1].toLowerCase() === "debug";
callback(true);
return;
}
}
// If we're here, we didn't get the current level.
callback(false);
});
}
function setScanModeCommand(setActive, callback) {
scanModeActive = setActive;
doSetScanModeCommand(setActive, callback);
}
function wpsPbcCommand(callback) {
doBooleanCommand("WPS_PBC", "OK", callback);
}
function wpsPinCommand(pin, callback) {
doStringCommand("WPS_PIN any" + (pin === undefined ? "" : (" " + pin)),
callback);
}
function wpsCancelCommand(callback) {
doBooleanCommand("WPS_CANCEL", "OK", callback);
}
function startDriverCommand(callback) {
doBooleanCommand("DRIVER START", "OK");
}
function stopDriverCommand(callback) {
doBooleanCommand("DRIVER STOP", "OK");
}
function startPacketFiltering(callback) {
doBooleanCommand("DRIVER RXFILTER-ADD 0", "OK", function(ok) {
ok && doBooleanCommand("DRIVER RXFILTER-ADD 1", "OK", function(ok) {
ok && doBooleanCommand("DRIVER RXFILTER-ADD 3", "OK", function(ok) {
ok && doBooleanCommand("DRIVER RXFILTER-START", "OK", callback)
});
});
});
}
function stopPacketFiltering(callback) {
doBooleanCommand("DRIVER RXFILTER-STOP", "OK", function(ok) {
ok && doBooleanCommand("DRIVER RXFILTER-REMOVE 3", "OK", function(ok) {
ok && doBooleanCommand("DRIVER RXFILTER-REMOVE 1", "OK", function(ok) {
ok && doBooleanCommand("DRIVER RXFILTER-REMOVE 0", "OK", callback)
});
});
});
}
function doGetRssiCommand(cmd, callback) {
doCommand(cmd, function(data) {
var rssi = -200;
if (!data.status) {
// If we are associating, the reply is "OK".
var reply = data.reply;
if (reply != "OK") {
// Format is: <SSID> rssi XX". SSID can contain spaces.
var offset = reply.lastIndexOf("rssi ");
if (offset !== -1)
rssi = reply.substr(offset + 5) | 0;
}
}
callback(rssi);
});
}
function getRssiCommand(callback) {
doGetRssiCommand("DRIVER RSSI", callback);
}
function getRssiApproxCommand(callback) {
doGetRssiCommand("DRIVER RSSI-APPROX", callback);
}
function getLinkSpeedCommand(callback) {
doStringCommand("DRIVER LINKSPEED", function(reply) {
if (reply)
reply = reply.split(" ")[1] | 0; // Format: LinkSpeed XX
callback(reply);
});
}
function getConnectionInfoGB(callback) {
var rval = {};
getRssiApproxCommand(function(rssi) {
rval.rssi = rssi;
getLinkSpeedCommand(function(linkspeed) {
rval.linkspeed = linkspeed;
callback(rval);
});
});
}
function getConnectionInfoICS(callback) {
doStringCommand("SIGNAL_POLL", function(reply) {
if (!reply) {
callback(null);
return;
}
let rval = {};
var lines = reply.split("\n");
for (let i = 0; i < lines.length; ++i) {
let [key, value] = lines[i].split("=");
switch (key.toUpperCase()) {
case "RSSI":
rval.rssi = value | 0;
break;
case "LINKSPEED":
rval.linkspeed = value | 0;
break;
default:
// Ignore.
}
}
callback(rval);
});
}
function getMacAddressCommand(callback) {
doStringCommand("DRIVER MACADDR", function(reply) {
if (reply)
reply = reply.split(" ")[2]; // Format: Macaddr = XX.XX.XX.XX.XX.XX
callback(reply);
});
}
function setPowerModeCommand(mode, callback) {
doBooleanCommand("DRIVER POWERMODE " + (mode === "AUTO" ? 0 : 1), "OK", callback);
}
function getPowerModeCommand(callback) {
doStringCommand("DRIVER GETPOWER", function(reply) {
if (reply)
reply = (reply.split()[2]|0); // Format: powermode = XX
callback(reply);
});
}
function setNumAllowedChannelsCommand(numChannels, callback) {
doBooleanCommand("DRIVER SCAN-CHANNELS " + numChannels, "OK", callback);
}
function getNumAllowedChannelsCommand(callback) {
doStringCommand("DRIVER SCAN-CHANNELS", function(reply) {
if (reply)
reply = (reply.split()[2]|0); // Format: Scan-Channels = X
callback(reply);
});
}
function setBluetoothCoexistenceModeCommand(mode, callback) {
doBooleanCommand("DRIVER BTCOEXMODE " + mode, "OK", callback);
}
function setBluetoothCoexistenceScanModeCommand(mode, callback) {
doBooleanCommand("DRIVER BTCOEXSCAN-" + (mode ? "START" : "STOP"), "OK", callback);
}
function saveConfigCommand(callback) {
// Make sure we never write out a value for AP_SCAN other than 1
doBooleanCommand("AP_SCAN 1", "OK", function(ok) {
doBooleanCommand("SAVE_CONFIG", "OK", callback);
});
}
function reloadConfigCommand(callback) {
doBooleanCommand("RECONFIGURE", "OK", callback);
}
function setScanResultHandlingCommand(mode, callback) {
doBooleanCommand("AP_SCAN " + mode, "OK", callback);
}
function addToBlacklistCommand(bssid, callback) {
doBooleanCommand("BLACKLIST " + bssid, "OK", callback);
}
function clearBlacklistCommand(callback) {
doBooleanCommand("BLACKLIST clear", "OK", callback);
}
function setSuspendOptimizationsCommand(enabled, callback) {
doBooleanCommand("DRIVER SETSUSPENDOPT " + (enabled ? 0 : 1), "OK", callback);
}
function getProperty(key, defaultValue, callback) {
controlMessage({ cmd: "property_get", key: key, defaultValue: defaultValue }, function(data) {
callback(data.status < 0 ? null : data.value);
});
}
function setProperty(key, value, callback) {
controlMessage({ cmd: "property_set", key: key, value: value }, function(data) {
callback(!data.status);
});
}
function enableInterface(ifname, callback) {
controlMessage({ cmd: "ifc_enable", ifname: ifname }, function(data) {
callback(!data.status);
});
}
function disableInterface(ifname, callback) {
controlMessage({ cmd: "ifc_disable", ifname: ifname }, function(data) {
callback(!data.status);
});
}
function addHostRoute(ifname, route, callback) {
controlMessage({ cmd: "ifc_add_host_route", ifname: ifname, route: route }, function(data) {
callback(!data.status);
});
}
function removeHostRoutes(ifname, callback) {
controlMessage({ cmd: "ifc_remove_host_routes", ifname: ifname }, function(data) {
callback(!data.status);
});
}
function setDefaultRoute(ifname, route, callback) {
controlMessage({ cmd: "ifc_set_default_route", ifname: ifname, route: route }, function(data) {
callback(!data.status);
});
}
function getDefaultRoute(ifname, callback) {
controlMessage({ cmd: "ifc_get_default_route", ifname: ifname }, function(data) {
callback(!data.route);
});
}
function removeDefaultRoute(ifname, callback) {
controlMessage({ cmd: "ifc_remove_default_route", ifname: ifname }, function(data) {
callback(!data.status);
});
}
function resetConnections(ifname, callback) {
controlMessage({ cmd: "ifc_reset_connections", ifname: ifname }, function(data) {
callback(!data.status);
});
}
var dhcpInfo = null;
function runDhcp(ifname, callback) {
controlMessage({ cmd: "dhcp_do_request", ifname: ifname }, function(data) {
dhcpInfo = data.status ? null : data;
callback(dhcpInfo);
});
}
function stopDhcp(ifname, callback) {
controlMessage({ cmd: "dhcp_stop", ifname: ifname }, function(data) {
dhcpInfo = null;
notify("dhcplost");
callback(!data.status);
});
}
function releaseDhcpLease(ifname, callback) {
controlMessage({ cmd: "dhcp_release_lease", ifname: ifname }, function(data) {
dhcpInfo = null;
notify("dhcplost");
callback(!data.status);
});
}
function getDhcpError(callback) {
controlMessage({ cmd: "dhcp_get_errmsg" }, function(data) {
callback(data.error);
});
}
function configureInterface(ifname, ipaddr, mask, gateway, dns1, dns2, callback) {
controlMessage({ cmd: "ifc_configure", ifname: ifname,
ipaddr: ipaddr, mask: mask, gateway: gateway,
dns1: dns1, dns2: dns2}, function(data) {
callback(!data.status);
});
}
function runDhcpRenew(ifname, callback) {
controlMessage({ cmd: "dhcp_do_request", ifname: ifname }, function(data) {
if (!data.status)
dhcpInfo = data;
callback(data.status ? null : data);
});
}
var suppressEvents = false;
function notify(eventName, eventObject) {
if (suppressEvents)
return;
var handler = manager["on" + eventName];
if (handler) {
if (!eventObject)
eventObject = ({});
handler.call(eventObject);
}
}
function notifyStateChange(fields) {
// If we're already in the COMPLETED state, we might receive events from
// the supplicant that tell us that we're re-authenticating or reminding
// us that we're associated to a network. In those cases, we don't need to
// do anything, so just ignore them.
if (manager.state === "COMPLETED" &&
fields.state !== "DISCONNECTED" &&
fields.state !== "INTERFACE_DISABLED" &&
fields.state !== "INACTIVE" &&
fields.state !== "SCANNING") {
return false;
}
// Stop background scanning if we're trying to connect to a network.
if (manager.backgroundScanEnabled &&
(fields.state === "ASSOCIATING" ||
fields.state === "ASSOCIATED" ||
fields.state === "FOUR_WAY_HANDSHAKE" ||
fields.state === "GROUP_HANDSHAKE" ||
fields.state === "COMPLETED")) {
setBackgroundScan("OFF", function() {});
}
fields.prevState = manager.state;
manager.state = fields.state;
// Detect wpa_supplicant's loop iterations.
manager.supplicantLoopDetection(fields.prevState, fields.state);
notify("statechange", fields);
return true;
}
function parseStatus(status) {
if (status === null) {
debug("Unable to get wpa supplicant's status");
return;
}
var ssid;
var bssid;
var state;
var ip_address;
var id;
var lines = status.split("\n");
for (let i = 0; i < lines.length; ++i) {
let [key, value] = lines[i].split("=");
switch (key) {
case "wpa_state":
state = value;
break;
case "ssid":
ssid = value;
break;
case "bssid":
bssid = value;
break;
case "ip_address":
ip_address = value;
break;
case "id":
id = value;
break;
}
}
if (bssid && ssid) {
manager.connectionInfo.bssid = bssid;
manager.connectionInfo.ssid = ssid;
manager.connectionInfo.id = id;
}
if (ip_address)
dhcpInfo = { ip_address: ip_address };
notifyStateChange({ state: state, fromStatus: true });
// If we parse the status and the supplicant has already entered the
// COMPLETED state, then we need to set up DHCP right away.
if (state === "COMPLETED")
onconnected();
}
// try to connect to the supplicant
var connectTries = 0;
var retryTimer = null;
function connectCallback(ok) {
if (ok === 0) {
// Tell the event worker to start waiting for events.
retryTimer = null;
didConnectSupplicant(function(){});
return;
}
if (connectTries++ < 3) {
// try again in 5 seconds
if (!retryTimer)
retryTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
retryTimer.initWithCallback(function(timer) {
connectToSupplicant(connectCallback);
}, 5000, Ci.nsITimer.TYPE_ONE_SHOT);
return;
}
retryTimer = null;
notify("supplicantfailed");
}
manager.connectionDropped = function(callback) {
// If we got disconnected, kill the DHCP client in preparation for
// reconnection.
resetConnections(manager.ifname, function() {
stopDhcp(manager.ifname, function() {
callback();
});
});
}
manager.start = function() {
debug("detected SDK version " + sdkVersion);
connectToSupplicant(connectCallback);
}
function onconnected() {
// For now we do our own DHCP. In the future, this should be handed
// off to the Network Manager.
runDhcp(manager.ifname, function (data) {
if (!data) {
debug("DHCP failed to run");
notify("dhcpconnected", { info: data });
return;
}
setProperty("net." + manager.ifname + ".dns1", ipToString(data.dns1),
function(ok) {
if (!ok) {
debug("Unable to set net.<ifname>.dns1");
return;
}
setProperty("net." + manager.ifname + ".dns2", ipToString(data.dns2),
function(ok) {
if (!ok) {
debug("Unable to set net.<ifname>.dns2");
return;
}
setProperty("net." + manager.ifname + ".gw", ipToString(data.gateway),
function(ok) {
if (!ok) {
debug("Unable to set net.<ifname>.gw");
return;
}
notify("dhcpconnected", { info: data });
});
});
});
});
}
var supplicantStatesMap = (sdkVersion >= 15) ?
["DISCONNECTED", "INTERFACE_DISABLED", "INACTIVE", "SCANNING",
"AUTHENTICATING", "ASSOCIATING", "ASSOCIATED", "FOUR_WAY_HANDSHAKE",
"GROUP_HANDSHAKE", "COMPLETED"]
:
["DISCONNECTED", "INACTIVE", "SCANNING", "ASSOCIATING",
"ASSOCIATED", "FOUR_WAY_HANDSHAKE", "GROUP_HANDSHAKE",
"COMPLETED", "DORMANT", "UNINITIALIZED"];
var driverEventMap = { STOPPED: "driverstopped", STARTED: "driverstarted", HANGED: "driverhung" };
manager.getCurrentNetworkId = function (ssid, callback) {
manager.getConfiguredNetworks(function(networks) {
if (!networks) {
debug("Unable to get configured networks");
return callback(null);
}
for (let net in networks) {
let network = networks[net];
// Trying to get netId from
// 1. CURRENT network.
// 2. Trying to associate with SSID 'ssid' event
if (network.status === "CURRENT" ||
(ssid && ssid === dequote(network.ssid))) {
return callback(net);
}
}
callback(null);
});
}
// handle events sent to us by the event worker
function handleEvent(event) {
debug("Event coming in: " + event);
if (event.indexOf("CTRL-EVENT-") !== 0 && event.indexOf("WPS") !== 0) {
// Handle connection fail exception on WEP-128, while password length
// is not 5 nor 13 bytes.
if (event.indexOf("Association request to the driver failed") !== -1) {
notify("passwordmaybeincorrect");
if (manager.authenticationFailuresCount > MAX_RETRIES_ON_AUTHENTICATION_FAILURE) {
manager.authenticationFailuresCount = 0;
notify("disconnected", {ssid: manager.connectionInfo.ssid});
}
return true;
}
if (event.indexOf("WPA:") == 0 &&
event.indexOf("pre-shared key may be incorrect") != -1) {
notify("passwordmaybeincorrect");
}
// This is ugly, but we need to grab the SSID here. BSSID is not guaranteed
// to be provided, so don't grab BSSID here.
var match = /Trying to associate with.*SSID[ =]'(.*)'/.exec(event);
if (match) {
debug("Matched: " + match[1] + "\n");
manager.connectionInfo.ssid = match[1];
}
return true;
}
var space = event.indexOf(" ");
var eventData = event.substr(0, space + 1);
if (eventData.indexOf("CTRL-EVENT-STATE-CHANGE") === 0) {
// Parse the event data
var fields = {};
var tokens = event.substr(space + 1).split(" ");
for (var n = 0; n < tokens.length; ++n) {
var kv = tokens[n].split("=");
if (kv.length === 2)
fields[kv[0]] = kv[1];
}
if (!("state" in fields))
return true;
fields.state = supplicantStatesMap[fields.state];
// The BSSID field is only valid in the ASSOCIATING and ASSOCIATED
// states, except when we "reauth", except this seems to depend on the
// driver, so simply check to make sure that we don't have a null BSSID.
if (fields.BSSID !== "00:00:00:00:00:00")
manager.connectionInfo.bssid = fields.BSSID;
if (notifyStateChange(fields) && fields.state === "COMPLETED") {
onconnected();
}
return true;
}
if (eventData.indexOf("CTRL-EVENT-DRIVER-STATE") === 0) {
var handlerName = driverEventMap[eventData];
if (handlerName)
notify(handlerName);
return true;
}
if (eventData.indexOf("CTRL-EVENT-TERMINATING") === 0) {
// If the monitor socket is closed, we have already stopped the
// supplicant and we can stop waiting for more events and
// simply exit here (we don't have to notify about having lost
// the connection).
if (eventData.indexOf("connection closed") !== -1) {
notify("supplicantlost");
return false;
}
// As long we haven't seen too many recv errors yet, we
// will keep going for a bit longer
if (eventData.indexOf("recv error") !== -1 && ++recvErrors < 10)
return true;
notifyStateChange({ state: "DISCONNECTED", BSSID: null, id: -1 });
notify("supplicantlost");
return false;
}
if (eventData.indexOf("CTRL-EVENT-DISCONNECTED") === 0) {
var token = event.split(" ")[1];
var bssid = token.split("=")[1];
if (manager.authenticationFailuresCount > MAX_RETRIES_ON_AUTHENTICATION_FAILURE) {
manager.authenticationFailuresCount = 0;
notify("disconnected", {ssid: manager.connectionInfo.ssid});
}
manager.connectionInfo.bssid = null;
manager.connectionInfo.ssid = null;
manager.connectionInfo.id = -1;
return true;
}
// Association reject is triggered mostly on incorrect WEP key.
if (eventData.indexOf("CTRL-EVENT-ASSOC-REJECT") === 0) {
notify("passwordmaybeincorrect");
if (manager.authenticationFailuresCount > MAX_RETRIES_ON_AUTHENTICATION_FAILURE) {
manager.authenticationFailuresCount = 0;
notify("disconnected", {ssid: manager.connectionInfo.ssid});
}
return true;
}
if (eventData.indexOf("CTRL-EVENT-EAP-FAILURE") === 0) {
if (event.indexOf("EAP authentication failed") !== -1) {
notify("passwordmaybeincorrect");
}
return true;
}
if (eventData.indexOf("CTRL-EVENT-CONNECTED") === 0) {
// Format: CTRL-EVENT-CONNECTED - Connection to 00:1e:58:ec:d5:6d completed (reauth) [id=1 id_str=]
var bssid = event.split(" ")[4];
var id = event.substr(event.indexOf("id=")).split(" ")[0];
// Read current BSSID here, it will always being provided.
manager.connectionInfo.bssid = bssid;
return true;
}
if (eventData.indexOf("CTRL-EVENT-SCAN-RESULTS") === 0) {
debug("Notifying of scan results available");
if (reEnableBackgroundScan) {
reEnableBackgroundScan = false;
setBackgroundScan("ON", function() {});
}
notify("scanresultsavailable");
return true;
}
if (eventData.indexOf("WPS-TIMEOUT") === 0) {
notifyStateChange({ state: "WPS_TIMEOUT", BSSID: null, id: -1 });
return true;
}
if (eventData.indexOf("WPS-FAIL") === 0) {
notifyStateChange({ state: "WPS_FAIL", BSSID: null, id: -1 });
return true;
}
if (eventData.indexOf("WPS-OVERLAP-DETECTED") === 0) {
notifyStateChange({ state: "WPS_OVERLAP_DETECTED", BSSID: null, id: -1 });
return true;
}
// unknown event
return true;
}
const SUPP_PROP = "init.svc.wpa_supplicant";
function killSupplicant(callback) {
// It is interesting to note that this function does exactly what
// wifi_stop_supplicant does. Unforunately, on the Galaxy S2, Samsung
// changed that function in a way that means that it doesn't recognize
// wpa_supplicant as already running. Therefore, we have to roll our own
// version here.
var count = 0;
var timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
function tick() {
getProperty(SUPP_PROP, "stopped", function (result) {
if (result === null) {
callback();
return;
}
if (result === "stopped" || ++count >= 5) {
// Either we succeeded or ran out of time.
timer = null;
callback();
return;
}
// Else it's still running, continue waiting.
timer.initWithCallback(tick, 1000, Ci.nsITimer.TYPE_ONE_SHOT);
});
}
setProperty("ctl.stop", "wpa_supplicant", tick);
}
function didConnectSupplicant(callback) {
waitForEvent();
// Load up the supplicant state.