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