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