wifi: avoid device double release on disable
[platform/upstream/connman.git] / plugins / wifi.c
1 /*
2  *
3  *  Connection Manager
4  *
5  *  Copyright (C) 2007-2012  Intel Corporation. All rights reserved.
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License version 2 as
9  *  published by the Free Software Foundation.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  */
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <unistd.h>
27 #include <stdlib.h>
28 #include <errno.h>
29 #include <stdio.h>
30 #include <string.h>
31 #include <sys/ioctl.h>
32 #include <sys/socket.h>
33 #include <linux/if_arp.h>
34 #include <linux/wireless.h>
35 #include <net/ethernet.h>
36
37 #ifndef IFF_LOWER_UP
38 #define IFF_LOWER_UP    0x10000
39 #endif
40
41 #include <dbus/dbus.h>
42 #include <glib.h>
43
44 #define CONNMAN_API_SUBJECT_TO_CHANGE
45 #include <connman/plugin.h>
46 #include <connman/inet.h>
47 #include <connman/device.h>
48 #include <connman/rtnl.h>
49 #include <connman/technology.h>
50 #include <connman/service.h>
51 #include <connman/log.h>
52 #include <connman/option.h>
53 #include <connman/storage.h>
54 #include <include/setting.h>
55 #include <connman/provision.h>
56
57 #include <gsupplicant/gsupplicant.h>
58
59 #define CLEANUP_TIMEOUT   8     /* in seconds */
60 #define INACTIVE_TIMEOUT  12    /* in seconds */
61 #define MAXIMUM_RETRIES   2
62 #define FAVORITE_MAXIMUM_RETRIES 4
63
64 #define BGSCAN_DEFAULT "simple:30:-45:300"
65 #define AUTOSCAN_DEFAULT "exponential:3:300"
66
67 static struct connman_technology *wifi_technology = NULL;
68
69 struct hidden_params {
70         char ssid[32];
71         unsigned int ssid_len;
72         char *identity;
73         char *passphrase;
74         gpointer user_data;
75 };
76
77 /**
78  * Used for autoscan "emulation".
79  * Should be removed when wpa_s autoscan support will be by default.
80  */
81 struct autoscan_params {
82         int base;
83         int limit;
84         int interval;
85         unsigned int timeout;
86 };
87
88 struct wifi_data {
89         char *identifier;
90         struct connman_device *device;
91         struct connman_network *network;
92         struct connman_network *pending_network;
93         GSList *networks;
94         GSupplicantInterface *interface;
95         GSupplicantState state;
96         connman_bool_t disabling;
97         connman_bool_t connected;
98         connman_bool_t disconnecting;
99         connman_bool_t tethering;
100         connman_bool_t bridged;
101         const char *bridge;
102         int index;
103         unsigned flags;
104         unsigned int watch;
105         int retries;
106         struct hidden_params *hidden;
107         /**
108          * autoscan "emulation".
109          */
110         struct autoscan_params *autoscan;
111 };
112
113 static GList *iface_list = NULL;
114
115 static void start_autoscan(struct connman_device *device);
116
117 static void handle_tethering(struct wifi_data *wifi)
118 {
119         if (wifi->tethering == FALSE)
120                 return;
121
122         if (wifi->bridge == NULL)
123                 return;
124
125         if (wifi->bridged == TRUE)
126                 return;
127
128         DBG("index %d bridge %s", wifi->index, wifi->bridge);
129
130         if (connman_inet_add_to_bridge(wifi->index, wifi->bridge) < 0)
131                 return;
132
133         wifi->bridged = TRUE;
134 }
135
136 static void wifi_newlink(unsigned flags, unsigned change, void *user_data)
137 {
138         struct connman_device *device = user_data;
139         struct wifi_data *wifi = connman_device_get_data(device);
140
141         if (wifi == NULL)
142                 return;
143
144         DBG("index %d flags %d change %d", wifi->index, flags, change);
145
146         if ((wifi->flags & IFF_UP) != (flags & IFF_UP)) {
147                 if (flags & IFF_UP)
148                         DBG("interface up");
149                 else
150                         DBG("interface down");
151         }
152
153         if ((wifi->flags & IFF_LOWER_UP) != (flags & IFF_LOWER_UP)) {
154                 if (flags & IFF_LOWER_UP) {
155                         DBG("carrier on");
156
157                         handle_tethering(wifi);
158                 } else
159                         DBG("carrier off");
160         }
161
162         wifi->flags = flags;
163 }
164
165 static int wifi_probe(struct connman_device *device)
166 {
167         struct wifi_data *wifi;
168
169         DBG("device %p", device);
170
171         wifi = g_try_new0(struct wifi_data, 1);
172         if (wifi == NULL)
173                 return -ENOMEM;
174
175         wifi->disabling = FALSE;
176         wifi->connected = FALSE;
177         wifi->disconnecting = FALSE;
178         wifi->tethering = FALSE;
179         wifi->bridged = FALSE;
180         wifi->bridge = NULL;
181         wifi->state = G_SUPPLICANT_STATE_INACTIVE;
182
183         connman_device_set_data(device, wifi);
184         wifi->device = connman_device_ref(device);
185
186         wifi->index = connman_device_get_index(device);
187         wifi->flags = 0;
188
189         wifi->watch = connman_rtnl_add_newlink_watch(wifi->index,
190                                                         wifi_newlink, device);
191
192         iface_list = g_list_append(iface_list, wifi);
193
194         return 0;
195 }
196
197 static void remove_networks(struct connman_device *device,
198                                 struct wifi_data *wifi)
199 {
200         GSList *list;
201
202         for (list = wifi->networks; list != NULL; list = list->next) {
203                 struct connman_network *network = list->data;
204
205                 connman_device_remove_network(device, network);
206                 connman_network_unref(network);
207         }
208
209         g_slist_free(wifi->networks);
210         wifi->networks = NULL;
211 }
212
213 static void reset_autoscan(struct connman_device *device)
214 {
215         struct wifi_data *wifi = connman_device_get_data(device);
216         struct autoscan_params *autoscan;
217
218         DBG("");
219
220         if (wifi == NULL || wifi->autoscan == NULL)
221                 return;
222
223         autoscan = wifi->autoscan;
224
225         if (autoscan->timeout == 0 && autoscan->interval == 0)
226                 return;
227
228         g_source_remove(autoscan->timeout);
229
230         autoscan->timeout = 0;
231         autoscan->interval = 0;
232
233         connman_device_unref(device);
234 }
235
236 static void stop_autoscan(struct connman_device *device)
237 {
238         const struct wifi_data *wifi = connman_device_get_data(device);
239
240         if (wifi == NULL || wifi->autoscan == NULL)
241                 return;
242
243         reset_autoscan(device);
244
245         connman_device_set_scanning(device, FALSE);
246 }
247
248 static void wifi_remove(struct connman_device *device)
249 {
250         struct wifi_data *wifi = connman_device_get_data(device);
251
252         DBG("device %p wifi %p", device, wifi);
253
254         if (wifi == NULL)
255                 return;
256
257         iface_list = g_list_remove(iface_list, wifi);
258
259         remove_networks(device, wifi);
260
261         connman_device_set_powered(device, FALSE);
262         connman_device_set_data(device, NULL);
263         connman_device_unref(wifi->device);
264         connman_rtnl_remove_watch(wifi->watch);
265
266         g_supplicant_interface_set_data(wifi->interface, NULL);
267
268         g_free(wifi->autoscan);
269         g_free(wifi->identifier);
270         g_free(wifi);
271 }
272
273 static gboolean is_duplicate(GSList *list, gchar *ssid, int ssid_len)
274 {
275         GSList *iter;
276
277         for (iter = list; iter != NULL; iter = g_slist_next(iter)) {
278                 struct scan_ssid *scan_ssid = iter->data;
279
280                 if (ssid_len == scan_ssid->ssid_len &&
281                                 memcmp(ssid, scan_ssid->ssid, ssid_len) == 0)
282                         return TRUE;
283         }
284
285         return FALSE;
286 }
287
288 static int add_scan_param(gchar *hex_ssid, char *raw_ssid, int ssid_len,
289                         int freq, GSupplicantScanParams *scan_data,
290                         int driver_max_scan_ssids, char *ssid_name)
291 {
292         unsigned int i;
293         struct scan_ssid *scan_ssid;
294
295         if (driver_max_scan_ssids > scan_data->num_ssids &&
296                         (hex_ssid != NULL || raw_ssid != NULL)) {
297                 gchar *ssid;
298                 unsigned int j = 0, hex;
299
300                 if (hex_ssid != NULL) {
301                         size_t hex_ssid_len = strlen(hex_ssid);
302
303                         ssid = g_try_malloc0(hex_ssid_len / 2);
304                         if (ssid == NULL)
305                                 return -ENOMEM;
306
307                         for (i = 0; i < hex_ssid_len; i += 2) {
308                                 sscanf(hex_ssid + i, "%02x", &hex);
309                                 ssid[j++] = hex;
310                         }
311                 } else {
312                         ssid = raw_ssid;
313                         j = ssid_len;
314                 }
315
316                 /*
317                  * If we have already added hidden AP to the list,
318                  * then do not do it again. This might happen if you have
319                  * used or are using multiple wifi cards, so in that case
320                  * you might have multiple service files for same AP.
321                  */
322                 if (is_duplicate(scan_data->ssids, ssid, j) == TRUE)
323                         return 0;
324
325                 scan_ssid = g_try_new(struct scan_ssid, 1);
326                 if (scan_ssid == NULL) {
327                         g_free(ssid);
328                         return -ENOMEM;
329                 }
330
331                 memcpy(scan_ssid->ssid, ssid, j);
332                 scan_ssid->ssid_len = j;
333                 scan_data->ssids = g_slist_prepend(scan_data->ssids,
334                                                                 scan_ssid);
335
336                 scan_data->num_ssids++;
337
338                 DBG("SSID %s added to scanned list of %d entries", ssid_name,
339                                                         scan_data->num_ssids);
340
341                 if (hex_ssid != NULL)
342                         g_free(ssid);
343         } else
344                 return -EINVAL;
345
346         scan_data->ssids = g_slist_reverse(scan_data->ssids);
347
348         if (scan_data->freqs == NULL) {
349                 scan_data->freqs = g_try_malloc0(sizeof(uint16_t) *
350                                                 scan_data->num_ssids);
351                 if (scan_data->freqs == NULL) {
352                         g_slist_free_full(scan_data->ssids, g_free);
353                         return -ENOMEM;
354                 }
355         } else {
356                 scan_data->freqs = g_try_realloc(scan_data->freqs,
357                                 sizeof(uint16_t) * scan_data->num_ssids);
358                 if (scan_data->freqs == NULL) {
359                         g_slist_free_full(scan_data->ssids, g_free);
360                         return -ENOMEM;
361                 }
362                 scan_data->freqs[scan_data->num_ssids - 1] = 0;
363         }
364
365         /* Don't add duplicate entries */
366         for (i = 0; i < scan_data->num_ssids; i++) {
367                 if (scan_data->freqs[i] == 0) {
368                         scan_data->freqs[i] = freq;
369                         break;
370                 } else if (scan_data->freqs[i] == freq)
371                         break;
372         }
373
374         return 1;
375 }
376
377 static int get_hidden_connections(int max_ssids,
378                                 GSupplicantScanParams *scan_data)
379 {
380         struct connman_config_entry **entries;
381         GKeyFile *keyfile;
382         gchar **services;
383         char *ssid, *name;
384         int i, freq, ret;
385         gboolean value;
386         int num_ssids = 0, add_param_failed = 0;
387
388         services = connman_storage_get_services();
389         for (i = 0; services && services[i]; i++) {
390                 if (strncmp(services[i], "wifi_", 5) != 0)
391                         continue;
392
393                 keyfile = connman_storage_load_service(services[i]);
394                 if (keyfile == NULL)
395                         continue;
396
397                 value = g_key_file_get_boolean(keyfile,
398                                         services[i], "Hidden", NULL);
399                 if (value == FALSE) {
400                         g_key_file_free(keyfile);
401                         continue;
402                 }
403
404                 value = g_key_file_get_boolean(keyfile,
405                                         services[i], "Favorite", NULL);
406                 if (value == FALSE) {
407                         g_key_file_free(keyfile);
408                         continue;
409                 }
410
411                 ssid = g_key_file_get_string(keyfile,
412                                         services[i], "SSID", NULL);
413
414                 freq = g_key_file_get_integer(keyfile, services[i],
415                                         "Frequency", NULL);
416
417                 name = g_key_file_get_string(keyfile, services[i], "Name",
418                                                                 NULL);
419
420                 ret = add_scan_param(ssid, NULL, 0, freq, scan_data,
421                                 max_ssids, name);
422                 if (ret < 0)
423                         add_param_failed++;
424                 else if (ret > 0)
425                         num_ssids++;
426
427                 g_free(name);
428                 g_key_file_free(keyfile);
429         }
430
431         /*
432          * Check if there are any hidden AP that needs to be provisioned.
433          */
434         entries = connman_config_get_entries("wifi");
435         for (i = 0; entries && entries[i]; i++) {
436                 int len;
437
438                 if (entries[i]->hidden == FALSE)
439                         continue;
440
441                 if (entries[i]->ssid == NULL) {
442                         ssid = entries[i]->name;
443                         len = strlen(ssid);
444                 } else {
445                         ssid = entries[i]->ssid;
446                         len = entries[i]->ssid_len;
447                 }
448
449                 if (ssid == NULL)
450                         continue;
451
452                 ret = add_scan_param(NULL, ssid, len, 0, scan_data,
453                                                         max_ssids, ssid);
454                 if (ret < 0)
455                         add_param_failed++;
456                 else if (ret > 0)
457                         num_ssids++;
458         }
459
460         connman_config_free_entries(entries);
461
462         if (add_param_failed > 0)
463                 DBG("Unable to scan %d out of %d SSIDs (max is %d)",
464                         add_param_failed, num_ssids, max_ssids);
465
466         g_strfreev(services);
467
468         return num_ssids > max_ssids ? max_ssids : num_ssids;
469 }
470
471 static int throw_wifi_scan(struct connman_device *device,
472                         GSupplicantInterfaceCallback callback)
473 {
474         struct wifi_data *wifi = connman_device_get_data(device);
475         int ret;
476
477         if (wifi == NULL)
478                 return -ENODEV;
479
480         DBG("device %p %p", device, wifi->interface);
481
482         if (wifi->tethering == TRUE)
483                 return -EBUSY;
484
485         if (connman_device_get_scanning(device) == TRUE)
486                 return -EALREADY;
487
488         connman_device_ref(device);
489
490         ret = g_supplicant_interface_scan(wifi->interface, NULL,
491                                                 callback, device);
492         if (ret == 0)
493                 connman_device_set_scanning(device, TRUE);
494         else
495                 connman_device_unref(device);
496
497         return ret;
498 }
499
500 static void hidden_free(struct hidden_params *hidden)
501 {
502         if (hidden == NULL)
503                 return;
504
505         g_free(hidden->identity);
506         g_free(hidden->passphrase);
507         g_free(hidden);
508 }
509
510 static void scan_callback(int result, GSupplicantInterface *interface,
511                                                 void *user_data)
512 {
513         struct connman_device *device = user_data;
514         struct wifi_data *wifi = connman_device_get_data(device);
515
516         DBG("result %d wifi %p", result, wifi);
517
518         if (wifi != NULL && wifi->hidden != NULL) {
519                 connman_network_clear_hidden(wifi->hidden->user_data);
520                 hidden_free(wifi->hidden);
521                 wifi->hidden = NULL;
522         }
523
524         if (result < 0)
525                 connman_device_reset_scanning(device);
526
527         connman_device_set_scanning(device, FALSE);
528
529         if (result != -ENOLINK)
530                 start_autoscan(device);
531
532         /*
533          * If we are here then we were scanning; however, if we are also
534          * mid-flight disabling the interface, then wifi_disable has
535          * already unreferenced the device and we needn't do it here.
536          */
537
538         if (wifi->disabling != TRUE)
539                 connman_device_unref(device);
540 }
541
542 static void scan_callback_hidden(int result,
543                         GSupplicantInterface *interface, void *user_data)
544 {
545         struct connman_device *device = user_data;
546         struct wifi_data *wifi = connman_device_get_data(device);
547         GSupplicantScanParams *scan_params;
548         int driver_max_ssids, ret;
549
550         DBG("result %d wifi %p", result, wifi);
551
552         if (wifi == NULL)
553                 goto out;
554
555         /*
556          * Scan hidden networks so that we can autoconnect to them.
557          * We will assume 1 as a default number of ssid to scan.
558          */
559         driver_max_ssids = g_supplicant_interface_get_max_scan_ssids(
560                                                         wifi->interface);
561         if (driver_max_ssids == 0)
562                 driver_max_ssids = 1;
563
564         DBG("max ssids %d", driver_max_ssids);
565
566         scan_params = g_try_malloc0(sizeof(GSupplicantScanParams));
567         if (scan_params == NULL)
568                 goto out;
569
570         if (get_hidden_connections(driver_max_ssids, scan_params) > 0) {
571                 ret = g_supplicant_interface_scan(wifi->interface,
572                                                         scan_params,
573                                                         scan_callback,
574                                                         device);
575                 if (ret == 0)
576                         return;
577         }
578
579         g_supplicant_free_scan_params(scan_params);
580
581 out:
582         scan_callback(result, interface, user_data);
583 }
584
585 static gboolean autoscan_timeout(gpointer data)
586 {
587         struct connman_device *device = data;
588         struct wifi_data *wifi = connman_device_get_data(device);
589         struct autoscan_params *autoscan;
590         int interval;
591
592         if (wifi == NULL)
593                 return FALSE;
594
595         autoscan = wifi->autoscan;
596
597         if (autoscan->interval <= 0) {
598                 interval = autoscan->base;
599                 goto set_interval;
600         } else
601                 interval = autoscan->interval * autoscan->base;
602
603         if (autoscan->interval >= autoscan->limit)
604                 interval = autoscan->limit;
605
606         throw_wifi_scan(wifi->device, scan_callback_hidden);
607
608 set_interval:
609         DBG("interval %d", interval);
610
611         autoscan->interval = interval;
612
613         autoscan->timeout = g_timeout_add_seconds(interval,
614                                                 autoscan_timeout, device);
615
616         return FALSE;
617 }
618
619 static void start_autoscan(struct connman_device *device)
620 {
621         struct wifi_data *wifi = connman_device_get_data(device);
622         struct autoscan_params *autoscan;
623
624         DBG("");
625
626         if (wifi == NULL)
627                 return;
628
629         autoscan = wifi->autoscan;
630         if (autoscan == NULL)
631                 return;
632
633         if (autoscan->timeout > 0 || autoscan->interval > 0)
634                 return;
635
636         connman_device_ref(device);
637
638         autoscan_timeout(device);
639 }
640
641 static struct autoscan_params *parse_autoscan_params(const char *params)
642 {
643         struct autoscan_params *autoscan;
644         char **list_params;
645         int limit;
646         int base;
647
648         DBG("Emulating autoscan");
649
650         list_params = g_strsplit(params, ":", 0);
651         if (list_params == 0)
652                 return NULL;
653
654         if (g_strv_length(list_params) < 3) {
655                 g_strfreev(list_params);
656                 return NULL;
657         }
658
659         base = atoi(list_params[1]);
660         limit = atoi(list_params[2]);
661
662         g_strfreev(list_params);
663
664         autoscan = g_try_malloc0(sizeof(struct autoscan_params));
665         if (autoscan == NULL) {
666                 DBG("Could not allocate memory for autoscan");
667                 return NULL;
668         }
669
670         DBG("base %d - limit %d", base, limit);
671         autoscan->base = base;
672         autoscan->limit = limit;
673
674         return autoscan;
675 }
676
677 static void setup_autoscan(struct wifi_data *wifi)
678 {
679         if (wifi->autoscan == NULL)
680                 wifi->autoscan = parse_autoscan_params(AUTOSCAN_DEFAULT);
681
682         start_autoscan(wifi->device);
683 }
684
685 static void interface_autoscan_callback(int result,
686                                         GSupplicantInterface *interface,
687                                                         void *user_data)
688 {
689         struct wifi_data *wifi = user_data;
690
691         if (result < 0) {
692                 DBG("Could not enable Autoscan, falling back...");
693                 setup_autoscan(wifi);
694         }
695 }
696
697 static void interface_create_callback(int result,
698                                         GSupplicantInterface *interface,
699                                                         void *user_data)
700 {
701         struct wifi_data *wifi = user_data;
702
703         DBG("result %d ifname %s, wifi %p", result,
704                                 g_supplicant_interface_get_ifname(interface),
705                                 wifi);
706
707         if (result < 0 || wifi == NULL)
708                 return;
709
710         wifi->interface = interface;
711         g_supplicant_interface_set_data(interface, wifi);
712
713         if (g_supplicant_interface_get_ready(interface) == FALSE)
714                 return;
715
716         DBG("interface is ready wifi %p tethering %d", wifi, wifi->tethering);
717
718         if (wifi->device == NULL) {
719                 connman_error("WiFi device not set");
720                 return;
721         }
722
723         connman_device_set_powered(wifi->device, TRUE);
724
725         if (connman_setting_get_bool("BackgroundScanning") == FALSE)
726                 return;
727
728         /* Setting up automatic scanning */
729         if (g_supplicant_interface_autoscan(interface, AUTOSCAN_DEFAULT,
730                                 interface_autoscan_callback, wifi) < 0) {
731                 DBG("Could not enable Autoscan, falling back...");
732                 setup_autoscan(wifi);
733         }
734 }
735
736 /*
737  * The sole function of this callback is to avoid a race between scan completion
738  * and wifi_disable that can otherwise cause a reference count underflow if the
739  * disabling state is not tracked and observed.
740  */
741 static void interface_remove_callback(int result,
742                                         GSupplicantInterface *interface,
743                                                         void *user_data)
744 {
745         struct wifi_data *wifi = user_data;
746
747         DBG("result %d ifname %s, wifi %p", result,
748                                 g_supplicant_interface_get_ifname(interface),
749                                 wifi);
750
751         if (result < 0 || wifi == NULL)
752                 return;
753
754         wifi->disabling = FALSE;
755 }
756
757 static int wifi_enable(struct connman_device *device)
758 {
759         struct wifi_data *wifi = connman_device_get_data(device);
760         const char *interface = connman_device_get_string(device, "Interface");
761         const char *driver = connman_option_get_string("wifi");
762         int ret;
763
764         DBG("device %p %p", device, wifi);
765
766         if (wifi == NULL)
767                 return -ENODEV;
768
769         ret = g_supplicant_interface_create(interface, driver, NULL,
770                                                 interface_create_callback,
771                                                         wifi);
772         if (ret < 0)
773                 return ret;
774
775         wifi->disabling = FALSE;
776
777         return -EINPROGRESS;
778 }
779
780 static int wifi_disable(struct connman_device *device)
781 {
782         struct wifi_data *wifi = connman_device_get_data(device);
783         int ret;
784
785         DBG("device %p wifi %p", device, wifi);
786
787         if (wifi == NULL)
788                 return -ENODEV;
789
790         wifi->connected = FALSE;
791         wifi->disconnecting = FALSE;
792
793         if (wifi->pending_network != NULL)
794                 wifi->pending_network = NULL;
795
796         stop_autoscan(device);
797
798         /* In case of a user scan, device is still referenced */
799         if (connman_device_get_scanning(device) == TRUE) {
800                 connman_device_set_scanning(device, FALSE);
801                 connman_device_unref(wifi->device);
802         }
803
804         remove_networks(device, wifi);
805
806         ret = g_supplicant_interface_remove(wifi->interface,
807                                                 interface_remove_callback,
808                                                         wifi);
809         if (ret < 0)
810                 return ret;
811
812         wifi->disabling = TRUE;
813
814         return -EINPROGRESS;
815 }
816
817 struct last_connected {
818         GTimeVal modified;
819         gchar *ssid;
820         int freq;
821 };
822
823 static gint sort_entry(gconstpointer a, gconstpointer b, gpointer user_data)
824 {
825         GTimeVal *aval = (GTimeVal *)a;
826         GTimeVal *bval = (GTimeVal *)b;
827
828         /* Note that the sort order is descending */
829         if (aval->tv_sec < bval->tv_sec)
830                 return 1;
831
832         if (aval->tv_sec > bval->tv_sec)
833                 return -1;
834
835         return 0;
836 }
837
838 static void free_entry(gpointer data)
839 {
840         struct last_connected *entry = data;
841
842         g_free(entry->ssid);
843         g_free(entry);
844 }
845
846 static int get_latest_connections(int max_ssids,
847                                 GSupplicantScanParams *scan_data)
848 {
849         GSequenceIter *iter;
850         GSequence *latest_list;
851         struct last_connected *entry;
852         GKeyFile *keyfile;
853         GTimeVal modified;
854         gchar **services;
855         gchar *str;
856         char *ssid;
857         int i, freq;
858         int num_ssids = 0;
859
860         latest_list = g_sequence_new(free_entry);
861         if (latest_list == NULL)
862                 return -ENOMEM;
863
864         services = connman_storage_get_services();
865         for (i = 0; services && services[i]; i++) {
866                 if (strncmp(services[i], "wifi_", 5) != 0)
867                         continue;
868
869                 keyfile = connman_storage_load_service(services[i]);
870                 if (keyfile == NULL)
871                         continue;
872
873                 str = g_key_file_get_string(keyfile,
874                                         services[i], "Favorite", NULL);
875                 if (str == NULL || g_strcmp0(str, "true")) {
876                         if (str)
877                                 g_free(str);
878                         g_key_file_free(keyfile);
879                         continue;
880                 }
881                 g_free(str);
882
883                 str = g_key_file_get_string(keyfile,
884                                         services[i], "AutoConnect", NULL);
885                 if (str == NULL || g_strcmp0(str, "true")) {
886                         if (str)
887                                 g_free(str);
888                         g_key_file_free(keyfile);
889                         continue;
890                 }
891                 g_free(str);
892
893                 str = g_key_file_get_string(keyfile,
894                                         services[i], "Modified", NULL);
895                 if (str != NULL) {
896                         g_time_val_from_iso8601(str, &modified);
897                         g_free(str);
898                 }
899
900                 ssid = g_key_file_get_string(keyfile,
901                                         services[i], "SSID", NULL);
902
903                 freq = g_key_file_get_integer(keyfile, services[i],
904                                         "Frequency", NULL);
905                 if (freq) {
906                         entry = g_try_new(struct last_connected, 1);
907                         if (entry == NULL) {
908                                 g_sequence_free(latest_list);
909                                 g_key_file_free(keyfile);
910                                 g_free(ssid);
911                                 return -ENOMEM;
912                         }
913
914                         entry->ssid = ssid;
915                         entry->modified = modified;
916                         entry->freq = freq;
917
918                         g_sequence_insert_sorted(latest_list, entry,
919                                                 sort_entry, NULL);
920                         num_ssids++;
921                 } else
922                         g_free(ssid);
923
924                 g_key_file_free(keyfile);
925         }
926
927         g_strfreev(services);
928
929         num_ssids = num_ssids > max_ssids ? max_ssids : num_ssids;
930
931         iter = g_sequence_get_begin_iter(latest_list);
932
933         for (i = 0; i < num_ssids; i++) {
934                 entry = g_sequence_get(iter);
935
936                 DBG("ssid %s freq %d modified %lu", entry->ssid, entry->freq,
937                                                 entry->modified.tv_sec);
938
939                 add_scan_param(entry->ssid, NULL, 0, entry->freq, scan_data,
940                                                 max_ssids, entry->ssid);
941
942                 iter = g_sequence_iter_next(iter);
943         }
944
945         g_sequence_free(latest_list);
946         return num_ssids;
947 }
948
949 static int wifi_scan_simple(struct connman_device *device)
950 {
951         reset_autoscan(device);
952
953         return throw_wifi_scan(device, scan_callback_hidden);
954 }
955
956 /*
957  * Note that the hidden scan is only used when connecting to this specific
958  * hidden AP first time. It is not used when system autoconnects to hidden AP.
959  */
960 static int wifi_scan(struct connman_device *device,
961                 const char *ssid, unsigned int ssid_len,
962                 const char *identity, const char* passphrase,
963                 gpointer user_data)
964 {
965         struct wifi_data *wifi = connman_device_get_data(device);
966         GSupplicantScanParams *scan_params = NULL;
967         struct scan_ssid *scan_ssid;
968         struct hidden_params *hidden;
969         int ret;
970         int driver_max_ssids = 0;
971         connman_bool_t do_hidden;
972
973         if (wifi == NULL)
974                 return -ENODEV;
975
976         DBG("device %p wifi %p hidden ssid %s", device, wifi->interface, ssid);
977
978         if (wifi->tethering == TRUE)
979                 return 0;
980
981         if (connman_device_get_scanning(device) == TRUE)
982                 return -EALREADY;
983
984         if (ssid == NULL || ssid_len == 0 || ssid_len > 32) {
985                 do_hidden = FALSE;
986         } else {
987                 if (wifi->hidden != NULL)
988                         return -EBUSY;
989
990                 do_hidden = TRUE;
991         }
992
993         if (do_hidden == FALSE) {
994                 driver_max_ssids = g_supplicant_interface_get_max_scan_ssids(
995                                                         wifi->interface);
996                 DBG("max ssids %d", driver_max_ssids);
997                 if (driver_max_ssids == 0)
998                         return wifi_scan_simple(device);
999         }
1000
1001         scan_params = g_try_malloc0(sizeof(GSupplicantScanParams));
1002         if (scan_params == NULL)
1003                 return -ENOMEM;
1004
1005         if (do_hidden == TRUE) {
1006                 scan_ssid = g_try_new(struct scan_ssid, 1);
1007                 if (scan_ssid == NULL) {
1008                         g_free(scan_params);
1009                         return -ENOMEM;
1010                 }
1011
1012                 memcpy(scan_ssid->ssid, ssid, ssid_len);
1013                 scan_ssid->ssid_len = ssid_len;
1014                 scan_params->ssids = g_slist_prepend(scan_params->ssids,
1015                                                                 scan_ssid);
1016                 scan_params->num_ssids = 1;
1017
1018                 hidden = g_try_new0(struct hidden_params, 1);
1019                 if (hidden == NULL) {
1020                         g_free(scan_params);
1021                         return -ENOMEM;
1022                 }
1023
1024                 memcpy(hidden->ssid, ssid, ssid_len);
1025                 hidden->ssid_len = ssid_len;
1026                 hidden->identity = g_strdup(identity);
1027                 hidden->passphrase = g_strdup(passphrase);
1028                 hidden->user_data = user_data;
1029                 wifi->hidden = hidden;
1030
1031         } else {
1032                 ret = get_latest_connections(driver_max_ssids, scan_params);
1033                 if (ret <= 0) {
1034                         g_supplicant_free_scan_params(scan_params);
1035                         return wifi_scan_simple(device);
1036                 }
1037         }
1038
1039         connman_device_ref(device);
1040
1041         reset_autoscan(device);
1042
1043         ret = g_supplicant_interface_scan(wifi->interface, scan_params,
1044                                                 scan_callback, device);
1045         if (ret == 0)
1046                 connman_device_set_scanning(device, TRUE);
1047         else {
1048                 g_supplicant_free_scan_params(scan_params);
1049                 connman_device_unref(device);
1050
1051                 if (do_hidden == TRUE) {
1052                         hidden_free(wifi->hidden);
1053                         wifi->hidden = NULL;
1054                 }
1055         }
1056
1057         return ret;
1058 }
1059
1060 static void wifi_regdom_callback(int result,
1061                                         const char *alpha2,
1062                                                 void *user_data)
1063 {
1064         struct connman_device *device = user_data;
1065
1066         connman_device_regdom_notify(device, result, alpha2);
1067
1068         connman_device_unref(device);
1069 }
1070
1071 static int wifi_set_regdom(struct connman_device *device, const char *alpha2)
1072 {
1073         struct wifi_data *wifi = connman_device_get_data(device);
1074         int ret;
1075
1076         if (wifi == NULL)
1077                 return -EINVAL;
1078
1079         connman_device_ref(device);
1080
1081         ret = g_supplicant_interface_set_country(wifi->interface,
1082                                                 wifi_regdom_callback,
1083                                                         alpha2, device);
1084         if (ret != 0)
1085                 connman_device_unref(device);
1086
1087         return ret;
1088 }
1089
1090 static struct connman_device_driver wifi_ng_driver = {
1091         .name           = "wifi",
1092         .type           = CONNMAN_DEVICE_TYPE_WIFI,
1093         .priority       = CONNMAN_DEVICE_PRIORITY_LOW,
1094         .probe          = wifi_probe,
1095         .remove         = wifi_remove,
1096         .enable         = wifi_enable,
1097         .disable        = wifi_disable,
1098         .scan           = wifi_scan,
1099         .set_regdom     = wifi_set_regdom,
1100 };
1101
1102 static void system_ready(void)
1103 {
1104         DBG("");
1105
1106         if (connman_device_driver_register(&wifi_ng_driver) < 0)
1107                 connman_error("Failed to register WiFi driver");
1108 }
1109
1110 static void system_killed(void)
1111 {
1112         DBG("");
1113
1114         connman_device_driver_unregister(&wifi_ng_driver);
1115 }
1116
1117 static int network_probe(struct connman_network *network)
1118 {
1119         DBG("network %p", network);
1120
1121         return 0;
1122 }
1123
1124 static void network_remove(struct connman_network *network)
1125 {
1126         struct connman_device *device = connman_network_get_device(network);
1127         struct wifi_data *wifi;
1128
1129         DBG("network %p", network);
1130
1131         wifi = connman_device_get_data(device);
1132         if (wifi == NULL)
1133                 return;
1134
1135         if (wifi->network != network)
1136                 return;
1137
1138         wifi->network = NULL;
1139 }
1140
1141 static void connect_callback(int result, GSupplicantInterface *interface,
1142                                                         void *user_data)
1143 {
1144         struct connman_network *network = user_data;
1145
1146         DBG("network %p result %d", network, result);
1147
1148         if (result == -ENOKEY) {
1149                 connman_network_set_error(network,
1150                                         CONNMAN_NETWORK_ERROR_INVALID_KEY);
1151         } else if (result < 0) {
1152                 connman_network_set_error(network,
1153                                         CONNMAN_NETWORK_ERROR_CONFIGURE_FAIL);
1154         }
1155 }
1156
1157 static GSupplicantSecurity network_security(const char *security)
1158 {
1159         if (g_str_equal(security, "none") == TRUE)
1160                 return G_SUPPLICANT_SECURITY_NONE;
1161         else if (g_str_equal(security, "wep") == TRUE)
1162                 return G_SUPPLICANT_SECURITY_WEP;
1163         else if (g_str_equal(security, "psk") == TRUE)
1164                 return G_SUPPLICANT_SECURITY_PSK;
1165         else if (g_str_equal(security, "wpa") == TRUE)
1166                 return G_SUPPLICANT_SECURITY_PSK;
1167         else if (g_str_equal(security, "rsn") == TRUE)
1168                 return G_SUPPLICANT_SECURITY_PSK;
1169         else if (g_str_equal(security, "ieee8021x") == TRUE)
1170                 return G_SUPPLICANT_SECURITY_IEEE8021X;
1171
1172         return G_SUPPLICANT_SECURITY_UNKNOWN;
1173 }
1174
1175 static void ssid_init(GSupplicantSSID *ssid, struct connman_network *network)
1176 {
1177         const char *security, *passphrase, *agent_passphrase;
1178
1179         memset(ssid, 0, sizeof(*ssid));
1180         ssid->mode = G_SUPPLICANT_MODE_INFRA;
1181         ssid->ssid = connman_network_get_blob(network, "WiFi.SSID",
1182                                                 &ssid->ssid_len);
1183         ssid->scan_ssid = 1;
1184         security = connman_network_get_string(network, "WiFi.Security");
1185         ssid->security = network_security(security);
1186         passphrase = connman_network_get_string(network,
1187                                                 "WiFi.Passphrase");
1188         if (passphrase == NULL || strlen(passphrase) == 0) {
1189
1190                 /* Use agent provided passphrase as a fallback */
1191                 agent_passphrase = connman_network_get_string(network,
1192                                                 "WiFi.AgentPassphrase");
1193
1194                 if (agent_passphrase == NULL || strlen(agent_passphrase) == 0)
1195                         ssid->passphrase = NULL;
1196                 else
1197                         ssid->passphrase = agent_passphrase;
1198         } else
1199                 ssid->passphrase = passphrase;
1200
1201         ssid->eap = connman_network_get_string(network, "WiFi.EAP");
1202
1203         /*
1204          * If our private key password is unset,
1205          * we use the supplied passphrase. That is needed
1206          * for PEAP where 2 passphrases (identity and client
1207          * cert may have to be provided.
1208          */
1209         if (connman_network_get_string(network,
1210                                         "WiFi.PrivateKeyPassphrase") == NULL)
1211                 connman_network_set_string(network,
1212                                                 "WiFi.PrivateKeyPassphrase",
1213                                                 ssid->passphrase);
1214         /* We must have an identity for both PEAP and TLS */
1215         ssid->identity = connman_network_get_string(network, "WiFi.Identity");
1216
1217         /* Use agent provided identity as a fallback */
1218         if (ssid->identity == NULL || strlen(ssid->identity) == 0)
1219                 ssid->identity = connman_network_get_string(network,
1220                                                         "WiFi.AgentIdentity");
1221
1222         ssid->ca_cert_path = connman_network_get_string(network,
1223                                                         "WiFi.CACertFile");
1224         ssid->client_cert_path = connman_network_get_string(network,
1225                                                         "WiFi.ClientCertFile");
1226         ssid->private_key_path = connman_network_get_string(network,
1227                                                         "WiFi.PrivateKeyFile");
1228         ssid->private_key_passphrase = connman_network_get_string(network,
1229                                                 "WiFi.PrivateKeyPassphrase");
1230         ssid->phase2_auth = connman_network_get_string(network, "WiFi.Phase2");
1231
1232         ssid->use_wps = connman_network_get_bool(network, "WiFi.UseWPS");
1233         ssid->pin_wps = connman_network_get_string(network, "WiFi.PinWPS");
1234
1235         if (connman_setting_get_bool("BackgroundScanning") == TRUE)
1236                 ssid->bgscan = BGSCAN_DEFAULT;
1237 }
1238
1239 static int network_connect(struct connman_network *network)
1240 {
1241         struct connman_device *device = connman_network_get_device(network);
1242         struct wifi_data *wifi;
1243         GSupplicantInterface *interface;
1244         GSupplicantSSID *ssid;
1245
1246         DBG("network %p", network);
1247
1248         if (device == NULL)
1249                 return -ENODEV;
1250
1251         wifi = connman_device_get_data(device);
1252         if (wifi == NULL)
1253                 return -ENODEV;
1254
1255         ssid = g_try_malloc0(sizeof(GSupplicantSSID));
1256         if (ssid == NULL)
1257                 return -ENOMEM;
1258
1259         interface = wifi->interface;
1260
1261         ssid_init(ssid, network);
1262
1263         if (wifi->disconnecting == TRUE)
1264                 wifi->pending_network = network;
1265         else {
1266                 wifi->network = network;
1267                 wifi->retries = 0;
1268
1269                 return g_supplicant_interface_connect(interface, ssid,
1270                                                 connect_callback, network);
1271         }
1272
1273         return -EINPROGRESS;
1274 }
1275
1276 static void disconnect_callback(int result, GSupplicantInterface *interface,
1277                                                                 void *user_data)
1278 {
1279         struct wifi_data *wifi = user_data;
1280
1281         DBG("result %d supplicant interface %p wifi %p",
1282                         result, interface, wifi);
1283
1284         if (result == -ECONNABORTED) {
1285                 DBG("wifi interface no longer available");
1286                 return;
1287         }
1288
1289         if (wifi->network != NULL) {
1290                 /*
1291                  * if result < 0 supplican return an error because
1292                  * the network is not current.
1293                  * we wont receive G_SUPPLICANT_STATE_DISCONNECTED since it
1294                  * failed, call connman_network_set_connected to report
1295                  * disconnect is completed.
1296                  */
1297                 if (result < 0)
1298                         connman_network_set_connected(wifi->network, FALSE);
1299         }
1300
1301         wifi->network = NULL;
1302
1303         wifi->disconnecting = FALSE;
1304
1305         if (wifi->pending_network != NULL) {
1306                 network_connect(wifi->pending_network);
1307                 wifi->pending_network = NULL;
1308         }
1309
1310         start_autoscan(wifi->device);
1311 }
1312
1313 static int network_disconnect(struct connman_network *network)
1314 {
1315         struct connman_device *device = connman_network_get_device(network);
1316         struct wifi_data *wifi;
1317         int err;
1318
1319         DBG("network %p", network);
1320
1321         wifi = connman_device_get_data(device);
1322         if (wifi == NULL || wifi->interface == NULL)
1323                 return -ENODEV;
1324
1325         connman_network_set_associating(network, FALSE);
1326
1327         if (wifi->disconnecting == TRUE)
1328                 return -EALREADY;
1329
1330         wifi->disconnecting = TRUE;
1331
1332         err = g_supplicant_interface_disconnect(wifi->interface,
1333                                                 disconnect_callback, wifi);
1334         if (err < 0)
1335                 wifi->disconnecting = FALSE;
1336
1337         return err;
1338 }
1339
1340 static struct connman_network_driver network_driver = {
1341         .name           = "wifi",
1342         .type           = CONNMAN_NETWORK_TYPE_WIFI,
1343         .priority       = CONNMAN_NETWORK_PRIORITY_LOW,
1344         .probe          = network_probe,
1345         .remove         = network_remove,
1346         .connect        = network_connect,
1347         .disconnect     = network_disconnect,
1348 };
1349
1350 static void interface_added(GSupplicantInterface *interface)
1351 {
1352         const char *ifname = g_supplicant_interface_get_ifname(interface);
1353         const char *driver = g_supplicant_interface_get_driver(interface);
1354         struct wifi_data *wifi;
1355
1356         wifi = g_supplicant_interface_get_data(interface);
1357
1358         /*
1359          * We can get here with a NULL wifi pointer when
1360          * the interface added signal is sent before the
1361          * interface creation callback is called.
1362          */
1363         if (wifi == NULL)
1364                 return;
1365
1366         DBG("ifname %s driver %s wifi %p tethering %d",
1367                         ifname, driver, wifi, wifi->tethering);
1368
1369         if (wifi->device == NULL) {
1370                 connman_error("WiFi device not set");
1371                 return;
1372         }
1373
1374         connman_device_set_powered(wifi->device, TRUE);
1375
1376         if (wifi->tethering == TRUE)
1377                 return;
1378 }
1379
1380 static connman_bool_t is_idle(struct wifi_data *wifi)
1381 {
1382         DBG("state %d", wifi->state);
1383
1384         switch (wifi->state) {
1385         case G_SUPPLICANT_STATE_UNKNOWN:
1386         case G_SUPPLICANT_STATE_DISABLED:
1387         case G_SUPPLICANT_STATE_DISCONNECTED:
1388         case G_SUPPLICANT_STATE_INACTIVE:
1389         case G_SUPPLICANT_STATE_SCANNING:
1390                 return TRUE;
1391
1392         case G_SUPPLICANT_STATE_AUTHENTICATING:
1393         case G_SUPPLICANT_STATE_ASSOCIATING:
1394         case G_SUPPLICANT_STATE_ASSOCIATED:
1395         case G_SUPPLICANT_STATE_4WAY_HANDSHAKE:
1396         case G_SUPPLICANT_STATE_GROUP_HANDSHAKE:
1397         case G_SUPPLICANT_STATE_COMPLETED:
1398                 return FALSE;
1399         }
1400
1401         return FALSE;
1402 }
1403
1404 static connman_bool_t is_idle_wps(GSupplicantInterface *interface,
1405                                                 struct wifi_data *wifi)
1406 {
1407         /* First, let's check if WPS processing did not went wrong */
1408         if (g_supplicant_interface_get_wps_state(interface) ==
1409                 G_SUPPLICANT_WPS_STATE_FAIL)
1410                 return FALSE;
1411
1412         /* Unlike normal connection, being associated while processing wps
1413          * actually means that we are idling. */
1414         switch (wifi->state) {
1415         case G_SUPPLICANT_STATE_UNKNOWN:
1416         case G_SUPPLICANT_STATE_DISABLED:
1417         case G_SUPPLICANT_STATE_DISCONNECTED:
1418         case G_SUPPLICANT_STATE_INACTIVE:
1419         case G_SUPPLICANT_STATE_SCANNING:
1420         case G_SUPPLICANT_STATE_ASSOCIATED:
1421                 return TRUE;
1422         case G_SUPPLICANT_STATE_AUTHENTICATING:
1423         case G_SUPPLICANT_STATE_ASSOCIATING:
1424         case G_SUPPLICANT_STATE_4WAY_HANDSHAKE:
1425         case G_SUPPLICANT_STATE_GROUP_HANDSHAKE:
1426         case G_SUPPLICANT_STATE_COMPLETED:
1427                 return FALSE;
1428         }
1429
1430         return FALSE;
1431 }
1432
1433 static connman_bool_t handle_wps_completion(GSupplicantInterface *interface,
1434                                         struct connman_network *network,
1435                                         struct connman_device *device,
1436                                         struct wifi_data *wifi)
1437 {
1438         connman_bool_t wps;
1439
1440         wps = connman_network_get_bool(network, "WiFi.UseWPS");
1441         if (wps == TRUE) {
1442                 const unsigned char *ssid, *wps_ssid;
1443                 unsigned int ssid_len, wps_ssid_len;
1444                 const char *wps_key;
1445
1446                 /* Checking if we got associated with requested
1447                  * network */
1448                 ssid = connman_network_get_blob(network, "WiFi.SSID",
1449                                                 &ssid_len);
1450
1451                 wps_ssid = g_supplicant_interface_get_wps_ssid(
1452                         interface, &wps_ssid_len);
1453
1454                 if (wps_ssid == NULL || wps_ssid_len != ssid_len ||
1455                                 memcmp(ssid, wps_ssid, ssid_len) != 0) {
1456                         connman_network_set_associating(network, FALSE);
1457                         g_supplicant_interface_disconnect(wifi->interface,
1458                                                 disconnect_callback, wifi);
1459                         return FALSE;
1460                 }
1461
1462                 wps_key = g_supplicant_interface_get_wps_key(interface);
1463                 connman_network_set_string(network, "WiFi.Passphrase",
1464                                         wps_key);
1465
1466                 connman_network_set_string(network, "WiFi.PinWPS", NULL);
1467         }
1468
1469         return TRUE;
1470 }
1471
1472 static connman_bool_t handle_4way_handshake_failure(GSupplicantInterface *interface,
1473                                         struct connman_network *network,
1474                                         struct wifi_data *wifi)
1475 {
1476         struct connman_service *service;
1477
1478         if (wifi->state != G_SUPPLICANT_STATE_4WAY_HANDSHAKE)
1479                 return FALSE;
1480
1481         service = connman_service_lookup_from_network(network);
1482         if (service == NULL)
1483                 return FALSE;
1484
1485         wifi->retries++;
1486
1487         if (connman_service_get_favorite(service) == TRUE) {
1488                 if (wifi->retries < FAVORITE_MAXIMUM_RETRIES)
1489                         return TRUE;
1490         } else if (wifi->retries < MAXIMUM_RETRIES)
1491                 return TRUE;
1492
1493         connman_network_set_error(network, CONNMAN_NETWORK_ERROR_INVALID_KEY);
1494
1495         return FALSE;
1496 }
1497
1498 static void interface_state(GSupplicantInterface *interface)
1499 {
1500         struct connman_network *network;
1501         struct connman_device *device;
1502         struct wifi_data *wifi;
1503         GSupplicantState state = g_supplicant_interface_get_state(interface);
1504         connman_bool_t wps;
1505
1506         wifi = g_supplicant_interface_get_data(interface);
1507
1508         DBG("wifi %p interface state %d", wifi, state);
1509
1510         if (wifi == NULL)
1511                 return;
1512
1513         network = wifi->network;
1514         device = wifi->device;
1515
1516         if (device == NULL || network == NULL)
1517                 return;
1518
1519         switch (state) {
1520         case G_SUPPLICANT_STATE_SCANNING:
1521                 break;
1522
1523         case G_SUPPLICANT_STATE_AUTHENTICATING:
1524         case G_SUPPLICANT_STATE_ASSOCIATING:
1525                 stop_autoscan(device);
1526
1527                 if (wifi->connected == FALSE)
1528                         connman_network_set_associating(network, TRUE);
1529
1530                 break;
1531
1532         case G_SUPPLICANT_STATE_COMPLETED:
1533                 /* though it should be already stopped: */
1534                 stop_autoscan(device);
1535
1536                 if (handle_wps_completion(interface, network, device, wifi) ==
1537                                                                         FALSE)
1538                         break;
1539
1540                 connman_network_set_connected(network, TRUE);
1541                 break;
1542
1543         case G_SUPPLICANT_STATE_DISCONNECTED:
1544                 /*
1545                  * If we're in one of the idle modes, we have
1546                  * not started association yet and thus setting
1547                  * those ones to FALSE could cancel an association
1548                  * in progress.
1549                  */
1550                 wps = connman_network_get_bool(network, "WiFi.UseWPS");
1551                 if (wps == TRUE)
1552                         if (is_idle_wps(interface, wifi) == TRUE)
1553                                 break;
1554
1555                 if (is_idle(wifi))
1556                         break;
1557
1558                 /* If previous state was 4way-handshake, then
1559                  * it's either: psk was incorrect and thus we retry
1560                  * or if we reach the maximum retries we declare the
1561                  * psk as wrong */
1562                 if (handle_4way_handshake_failure(interface,
1563                                                 network, wifi) == TRUE)
1564                         break;
1565
1566                 /* We disable the selected network, if not then
1567                  * wpa_supplicant will loop retrying */
1568                 if (g_supplicant_interface_enable_selected_network(interface,
1569                                                 FALSE) != 0)
1570                         DBG("Could not disables selected network");
1571
1572                 connman_network_set_connected(network, FALSE);
1573                 connman_network_set_associating(network, FALSE);
1574                 wifi->disconnecting = FALSE;
1575
1576                 start_autoscan(device);
1577
1578                 break;
1579
1580         case G_SUPPLICANT_STATE_INACTIVE:
1581                 connman_network_set_associating(network, FALSE);
1582                 start_autoscan(device);
1583
1584                 break;
1585
1586         case G_SUPPLICANT_STATE_UNKNOWN:
1587         case G_SUPPLICANT_STATE_DISABLED:
1588         case G_SUPPLICANT_STATE_ASSOCIATED:
1589         case G_SUPPLICANT_STATE_4WAY_HANDSHAKE:
1590         case G_SUPPLICANT_STATE_GROUP_HANDSHAKE:
1591                 break;
1592         }
1593
1594         wifi->state = state;
1595
1596         /* Saving wpa_s state policy:
1597          * If connected and if the state changes are roaming related:
1598          * --> We stay connected
1599          * If completed
1600          * --> We are connected
1601          * All other case:
1602          * --> We are not connected
1603          * */
1604         switch (state) {
1605         case G_SUPPLICANT_STATE_AUTHENTICATING:
1606         case G_SUPPLICANT_STATE_ASSOCIATING:
1607         case G_SUPPLICANT_STATE_ASSOCIATED:
1608         case G_SUPPLICANT_STATE_4WAY_HANDSHAKE:
1609         case G_SUPPLICANT_STATE_GROUP_HANDSHAKE:
1610                 if (wifi->connected == TRUE)
1611                         connman_warn("Probably roaming right now!"
1612                                                 " Staying connected...");
1613                 else
1614                         wifi->connected = FALSE;
1615                 break;
1616         case G_SUPPLICANT_STATE_COMPLETED:
1617                 wifi->connected = TRUE;
1618                 break;
1619         default:
1620                 wifi->connected = FALSE;
1621                 break;
1622         }
1623
1624         DBG("DONE");
1625 }
1626
1627 static void interface_removed(GSupplicantInterface *interface)
1628 {
1629         const char *ifname = g_supplicant_interface_get_ifname(interface);
1630         struct wifi_data *wifi;
1631
1632         DBG("ifname %s", ifname);
1633
1634         wifi = g_supplicant_interface_get_data(interface);
1635
1636         if (wifi != NULL && wifi->tethering == TRUE)
1637                 return;
1638
1639         if (wifi == NULL || wifi->device == NULL) {
1640                 DBG("wifi interface already removed");
1641                 return;
1642         }
1643
1644         wifi->interface = NULL;
1645         connman_device_set_powered(wifi->device, FALSE);
1646 }
1647
1648 static void scan_started(GSupplicantInterface *interface)
1649 {
1650         DBG("");
1651 }
1652
1653 static void scan_finished(GSupplicantInterface *interface)
1654 {
1655         DBG("");
1656 }
1657
1658 static unsigned char calculate_strength(GSupplicantNetwork *supplicant_network)
1659 {
1660         unsigned char strength;
1661
1662         strength = 120 + g_supplicant_network_get_signal(supplicant_network);
1663         if (strength > 100)
1664                 strength = 100;
1665
1666         return strength;
1667 }
1668
1669 static void network_added(GSupplicantNetwork *supplicant_network)
1670 {
1671         struct connman_network *network;
1672         GSupplicantInterface *interface;
1673         struct wifi_data *wifi;
1674         const char *name, *identifier, *security, *group, *mode;
1675         const unsigned char *ssid;
1676         unsigned int ssid_len;
1677         connman_bool_t wps;
1678         connman_bool_t wps_pbc;
1679         connman_bool_t wps_ready;
1680         connman_bool_t wps_advertizing;
1681
1682         DBG("");
1683
1684         interface = g_supplicant_network_get_interface(supplicant_network);
1685         wifi = g_supplicant_interface_get_data(interface);
1686         name = g_supplicant_network_get_name(supplicant_network);
1687         identifier = g_supplicant_network_get_identifier(supplicant_network);
1688         security = g_supplicant_network_get_security(supplicant_network);
1689         group = g_supplicant_network_get_identifier(supplicant_network);
1690         wps = g_supplicant_network_get_wps(supplicant_network);
1691         wps_pbc = g_supplicant_network_is_wps_pbc(supplicant_network);
1692         wps_ready = g_supplicant_network_is_wps_active(supplicant_network);
1693         wps_advertizing = g_supplicant_network_is_wps_advertizing(
1694                                                         supplicant_network);
1695         mode = g_supplicant_network_get_mode(supplicant_network);
1696
1697         if (wifi == NULL)
1698                 return;
1699
1700         ssid = g_supplicant_network_get_ssid(supplicant_network, &ssid_len);
1701
1702         network = connman_device_get_network(wifi->device, identifier);
1703
1704         if (network == NULL) {
1705                 network = connman_network_create(identifier,
1706                                                 CONNMAN_NETWORK_TYPE_WIFI);
1707                 if (network == NULL)
1708                         return;
1709
1710                 connman_network_set_index(network, wifi->index);
1711
1712                 if (connman_device_add_network(wifi->device, network) < 0) {
1713                         connman_network_unref(network);
1714                         return;
1715                 }
1716
1717                 wifi->networks = g_slist_prepend(wifi->networks, network);
1718         }
1719
1720         if (name != NULL && name[0] != '\0')
1721                 connman_network_set_name(network, name);
1722
1723         connman_network_set_blob(network, "WiFi.SSID",
1724                                                 ssid, ssid_len);
1725         connman_network_set_string(network, "WiFi.Security", security);
1726         connman_network_set_strength(network,
1727                                 calculate_strength(supplicant_network));
1728         connman_network_set_bool(network, "WiFi.WPS", wps);
1729
1730         if (wps == TRUE) {
1731                 /* Is AP advertizing for WPS association?
1732                  * If so, we decide to use WPS by default */
1733                 if (wps_ready == TRUE && wps_pbc == TRUE &&
1734                                                 wps_advertizing == TRUE)
1735                         connman_network_set_bool(network, "WiFi.UseWPS", TRUE);
1736         }
1737
1738         connman_network_set_frequency(network,
1739                         g_supplicant_network_get_frequency(supplicant_network));
1740
1741         connman_network_set_available(network, TRUE);
1742         connman_network_set_string(network, "WiFi.Mode", mode);
1743
1744         if (ssid != NULL)
1745                 connman_network_set_group(network, group);
1746
1747         if (wifi->hidden != NULL && ssid != NULL) {
1748                 if (wifi->hidden->ssid_len == ssid_len &&
1749                                 memcmp(wifi->hidden->ssid, ssid,
1750                                                 ssid_len) == 0) {
1751                         connman_network_connect_hidden(network,
1752                                         wifi->hidden->identity,
1753                                         wifi->hidden->passphrase,
1754                                         wifi->hidden->user_data);
1755                         wifi->hidden->user_data = NULL;
1756                         hidden_free(wifi->hidden);
1757                         wifi->hidden = NULL;
1758                 }
1759         }
1760 }
1761
1762 static void network_removed(GSupplicantNetwork *network)
1763 {
1764         GSupplicantInterface *interface;
1765         struct wifi_data *wifi;
1766         const char *name, *identifier;
1767         struct connman_network *connman_network;
1768
1769         interface = g_supplicant_network_get_interface(network);
1770         wifi = g_supplicant_interface_get_data(interface);
1771         identifier = g_supplicant_network_get_identifier(network);
1772         name = g_supplicant_network_get_name(network);
1773
1774         DBG("name %s", name);
1775
1776         if (wifi == NULL)
1777                 return;
1778
1779         connman_network = connman_device_get_network(wifi->device, identifier);
1780         if (connman_network == NULL)
1781                 return;
1782
1783         wifi->networks = g_slist_remove(wifi->networks, connman_network);
1784
1785         connman_device_remove_network(wifi->device, connman_network);
1786         connman_network_unref(connman_network);
1787 }
1788
1789 static void network_changed(GSupplicantNetwork *network, const char *property)
1790 {
1791         GSupplicantInterface *interface;
1792         struct wifi_data *wifi;
1793         const char *name, *identifier;
1794         struct connman_network *connman_network;
1795
1796         interface = g_supplicant_network_get_interface(network);
1797         wifi = g_supplicant_interface_get_data(interface);
1798         identifier = g_supplicant_network_get_identifier(network);
1799         name = g_supplicant_network_get_name(network);
1800
1801         DBG("name %s", name);
1802
1803         if (wifi == NULL)
1804                 return;
1805
1806         connman_network = connman_device_get_network(wifi->device, identifier);
1807         if (connman_network == NULL)
1808                 return;
1809
1810         if (g_str_equal(property, "Signal") == TRUE) {
1811                connman_network_set_strength(connman_network,
1812                                         calculate_strength(network));
1813                connman_network_update(connman_network);
1814         }
1815 }
1816
1817 static void debug(const char *str)
1818 {
1819         if (getenv("CONNMAN_SUPPLICANT_DEBUG"))
1820                 connman_debug("%s", str);
1821 }
1822
1823 static const GSupplicantCallbacks callbacks = {
1824         .system_ready           = system_ready,
1825         .system_killed          = system_killed,
1826         .interface_added        = interface_added,
1827         .interface_state        = interface_state,
1828         .interface_removed      = interface_removed,
1829         .scan_started           = scan_started,
1830         .scan_finished          = scan_finished,
1831         .network_added          = network_added,
1832         .network_removed        = network_removed,
1833         .network_changed        = network_changed,
1834         .debug                  = debug,
1835 };
1836
1837
1838 static int tech_probe(struct connman_technology *technology)
1839 {
1840         wifi_technology = technology;
1841
1842         return 0;
1843 }
1844
1845 static void tech_remove(struct connman_technology *technology)
1846 {
1847         wifi_technology = NULL;
1848 }
1849
1850 struct wifi_tethering_info {
1851         struct wifi_data *wifi;
1852         struct connman_technology *technology;
1853         char *ifname;
1854         GSupplicantSSID *ssid;
1855 };
1856
1857 static GSupplicantSSID *ssid_ap_init(const char *ssid, const char *passphrase)
1858 {
1859         GSupplicantSSID *ap;
1860
1861         ap = g_try_malloc0(sizeof(GSupplicantSSID));
1862         if (ap == NULL)
1863                 return NULL;
1864
1865         ap->mode = G_SUPPLICANT_MODE_MASTER;
1866         ap->ssid = ssid;
1867         ap->ssid_len = strlen(ssid);
1868         ap->scan_ssid = 0;
1869         ap->freq = 2412;
1870
1871         if (passphrase == NULL || strlen(passphrase) == 0) {
1872                 ap->security = G_SUPPLICANT_SECURITY_NONE;
1873                 ap->passphrase = NULL;
1874         } else {
1875                ap->security = G_SUPPLICANT_SECURITY_PSK;
1876                ap->protocol = G_SUPPLICANT_PROTO_RSN;
1877                ap->pairwise_cipher = G_SUPPLICANT_PAIRWISE_CCMP;
1878                ap->group_cipher = G_SUPPLICANT_GROUP_CCMP;
1879                ap->passphrase = passphrase;
1880         }
1881
1882         return ap;
1883 }
1884
1885 static void ap_start_callback(int result, GSupplicantInterface *interface,
1886                                                         void *user_data)
1887 {
1888         struct wifi_tethering_info *info = user_data;
1889
1890         DBG("result %d index %d bridge %s",
1891                 result, info->wifi->index, info->wifi->bridge);
1892
1893         if (result < 0) {
1894                 connman_inet_remove_from_bridge(info->wifi->index,
1895                                                         info->wifi->bridge);
1896                 connman_technology_tethering_notify(info->technology, FALSE);
1897         }
1898
1899         g_free(info->ifname);
1900         g_free(info);
1901 }
1902
1903 static void ap_create_callback(int result,
1904                                 GSupplicantInterface *interface,
1905                                         void *user_data)
1906 {
1907         struct wifi_tethering_info *info = user_data;
1908
1909         DBG("result %d ifname %s", result,
1910                                 g_supplicant_interface_get_ifname(interface));
1911
1912         if (result < 0) {
1913                 connman_inet_remove_from_bridge(info->wifi->index,
1914                                                         info->wifi->bridge);
1915                 connman_technology_tethering_notify(info->technology, FALSE);
1916
1917                 g_free(info->ifname);
1918                 g_free(info);
1919                 return;
1920         }
1921
1922         info->wifi->interface = interface;
1923         g_supplicant_interface_set_data(interface, info->wifi);
1924
1925         if (g_supplicant_interface_set_apscan(interface, 2) < 0)
1926                 connman_error("Failed to set interface ap_scan property");
1927
1928         g_supplicant_interface_connect(interface, info->ssid,
1929                                                 ap_start_callback, info);
1930 }
1931
1932 static void sta_remove_callback(int result,
1933                                 GSupplicantInterface *interface,
1934                                         void *user_data)
1935 {
1936         struct wifi_tethering_info *info = user_data;
1937         const char *driver = connman_option_get_string("wifi");
1938
1939         DBG("ifname %s result %d ", info->ifname, result);
1940
1941         if (result < 0) {
1942                 info->wifi->tethering = TRUE;
1943
1944                 g_free(info->ifname);
1945                 g_free(info);
1946                 return;
1947         }
1948
1949         info->wifi->interface = NULL;
1950
1951         connman_technology_tethering_notify(info->technology, TRUE);
1952
1953         g_supplicant_interface_create(info->ifname, driver, info->wifi->bridge,
1954                                                 ap_create_callback,
1955                                                         info);
1956 }
1957
1958 static int tech_set_tethering(struct connman_technology *technology,
1959                                 const char *identifier, const char *passphrase,
1960                                 const char *bridge, connman_bool_t enabled)
1961 {
1962         GList *list;
1963         GSupplicantInterface *interface;
1964         struct wifi_data *wifi;
1965         struct wifi_tethering_info *info;
1966         const char *ifname;
1967         unsigned int mode;
1968         int err;
1969
1970         DBG("");
1971
1972         if (enabled == FALSE) {
1973                 for (list = iface_list; list; list = list->next) {
1974                         wifi = list->data;
1975
1976                         if (wifi->tethering == TRUE) {
1977                                 wifi->tethering = FALSE;
1978
1979                                 connman_inet_remove_from_bridge(wifi->index,
1980                                                                         bridge);
1981                                 wifi->bridged = FALSE;
1982                         }
1983                 }
1984
1985                 connman_technology_tethering_notify(technology, FALSE);
1986
1987                 return 0;
1988         }
1989
1990         for (list = iface_list; list; list = list->next) {
1991                 wifi = list->data;
1992
1993                 interface = wifi->interface;
1994
1995                 if (interface == NULL)
1996                         continue;
1997
1998                 ifname = g_supplicant_interface_get_ifname(wifi->interface);
1999
2000                 mode = g_supplicant_interface_get_mode(interface);
2001                 if ((mode & G_SUPPLICANT_CAPABILITY_MODE_AP) == 0) {
2002                         DBG("%s does not support AP mode", ifname);
2003                         continue;
2004                 }
2005
2006                 info = g_try_malloc0(sizeof(struct wifi_tethering_info));
2007                 if (info == NULL)
2008                         return -ENOMEM;
2009
2010                 info->wifi = wifi;
2011                 info->technology = technology;
2012                 info->wifi->bridge = bridge;
2013                 info->ssid = ssid_ap_init(identifier, passphrase);
2014                 if (info->ssid == NULL) {
2015                         g_free(info);
2016                         continue;
2017                 }
2018                 info->ifname = g_strdup(ifname);
2019                 if (info->ifname == NULL) {
2020                         g_free(info);
2021                         continue;
2022                 }
2023
2024                 info->wifi->tethering = TRUE;
2025
2026                 err = g_supplicant_interface_remove(interface,
2027                                                 sta_remove_callback,
2028                                                         info);
2029                 if (err == 0)
2030                         return err;
2031         }
2032
2033         return -EOPNOTSUPP;
2034 }
2035
2036 static void regdom_callback(int result, const char *alpha2, void *user_data)
2037 {
2038         DBG("");
2039
2040         if (wifi_technology == NULL)
2041                 return;
2042
2043         if (result != 0)
2044                 alpha2 = NULL;
2045
2046         connman_technology_regdom_notify(wifi_technology, alpha2);
2047 }
2048
2049 static int tech_set_regdom(struct connman_technology *technology, const char *alpha2)
2050 {
2051         return g_supplicant_set_country(alpha2, regdom_callback, NULL);
2052 }
2053
2054 static struct connman_technology_driver tech_driver = {
2055         .name           = "wifi",
2056         .type           = CONNMAN_SERVICE_TYPE_WIFI,
2057         .probe          = tech_probe,
2058         .remove         = tech_remove,
2059         .set_tethering  = tech_set_tethering,
2060         .set_regdom     = tech_set_regdom,
2061 };
2062
2063 static int wifi_init(void)
2064 {
2065         int err;
2066
2067         err = connman_network_driver_register(&network_driver);
2068         if (err < 0)
2069                 return err;
2070
2071         err = g_supplicant_register(&callbacks);
2072         if (err < 0) {
2073                 connman_network_driver_unregister(&network_driver);
2074                 return err;
2075         }
2076
2077         err = connman_technology_driver_register(&tech_driver);
2078         if (err < 0) {
2079                 g_supplicant_unregister(&callbacks);
2080                 connman_network_driver_unregister(&network_driver);
2081                 return err;
2082         }
2083
2084         return 0;
2085 }
2086
2087 static void wifi_exit(void)
2088 {
2089         DBG();
2090
2091         connman_technology_driver_unregister(&tech_driver);
2092
2093         g_supplicant_unregister(&callbacks);
2094
2095         connman_network_driver_unregister(&network_driver);
2096 }
2097
2098 CONNMAN_PLUGIN_DEFINE(wifi, "WiFi interface plugin", VERSION,
2099                 CONNMAN_PLUGIN_PRIORITY_DEFAULT, wifi_init, wifi_exit)