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