summaryrefslogtreecommitdiff
path: root/src/gclue-wifi.c
blob: cd20b0dfddc1791af01d9b9e70f612cdbc7e4253 (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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
/* vim: set et ts=8 sw=8: */
/*
 * Copyright 2014 Red Hat, Inc.
 *
 * Geoclue 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 2 of the License, or (at your option)
 * any later version.
 *
 * Geoclue 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 Geoclue; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Authors: Zeeshan Ali (Khattak) <zeeshanak@gnome.org>
 */

#include <stdlib.h>
#include <glib.h>
#include <string.h>
#include <config.h>
#include "gclue-wifi.h"
#include "gclue-3g.h"
#include "gclue-config.h"
#include "gclue-error.h"
#include "gclue-mozilla.h"

#define WIFI_SCAN_TIMEOUT_HIGH_ACCURACY 10
/* Since this is only used for city-level accuracy, 5 minutes between each
 * scan is more than enough.
 */
#define WIFI_SCAN_TIMEOUT_LOW_ACCURACY  300

/* WiFi APs at and below this signal level in scan results are ignored.
 * In dBm units.
 */
#define WIFI_SCAN_BSS_NOISE_LEVEL -90

#define BSSID_LEN 6
#define BSSID_STR_LEN 17
#define MAX_SSID_LEN 32

/* Drop entries from the cache when they are more than 48 hours old. If we are
 * polling at high accuracy for that entire period, that gives a maximum cache
 * size of 17280 entries. At roughly 400B each, that’s about 7MB of heap for a
 * full cache (excluding overheads). */
#define CACHE_ENTRY_MAX_AGE_SECONDS (48 * 60 * 60)

/* The signal strength can typically vary by ±5 for a stationary laptop, so
 * match cache entries with that tolerance.
 * In dBm units.
 */
#define CACHE_ENTRY_MATCH_SIGNAL_WINDOW 10

/**
 * SECTION:gclue-wifi
 * @short_description: WiFi-based geolocation
 * @include: gclue-glib/gclue-wifi.h
 *
 * Contains functions to get the geolocation based on nearby WiFi networks.
 **/

static GClueLocationSourceStartResult
gclue_wifi_start (GClueLocationSource *source);
static GClueLocationSourceStopResult
gclue_wifi_stop (GClueLocationSource *source);

static guint
variant_hash (gconstpointer key);

static void
gclue_wifi_refresh_async (GClueWebSource      *source,
                          GCancellable        *cancellable,
                          GAsyncReadyCallback  callback,
                          gpointer             user_data);
static GClueLocation *
gclue_wifi_refresh_finish (GClueWebSource  *source,
                           GAsyncResult    *result,
                           GError         **error);

static void
disconnect_cache_prune_timeout (GClueWifi *wifi);

typedef struct {
        GArray *signals;
        GClueLocation *location;
} LocationCacheElement;

static LocationCacheElement *
location_cache_element_new (GArray *signals,
                            GClueLocation *location)
{
        LocationCacheElement *element;

        element = g_slice_new (LocationCacheElement);
        element->signals = signals;
        element->location = g_object_ref (location);
        return element;
}

static void location_cache_element_free (gpointer data)
{
        LocationCacheElement *element = data;

        if (element->signals)
                g_array_free (element->signals, TRUE);
        g_clear_object (&element->location);
        g_slice_free (LocationCacheElement, element);
}

typedef struct {
        GList *elements;
} LocationCacheValue;

static LocationCacheValue *
location_cache_value_new (void)
{
        LocationCacheValue *value;

        value = g_slice_new (LocationCacheValue);
        value->elements = NULL;
        return value;
}

static void location_cache_value_free (gpointer data)
{
        LocationCacheValue *value = data;

        g_list_free_full (value->elements, location_cache_element_free);
        g_slice_free (LocationCacheValue, value);
}

struct _GClueWifiPrivate {
        GCancellable *intf_cancellable, *bss_cancellable;
        GClueMozilla *mozilla;
        WPASupplicant *supplicant;
        WPAInterface *interface;
        GHashTable *bss_proxies;
        GHashTable *ignored_bss_proxies;
        gboolean bss_list_changed;

        gulong bss_added_id;
        gulong bss_removed_id;
        gulong scan_done_id;
        guint scan_wait_id;

        guint scan_timeout;

        GHashTable *location_cache;  /* (element-type GVariant LocationCacheValue) (owned) */
        guint cache_prune_timeout_id;
        guint cache_hits, cache_misses;

#if GLIB_CHECK_VERSION(2, 64, 0)
        GMemoryMonitor *memory_monitor;
        gulong low_memory_warning_id;
#endif
};

static SoupMessage *
gclue_wifi_create_query (GClueWebSource *source,
                         const char **query_data_description,
                         GError        **error);
static SoupMessage *
gclue_wifi_create_submit_query (GClueWebSource  *source,
                                GClueLocation   *location,
                                GError         **error);
static GClueAccuracyLevel
gclue_wifi_get_available_accuracy_level (GClueWebSource *source,
                                         gboolean        net_available);

G_DEFINE_TYPE_WITH_CODE (GClueWifi,
                         gclue_wifi,
                         GCLUE_TYPE_WEB_SOURCE,
                         G_ADD_PRIVATE (GClueWifi))

static void
disconnect_bss_signals (GClueWifi *wifi);
static void
on_scan_call_done (GObject      *source_object,
                   GAsyncResult *res,
                   gpointer      user_data);
static void
on_scan_done (WPAInterface *object,
              gboolean      success,
              gpointer      user_data);

static void
gclue_wifi_finalize (GObject *gwifi)
{
        GClueWifi *wifi = (GClueWifi *) gwifi;

        G_OBJECT_CLASS (gclue_wifi_parent_class)->finalize (gwifi);

        g_cancellable_cancel (wifi->priv->intf_cancellable);

        disconnect_bss_signals (wifi);
        disconnect_cache_prune_timeout (wifi);

        g_clear_object (&wifi->priv->supplicant);
        g_clear_object (&wifi->priv->interface);
        g_clear_pointer (&wifi->priv->bss_proxies, g_hash_table_unref);
        g_clear_pointer (&wifi->priv->ignored_bss_proxies, g_hash_table_unref);
        g_clear_pointer (&wifi->priv->location_cache, g_hash_table_unref);
        g_clear_object (&wifi->priv->mozilla);
        g_clear_object (&wifi->priv->intf_cancellable);
}

static void
gclue_wifi_constructed (GObject *object);

static void
gclue_wifi_class_init (GClueWifiClass *klass)
{
        GClueWebSourceClass *web_class = GCLUE_WEB_SOURCE_CLASS (klass);
        GClueLocationSourceClass *source_class = GCLUE_LOCATION_SOURCE_CLASS (klass);
        GObjectClass *gwifi_class = G_OBJECT_CLASS (klass);

        source_class->start = gclue_wifi_start;
        source_class->stop = gclue_wifi_stop;
        web_class->refresh_async = gclue_wifi_refresh_async;
        web_class->refresh_finish = gclue_wifi_refresh_finish;
        web_class->create_submit_query = gclue_wifi_create_submit_query;
        web_class->create_query = gclue_wifi_create_query;
        web_class->get_available_accuracy_level =
                gclue_wifi_get_available_accuracy_level;
        gwifi_class->finalize = gclue_wifi_finalize;
        gwifi_class->constructed = gclue_wifi_constructed;
}

static void
on_bss_added (WPAInterface *object,
              const gchar  *path,
              GVariant     *properties,
              gpointer      user_data);

static guint
variant_to_string (GVariant *variant, guint max_len, char *ret)
{
        guint i;
        guint len;

        len = g_variant_n_children (variant);
        if (len == 0)
                return 0;
        g_return_val_if_fail(len <= max_len, 0);
        ret[len] = '\0';

        for (i = 0; i < len; i++)
                g_variant_get_child (variant,
                                     i,
                                     "y",
                                     &ret[i]);

        return len;
}

static guint
get_ssid_from_bss (WPABSS *bss, char *ssid)
{
        GVariant *variant = wpa_bss_get_ssid (bss);

        return variant_to_string (variant, MAX_SSID_LEN, ssid);
}

static gboolean
get_bssid_from_bss (WPABSS *bss, char *bssid)
{
        GVariant *variant;
        char raw_bssid[BSSID_LEN + 1] = { 0 };
        guint raw_len, i;

        variant = wpa_bss_get_bssid (bss);
        if (variant == NULL)
                return FALSE;

        raw_len = variant_to_string (variant, BSSID_LEN, raw_bssid);
        g_return_val_if_fail (raw_len == BSSID_LEN, FALSE);

        for (i = 0; i < BSSID_LEN; i++) {
                unsigned char c = (unsigned char) raw_bssid[i];

                if (i == BSSID_LEN - 1) {
                        g_snprintf (bssid + (i * 3), 3, "%02x", c);
                } else {
                        g_snprintf (bssid + (i * 3), 4, "%02x:", c);
                }
        }

        return TRUE;
}

static void
add_bss_proxy (GClueWifi *wifi,
               WPABSS    *bss)
{
        const char *path;

        path = g_dbus_proxy_get_object_path (G_DBUS_PROXY (bss));
        if (g_hash_table_replace (wifi->priv->bss_proxies,
                                  g_strdup (path),
                                  bss)) {
                char ssid[MAX_SSID_LEN + 1] = { 0 };

                wifi->priv->bss_list_changed = TRUE;
                get_ssid_from_bss (bss, ssid);
                g_debug ("WiFi AP '%s' added.", ssid);
        }
}

static void
on_bss_signal_notify (GObject    *gobject,
                      GParamSpec *pspec,
                      gpointer    user_data)
{
        GClueWifi *wifi = GCLUE_WIFI (user_data);
        WPABSS *bss = WPA_BSS (gobject);
        const char *path;

        if (wpa_bss_get_signal (bss) <= WIFI_SCAN_BSS_NOISE_LEVEL) {
                char bssid[BSSID_STR_LEN + 1] = { 0 };

                get_bssid_from_bss (bss, bssid);
                g_debug ("WiFi AP '%s' still has very low strength (%d dBm)"
                         ", ignoring again…",
                         bssid,
                         wpa_bss_get_signal (bss));
                return;
        }

        g_signal_handlers_disconnect_by_func (G_OBJECT (bss),
                                              on_bss_signal_notify,
                                              user_data);
        add_bss_proxy (wifi, g_object_ref (bss));
        path = g_dbus_proxy_get_object_path (G_DBUS_PROXY (bss));
        g_hash_table_remove (wifi->priv->ignored_bss_proxies, path);
}

static void
on_bss_proxy_ready (GObject      *source_object,
                    GAsyncResult *res,
                    gpointer      user_data)
{
        GClueWifi *wifi;
        WPABSS *bss;
        g_autoptr(GError) error = NULL;
        char ssid[MAX_SSID_LEN + 1] = { 0 };

        bss = wpa_bss_proxy_new_for_bus_finish (res, &error);
        if (bss == NULL) {
                if (error && !g_error_matches (error, G_IO_ERROR,
                                               G_IO_ERROR_CANCELLED)) {
                        g_warning ("BSS proxy setup failed: %s",
                                   error->message);
                }

                return;
        }

        wifi = GCLUE_WIFI (user_data);

        if (gclue_mozilla_should_ignore_bss (bss)) {
                g_object_unref (bss);

                return;
        }

        get_ssid_from_bss (bss, ssid);
        g_debug ("Got WiFi AP '%s'", ssid);

        if (wpa_bss_get_signal (bss) <= WIFI_SCAN_BSS_NOISE_LEVEL) {
                const char *path;
                char bssid[BSSID_STR_LEN + 1] = { 0 };

                get_bssid_from_bss (bss, bssid);
                g_debug ("WiFi AP '%s' has very low strength (%d dBm)"
                         ", ignoring for now…",
                         bssid,
                         wpa_bss_get_signal (bss));
                g_signal_connect (G_OBJECT (bss),
                                  "notify::signal",
                                  G_CALLBACK (on_bss_signal_notify),
                                  user_data);
                path = g_dbus_proxy_get_object_path (G_DBUS_PROXY (bss));
                g_hash_table_replace (wifi->priv->ignored_bss_proxies,
                                      g_strdup (path),
                                      bss);
                return;
        }

        add_bss_proxy (wifi, bss);
}

static void
on_bss_added (WPAInterface *object,
              const gchar  *path,
              GVariant     *properties,
              gpointer      user_data)
{
        GClueWifi *wifi = GCLUE_WIFI (user_data);

        wpa_bss_proxy_new_for_bus (G_BUS_TYPE_SYSTEM,
                                   G_DBUS_PROXY_FLAGS_NONE,
                                   "fi.w1.wpa_supplicant1",
                                   path,
                                   wifi->priv->bss_cancellable,
                                   on_bss_proxy_ready,
                                   wifi);
}

static gboolean
remove_bss_from_hashtable (const gchar *path, GHashTable *hash_table)
{
        char ssid[MAX_SSID_LEN + 1] = { 0 };
        WPABSS *bss = NULL;

        bss = g_hash_table_lookup (hash_table, path);
        if (bss == NULL)
                return FALSE;

        get_ssid_from_bss (bss, ssid);
        g_debug ("WiFi AP '%s' removed.", ssid);

        g_hash_table_remove (hash_table, path);

        return TRUE;
}

static void
on_bss_removed (WPAInterface *object,
                const gchar  *path,
                gpointer      user_data)
{
        GClueWifiPrivate *priv = GCLUE_WIFI (user_data)->priv;

        if (remove_bss_from_hashtable (path, priv->bss_proxies))
                priv->bss_list_changed = TRUE;
        remove_bss_from_hashtable (path, priv->ignored_bss_proxies);
}

static void
start_wifi_scan (GClueWifi *wifi)
{
        GClueWifiPrivate *priv = wifi->priv;
        GVariantBuilder builder;
        GVariant *args;

        g_debug ("Starting WiFi scan…");

        if (priv->scan_done_id == 0)
                priv->scan_done_id = g_signal_connect
                                        (priv->interface,
                                         "scan-done",
                                         G_CALLBACK (on_scan_done),
                                         wifi);

        g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
        g_variant_builder_add (&builder,
                               "{sv}",
                               "Type", g_variant_new ("s", "passive"));
        args = g_variant_builder_end (&builder);

        wpa_interface_call_scan (WPA_INTERFACE (priv->interface),
                                 args,
                                 priv->bss_cancellable,
                                 on_scan_call_done,
                                 wifi);
}

static void
cancel_wifi_scan (GClueWifi *wifi)
{
        GClueWifiPrivate *priv = wifi->priv;

        if (priv->scan_timeout != 0) {
                g_source_remove (priv->scan_timeout);
                priv->scan_timeout = 0;
        }

        if (priv->scan_wait_id != 0) {
                g_source_remove (priv->scan_wait_id);
                priv->scan_wait_id = 0;
        }

        if (priv->scan_done_id != 0) {
                g_signal_handler_disconnect (priv->interface,
                                             priv->scan_done_id);
                priv->scan_done_id = 0;
        }
}

static gboolean
on_scan_timeout (gpointer user_data)
{
        GClueWifi *wifi = GCLUE_WIFI (user_data);
        GClueWifiPrivate *priv = wifi->priv;

        priv->scan_timeout = 0;

        if (priv->interface == NULL)
                return G_SOURCE_REMOVE;

        start_wifi_scan (wifi);

        return G_SOURCE_REMOVE;
}

gboolean gclue_wifi_should_skip_bsss (GClueAccuracyLevel level)
{
        return level < GCLUE_ACCURACY_LEVEL_STREET;
}

static gboolean
on_scan_wait_done (gpointer wifi)
{
        GClueWifiPrivate *priv;

        g_return_val_if_fail (GCLUE_IS_WIFI (wifi), G_SOURCE_REMOVE);
        priv = GCLUE_WIFI(wifi)->priv;

        /* We have the latest scan result */
        gclue_mozilla_set_wifi (priv->mozilla, wifi);

        if (priv->bss_list_changed) {
                priv->bss_list_changed = FALSE;
                g_debug ("WiFi BSS list changed, refreshing location…");
                gclue_mozilla_set_bss_dirty (priv->mozilla);
                gclue_web_source_refresh (GCLUE_WEB_SOURCE (wifi));
        }
        priv->scan_wait_id = 0;

        return G_SOURCE_REMOVE;
}

static GClueAccuracyLevel
get_accuracy_level (GClueWifi *wifi)
{
        GClueAccuracyLevel level;

        g_object_get (G_OBJECT (wifi), "accuracy-level", &level, NULL);
        return level;
}

static void
on_scan_done (WPAInterface *object,
              gboolean      success,
              gpointer      user_data)
{
        GClueWifi *wifi = GCLUE_WIFI (user_data);
        GClueWifiPrivate *priv = wifi->priv;
        guint timeout;

        if (!success) {
                g_warning ("WiFi scan failed");

                return;
        }

        if (priv->interface == NULL)
                return;

        if (priv->scan_wait_id != 0)
            g_source_remove (priv->scan_wait_id);

        priv->scan_wait_id = g_timeout_add_seconds (1, on_scan_wait_done, wifi);

        /* If there was another scan already scheduled, cancel that and
         * re-schedule. Regardless of our internal book-keeping, this can happen
         * if wpa_supplicant emits the `ScanDone` signal due to a scan being
         * initiated by another client. */
        if (priv->scan_timeout != 0) {
                g_source_remove (priv->scan_timeout);
                priv->scan_timeout = 0;
        }

        /* With high-enough accuracy requests, we need to scan more often since
         * user's location can change quickly. With low accuracy, we don't since
         * we wouldn't want to drain power unnecessarily.
         */
        if (get_accuracy_level (wifi) >= GCLUE_ACCURACY_LEVEL_STREET)
                timeout = WIFI_SCAN_TIMEOUT_HIGH_ACCURACY;
        else
                timeout = WIFI_SCAN_TIMEOUT_LOW_ACCURACY;
        priv->scan_timeout = g_timeout_add_seconds (timeout,
                                                    on_scan_timeout,
                                                    wifi);
        g_debug ("WiFi scan done, next scheduled in %u seconds", timeout);
}

static void
on_scan_call_done (GObject      *source_object,
                   GAsyncResult *res,
                   gpointer      user_data)
{
        g_autoptr(GError) error = NULL;

        if (!wpa_interface_call_scan_finish (WPA_INTERFACE (source_object),
                                             res, &error)) {
                GClueWifi *wifi;

                if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
                        return;
                }

                wifi = GCLUE_WIFI (user_data);

                if (error) {
                        g_warning ("Scanning of WiFi networks failed: %s",
                                   error->message);
                }

                cancel_wifi_scan (wifi);
        }
}

static void
connect_bss_signals (GClueWifi *wifi)
{
        GClueWifiPrivate *priv = wifi->priv;
        const gchar *const *bss_list;
        guint i;

        if (priv->bss_added_id != 0)
                return;
        if (priv->interface == NULL) {
                gclue_web_source_refresh (GCLUE_WEB_SOURCE (wifi));

                return;
        }

        g_assert (!priv->bss_cancellable);
        priv->bss_cancellable = g_cancellable_new ();

        start_wifi_scan (wifi);

        priv->bss_list_changed = TRUE;
        priv->bss_added_id = g_signal_connect (priv->interface,
                                               "bss-added",
                                               G_CALLBACK (on_bss_added),
                                               wifi);
        priv->bss_removed_id = g_signal_connect (priv->interface,
                                                "bss-removed",
                                                G_CALLBACK (on_bss_removed),
                                                wifi);

        bss_list = wpa_interface_get_bsss (WPA_INTERFACE (priv->interface));
        if (bss_list == NULL)
                return;

        for (i = 0; bss_list[i] != NULL; i++)
                on_bss_added (WPA_INTERFACE (priv->interface),
                              bss_list[i],
                              NULL,
                              wifi);
}

static void
disconnect_bss_signals (GClueWifi *wifi)
{
        GClueWifiPrivate *priv = wifi->priv;

        if (priv->bss_cancellable) {
                g_debug ("Cancelling WiFi requests");
                g_cancellable_cancel (priv->bss_cancellable);
                g_clear_object (&priv->bss_cancellable);
        }

        cancel_wifi_scan (wifi);

        if (priv->bss_added_id != 0) {
                g_signal_handler_disconnect (priv->interface,
                                             priv->bss_added_id);
                priv->bss_added_id = 0;
        }
        if (priv->bss_removed_id != 0) {
                g_signal_handler_disconnect (priv->interface,
                                             priv->bss_removed_id);
                priv->bss_removed_id = 0;
        }

        g_hash_table_remove_all (priv->bss_proxies);
        g_hash_table_remove_all (priv->ignored_bss_proxies);
}

static void
cache_prune (GClueWifi *wifi)
{
        GClueWifiPrivate *priv = wifi->priv;
        GHashTableIter iter;
        gpointer value;
        guint64 cutoff_seconds;
        guint old_cache_size, removed_elements = 0;

        old_cache_size = g_hash_table_size (priv->location_cache);
        cutoff_seconds = g_get_real_time () / G_USEC_PER_SEC - CACHE_ENTRY_MAX_AGE_SECONDS;

        g_hash_table_iter_init (&iter, priv->location_cache);
        while (g_hash_table_iter_next (&iter, NULL, &value)) {
                LocationCacheValue *lcvalue = (LocationCacheValue *)value;
                GList *l = lcvalue->elements;

                g_assert (l);
                while (l) {
                        LocationCacheElement *element = (LocationCacheElement *)l->data;
                        GList *lnext = l->next;

                        /* Keep this location? */
                        if (gclue_location_get_timestamp (element->location) >
                            cutoff_seconds)
                                goto next_el;

                        location_cache_element_free (element);
                        lcvalue->elements = g_list_delete_link (lcvalue->elements, l);
                        removed_elements++;

                        /* Deleted the last entry (element) in this hash bucket?
                         * Remove this hash table entry then.
                         */
                        if (!lcvalue->elements) {
                                g_assert (!lnext);
                                g_hash_table_iter_remove (&iter);
                        }

                next_el:
                        l = lnext;
                }
        }

        g_debug ("Pruned cache (old size: %u, new size: %u, removed elements: %u)",
                 old_cache_size, g_hash_table_size (priv->location_cache),
                 removed_elements);
}

#if GLIB_CHECK_VERSION(2, 64, 0)
static void
cache_empty (GClueWifi *wifi)
{
        GClueWifiPrivate *priv = wifi->priv;

        g_debug ("Emptying cache");
        g_hash_table_remove_all (priv->location_cache);
}
#endif  /* GLib ≥ 2.64.0 */

static gboolean
cache_prune_timeout_cb (gpointer user_data)
{
        GClueWifi *wifi = GCLUE_WIFI (user_data);

        cache_prune (wifi);

        return G_SOURCE_CONTINUE;
}

#if GLIB_CHECK_VERSION(2, 64, 0)
static void
low_memory_warning_cb (GMemoryMonitor             *memory_monitor,
                       GMemoryMonitorWarningLevel  level,
                       gpointer                    user_data)
{
        GClueWifi *wifi = GCLUE_WIFI (user_data);

        if (level == G_MEMORY_MONITOR_WARNING_LEVEL_LOW)
                cache_prune (wifi);
        else if (level > G_MEMORY_MONITOR_WARNING_LEVEL_LOW)
                cache_empty (wifi);
}
#endif  /* GLib ≥ 2.64.0 */

static void
connect_cache_prune_timeout (GClueWifi *wifi)
{
        GClueWifiPrivate *priv = wifi->priv;

        g_debug ("Connecting cache prune timeout");

        /* Run the prune at twice the expiry frequency, which should allow us to
         * sample often enough to keep the expiries at that frequency, as per
         * Nyquist. */
        if (priv->cache_prune_timeout_id != 0)
                g_source_remove (priv->cache_prune_timeout_id);
        priv->cache_prune_timeout_id = g_timeout_add_seconds (CACHE_ENTRY_MAX_AGE_SECONDS / 2,
                                                              cache_prune_timeout_cb,
                                                              wifi);

#if GLIB_CHECK_VERSION(2, 64, 0)
        if (priv->memory_monitor == NULL) {
                priv->memory_monitor = g_memory_monitor_dup_default ();
                priv->low_memory_warning_id = g_signal_connect (priv->memory_monitor,
                                                                "low-memory-warning",
                                                                G_CALLBACK (low_memory_warning_cb),
                                                                wifi);
        }
#endif
}

static void
disconnect_cache_prune_timeout (GClueWifi *wifi)
{
        GClueWifiPrivate *priv = wifi->priv;

        g_debug ("Disconnecting cache prune timeout");

        /* Run one last prune. */
        cache_prune (wifi);

#if GLIB_CHECK_VERSION(2, 64, 0)
        if (priv->low_memory_warning_id != 0 && priv->memory_monitor != NULL)
                g_signal_handler_disconnect (priv->memory_monitor, priv->low_memory_warning_id);
        g_clear_object (&priv->memory_monitor);
#endif

        if (priv->cache_prune_timeout_id != 0)
                g_source_remove (priv->cache_prune_timeout_id);
        priv->cache_prune_timeout_id = 0;
}

static GClueLocationSourceStartResult
gclue_wifi_start (GClueLocationSource *source)
{
        GClueLocationSourceClass *base_class;
        GClueLocationSourceStartResult base_result;

        g_return_val_if_fail (GCLUE_IS_WIFI (source),
                              GCLUE_LOCATION_SOURCE_START_RESULT_FAILED);

        base_class = GCLUE_LOCATION_SOURCE_CLASS (gclue_wifi_parent_class);
        base_result = base_class->start (source);
        if (base_result != GCLUE_LOCATION_SOURCE_START_RESULT_OK)
                return base_result;

        connect_cache_prune_timeout (GCLUE_WIFI (source));
        connect_bss_signals (GCLUE_WIFI (source));

        return base_result;
}

static GClueLocationSourceStopResult
gclue_wifi_stop (GClueLocationSource *source)
{
        GClueWifi *wifi = GCLUE_WIFI (source);
        GClueWifiPrivate *priv = wifi->priv;
        GClueLocationSourceClass *base_class;
        GClueLocationSourceStopResult base_result;

        g_return_val_if_fail (GCLUE_IS_WIFI (source), FALSE);

        base_class = GCLUE_LOCATION_SOURCE_CLASS (gclue_wifi_parent_class);
        base_result = base_class->stop (source);
        if (base_result == GCLUE_LOCATION_SOURCE_STOP_RESULT_STILL_USED)
                return base_result;

        disconnect_bss_signals (GCLUE_WIFI (source));
        disconnect_cache_prune_timeout (GCLUE_WIFI (source));

        if (gclue_mozilla_test_set_wifi (priv->mozilla, wifi, NULL)) {
                g_debug ("Removed us as the WiFi source on stop");
        }

        return base_result;
}

static GClueAccuracyLevel
gclue_wifi_get_available_accuracy_level (GClueWebSource *source,
                                         gboolean        net_available)
{
        GClueWifi *wifi = GCLUE_WIFI (source);
        GClueWifiPrivate *priv = wifi->priv;

        if (!net_available)
                return GCLUE_ACCURACY_LEVEL_NONE;
        else if (!priv->interface)
                return GCLUE_ACCURACY_LEVEL_CITY;
        else
                return MIN (get_accuracy_level (wifi), GCLUE_ACCURACY_LEVEL_STREET);
}

static void
on_interface_proxy_ready (GObject      *source_object,
                          GAsyncResult *res,
                          gpointer      user_data)
{
        GClueWifi *wifi;
        WPAInterface *interface;
        g_autoptr(GError) error = NULL;

        interface = wpa_interface_proxy_new_for_bus_finish (res, &error);
        if (interface == NULL) {
                if (error) {
                        if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
                                return;
                        }

                        g_warning ("Interface proxy add failed: %s",
                                   error->message);
                }

                return;
        }

        wifi = GCLUE_WIFI (user_data);
        if (wifi->priv->interface != NULL) {
                g_object_unref (interface);
                return;
        }

        wifi->priv->interface = interface;
        g_debug ("WiFi device '%s' added.",
                 wpa_interface_get_ifname (interface));

        if (gclue_location_source_get_active (GCLUE_LOCATION_SOURCE (wifi)))
                connect_bss_signals (wifi);
        else
                gclue_web_source_refresh (GCLUE_WEB_SOURCE (wifi));
}

static void
on_interface_added (WPASupplicant *supplicant,
                    const gchar   *path,
                    GVariant      *properties,
                    gpointer       user_data)
{
        GClueWifi *wifi = GCLUE_WIFI (user_data);

        if (wifi->priv->interface != NULL)
                return;

        wpa_interface_proxy_new_for_bus (G_BUS_TYPE_SYSTEM,
                                         G_DBUS_PROXY_FLAGS_NONE,
                                         "fi.w1.wpa_supplicant1",
                                         path,
                                         wifi->priv->intf_cancellable,
                                         on_interface_proxy_ready,
                                         wifi);
}

static void
on_interface_removed (WPASupplicant *supplicant,
                      const gchar   *path,
                      gpointer       user_data)
{
        GClueWifi *wifi = GCLUE_WIFI (user_data);
        GClueWifiPrivate *priv = wifi->priv;
        const char *object_path;

        if (priv->interface == NULL)
                return;

        object_path = g_dbus_proxy_get_object_path
                        (G_DBUS_PROXY (priv->interface));
        if (g_strcmp0 (object_path, path) != 0)
                return;

        g_debug ("WiFi device '%s' removed.",
                 wpa_interface_get_ifname (priv->interface));

        disconnect_bss_signals (wifi);
        g_clear_object (&wifi->priv->interface);

        if (gclue_mozilla_test_set_wifi (priv->mozilla, wifi, NULL)) {
                g_debug ("Removed interface was the WiFi source");
        }

        gclue_web_source_refresh (GCLUE_WEB_SOURCE (wifi));
}

static void
gclue_wifi_init (GClueWifi *wifi)
{
        GClueWebSource *web_source = GCLUE_WEB_SOURCE (wifi);

        wifi->priv = gclue_wifi_get_instance_private (wifi);

        wifi->priv->intf_cancellable = g_cancellable_new ();
        wifi->priv->mozilla = gclue_mozilla_get_singleton ();
        gclue_web_source_set_locate_url (web_source,
                                         gclue_mozilla_get_locate_url (wifi->priv->mozilla));
        gclue_web_source_set_submit_url (web_source,
                                         gclue_mozilla_get_submit_url (wifi->priv->mozilla));

        wifi->priv->bss_proxies = g_hash_table_new_full (g_str_hash,
                                                         g_str_equal,
                                                         g_free,
                                                         g_object_unref);
        wifi->priv->ignored_bss_proxies = g_hash_table_new_full (g_str_hash,
                                                                 g_str_equal,
                                                                 g_free,
                                                                 g_object_unref);
        wifi->priv->location_cache = g_hash_table_new_full (variant_hash,
                                                            g_variant_equal,
                                                            (GDestroyNotify) g_variant_unref,
                                                            location_cache_value_free);
}

static void
gclue_wifi_constructed (GObject *object)
{
        GClueWifi *wifi = GCLUE_WIFI (object);
        GClueWifiPrivate *priv = wifi->priv;
        const gchar *const *interfaces;
        g_autoptr(GError) error = NULL;

        G_OBJECT_CLASS (gclue_wifi_parent_class)->constructed (object);

        if (get_accuracy_level (wifi) == GCLUE_ACCURACY_LEVEL_CITY) {
                GClueConfig *config = gclue_config_get_singleton ();

                if (!gclue_config_get_enable_wifi_source (config))
                        goto refresh_n_exit;
        }

        /* FIXME: We should be using async variant */
        priv->supplicant = wpa_supplicant_proxy_new_for_bus_sync
                        (G_BUS_TYPE_SYSTEM,
                         G_DBUS_PROXY_FLAGS_NONE,
                         "fi.w1.wpa_supplicant1",
                         "/fi/w1/wpa_supplicant1",
                         NULL,
                         &error);
        if (priv->supplicant == NULL) {
                if (error)
                        g_warning ("Failed to connect to wpa_supplicant service: %s",
                                   error->message);
                goto refresh_n_exit;
        }

        g_signal_connect_object (priv->supplicant,
                                 "interface-added",
                                 G_CALLBACK (on_interface_added),
                                 wifi, 0);
        g_signal_connect_object (priv->supplicant,
                                 "interface-removed",
                                 G_CALLBACK (on_interface_removed),
                                 wifi, 0);

        interfaces = wpa_supplicant_get_interfaces (priv->supplicant);
        if (interfaces != NULL && interfaces[0] != NULL)
                on_interface_added (priv->supplicant,
                                    interfaces[0],
                                    NULL,
                                    wifi);

refresh_n_exit:
        gclue_web_source_refresh (GCLUE_WEB_SOURCE (object));
}

static void
on_wifi_destroyed (gpointer data,
                   GObject *where_the_object_was)
{
        GClueWifi **wifi = (GClueWifi **) data;

        *wifi = NULL;
}

/**
 * gclue_wifi_new:
 *
 * Get the #GClueWifi singleton, for the specified max accuracy level @level.
 *
 * Returns: (transfer full): a new ref to #GClueWifi. Use g_object_unref()
 * when done.
 **/
GClueWifi *
gclue_wifi_get_singleton (GClueAccuracyLevel level)
{
        static GClueWifi *wifi[] = { NULL, NULL, NULL };
        guint i;
        GClueConfig *config = gclue_config_get_singleton ();
        gboolean wifi_enabled;
        gboolean scramble_location = FALSE;
        gboolean compute_movement = FALSE;

        g_return_val_if_fail (level >= GCLUE_ACCURACY_LEVEL_CITY, NULL);

        wifi_enabled = gclue_config_get_enable_wifi_source (config);
        if (level == GCLUE_ACCURACY_LEVEL_CITY) {
                i = 0;
                if (wifi_enabled)
                        scramble_location = TRUE;
        } else if (level == GCLUE_ACCURACY_LEVEL_NEIGHBORHOOD) {
                g_return_val_if_fail (wifi_enabled, NULL);

                i = 1;
                scramble_location = TRUE;
        } else {
                g_return_val_if_fail (wifi_enabled, NULL);

                i = 2;
                compute_movement = TRUE;
        }

        if (wifi[i] == NULL) {
                wifi[i] = g_object_new (GCLUE_TYPE_WIFI,
                                        "accuracy-level", level,
                                        "scramble-location", scramble_location,
                                        "compute-movement", compute_movement,
                                        NULL);
                g_object_weak_ref (G_OBJECT (wifi[i]),
                                   on_wifi_destroyed,
                                   &wifi[i]);
        } else
                g_object_ref (wifi[i]);

        return wifi[i];
}

static gboolean
wifi_should_skip_tower (GClueWifi *wifi)
{
        return gclue_3g_should_skip_tower (get_accuracy_level (wifi));
}

/* Can return NULL, signifying an empty BSS list. */
GList *
gclue_wifi_get_bss_list (GClueWifi *wifi)
{
        return g_hash_table_get_values (wifi->priv->bss_proxies);
}

static SoupMessage *
gclue_wifi_create_query (GClueWebSource *source,
                         const char **query_data_description,
                         GError        **error)
{
        GClueWifi *wifi = GCLUE_WIFI (source);
        gboolean skip_tower;

        if (wifi->priv->interface == NULL) {
                goto create_query;
        }

        /* Empty list? */
        if (!g_hash_table_size (wifi->priv->bss_proxies)) {
                g_set_error_literal (error,
                                     G_IO_ERROR,
                                     G_IO_ERROR_FAILED,
                                     "No WiFi networks found");
                return NULL;
        }

create_query:
        skip_tower = wifi_should_skip_tower (wifi);
        if (skip_tower) {
                g_debug ("Will skip 3GPP tower in query due to our accuracy level");
        }

        return gclue_mozilla_create_query (wifi->priv->mozilla, skip_tower, FALSE,
                                           query_data_description, error);
}

static SoupMessage *
gclue_wifi_create_submit_query (GClueWebSource  *source,
                                GClueLocation   *location,
                                GError         **error)
{
        GClueWifi *wifi = GCLUE_WIFI (source);
        SoupMessage * msg;

        if (wifi->priv->interface == NULL) {
                g_set_error_literal (error,
                                     G_IO_ERROR,
                                     G_IO_ERROR_FAILED,
                                     "No WiFi devices available");
                return NULL;
        }

        /* Empty list? */
        if (!g_hash_table_size (wifi->priv->bss_proxies)) {
                g_set_error_literal (error,
                                     G_IO_ERROR,
                                     G_IO_ERROR_FAILED,
                                     "No WiFi networks found");
                return NULL;
        }

        msg = gclue_mozilla_create_submit_query (wifi->priv->mozilla,
                                                 location,
                                                 error);
        return msg;
}

static void refresh_cb (GObject      *source_object,
                        GAsyncResult *result,
                        gpointer      user_data);

static gint
bss_compare (gconstpointer a,
             gconstpointer b)
{
        WPABSS **_bss_a = (WPABSS **) a;
        WPABSS **_bss_b = (WPABSS **) b;
        WPABSS *bss_a = WPA_BSS (*_bss_a);
        WPABSS *bss_b = WPA_BSS (*_bss_b);
        GVariant *bssid_a = wpa_bss_get_bssid (bss_a);
        GVariant *bssid_b = wpa_bss_get_bssid (bss_b);
        g_autoptr(GBytes) bssid_bytes_a = NULL;
        g_autoptr(GBytes) bssid_bytes_b = NULL;

        /* Can’t use g_variant_compare() as it isn’t defined over `ay` types */
        if (bssid_a == NULL && bssid_b == NULL)
                return 0;
        else if (bssid_a == NULL)
                return -1;
        else if (bssid_b == NULL)
                return 1;

        bssid_bytes_a = g_variant_get_data_as_bytes (bssid_a);
        bssid_bytes_b = g_variant_get_data_as_bytes (bssid_b);

        return g_bytes_compare (bssid_bytes_a, bssid_bytes_b);
}

static guint
variant_hash (gconstpointer key)
{
        GVariant *variant = (GVariant *) key;
        g_autoptr(GBytes) bytes = g_variant_get_data_as_bytes (variant);
        return g_bytes_hash (bytes);
}

static void location_cache_key_fill_tower (GClueWifi *wifi, GClue3GTower *tower)
{
        GClueWifiPrivate *priv = wifi->priv;
        GClue3GTower *moztower;

        memset (tower, 0, sizeof (*tower));
        tower->tec = GCLUE_TOWER_TEC_NO_FIX;

        moztower = gclue_mozilla_get_tower (priv->mozilla);
        if (!moztower || wifi_should_skip_tower (wifi)) {
                return;
        }

        g_assert (moztower->tec != GCLUE_TOWER_TEC_NO_FIX);
        *tower = *moztower;
}

static void location_cache_key_add_tower (GClueWifi *wifi, GVariantBuilder *builder)
{
        GClue3GTower tower;

        location_cache_key_fill_tower (wifi, &tower);
        g_variant_builder_add (builder, "u", (guint32)tower.tec);
        g_variant_builder_add (builder, "s", tower.opc);
        g_variant_builder_add (builder, "t", (guint64)tower.lac);
        g_variant_builder_add (builder, "t", (guint64)tower.cell_id);
}

static GPtrArray *
get_location_cache_bss_array (GClueWifi *wifi)
{
        GHashTableIter iter;
        gpointer value;
        g_autoptr(GPtrArray) bss_array = g_ptr_array_new_with_free_func (NULL);  /* (element-type WPABSS) */

        /* The Mozilla service puts BSSID and signal strength for each BSS into
         * its query. Pack the whole lot into a #GVariant for simplicity, sorted
         * by MAC address. The sorting has to happen in an array beforehand,
         * as variants are immutable.
         */
        g_hash_table_iter_init (&iter, wifi->priv->bss_proxies);

        while (g_hash_table_iter_next (&iter, NULL, &value)) {
                WPABSS *bss = WPA_BSS (value);
                if (bss != NULL)
                        g_ptr_array_add (bss_array, bss);
        }

        g_ptr_array_sort (bss_array, bss_compare);

        return g_steal_pointer (&bss_array);
}

static GVariant *
get_location_cache_hashtable_key (GClueWifi *wifi, GPtrArray *bss_array)
{
        guint i;
        GVariantBuilder builder;

        /* Serialise to a variant. */
        g_variant_builder_init (&builder, G_VARIANT_TYPE ("(usttaay)"));
        location_cache_key_add_tower (wifi, &builder);

        g_variant_builder_open (&builder, G_VARIANT_TYPE ("aay"));
        for (i = 0; i < bss_array->len; i++) {
                WPABSS *bss = WPA_BSS (bss_array->pdata[i]);
                GVariant *bssid;

                bssid = wpa_bss_get_bssid (bss);
                if (bssid == NULL)
                        continue;

                g_variant_builder_add_value (&builder, bssid);
        }
        g_variant_builder_close (&builder);

        return g_variant_builder_end (&builder);
}

static GArray *
get_location_cache_signal_array (GClueWifi *wifi, GPtrArray *bss_array)
{
        g_autoptr(GArray) signal_array = NULL;
        guint i;

        signal_array = g_array_sized_new (FALSE, FALSE, sizeof (gint16), bss_array->len);
        for (i = 0; i < bss_array->len; i++) {
                WPABSS *bss = WPA_BSS (bss_array->pdata[i]);
                gint16 signal = wpa_bss_get_signal (bss);

                g_array_append_val (signal_array, signal);
        }

        return g_steal_pointer (&signal_array);
}

static gboolean cached_signals_match (GArray *signals1, GArray *signals2)
{
        guint i;

        if (signals1->len != signals2->len) {
                g_warning ("Different signal count in one hash table entry: %u vs %u",
                           signals1->len, signals2->len);
                return FALSE;
        }

        for (i = 0; i < signals1->len; i++) {
                gint s1 = g_array_index (signals1, gint16, i);
                gint s2 = g_array_index (signals2, gint16, i);

                if (ABS (s1 - s2) > CACHE_ENTRY_MATCH_SIGNAL_WINDOW / 2)
                        return FALSE;
        }

        return TRUE;
}

static GClueLocation *
find_cached_location (GHashTable *cache, GVariant *key, GArray *signals)
{
        g_autofree gchar *key_str = g_variant_print (key, FALSE);
        GClueLocation *location = NULL;
        LocationCacheValue *value;
        GList *l;

        value = g_hash_table_lookup (cache, key);
        if (!value) {
                g_debug ("Cache miss for key %s", key_str);
                return NULL;
        }

        g_assert (value->elements);
        for (l = value->elements; l; l = l->next) {
                LocationCacheElement *element = l->data;

                if (location &&
                    gclue_location_get_accuracy (element->location) >=
                    gclue_location_get_accuracy (location)) {
                        /* Have at least as accurate location already,
                         * don't bother with comparing signals.
                         */
                        continue;
                }

                if (!cached_signals_match (element->signals, signals))
                        continue;

                location = element->location;
        }

        if (location) {
                g_debug ("Cache hit for key %s: got location %p (%s)",
                         key_str, location,
                         gclue_location_get_description (location));
        } else {
                g_debug ("Cache had key %s, but with different signals", key_str);
        }

        return location;
}

typedef struct {
        GVariant *cache_key;
        GArray *signals;
} RefreshTaskData;

static RefreshTaskData *
refresh_task_data_new (GVariant *cache_key,
                       GArray *signals)
{
        RefreshTaskData *tdata;

        tdata = g_slice_new (RefreshTaskData);
        tdata->cache_key = g_variant_ref (cache_key);
        tdata->signals = signals;
        return tdata;
}

static void refresh_task_data_free (gpointer data)
{
        RefreshTaskData *rdata = data;

        g_clear_pointer (&rdata->cache_key, g_variant_unref);
        if (rdata->signals)
                g_array_free (rdata->signals, TRUE);
        g_slice_free (RefreshTaskData, rdata);
}

static void
gclue_wifi_refresh_async (GClueWebSource      *source,
                          GCancellable        *cancellable,
                          GAsyncReadyCallback  callback,
                          gpointer             user_data)
{
        GClueWifi *wifi = GCLUE_WIFI (source);
        g_autoptr(GTask) task = g_task_new (source, cancellable, callback, user_data);
        g_autoptr(GPtrArray) bss_array = get_location_cache_bss_array (wifi);
        g_autoptr(GVariant) cache_key = get_location_cache_hashtable_key (wifi, bss_array);
        g_autoptr(GArray) signal_array = get_location_cache_signal_array (wifi, bss_array);
        GClueLocation *cached_location = find_cached_location (wifi->priv->location_cache,
                                                               cache_key, signal_array);
        RefreshTaskData *tdata;

        g_task_set_source_tag (task, gclue_wifi_refresh_async);

        if (gclue_location_source_get_active (GCLUE_LOCATION_SOURCE (source))) {
                /* Try the cache. */
                if (cached_location != NULL) {
                        g_autoptr(GClueLocation) new_location = NULL;

                        wifi->priv->cache_hits++;

                        /* Duplicate the location so its timestamp is updated. */
                        new_location = gclue_location_duplicate_fresh (cached_location);
                        gclue_location_source_set_location (GCLUE_LOCATION_SOURCE (source), new_location);

                        g_task_return_pointer (task, g_steal_pointer (&new_location), g_object_unref);
                        return;
                }

                wifi->priv->cache_misses++;
        }

        tdata = refresh_task_data_new (cache_key, g_steal_pointer (&signal_array));
        g_task_set_task_data (task, tdata, refresh_task_data_free);

        /* Fall back to querying the web service. */
        GCLUE_WEB_SOURCE_CLASS (gclue_wifi_parent_class)->refresh_async (source, cancellable, refresh_cb, g_steal_pointer (&task));
}

static void
add_cached_location (GHashTable *cache,
                     GVariant *key, GArray **signals,
                     GClueLocation *location)
{
        LocationCacheValue *value;
        LocationCacheElement *element;

        value = g_hash_table_lookup (cache, key);
        if (!value) {
                value = location_cache_value_new ();
                g_hash_table_insert (cache, g_variant_ref (key), value);
        }

        element = location_cache_element_new (g_steal_pointer (signals), location);
        value->elements = g_list_prepend (value->elements, element);
}

static void
refresh_cb (GObject      *source_object,
            GAsyncResult *result,
            gpointer      user_data)
{
        GClueWebSource *source = GCLUE_WEB_SOURCE (source_object);
        GClueWifi *wifi = GCLUE_WIFI (source);
        g_autoptr(GTask) task = g_steal_pointer (&user_data);
        g_autoptr(GClueLocation) location = NULL;
        g_autoptr(GError) local_error = NULL;
        RefreshTaskData *tdata;
        g_autofree gchar *cache_key_str = NULL;
        double cache_hit_ratio;

        /* Finish querying the web service. */
        location = GCLUE_WEB_SOURCE_CLASS (gclue_wifi_parent_class)->refresh_finish (source, result, &local_error);

        if (local_error != NULL) {
                g_task_return_error (task, g_steal_pointer (&local_error));
                return;
        }

        /* Cache the result. */
        tdata = g_task_get_task_data (task);
        cache_key_str = g_variant_print (tdata->cache_key, FALSE);
        add_cached_location (wifi->priv->location_cache,
                             tdata->cache_key, &tdata->signals,
                             location);

        if (wifi->priv->cache_hits || wifi->priv->cache_misses) {
                double cache_attempts;

                cache_attempts = wifi->priv->cache_hits;
                cache_attempts += wifi->priv->cache_misses;
                cache_hit_ratio = wifi->priv->cache_hits * 100.0 / cache_attempts;
        } else {
                cache_hit_ratio = 0;
        }

        g_debug ("Adding %s / %s to cache (new size: %u; hit ratio %.2f%%)",
                 cache_key_str,
                 gclue_location_get_description (location),
                 g_hash_table_size (wifi->priv->location_cache),
                 cache_hit_ratio);

        g_task_return_pointer (task, g_steal_pointer (&location), g_object_unref);
}

static GClueLocation *
gclue_wifi_refresh_finish (GClueWebSource  *source,
                           GAsyncResult    *result,
                           GError         **error)
{
        GTask *task = G_TASK (result);

        return g_task_propagate_pointer (task, error);
}