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