wifi: Do not start autoscan if interface was not ready
[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
520         if (result != -ENOLINK)
521                 start_autoscan(device);
522
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_DISABLED:
1335         case G_SUPPLICANT_STATE_DISCONNECTED:
1336         case G_SUPPLICANT_STATE_INACTIVE:
1337         case G_SUPPLICANT_STATE_SCANNING:
1338                 return TRUE;
1339
1340         case G_SUPPLICANT_STATE_AUTHENTICATING:
1341         case G_SUPPLICANT_STATE_ASSOCIATING:
1342         case G_SUPPLICANT_STATE_ASSOCIATED:
1343         case G_SUPPLICANT_STATE_4WAY_HANDSHAKE:
1344         case G_SUPPLICANT_STATE_GROUP_HANDSHAKE:
1345         case G_SUPPLICANT_STATE_COMPLETED:
1346                 return FALSE;
1347         }
1348
1349         return FALSE;
1350 }
1351
1352 static connman_bool_t is_idle_wps(GSupplicantInterface *interface,
1353                                                 struct wifi_data *wifi)
1354 {
1355         /* First, let's check if WPS processing did not went wrong */
1356         if (g_supplicant_interface_get_wps_state(interface) ==
1357                 G_SUPPLICANT_WPS_STATE_FAIL)
1358                 return FALSE;
1359
1360         /* Unlike normal connection, being associated while processing wps
1361          * actually means that we are idling. */
1362         switch (wifi->state) {
1363         case G_SUPPLICANT_STATE_UNKNOWN:
1364         case G_SUPPLICANT_STATE_DISABLED:
1365         case G_SUPPLICANT_STATE_DISCONNECTED:
1366         case G_SUPPLICANT_STATE_INACTIVE:
1367         case G_SUPPLICANT_STATE_SCANNING:
1368         case G_SUPPLICANT_STATE_ASSOCIATED:
1369                 return TRUE;
1370         case G_SUPPLICANT_STATE_AUTHENTICATING:
1371         case G_SUPPLICANT_STATE_ASSOCIATING:
1372         case G_SUPPLICANT_STATE_4WAY_HANDSHAKE:
1373         case G_SUPPLICANT_STATE_GROUP_HANDSHAKE:
1374         case G_SUPPLICANT_STATE_COMPLETED:
1375                 return FALSE;
1376         }
1377
1378         return FALSE;
1379 }
1380
1381 static connman_bool_t handle_wps_completion(GSupplicantInterface *interface,
1382                                         struct connman_network *network,
1383                                         struct connman_device *device,
1384                                         struct wifi_data *wifi)
1385 {
1386         connman_bool_t wps;
1387
1388         wps = connman_network_get_bool(network, "WiFi.UseWPS");
1389         if (wps == TRUE) {
1390                 const unsigned char *ssid, *wps_ssid;
1391                 unsigned int ssid_len, wps_ssid_len;
1392                 const char *wps_key;
1393
1394                 /* Checking if we got associated with requested
1395                  * network */
1396                 ssid = connman_network_get_blob(network, "WiFi.SSID",
1397                                                 &ssid_len);
1398
1399                 wps_ssid = g_supplicant_interface_get_wps_ssid(
1400                         interface, &wps_ssid_len);
1401
1402                 if (wps_ssid == NULL || wps_ssid_len != ssid_len ||
1403                                 memcmp(ssid, wps_ssid, ssid_len) != 0) {
1404                         connman_network_set_associating(network, FALSE);
1405                         g_supplicant_interface_disconnect(wifi->interface,
1406                                                 disconnect_callback, wifi);
1407                         return FALSE;
1408                 }
1409
1410                 wps_key = g_supplicant_interface_get_wps_key(interface);
1411                 connman_network_set_string(network, "WiFi.Passphrase",
1412                                         wps_key);
1413
1414                 connman_network_set_string(network, "WiFi.PinWPS", NULL);
1415         }
1416
1417         return TRUE;
1418 }
1419
1420 static connman_bool_t handle_4way_handshake_failure(GSupplicantInterface *interface,
1421                                         struct connman_network *network,
1422                                         struct wifi_data *wifi)
1423 {
1424         struct connman_service *service;
1425
1426         if (wifi->state != G_SUPPLICANT_STATE_4WAY_HANDSHAKE)
1427                 return FALSE;
1428
1429         service = connman_service_lookup_from_network(network);
1430         if (service == NULL)
1431                 return FALSE;
1432
1433         wifi->retries++;
1434
1435         if (connman_service_get_favorite(service) == TRUE) {
1436                 if (wifi->retries < FAVORITE_MAXIMUM_RETRIES)
1437                         return TRUE;
1438         } else if (wifi->retries < MAXIMUM_RETRIES)
1439                 return TRUE;
1440
1441         connman_network_set_error(network, CONNMAN_NETWORK_ERROR_INVALID_KEY);
1442
1443         return FALSE;
1444 }
1445
1446 static void interface_state(GSupplicantInterface *interface)
1447 {
1448         struct connman_network *network;
1449         struct connman_device *device;
1450         struct wifi_data *wifi;
1451         GSupplicantState state = g_supplicant_interface_get_state(interface);
1452         connman_bool_t wps;
1453
1454         wifi = g_supplicant_interface_get_data(interface);
1455
1456         DBG("wifi %p interface state %d", wifi, state);
1457
1458         if (wifi == NULL)
1459                 return;
1460
1461         network = wifi->network;
1462         device = wifi->device;
1463
1464         if (device == NULL || network == NULL)
1465                 return;
1466
1467         switch (state) {
1468         case G_SUPPLICANT_STATE_SCANNING:
1469                 break;
1470
1471         case G_SUPPLICANT_STATE_AUTHENTICATING:
1472         case G_SUPPLICANT_STATE_ASSOCIATING:
1473                 stop_autoscan(device);
1474
1475                 if (wifi->connected == FALSE)
1476                         connman_network_set_associating(network, TRUE);
1477
1478                 break;
1479
1480         case G_SUPPLICANT_STATE_COMPLETED:
1481                 /* though it should be already stopped: */
1482                 stop_autoscan(device);
1483
1484                 if (handle_wps_completion(interface, network, device, wifi) ==
1485                                                                         FALSE)
1486                         break;
1487
1488                 connman_network_set_connected(network, TRUE);
1489                 break;
1490
1491         case G_SUPPLICANT_STATE_DISCONNECTED:
1492                 /*
1493                  * If we're in one of the idle modes, we have
1494                  * not started association yet and thus setting
1495                  * those ones to FALSE could cancel an association
1496                  * in progress.
1497                  */
1498                 wps = connman_network_get_bool(network, "WiFi.UseWPS");
1499                 if (wps == TRUE)
1500                         if (is_idle_wps(interface, wifi) == TRUE)
1501                                 break;
1502
1503                 if (is_idle(wifi))
1504                         break;
1505
1506                 /* If previous state was 4way-handshake, then
1507                  * it's either: psk was incorrect and thus we retry
1508                  * or if we reach the maximum retries we declare the
1509                  * psk as wrong */
1510                 if (handle_4way_handshake_failure(interface,
1511                                                 network, wifi) == TRUE)
1512                         break;
1513
1514                 /* We disable the selected network, if not then
1515                  * wpa_supplicant will loop retrying */
1516                 if (g_supplicant_interface_enable_selected_network(interface,
1517                                                 FALSE) != 0)
1518                         DBG("Could not disables selected network");
1519
1520                 connman_network_set_connected(network, FALSE);
1521                 connman_network_set_associating(network, FALSE);
1522                 wifi->disconnecting = FALSE;
1523
1524                 start_autoscan(device);
1525
1526                 break;
1527
1528         case G_SUPPLICANT_STATE_INACTIVE:
1529                 connman_network_set_associating(network, FALSE);
1530                 start_autoscan(device);
1531
1532                 break;
1533
1534         case G_SUPPLICANT_STATE_UNKNOWN:
1535         case G_SUPPLICANT_STATE_DISABLED:
1536         case G_SUPPLICANT_STATE_ASSOCIATED:
1537         case G_SUPPLICANT_STATE_4WAY_HANDSHAKE:
1538         case G_SUPPLICANT_STATE_GROUP_HANDSHAKE:
1539                 break;
1540         }
1541
1542         wifi->state = state;
1543
1544         /* Saving wpa_s state policy:
1545          * If connected and if the state changes are roaming related:
1546          * --> We stay connected
1547          * If completed
1548          * --> We are connected
1549          * All other case:
1550          * --> We are not connected
1551          * */
1552         switch (state) {
1553         case G_SUPPLICANT_STATE_AUTHENTICATING:
1554         case G_SUPPLICANT_STATE_ASSOCIATING:
1555         case G_SUPPLICANT_STATE_ASSOCIATED:
1556         case G_SUPPLICANT_STATE_4WAY_HANDSHAKE:
1557         case G_SUPPLICANT_STATE_GROUP_HANDSHAKE:
1558                 if (wifi->connected == TRUE)
1559                         connman_warn("Probably roaming right now!"
1560                                                 " Staying connected...");
1561                 else
1562                         wifi->connected = FALSE;
1563                 break;
1564         case G_SUPPLICANT_STATE_COMPLETED:
1565                 wifi->connected = TRUE;
1566                 break;
1567         default:
1568                 wifi->connected = FALSE;
1569                 break;
1570         }
1571
1572         DBG("DONE");
1573 }
1574
1575 static void interface_removed(GSupplicantInterface *interface)
1576 {
1577         const char *ifname = g_supplicant_interface_get_ifname(interface);
1578         struct wifi_data *wifi;
1579
1580         DBG("ifname %s", ifname);
1581
1582         wifi = g_supplicant_interface_get_data(interface);
1583
1584         if (wifi != NULL && wifi->tethering == TRUE)
1585                 return;
1586
1587         if (wifi == NULL || wifi->device == NULL) {
1588                 DBG("wifi interface already removed");
1589                 return;
1590         }
1591
1592         wifi->interface = NULL;
1593         connman_device_set_powered(wifi->device, FALSE);
1594 }
1595
1596 static void scan_started(GSupplicantInterface *interface)
1597 {
1598         DBG("");
1599 }
1600
1601 static void scan_finished(GSupplicantInterface *interface)
1602 {
1603         DBG("");
1604 }
1605
1606 static unsigned char calculate_strength(GSupplicantNetwork *supplicant_network)
1607 {
1608         unsigned char strength;
1609
1610         strength = 120 + g_supplicant_network_get_signal(supplicant_network);
1611         if (strength > 100)
1612                 strength = 100;
1613
1614         return strength;
1615 }
1616
1617 static void network_added(GSupplicantNetwork *supplicant_network)
1618 {
1619         struct connman_network *network;
1620         GSupplicantInterface *interface;
1621         struct wifi_data *wifi;
1622         const char *name, *identifier, *security, *group, *mode;
1623         const unsigned char *ssid;
1624         unsigned int ssid_len;
1625         connman_bool_t wps;
1626         connman_bool_t wps_pbc;
1627         connman_bool_t wps_ready;
1628         connman_bool_t wps_advertizing;
1629
1630         DBG("");
1631
1632         interface = g_supplicant_network_get_interface(supplicant_network);
1633         wifi = g_supplicant_interface_get_data(interface);
1634         name = g_supplicant_network_get_name(supplicant_network);
1635         identifier = g_supplicant_network_get_identifier(supplicant_network);
1636         security = g_supplicant_network_get_security(supplicant_network);
1637         group = g_supplicant_network_get_identifier(supplicant_network);
1638         wps = g_supplicant_network_get_wps(supplicant_network);
1639         wps_pbc = g_supplicant_network_is_wps_pbc(supplicant_network);
1640         wps_ready = g_supplicant_network_is_wps_active(supplicant_network);
1641         wps_advertizing = g_supplicant_network_is_wps_advertizing(
1642                                                         supplicant_network);
1643         mode = g_supplicant_network_get_mode(supplicant_network);
1644
1645         if (wifi == NULL)
1646                 return;
1647
1648         ssid = g_supplicant_network_get_ssid(supplicant_network, &ssid_len);
1649
1650         network = connman_device_get_network(wifi->device, identifier);
1651
1652         if (network == NULL) {
1653                 network = connman_network_create(identifier,
1654                                                 CONNMAN_NETWORK_TYPE_WIFI);
1655                 if (network == NULL)
1656                         return;
1657
1658                 connman_network_set_index(network, wifi->index);
1659
1660                 if (connman_device_add_network(wifi->device, network) < 0) {
1661                         connman_network_unref(network);
1662                         return;
1663                 }
1664
1665                 wifi->networks = g_slist_prepend(wifi->networks, network);
1666         }
1667
1668         if (name != NULL && name[0] != '\0')
1669                 connman_network_set_name(network, name);
1670
1671         connman_network_set_blob(network, "WiFi.SSID",
1672                                                 ssid, ssid_len);
1673         connman_network_set_string(network, "WiFi.Security", security);
1674         connman_network_set_strength(network,
1675                                 calculate_strength(supplicant_network));
1676         connman_network_set_bool(network, "WiFi.WPS", wps);
1677
1678         if (wps == TRUE) {
1679                 /* Is AP advertizing for WPS association?
1680                  * If so, we decide to use WPS by default */
1681                 if (wps_ready == TRUE && wps_pbc == TRUE &&
1682                                                 wps_advertizing == TRUE)
1683                         connman_network_set_bool(network, "WiFi.UseWPS", TRUE);
1684         }
1685
1686         connman_network_set_frequency(network,
1687                         g_supplicant_network_get_frequency(supplicant_network));
1688
1689         connman_network_set_available(network, TRUE);
1690         connman_network_set_string(network, "WiFi.Mode", mode);
1691
1692         if (ssid != NULL)
1693                 connman_network_set_group(network, group);
1694
1695         if (wifi->hidden != NULL && ssid != NULL) {
1696                 if (wifi->hidden->ssid_len == ssid_len &&
1697                                 memcmp(wifi->hidden->ssid, ssid,
1698                                                 ssid_len) == 0) {
1699                         connman_network_connect_hidden(network,
1700                                         wifi->hidden->identity,
1701                                         wifi->hidden->passphrase,
1702                                         wifi->hidden->user_data);
1703                         wifi->hidden->user_data = NULL;
1704                         hidden_free(wifi->hidden);
1705                         wifi->hidden = NULL;
1706                 }
1707         }
1708 }
1709
1710 static void network_removed(GSupplicantNetwork *network)
1711 {
1712         GSupplicantInterface *interface;
1713         struct wifi_data *wifi;
1714         const char *name, *identifier;
1715         struct connman_network *connman_network;
1716
1717         interface = g_supplicant_network_get_interface(network);
1718         wifi = g_supplicant_interface_get_data(interface);
1719         identifier = g_supplicant_network_get_identifier(network);
1720         name = g_supplicant_network_get_name(network);
1721
1722         DBG("name %s", name);
1723
1724         if (wifi == NULL)
1725                 return;
1726
1727         connman_network = connman_device_get_network(wifi->device, identifier);
1728         if (connman_network == NULL)
1729                 return;
1730
1731         wifi->networks = g_slist_remove(wifi->networks, connman_network);
1732
1733         connman_device_remove_network(wifi->device, connman_network);
1734         connman_network_unref(connman_network);
1735 }
1736
1737 static void network_changed(GSupplicantNetwork *network, const char *property)
1738 {
1739         GSupplicantInterface *interface;
1740         struct wifi_data *wifi;
1741         const char *name, *identifier;
1742         struct connman_network *connman_network;
1743
1744         interface = g_supplicant_network_get_interface(network);
1745         wifi = g_supplicant_interface_get_data(interface);
1746         identifier = g_supplicant_network_get_identifier(network);
1747         name = g_supplicant_network_get_name(network);
1748
1749         DBG("name %s", name);
1750
1751         if (wifi == NULL)
1752                 return;
1753
1754         connman_network = connman_device_get_network(wifi->device, identifier);
1755         if (connman_network == NULL)
1756                 return;
1757
1758         if (g_str_equal(property, "Signal") == TRUE) {
1759                connman_network_set_strength(connman_network,
1760                                         calculate_strength(network));
1761                connman_network_update(connman_network);
1762         }
1763 }
1764
1765 static void debug(const char *str)
1766 {
1767         if (getenv("CONNMAN_SUPPLICANT_DEBUG"))
1768                 connman_debug("%s", str);
1769 }
1770
1771 static const GSupplicantCallbacks callbacks = {
1772         .system_ready           = system_ready,
1773         .system_killed          = system_killed,
1774         .interface_added        = interface_added,
1775         .interface_state        = interface_state,
1776         .interface_removed      = interface_removed,
1777         .scan_started           = scan_started,
1778         .scan_finished          = scan_finished,
1779         .network_added          = network_added,
1780         .network_removed        = network_removed,
1781         .network_changed        = network_changed,
1782         .debug                  = debug,
1783 };
1784
1785
1786 static int tech_probe(struct connman_technology *technology)
1787 {
1788         wifi_technology = technology;
1789
1790         return 0;
1791 }
1792
1793 static void tech_remove(struct connman_technology *technology)
1794 {
1795         wifi_technology = NULL;
1796 }
1797
1798 struct wifi_tethering_info {
1799         struct wifi_data *wifi;
1800         struct connman_technology *technology;
1801         char *ifname;
1802         GSupplicantSSID *ssid;
1803 };
1804
1805 static GSupplicantSSID *ssid_ap_init(const char *ssid, const char *passphrase)
1806 {
1807         GSupplicantSSID *ap;
1808
1809         ap = g_try_malloc0(sizeof(GSupplicantSSID));
1810         if (ap == NULL)
1811                 return NULL;
1812
1813         ap->mode = G_SUPPLICANT_MODE_MASTER;
1814         ap->ssid = ssid;
1815         ap->ssid_len = strlen(ssid);
1816         ap->scan_ssid = 0;
1817         ap->freq = 2412;
1818
1819         if (passphrase == NULL || strlen(passphrase) == 0) {
1820                 ap->security = G_SUPPLICANT_SECURITY_NONE;
1821                 ap->passphrase = NULL;
1822         } else {
1823                ap->security = G_SUPPLICANT_SECURITY_PSK;
1824                ap->protocol = G_SUPPLICANT_PROTO_RSN;
1825                ap->pairwise_cipher = G_SUPPLICANT_PAIRWISE_CCMP;
1826                ap->group_cipher = G_SUPPLICANT_GROUP_CCMP;
1827                ap->passphrase = passphrase;
1828         }
1829
1830         return ap;
1831 }
1832
1833 static void ap_start_callback(int result, GSupplicantInterface *interface,
1834                                                         void *user_data)
1835 {
1836         struct wifi_tethering_info *info = user_data;
1837
1838         DBG("result %d index %d bridge %s",
1839                 result, info->wifi->index, info->wifi->bridge);
1840
1841         if (result < 0) {
1842                 connman_inet_remove_from_bridge(info->wifi->index,
1843                                                         info->wifi->bridge);
1844                 connman_technology_tethering_notify(info->technology, FALSE);
1845         }
1846
1847         g_free(info->ifname);
1848         g_free(info);
1849 }
1850
1851 static void ap_create_callback(int result,
1852                                 GSupplicantInterface *interface,
1853                                         void *user_data)
1854 {
1855         struct wifi_tethering_info *info = user_data;
1856
1857         DBG("result %d ifname %s", result,
1858                                 g_supplicant_interface_get_ifname(interface));
1859
1860         if (result < 0) {
1861                 connman_inet_remove_from_bridge(info->wifi->index,
1862                                                         info->wifi->bridge);
1863                 connman_technology_tethering_notify(info->technology, FALSE);
1864
1865                 g_free(info->ifname);
1866                 g_free(info);
1867                 return;
1868         }
1869
1870         info->wifi->interface = interface;
1871         g_supplicant_interface_set_data(interface, info->wifi);
1872
1873         if (g_supplicant_interface_set_apscan(interface, 2) < 0)
1874                 connman_error("Failed to set interface ap_scan property");
1875
1876         g_supplicant_interface_connect(interface, info->ssid,
1877                                                 ap_start_callback, info);
1878 }
1879
1880 static void sta_remove_callback(int result,
1881                                 GSupplicantInterface *interface,
1882                                         void *user_data)
1883 {
1884         struct wifi_tethering_info *info = user_data;
1885         const char *driver = connman_option_get_string("wifi");
1886
1887         DBG("ifname %s result %d ", info->ifname, result);
1888
1889         if (result < 0) {
1890                 info->wifi->tethering = TRUE;
1891
1892                 g_free(info->ifname);
1893                 g_free(info);
1894                 return;
1895         }
1896
1897         info->wifi->interface = NULL;
1898
1899         connman_technology_tethering_notify(info->technology, TRUE);
1900
1901         g_supplicant_interface_create(info->ifname, driver, info->wifi->bridge,
1902                                                 ap_create_callback,
1903                                                         info);
1904 }
1905
1906 static int tech_set_tethering(struct connman_technology *technology,
1907                                 const char *identifier, const char *passphrase,
1908                                 const char *bridge, connman_bool_t enabled)
1909 {
1910         GList *list;
1911         GSupplicantInterface *interface;
1912         struct wifi_data *wifi;
1913         struct wifi_tethering_info *info;
1914         const char *ifname;
1915         unsigned int mode;
1916         int err;
1917
1918         DBG("");
1919
1920         if (enabled == FALSE) {
1921                 for (list = iface_list; list; list = list->next) {
1922                         wifi = list->data;
1923
1924                         if (wifi->tethering == TRUE) {
1925                                 wifi->tethering = FALSE;
1926
1927                                 connman_inet_remove_from_bridge(wifi->index,
1928                                                                         bridge);
1929                                 wifi->bridged = FALSE;
1930                         }
1931                 }
1932
1933                 connman_technology_tethering_notify(technology, FALSE);
1934
1935                 return 0;
1936         }
1937
1938         for (list = iface_list; list; list = list->next) {
1939                 wifi = list->data;
1940
1941                 interface = wifi->interface;
1942
1943                 if (interface == NULL)
1944                         continue;
1945
1946                 ifname = g_supplicant_interface_get_ifname(wifi->interface);
1947
1948                 mode = g_supplicant_interface_get_mode(interface);
1949                 if ((mode & G_SUPPLICANT_CAPABILITY_MODE_AP) == 0) {
1950                         DBG("%s does not support AP mode", ifname);
1951                         continue;
1952                 }
1953
1954                 info = g_try_malloc0(sizeof(struct wifi_tethering_info));
1955                 if (info == NULL)
1956                         return -ENOMEM;
1957
1958                 info->wifi = wifi;
1959                 info->technology = technology;
1960                 info->wifi->bridge = bridge;
1961                 info->ssid = ssid_ap_init(identifier, passphrase);
1962                 if (info->ssid == NULL) {
1963                         g_free(info);
1964                         continue;
1965                 }
1966                 info->ifname = g_strdup(ifname);
1967                 if (info->ifname == NULL) {
1968                         g_free(info);
1969                         continue;
1970                 }
1971
1972                 info->wifi->tethering = TRUE;
1973
1974                 err = g_supplicant_interface_remove(interface,
1975                                                 sta_remove_callback,
1976                                                         info);
1977                 if (err == 0)
1978                         return err;
1979         }
1980
1981         return -EOPNOTSUPP;
1982 }
1983
1984 static void regdom_callback(int result, const char *alpha2, void *user_data)
1985 {
1986         DBG("");
1987
1988         if (wifi_technology == NULL)
1989                 return;
1990
1991         if (result != 0)
1992                 alpha2 = NULL;
1993
1994         connman_technology_regdom_notify(wifi_technology, alpha2);
1995 }
1996
1997 static int tech_set_regdom(struct connman_technology *technology, const char *alpha2)
1998 {
1999         return g_supplicant_set_country(alpha2, regdom_callback, NULL);
2000 }
2001
2002 static struct connman_technology_driver tech_driver = {
2003         .name           = "wifi",
2004         .type           = CONNMAN_SERVICE_TYPE_WIFI,
2005         .probe          = tech_probe,
2006         .remove         = tech_remove,
2007         .set_tethering  = tech_set_tethering,
2008         .set_regdom     = tech_set_regdom,
2009 };
2010
2011 static int wifi_init(void)
2012 {
2013         int err;
2014
2015         err = connman_network_driver_register(&network_driver);
2016         if (err < 0)
2017                 return err;
2018
2019         err = g_supplicant_register(&callbacks);
2020         if (err < 0) {
2021                 connman_network_driver_unregister(&network_driver);
2022                 return err;
2023         }
2024
2025         err = connman_technology_driver_register(&tech_driver);
2026         if (err < 0) {
2027                 g_supplicant_unregister(&callbacks);
2028                 connman_network_driver_unregister(&network_driver);
2029                 return err;
2030         }
2031
2032         return 0;
2033 }
2034
2035 static void wifi_exit(void)
2036 {
2037         DBG();
2038
2039         connman_technology_driver_unregister(&tech_driver);
2040
2041         g_supplicant_unregister(&callbacks);
2042
2043         connman_network_driver_unregister(&network_driver);
2044 }
2045
2046 CONNMAN_PLUGIN_DEFINE(wifi, "WiFi interface plugin", VERSION,
2047                 CONNMAN_PLUGIN_PRIORITY_DEFAULT, wifi_init, wifi_exit)