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