fc304e3b96a03b448cd70a12dfb2422fa4b2a52b
[platform/upstream/connman.git] / plugins / wifi.c
1 /*
2  *
3  *  Connection Manager
4  *
5  *  Copyright (C) 2007-2014  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 <net/ethernet.h>
34 #include <linux/wireless.h>
35
36 #ifndef IFF_LOWER_UP
37 #define IFF_LOWER_UP    0x10000
38 #endif
39
40 #include <dbus/dbus.h>
41 #include <glib.h>
42
43 #define CONNMAN_API_SUBJECT_TO_CHANGE
44 #include <connman/plugin.h>
45 #include <connman/inet.h>
46 #include <connman/device.h>
47 #include <connman/rtnl.h>
48 #include <connman/technology.h>
49 #include <connman/service.h>
50 #include <connman/peer.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 #include <connman/utsname.h>
57 #include <connman/machine.h>
58 #include <connman/tethering.h>
59
60 #include <gsupplicant/gsupplicant.h>
61
62 #include "src/shared/util.h"
63
64 #define CLEANUP_TIMEOUT   8     /* in seconds */
65 #define INACTIVE_TIMEOUT  12    /* in seconds */
66 #define FAVORITE_MAXIMUM_RETRIES 2
67
68 #define BGSCAN_DEFAULT "simple:30:-65:300"
69 #define AUTOSCAN_EXPONENTIAL "exponential:3:300"
70 #define AUTOSCAN_SINGLE "single:3"
71
72 #define P2P_FIND_TIMEOUT 30
73 #define P2P_CONNECTION_TIMEOUT 100
74 #define P2P_LISTEN_PERIOD 500
75 #define P2P_LISTEN_INTERVAL 2000
76
77 #define ASSOC_STATUS_NO_CLIENT 17
78 #define LOAD_SHAPING_MAX_RETRIES 3
79
80 static struct connman_technology *wifi_technology = NULL;
81 static struct connman_technology *p2p_technology = NULL;
82
83 enum wifi_ap_capability{
84         WIFI_AP_UNKNOWN         = 0,
85         WIFI_AP_SUPPORTED       = 1,
86         WIFI_AP_NOT_SUPPORTED   = 2,
87 };
88
89 enum wifi_scanning_type {
90         WIFI_SCANNING_UNKNOWN   = 0,
91         WIFI_SCANNING_PASSIVE   = 1,
92         WIFI_SCANNING_ACTIVE    = 2,
93 };
94
95 struct hidden_params {
96         char ssid[32];
97         unsigned int ssid_len;
98         char *identity;
99         char *anonymous_identity;
100         char *subject_match;
101         char *altsubject_match;
102         char *domain_suffix_match;
103         char *domain_match;
104         char *passphrase;
105         char *security;
106         GSupplicantScanParams *scan_params;
107         gpointer user_data;
108 };
109
110 /**
111  * Used for autoscan "emulation".
112  * Should be removed when wpa_s autoscan support will be by default.
113  */
114 struct autoscan_params {
115         int base;
116         int limit;
117         int interval;
118         unsigned int timeout;
119 };
120
121 struct wifi_tethering_info {
122         struct wifi_data *wifi;
123         struct connman_technology *technology;
124         char *ifname;
125         GSupplicantSSID *ssid;
126 };
127
128 struct wifi_data {
129         char *identifier;
130         struct connman_device *device;
131         struct connman_network *network;
132         struct connman_network *pending_network;
133         GSList *networks;
134         GSupplicantInterface *interface;
135         GSupplicantState state;
136         bool connected;
137         bool disconnecting;
138         bool tethering;
139         enum wifi_ap_capability ap_supported;
140         bool bridged;
141         bool interface_ready;
142         const char *bridge;
143         int index;
144         unsigned flags;
145         unsigned int watch;
146         int retries;
147         int load_shaping_retries;
148         struct hidden_params *hidden;
149         bool postpone_hidden;
150         struct wifi_tethering_info *tethering_param;
151         /**
152          * autoscan "emulation".
153          */
154         struct autoscan_params *autoscan;
155         enum wifi_scanning_type scanning_type;
156         GSupplicantScanParams *scan_params;
157         unsigned int p2p_find_timeout;
158         unsigned int p2p_connection_timeout;
159         struct connman_peer *pending_peer;
160         GSList *peers;
161         bool p2p_connecting;
162         bool p2p_device;
163         int servicing;
164         int disconnect_code;
165         int assoc_code;
166 };
167
168 static GList *iface_list = NULL;
169
170 static GList *pending_wifi_device = NULL;
171 static GList *p2p_iface_list = NULL;
172 static bool wfd_service_registered = false;
173
174 static void start_autoscan(struct connman_device *device);
175 static int tech_set_tethering(struct connman_technology *technology,
176                                 const char *identifier, const char *passphrase,
177                                 const char *bridge, bool enabled);
178
179 static int p2p_tech_probe(struct connman_technology *technology)
180 {
181         p2p_technology = technology;
182
183         return 0;
184 }
185
186 static void p2p_tech_remove(struct connman_technology *technology)
187 {
188         p2p_technology = NULL;
189 }
190
191 static struct connman_technology_driver p2p_tech_driver = {
192         .name           = "p2p",
193         .type           = CONNMAN_SERVICE_TYPE_P2P,
194         .probe          = p2p_tech_probe,
195         .remove         = p2p_tech_remove,
196 };
197
198 static bool is_p2p_connecting(void)
199 {
200         GList *list;
201
202         for (list = iface_list; list; list = list->next) {
203                 struct wifi_data *wifi = list->data;
204
205                 if (wifi->p2p_connecting)
206                         return true;
207         }
208
209         return false;
210 }
211
212 static void add_pending_wifi_device(struct wifi_data *wifi)
213 {
214         if (g_list_find(pending_wifi_device, wifi))
215                 return;
216
217         pending_wifi_device = g_list_append(pending_wifi_device, wifi);
218 }
219
220 static struct wifi_data *get_pending_wifi_data(const char *ifname)
221 {
222         GList *list;
223
224         for (list = pending_wifi_device; list; list = list->next) {
225                 struct wifi_data *wifi;
226                 const char *dev_name;
227
228                 wifi = list->data;
229                 if (!wifi || !wifi->device)
230                         continue;
231
232                 dev_name = connman_device_get_string(wifi->device, "Interface");
233                 if (!g_strcmp0(ifname, dev_name)) {
234                         pending_wifi_device = g_list_delete_link(
235                                                 pending_wifi_device, list);
236                         return wifi;
237                 }
238         }
239
240         return NULL;
241 }
242
243 static void remove_pending_wifi_device(struct wifi_data *wifi)
244 {
245         GList *link;
246
247         link = g_list_find(pending_wifi_device, wifi);
248
249         if (!link)
250                 return;
251
252         pending_wifi_device = g_list_delete_link(pending_wifi_device, link);
253 }
254
255 static void peer_cancel_timeout(struct wifi_data *wifi)
256 {
257         if (wifi->p2p_connection_timeout > 0)
258                 g_source_remove(wifi->p2p_connection_timeout);
259
260         wifi->p2p_connection_timeout = 0;
261         wifi->p2p_connecting = false;
262
263         if (wifi->pending_peer) {
264                 connman_peer_unref(wifi->pending_peer);
265                 wifi->pending_peer = NULL;
266         }
267 }
268
269 static gboolean peer_connect_timeout(gpointer data)
270 {
271         struct wifi_data *wifi = data;
272
273         DBG("");
274
275         if (wifi->p2p_connecting) {
276                 enum connman_peer_state state = CONNMAN_PEER_STATE_FAILURE;
277                 GSupplicantPeer *gs_peer =
278                         g_supplicant_interface_peer_lookup(wifi->interface,
279                                 connman_peer_get_identifier(wifi->pending_peer));
280
281                 if (g_supplicant_peer_has_requested_connection(gs_peer))
282                         state = CONNMAN_PEER_STATE_IDLE;
283
284                 connman_peer_set_state(wifi->pending_peer, state);
285         }
286
287         peer_cancel_timeout(wifi);
288
289         return FALSE;
290 }
291
292 static void peer_connect_callback(int result, GSupplicantInterface *interface,
293                                                         void *user_data)
294 {
295         struct wifi_data *wifi = user_data;
296         struct connman_peer *peer = wifi->pending_peer;
297
298         DBG("peer %p - %d", peer, result);
299
300         if (!peer)
301                 return;
302
303         if (result < 0) {
304                 peer_connect_timeout(wifi);
305                 return;
306         }
307
308         connman_peer_set_state(peer, CONNMAN_PEER_STATE_ASSOCIATION);
309
310         wifi->p2p_connection_timeout = g_timeout_add_seconds(
311                                                 P2P_CONNECTION_TIMEOUT,
312                                                 peer_connect_timeout, wifi);
313 }
314
315 static int peer_connect(struct connman_peer *peer,
316                         enum connman_peer_wps_method wps_method,
317                         const char *wps_pin)
318 {
319         struct connman_device *device = connman_peer_get_device(peer);
320         GSupplicantPeerParams *peer_params;
321         GSupplicantPeer *gs_peer;
322         struct wifi_data *wifi;
323         bool pbc, pin;
324         int ret;
325
326         DBG("peer %p", peer);
327
328         if (!device)
329                 return -ENODEV;
330
331         wifi = connman_device_get_data(device);
332         if (!wifi || !wifi->interface)
333                 return -ENODEV;
334
335         if (wifi->p2p_connecting)
336                 return -EBUSY;
337
338         gs_peer = g_supplicant_interface_peer_lookup(wifi->interface,
339                                         connman_peer_get_identifier(peer));
340         if (!gs_peer)
341                 return -EINVAL;
342
343         pbc = g_supplicant_peer_is_wps_pbc(gs_peer);
344         pin = g_supplicant_peer_is_wps_pin(gs_peer);
345
346         switch (wps_method) {
347         case CONNMAN_PEER_WPS_UNKNOWN:
348                 if ((pbc && pin) || pin)
349                         return -ENOKEY;
350                 break;
351         case CONNMAN_PEER_WPS_PBC:
352                 if (!pbc)
353                         return -EINVAL;
354                 wps_pin = NULL;
355                 break;
356         case CONNMAN_PEER_WPS_PIN:
357                 if (!pin || !wps_pin)
358                         return -EINVAL;
359                 break;
360         }
361
362         peer_params = g_try_malloc0(sizeof(GSupplicantPeerParams));
363         if (!peer_params)
364                 return -ENOMEM;
365
366         peer_params->path = g_strdup(g_supplicant_peer_get_path(gs_peer));
367         if (wps_pin)
368                 peer_params->wps_pin = g_strdup(wps_pin);
369
370         peer_params->master = connman_peer_service_is_master();
371
372         ret = g_supplicant_interface_p2p_connect(wifi->interface, peer_params,
373                                                 peer_connect_callback, wifi);
374         if (ret == -EINPROGRESS) {
375                 wifi->pending_peer = connman_peer_ref(peer);
376                 wifi->p2p_connecting = true;
377         } else if (ret < 0) {
378                 g_free(peer_params->path);
379                 g_free(peer_params->wps_pin);
380                 g_free(peer_params);
381         }
382
383         return ret;
384 }
385
386 static int peer_disconnect(struct connman_peer *peer)
387 {
388         struct connman_device *device = connman_peer_get_device(peer);
389         GSupplicantPeerParams peer_params = {};
390         GSupplicantPeer *gs_peer;
391         struct wifi_data *wifi;
392         int ret;
393
394         DBG("peer %p", peer);
395
396         if (!device)
397                 return -ENODEV;
398
399         wifi = connman_device_get_data(device);
400         if (!wifi)
401                 return -ENODEV;
402
403         gs_peer = g_supplicant_interface_peer_lookup(wifi->interface,
404                                         connman_peer_get_identifier(peer));
405         if (!gs_peer)
406                 return -EINVAL;
407
408         peer_params.path = g_strdup(g_supplicant_peer_get_path(gs_peer));
409
410         ret = g_supplicant_interface_p2p_disconnect(wifi->interface,
411                                                         &peer_params);
412         g_free(peer_params.path);
413
414         if (ret == -EINPROGRESS) {
415                 peer_cancel_timeout(wifi);
416                 wifi->p2p_device = false;
417         }
418
419         return ret;
420 }
421
422 struct peer_service_registration {
423         peer_service_registration_cb_t callback;
424         void *user_data;
425 };
426
427 static bool is_service_wfd(const unsigned char *specs, int length)
428 {
429         if (length < 9 || specs[0] != 0 || specs[1] != 0 || specs[2] != 6)
430                 return false;
431
432         return true;
433 }
434
435 static void apply_p2p_listen_on_iface(gpointer data, gpointer user_data)
436 {
437         struct wifi_data *wifi = data;
438
439         if (!wifi->interface ||
440                         !g_supplicant_interface_has_p2p(wifi->interface))
441                 return;
442
443         if (!wifi->servicing) {
444                 g_supplicant_interface_p2p_listen(wifi->interface,
445                                 P2P_LISTEN_PERIOD, P2P_LISTEN_INTERVAL);
446         }
447
448         wifi->servicing++;
449 }
450
451 static void register_wfd_service_cb(int result,
452                                 GSupplicantInterface *iface, void *user_data)
453 {
454         struct peer_service_registration *reg_data = user_data;
455
456         DBG("");
457
458         if (result == 0)
459                 g_list_foreach(iface_list, apply_p2p_listen_on_iface, NULL);
460
461         if (reg_data && reg_data->callback) {
462                 reg_data->callback(result, reg_data->user_data);
463                 g_free(reg_data);
464         }
465 }
466
467 static GSupplicantP2PServiceParams *fill_in_peer_service_params(
468                                 const unsigned char *spec,
469                                 int spec_length, const unsigned char *query,
470                                 int query_length, int version)
471 {
472         GSupplicantP2PServiceParams *params;
473
474         params = g_try_malloc0(sizeof(GSupplicantP2PServiceParams));
475         if (!params)
476                 return NULL;
477
478         if (version > 0) {
479                 params->version = version;
480                 params->service = g_memdup(spec, spec_length);
481         } else if (query_length > 0 && spec_length > 0) {
482                 params->query = g_memdup(query, query_length);
483                 params->query_length = query_length;
484
485                 params->response = g_memdup(spec, spec_length);
486                 params->response_length = spec_length;
487         } else {
488                 params->wfd_ies = g_memdup(spec, spec_length);
489                 params->wfd_ies_length = spec_length;
490         }
491
492         return params;
493 }
494
495 static void free_peer_service_params(GSupplicantP2PServiceParams *params)
496 {
497         if (!params)
498                 return;
499
500         g_free(params->service);
501         g_free(params->query);
502         g_free(params->response);
503         g_free(params->wfd_ies);
504
505         g_free(params);
506 }
507
508 static int peer_register_wfd_service(const unsigned char *specification,
509                                 int specification_length,
510                                 peer_service_registration_cb_t callback,
511                                 void *user_data)
512 {
513         struct peer_service_registration *reg_data = NULL;
514         static GSupplicantP2PServiceParams *params;
515         int ret;
516
517         DBG("");
518
519         if (wfd_service_registered)
520                 return -EBUSY;
521
522         params = fill_in_peer_service_params(specification,
523                                         specification_length, NULL, 0, 0);
524         if (!params)
525                 return -ENOMEM;
526
527         reg_data = g_try_malloc0(sizeof(*reg_data));
528         if (!reg_data) {
529                 ret = -ENOMEM;
530                 goto error;
531         }
532
533         reg_data->callback = callback;
534         reg_data->user_data = user_data;
535
536         ret = g_supplicant_set_widi_ies(params,
537                                         register_wfd_service_cb, reg_data);
538         if (ret < 0 && ret != -EINPROGRESS)
539                 goto error;
540
541         wfd_service_registered = true;
542
543         return ret;
544 error:
545         free_peer_service_params(params);
546         g_free(reg_data);
547
548         return ret;
549 }
550
551 static void register_peer_service_cb(int result,
552                                 GSupplicantInterface *iface, void *user_data)
553 {
554         struct wifi_data *wifi = g_supplicant_interface_get_data(iface);
555         struct peer_service_registration *reg_data = user_data;
556
557         DBG("");
558
559         if (result == 0)
560                 apply_p2p_listen_on_iface(wifi, NULL);
561
562         if (reg_data->callback)
563                 reg_data->callback(result, reg_data->user_data);
564
565         g_free(reg_data);
566 }
567
568 static int peer_register_service(const unsigned char *specification,
569                                 int specification_length,
570                                 const unsigned char *query,
571                                 int query_length, int version,
572                                 peer_service_registration_cb_t callback,
573                                 void *user_data)
574 {
575         struct peer_service_registration *reg_data;
576         GSupplicantP2PServiceParams *params;
577         bool found = false;
578         int ret, ret_f;
579         GList *list;
580
581         DBG("");
582
583         if (specification && !version && !query &&
584                         is_service_wfd(specification, specification_length)) {
585                 return peer_register_wfd_service(specification,
586                                 specification_length, callback, user_data);
587         }
588
589         reg_data = g_try_malloc0(sizeof(*reg_data));
590         if (!reg_data)
591                 return -ENOMEM;
592
593         reg_data->callback = callback;
594         reg_data->user_data = user_data;
595
596         ret_f = -EOPNOTSUPP;
597
598         for (list = iface_list; list; list = list->next) {
599                 struct wifi_data *wifi = list->data;
600                 GSupplicantInterface *iface = wifi->interface;
601
602                 if (!g_supplicant_interface_has_p2p(iface))
603                         continue;
604
605                 params = fill_in_peer_service_params(specification,
606                                                 specification_length, query,
607                                                 query_length, version);
608                 if (!params)
609                         continue;
610
611                 if (!found) {
612                         ret_f = g_supplicant_interface_p2p_add_service(iface,
613                                 register_peer_service_cb, params, reg_data);
614                         if (ret_f == 0 || ret_f == -EINPROGRESS)
615                                 found = true;
616                         ret = ret_f;
617                 } else
618                         ret = g_supplicant_interface_p2p_add_service(iface,
619                                 register_peer_service_cb, params, NULL);
620                 if (ret != 0 && ret != -EINPROGRESS)
621                         free_peer_service_params(params);
622         }
623
624         if (ret_f != 0 && ret_f != -EINPROGRESS)
625                 g_free(reg_data);
626
627         return ret_f;
628 }
629
630 static int peer_unregister_wfd_service(void)
631 {
632         GSupplicantP2PServiceParams *params;
633         GList *list;
634
635         if (!wfd_service_registered)
636                 return -EALREADY;
637
638         params = fill_in_peer_service_params(NULL, 0, NULL, 0, 0);
639         if (!params)
640                 return -ENOMEM;
641
642         wfd_service_registered = false;
643
644         g_supplicant_set_widi_ies(params, NULL, NULL);
645
646         for (list = iface_list; list; list = list->next) {
647                 struct wifi_data *wifi = list->data;
648
649                 if (!g_supplicant_interface_has_p2p(wifi->interface))
650                         continue;
651
652                 wifi->servicing--;
653                 if (!wifi->servicing || wifi->servicing < 0) {
654                         g_supplicant_interface_p2p_listen(wifi->interface,
655                                                                         0, 0);
656                         wifi->servicing = 0;
657                 }
658         }
659
660         return 0;
661 }
662
663 static int peer_unregister_service(const unsigned char *specification,
664                                                 int specification_length,
665                                                 const unsigned char *query,
666                                                 int query_length, int version)
667 {
668         GSupplicantP2PServiceParams *params;
669         bool wfd = false;
670         GList *list;
671         int ret;
672
673         if (specification && !version && !query &&
674                         is_service_wfd(specification, specification_length)) {
675                 ret = peer_unregister_wfd_service();
676                 if (ret != 0 && ret != -EINPROGRESS)
677                         return ret;
678                 wfd = true;
679         }
680
681         for (list = iface_list; list; list = list->next) {
682                 struct wifi_data *wifi = list->data;
683                 GSupplicantInterface *iface = wifi->interface;
684
685                 if (wfd)
686                         goto stop_listening;
687
688                 if (!g_supplicant_interface_has_p2p(iface))
689                         continue;
690
691                 params = fill_in_peer_service_params(specification,
692                                                 specification_length, query,
693                                                 query_length, version);
694                 if (!params)
695                         continue;
696
697                 ret = g_supplicant_interface_p2p_del_service(iface, params);
698                 if (ret != 0 && ret != -EINPROGRESS)
699                         free_peer_service_params(params);
700 stop_listening:
701                 wifi->servicing--;
702                 if (!wifi->servicing || wifi->servicing < 0) {
703                         g_supplicant_interface_p2p_listen(iface, 0, 0);
704                         wifi->servicing = 0;
705                 }
706         }
707
708         return 0;
709 }
710
711 static struct connman_peer_driver peer_driver = {
712         .connect    = peer_connect,
713         .disconnect = peer_disconnect,
714         .register_service = peer_register_service,
715         .unregister_service = peer_unregister_service,
716 };
717
718 static void handle_tethering(struct wifi_data *wifi)
719 {
720         if (!wifi->tethering)
721                 return;
722
723         if (!wifi->bridge)
724                 return;
725
726         if (wifi->bridged)
727                 return;
728
729         DBG("index %d bridge %s", wifi->index, wifi->bridge);
730
731         if (connman_inet_add_to_bridge(wifi->index, wifi->bridge) < 0)
732                 return;
733
734         wifi->bridged = true;
735 }
736
737 static void wifi_newlink(unsigned flags, unsigned change, void *user_data)
738 {
739         struct connman_device *device = user_data;
740         struct wifi_data *wifi = connman_device_get_data(device);
741
742         if (!wifi)
743                 return;
744
745         DBG("index %d flags %d change %d", wifi->index, flags, change);
746
747         if ((wifi->flags & IFF_UP) != (flags & IFF_UP)) {
748                 if (flags & IFF_UP)
749                         DBG("interface up");
750                 else
751                         DBG("interface down");
752         }
753
754         if ((wifi->flags & IFF_LOWER_UP) != (flags & IFF_LOWER_UP)) {
755                 if (flags & IFF_LOWER_UP) {
756                         DBG("carrier on");
757
758                         handle_tethering(wifi);
759                 } else
760                         DBG("carrier off");
761         }
762
763         wifi->flags = flags;
764 }
765
766 static int wifi_probe(struct connman_device *device)
767 {
768         struct wifi_data *wifi;
769
770         DBG("device %p", device);
771
772         wifi = g_try_new0(struct wifi_data, 1);
773         if (!wifi)
774                 return -ENOMEM;
775
776         wifi->state = G_SUPPLICANT_STATE_INACTIVE;
777         wifi->ap_supported = WIFI_AP_UNKNOWN;
778         wifi->tethering_param = NULL;
779
780         connman_device_set_data(device, wifi);
781         wifi->device = connman_device_ref(device);
782
783         wifi->index = connman_device_get_index(device);
784         wifi->flags = 0;
785
786         wifi->watch = connman_rtnl_add_newlink_watch(wifi->index,
787                                                         wifi_newlink, device);
788         if (is_p2p_connecting())
789                 add_pending_wifi_device(wifi);
790         else
791                 iface_list = g_list_append(iface_list, wifi);
792
793         return 0;
794 }
795
796 static void remove_networks(struct connman_device *device,
797                                 struct wifi_data *wifi)
798 {
799         GSList *list;
800
801         for (list = wifi->networks; list; list = list->next) {
802                 struct connman_network *network = list->data;
803
804                 connman_device_remove_network(device, network);
805                 connman_network_unref(network);
806         }
807
808         g_slist_free(wifi->networks);
809         wifi->networks = NULL;
810 }
811
812 static void remove_peers(struct wifi_data *wifi)
813 {
814         GSList *list;
815
816         for (list = wifi->peers; list; list = list->next) {
817                 struct connman_peer *peer = list->data;
818
819                 connman_peer_unregister(peer);
820                 connman_peer_unref(peer);
821         }
822
823         g_slist_free(wifi->peers);
824         wifi->peers = NULL;
825 }
826
827 static void reset_autoscan(struct connman_device *device)
828 {
829         struct wifi_data *wifi = connman_device_get_data(device);
830         struct autoscan_params *autoscan;
831
832         DBG("");
833
834         if (!wifi || !wifi->autoscan)
835                 return;
836
837         autoscan = wifi->autoscan;
838
839         autoscan->interval = 0;
840
841         if (autoscan->timeout == 0)
842                 return;
843
844         g_source_remove(autoscan->timeout);
845         autoscan->timeout = 0;
846
847         connman_device_unref(device);
848 }
849
850 static void stop_autoscan(struct connman_device *device)
851 {
852         const struct wifi_data *wifi = connman_device_get_data(device);
853
854         if (!wifi || !wifi->autoscan)
855                 return;
856
857         reset_autoscan(device);
858
859         connman_device_set_scanning(device, CONNMAN_SERVICE_TYPE_WIFI, false);
860 }
861
862 static void check_p2p_technology(void)
863 {
864         bool p2p_exists = false;
865         GList *list;
866
867         for (list = iface_list; list; list = list->next) {
868                 struct wifi_data *w = list->data;
869
870                 if (w->interface &&
871                                 g_supplicant_interface_has_p2p(w->interface))
872                         p2p_exists = true;
873         }
874
875         if (!p2p_exists) {
876                 connman_technology_driver_unregister(&p2p_tech_driver);
877                 connman_peer_driver_unregister(&peer_driver);
878         }
879 }
880
881 static void wifi_remove(struct connman_device *device)
882 {
883         struct wifi_data *wifi = connman_device_get_data(device);
884
885         DBG("device %p wifi %p", device, wifi);
886
887         if (!wifi)
888                 return;
889
890         stop_autoscan(device);
891
892         if (wifi->p2p_device)
893                 p2p_iface_list = g_list_remove(p2p_iface_list, wifi);
894         else
895                 iface_list = g_list_remove(iface_list, wifi);
896
897         check_p2p_technology();
898
899         remove_pending_wifi_device(wifi);
900
901         if (connman_device_get_scanning(device, CONNMAN_SERVICE_TYPE_P2P)) {
902                 g_source_remove(wifi->p2p_find_timeout);
903                 connman_device_unref(wifi->device);
904         }
905
906         if (wifi->p2p_connection_timeout)
907                 g_source_remove(wifi->p2p_connection_timeout);
908
909         remove_networks(device, wifi);
910         remove_peers(wifi);
911
912         connman_device_set_powered(device, false);
913         connman_device_set_data(device, NULL);
914         connman_device_unref(wifi->device);
915         connman_rtnl_remove_watch(wifi->watch);
916
917         g_supplicant_interface_set_data(wifi->interface, NULL);
918
919         g_supplicant_interface_cancel(wifi->interface);
920
921         if (wifi->scan_params)
922                 g_supplicant_free_scan_params(wifi->scan_params);
923
924         g_free(wifi->autoscan);
925         g_free(wifi->identifier);
926         g_free(wifi);
927 }
928
929 static bool is_duplicate(GSList *list, gchar *ssid, int ssid_len)
930 {
931         GSList *iter;
932
933         for (iter = list; iter; iter = g_slist_next(iter)) {
934                 struct scan_ssid *scan_ssid = iter->data;
935
936                 if (ssid_len == scan_ssid->ssid_len &&
937                                 memcmp(ssid, scan_ssid->ssid, ssid_len) == 0)
938                         return true;
939         }
940
941         return false;
942 }
943
944 static int add_scan_param(gchar *hex_ssid, char *raw_ssid, int ssid_len,
945                         int freq, GSupplicantScanParams *scan_data,
946                         int driver_max_scan_ssids, char *ssid_name)
947 {
948         unsigned int i;
949         struct scan_ssid *scan_ssid;
950
951         if ((driver_max_scan_ssids == 0 ||
952                         driver_max_scan_ssids > scan_data->num_ssids) &&
953                         (hex_ssid || raw_ssid)) {
954                 gchar *ssid;
955                 unsigned int j = 0, hex;
956
957                 if (hex_ssid) {
958                         size_t hex_ssid_len = strlen(hex_ssid);
959
960                         ssid = g_try_malloc0(hex_ssid_len / 2);
961                         if (!ssid)
962                                 return -ENOMEM;
963
964                         for (i = 0; i < hex_ssid_len; i += 2) {
965                                 sscanf(hex_ssid + i, "%02x", &hex);
966                                 ssid[j++] = hex;
967                         }
968                 } else {
969                         ssid = raw_ssid;
970                         j = ssid_len;
971                 }
972
973                 /*
974                  * If we have already added hidden AP to the list,
975                  * then do not do it again. This might happen if you have
976                  * used or are using multiple wifi cards, so in that case
977                  * you might have multiple service files for same AP.
978                  */
979                 if (is_duplicate(scan_data->ssids, ssid, j)) {
980                         if (hex_ssid)
981                                 g_free(ssid);
982                         return 0;
983                 }
984
985                 scan_ssid = g_try_new(struct scan_ssid, 1);
986                 if (!scan_ssid) {
987                         if (hex_ssid)
988                                 g_free(ssid);
989                         return -ENOMEM;
990                 }
991
992                 memcpy(scan_ssid->ssid, ssid, j);
993                 scan_ssid->ssid_len = j;
994                 scan_data->ssids = g_slist_prepend(scan_data->ssids,
995                                                                 scan_ssid);
996
997                 scan_data->num_ssids++;
998
999                 DBG("SSID %s added to scanned list of %d entries", ssid_name,
1000                                                         scan_data->num_ssids);
1001
1002                 if (hex_ssid)
1003                         g_free(ssid);
1004         } else
1005                 return -EINVAL;
1006
1007         scan_data->ssids = g_slist_reverse(scan_data->ssids);
1008
1009         if (!scan_data->freqs) {
1010                 scan_data->freqs = g_try_malloc0(sizeof(uint16_t));
1011                 if (!scan_data->freqs) {
1012                         g_slist_free_full(scan_data->ssids, g_free);
1013                         return -ENOMEM;
1014                 }
1015
1016                 scan_data->num_freqs = 1;
1017                 scan_data->freqs[0] = freq;
1018         } else {
1019                 bool duplicate = false;
1020
1021                 /* Don't add duplicate entries */
1022                 for (i = 0; i < scan_data->num_freqs; i++) {
1023                         if (scan_data->freqs[i] == freq) {
1024                                 duplicate = true;
1025                                 break;
1026                         }
1027                 }
1028
1029                 if (!duplicate) {
1030                         scan_data->num_freqs++;
1031                         scan_data->freqs = g_try_realloc(scan_data->freqs,
1032                                 sizeof(uint16_t) * scan_data->num_freqs);
1033                         if (!scan_data->freqs) {
1034                                 g_slist_free_full(scan_data->ssids, g_free);
1035                                 return -ENOMEM;
1036                         }
1037                         scan_data->freqs[scan_data->num_freqs - 1] = freq;
1038                 }
1039         }
1040
1041         return 1;
1042 }
1043
1044 static int get_hidden_connections(GSupplicantScanParams *scan_data)
1045 {
1046         struct connman_config_entry **entries;
1047         GKeyFile *keyfile;
1048         gchar **services;
1049         char *ssid, *name;
1050         int i, ret;
1051         bool value;
1052         int num_ssids = 0, add_param_failed = 0;
1053
1054         services = connman_storage_get_services();
1055         for (i = 0; services && services[i]; i++) {
1056                 if (strncmp(services[i], "wifi_", 5) != 0)
1057                         continue;
1058
1059                 keyfile = connman_storage_load_service(services[i]);
1060                 if (!keyfile)
1061                         continue;
1062
1063                 value = g_key_file_get_boolean(keyfile,
1064                                         services[i], "Hidden", NULL);
1065                 if (!value) {
1066                         g_key_file_free(keyfile);
1067                         continue;
1068                 }
1069
1070                 value = g_key_file_get_boolean(keyfile,
1071                                         services[i], "Favorite", NULL);
1072                 if (!value) {
1073                         g_key_file_free(keyfile);
1074                         continue;
1075                 }
1076
1077                 ssid = g_key_file_get_string(keyfile,
1078                                         services[i], "SSID", NULL);
1079
1080                 name = g_key_file_get_string(keyfile, services[i], "Name",
1081                                                                 NULL);
1082
1083                 ret = add_scan_param(ssid, NULL, 0, 0, scan_data, 0, name);
1084                 if (ret < 0)
1085                         add_param_failed++;
1086                 else if (ret > 0)
1087                         num_ssids++;
1088
1089                 g_free(ssid);
1090                 g_free(name);
1091                 g_key_file_free(keyfile);
1092         }
1093
1094         /*
1095          * Check if there are any hidden AP that needs to be provisioned.
1096          */
1097         entries = connman_config_get_entries("wifi");
1098         for (i = 0; entries && entries[i]; i++) {
1099                 int len;
1100
1101                 if (!entries[i]->hidden)
1102                         continue;
1103
1104                 if (!entries[i]->ssid) {
1105                         ssid = entries[i]->name;
1106                         len = strlen(ssid);
1107                 } else {
1108                         ssid = entries[i]->ssid;
1109                         len = entries[i]->ssid_len;
1110                 }
1111
1112                 if (!ssid)
1113                         continue;
1114
1115                 ret = add_scan_param(NULL, ssid, len, 0, scan_data, 0, ssid);
1116                 if (ret < 0)
1117                         add_param_failed++;
1118                 else if (ret > 0)
1119                         num_ssids++;
1120         }
1121
1122         connman_config_free_entries(entries);
1123
1124         if (add_param_failed > 0)
1125                 DBG("Unable to scan %d out of %d SSIDs",
1126                                         add_param_failed, num_ssids);
1127
1128         g_strfreev(services);
1129
1130         return num_ssids;
1131 }
1132
1133 static int get_hidden_connections_params(struct wifi_data *wifi,
1134                                         GSupplicantScanParams *scan_params)
1135 {
1136         int driver_max_ssids, i;
1137         GSupplicantScanParams *orig_params;
1138
1139         /*
1140          * Scan hidden networks so that we can autoconnect to them.
1141          * We will assume 1 as a default number of ssid to scan.
1142          */
1143         driver_max_ssids = g_supplicant_interface_get_max_scan_ssids(
1144                                                         wifi->interface);
1145         if (driver_max_ssids == 0)
1146                 driver_max_ssids = 1;
1147
1148         DBG("max ssids %d", driver_max_ssids);
1149
1150         if (!wifi->scan_params) {
1151                 wifi->scan_params = g_try_malloc0(sizeof(GSupplicantScanParams));
1152                 if (!wifi->scan_params)
1153                         return 0;
1154
1155                 if (get_hidden_connections(wifi->scan_params) == 0) {
1156                         g_supplicant_free_scan_params(wifi->scan_params);
1157                         wifi->scan_params = NULL;
1158
1159                         return 0;
1160                 }
1161         }
1162
1163         orig_params = wifi->scan_params;
1164
1165         /* Let's transfer driver_max_ssids params */
1166         for (i = 0; i < driver_max_ssids; i++) {
1167                 struct scan_ssid *ssid;
1168
1169                 if (!wifi->scan_params->ssids)
1170                         break;
1171
1172                 ssid = orig_params->ssids->data;
1173                 orig_params->ssids = g_slist_remove(orig_params->ssids, ssid);
1174                 scan_params->ssids = g_slist_prepend(scan_params->ssids, ssid);
1175         }
1176
1177         if (i > 0) {
1178                 scan_params->num_ssids = i;
1179                 scan_params->ssids = g_slist_reverse(scan_params->ssids);
1180
1181                 scan_params->freqs = g_memdup(orig_params->freqs,
1182                                 sizeof(uint16_t) * orig_params->num_freqs);
1183                 if (!scan_params->freqs)
1184                         goto err;
1185
1186                 scan_params->num_freqs = orig_params->num_freqs;
1187
1188         } else
1189                 goto err;
1190
1191         orig_params->num_ssids -= scan_params->num_ssids;
1192
1193         return scan_params->num_ssids;
1194
1195 err:
1196         g_slist_free_full(scan_params->ssids, g_free);
1197         g_supplicant_free_scan_params(wifi->scan_params);
1198         wifi->scan_params = NULL;
1199
1200         return 0;
1201 }
1202
1203 static int throw_wifi_scan(struct connman_device *device,
1204                         GSupplicantInterfaceCallback callback)
1205 {
1206         struct wifi_data *wifi = connman_device_get_data(device);
1207         int ret;
1208
1209         if (!wifi)
1210                 return -ENODEV;
1211
1212         DBG("device %p %p", device, wifi->interface);
1213
1214         if (wifi->tethering)
1215                 return -EBUSY;
1216
1217         if (connman_device_get_scanning(device, CONNMAN_SERVICE_TYPE_WIFI))
1218                 return -EALREADY;
1219
1220         connman_device_ref(device);
1221
1222         ret = g_supplicant_interface_scan(wifi->interface, NULL,
1223                                                 callback, device);
1224         if (ret == 0) {
1225                 connman_device_set_scanning(device,
1226                                 CONNMAN_SERVICE_TYPE_WIFI, true);
1227         } else
1228                 connman_device_unref(device);
1229
1230         return ret;
1231 }
1232
1233 static void hidden_free(struct hidden_params *hidden)
1234 {
1235         if (!hidden)
1236                 return;
1237
1238         if (hidden->scan_params)
1239                 g_supplicant_free_scan_params(hidden->scan_params);
1240         g_free(hidden->identity);
1241         g_free(hidden->passphrase);
1242         g_free(hidden->security);
1243         g_free(hidden);
1244 }
1245
1246 static void scan_callback(int result, GSupplicantInterface *interface,
1247                                                 void *user_data)
1248 {
1249         struct connman_device *device = user_data;
1250         struct wifi_data *wifi = connman_device_get_data(device);
1251         bool scanning;
1252
1253         DBG("result %d wifi %p", result, wifi);
1254
1255         if (wifi) {
1256                 if (wifi->hidden && !wifi->postpone_hidden) {
1257                         connman_network_clear_hidden(wifi->hidden->user_data);
1258                         hidden_free(wifi->hidden);
1259                         wifi->hidden = NULL;
1260                 }
1261
1262                 if (wifi->scan_params) {
1263                         g_supplicant_free_scan_params(wifi->scan_params);
1264                         wifi->scan_params = NULL;
1265                 }
1266         }
1267
1268         if (result < 0)
1269                 connman_device_reset_scanning(device);
1270
1271         /* User is connecting to a hidden AP, let's wait for finished event */
1272         if (wifi && wifi->hidden && wifi->postpone_hidden) {
1273                 GSupplicantScanParams *scan_params;
1274                 int ret;
1275
1276                 wifi->postpone_hidden = false;
1277                 scan_params = wifi->hidden->scan_params;
1278                 wifi->hidden->scan_params = NULL;
1279
1280                 reset_autoscan(device);
1281
1282                 ret = g_supplicant_interface_scan(wifi->interface, scan_params,
1283                                                         scan_callback, device);
1284                 if (ret == 0)
1285                         return;
1286
1287                 /* On error, let's recall scan_callback, which will cleanup */
1288                 return scan_callback(ret, interface, user_data);
1289         }
1290
1291         scanning = connman_device_get_scanning(device, CONNMAN_SERVICE_TYPE_WIFI);
1292
1293         if (scanning) {
1294                 connman_device_set_scanning(device,
1295                                 CONNMAN_SERVICE_TYPE_WIFI, false);
1296         }
1297
1298         if (result != -ENOLINK)
1299                 start_autoscan(device);
1300
1301         /*
1302          * If we are here then we were scanning; however, if we are
1303          * also mid-flight disabling the interface, then wifi_disable
1304          * has already cleared the device scanning state and
1305          * unreferenced the device, obviating the need to do it here.
1306          */
1307
1308         if (scanning)
1309                 connman_device_unref(device);
1310 }
1311
1312 static void scan_callback_hidden(int result,
1313                         GSupplicantInterface *interface, void *user_data)
1314 {
1315         struct connman_device *device = user_data;
1316         struct wifi_data *wifi = connman_device_get_data(device);
1317         GSupplicantScanParams *scan_params;
1318         int ret;
1319
1320         DBG("result %d wifi %p", result, wifi);
1321
1322         if (!wifi)
1323                 goto out;
1324
1325         /* User is trying to connect to a hidden AP */
1326         if (wifi->hidden && wifi->postpone_hidden)
1327                 goto out;
1328
1329         scan_params = g_try_malloc0(sizeof(GSupplicantScanParams));
1330         if (!scan_params)
1331                 goto out;
1332
1333         if (get_hidden_connections_params(wifi, scan_params) > 0) {
1334                 ret = g_supplicant_interface_scan(wifi->interface,
1335                                                         scan_params,
1336                                                         scan_callback_hidden,
1337                                                         device);
1338                 if (ret == 0)
1339                         return;
1340         }
1341
1342         g_supplicant_free_scan_params(scan_params);
1343
1344 out:
1345         scan_callback(result, interface, user_data);
1346 }
1347
1348 static gboolean autoscan_timeout(gpointer data)
1349 {
1350         struct connman_device *device = data;
1351         struct wifi_data *wifi = connman_device_get_data(device);
1352         struct autoscan_params *autoscan;
1353         int interval;
1354
1355         if (!wifi)
1356                 return FALSE;
1357
1358         autoscan = wifi->autoscan;
1359
1360         if (autoscan->interval <= 0) {
1361                 interval = autoscan->base;
1362                 goto set_interval;
1363         } else
1364                 interval = autoscan->interval * autoscan->base;
1365
1366         if (interval > autoscan->limit)
1367                 interval = autoscan->limit;
1368
1369         throw_wifi_scan(wifi->device, scan_callback_hidden);
1370
1371         /*
1372          * In case BackgroundScanning is disabled, interval will reach the
1373          * limit exactly after the very first passive scanning. It allows
1374          * to ensure at most one passive scan is performed in such cases.
1375          */
1376         if (!connman_setting_get_bool("BackgroundScanning") &&
1377                                         interval == autoscan->limit) {
1378                 g_source_remove(autoscan->timeout);
1379                 autoscan->timeout = 0;
1380
1381                 connman_device_unref(device);
1382
1383                 return FALSE;
1384         }
1385
1386 set_interval:
1387         DBG("interval %d", interval);
1388
1389         autoscan->interval = interval;
1390
1391         autoscan->timeout = g_timeout_add_seconds(interval,
1392                                                 autoscan_timeout, device);
1393
1394         return FALSE;
1395 }
1396
1397 static void start_autoscan(struct connman_device *device)
1398 {
1399         struct wifi_data *wifi = connman_device_get_data(device);
1400         struct autoscan_params *autoscan;
1401
1402         DBG("");
1403
1404         if (!wifi)
1405                 return;
1406
1407         if (wifi->p2p_device)
1408                 return;
1409
1410         if (wifi->connected)
1411                 return;
1412
1413         autoscan = wifi->autoscan;
1414         if (!autoscan)
1415                 return;
1416
1417         if (autoscan->timeout > 0 || autoscan->interval > 0)
1418                 return;
1419
1420         connman_device_ref(device);
1421
1422         autoscan_timeout(device);
1423 }
1424
1425 static struct autoscan_params *parse_autoscan_params(const char *params)
1426 {
1427         struct autoscan_params *autoscan;
1428         char **list_params;
1429         int limit;
1430         int base;
1431
1432         DBG("");
1433
1434         list_params = g_strsplit(params, ":", 0);
1435         if (list_params == 0)
1436                 return NULL;
1437
1438         if (!g_strcmp0(list_params[0], "exponential") &&
1439                                 g_strv_length(list_params) == 3) {
1440                 base = atoi(list_params[1]);
1441                 limit = atoi(list_params[2]);
1442         } else if (!g_strcmp0(list_params[0], "single") &&
1443                                 g_strv_length(list_params) == 2)
1444                 base = limit = atoi(list_params[1]);
1445         else {
1446                 g_strfreev(list_params);
1447                 return NULL;
1448         }
1449
1450         DBG("Setup %s autoscanning", list_params[0]);
1451
1452         g_strfreev(list_params);
1453
1454         autoscan = g_try_malloc0(sizeof(struct autoscan_params));
1455         if (!autoscan) {
1456                 DBG("Could not allocate memory for autoscan");
1457                 return NULL;
1458         }
1459
1460         DBG("base %d - limit %d", base, limit);
1461         autoscan->base = base;
1462         autoscan->limit = limit;
1463
1464         return autoscan;
1465 }
1466
1467 static void setup_autoscan(struct wifi_data *wifi)
1468 {
1469         /*
1470          * If BackgroundScanning is enabled, setup exponential
1471          * autoscanning if it has not been previously done.
1472          */
1473         if (connman_setting_get_bool("BackgroundScanning")) {
1474                 wifi->autoscan = parse_autoscan_params(AUTOSCAN_EXPONENTIAL);
1475                 return;
1476         }
1477
1478         /*
1479          * On the contrary, if BackgroundScanning is disabled, update autoscan
1480          * parameters based on the type of scanning that is being performed.
1481          */
1482         if (wifi->autoscan) {
1483                 g_free(wifi->autoscan);
1484                 wifi->autoscan = NULL;
1485         }
1486
1487         switch (wifi->scanning_type) {
1488         case WIFI_SCANNING_PASSIVE:
1489                 /* Do not setup autoscan. */
1490                 break;
1491         case WIFI_SCANNING_ACTIVE:
1492                 /* Setup one single passive scan after active. */
1493                 wifi->autoscan = parse_autoscan_params(AUTOSCAN_SINGLE);
1494                 break;
1495         case WIFI_SCANNING_UNKNOWN:
1496                 /* Setup autoscan in this case but we should never fall here. */
1497                 wifi->autoscan = parse_autoscan_params(AUTOSCAN_SINGLE);
1498                 break;
1499         }
1500 }
1501
1502 static void finalize_interface_creation(struct wifi_data *wifi)
1503 {
1504         DBG("interface is ready wifi %p tethering %d", wifi, wifi->tethering);
1505
1506         if (!wifi->device) {
1507                 connman_error("WiFi device not set");
1508                 return;
1509         }
1510
1511         connman_device_set_powered(wifi->device, true);
1512
1513         if (wifi->p2p_device)
1514                 return;
1515
1516         if (!wifi->autoscan)
1517                 setup_autoscan(wifi);
1518
1519         start_autoscan(wifi->device);
1520 }
1521
1522 static void interface_create_callback(int result,
1523                                         GSupplicantInterface *interface,
1524                                                         void *user_data)
1525 {
1526         struct wifi_data *wifi = user_data;
1527
1528         DBG("result %d ifname %s, wifi %p", result,
1529                                 g_supplicant_interface_get_ifname(interface),
1530                                 wifi);
1531
1532         if (result < 0 || !wifi)
1533                 return;
1534
1535         wifi->interface = interface;
1536         g_supplicant_interface_set_data(interface, wifi);
1537
1538         if (g_supplicant_interface_get_ready(interface)) {
1539                 wifi->interface_ready = true;
1540                 finalize_interface_creation(wifi);
1541         }
1542 }
1543
1544 static int wifi_enable(struct connman_device *device)
1545 {
1546         struct wifi_data *wifi = connman_device_get_data(device);
1547         int index;
1548         char *interface;
1549         const char *driver = connman_option_get_string("wifi");
1550         int ret;
1551
1552         DBG("device %p %p", device, wifi);
1553
1554         index = connman_device_get_index(device);
1555         if (!wifi || index < 0)
1556                 return -ENODEV;
1557
1558         if (is_p2p_connecting())
1559                 return -EINPROGRESS;
1560
1561         interface = connman_inet_ifname(index);
1562         ret = g_supplicant_interface_create(interface, driver, NULL,
1563                                                 interface_create_callback,
1564                                                         wifi);
1565         g_free(interface);
1566
1567         if (ret < 0)
1568                 return ret;
1569
1570         return -EINPROGRESS;
1571 }
1572
1573 static int wifi_disable(struct connman_device *device)
1574 {
1575         struct wifi_data *wifi = connman_device_get_data(device);
1576         int ret;
1577
1578         DBG("device %p wifi %p", device, wifi);
1579
1580         if (!wifi)
1581                 return -ENODEV;
1582
1583         wifi->connected = false;
1584         wifi->disconnecting = false;
1585
1586         if (wifi->pending_network)
1587                 wifi->pending_network = NULL;
1588
1589         stop_autoscan(device);
1590
1591         if (connman_device_get_scanning(device, CONNMAN_SERVICE_TYPE_P2P)) {
1592                 g_source_remove(wifi->p2p_find_timeout);
1593                 wifi->p2p_find_timeout = 0;
1594                 connman_device_set_scanning(device, CONNMAN_SERVICE_TYPE_P2P, false);
1595                 connman_device_unref(wifi->device);
1596         }
1597
1598         /* In case of a user scan, device is still referenced */
1599         if (connman_device_get_scanning(device, CONNMAN_SERVICE_TYPE_WIFI)) {
1600                 connman_device_set_scanning(device,
1601                                 CONNMAN_SERVICE_TYPE_WIFI, false);
1602                 connman_device_unref(wifi->device);
1603         }
1604
1605         remove_networks(device, wifi);
1606         remove_peers(wifi);
1607
1608         ret = g_supplicant_interface_remove(wifi->interface, NULL, NULL);
1609         if (ret < 0)
1610                 return ret;
1611
1612         return -EINPROGRESS;
1613 }
1614
1615 struct last_connected {
1616         struct timeval modified;
1617         gchar *ssid;
1618         int freq;
1619 };
1620
1621 static gint sort_entry(gconstpointer a, gconstpointer b, gpointer user_data)
1622 {
1623         struct timeval *aval = (struct timeval *)a;
1624         struct timeval *bval = (struct timeval *)b;
1625
1626         /* Note that the sort order is descending */
1627         if (aval->tv_sec < bval->tv_sec)
1628                 return 1;
1629
1630         if (aval->tv_sec > bval->tv_sec)
1631                 return -1;
1632
1633         return 0;
1634 }
1635
1636 static void free_entry(gpointer data)
1637 {
1638         struct last_connected *entry = data;
1639
1640         g_free(entry->ssid);
1641         g_free(entry);
1642 }
1643
1644 static int get_latest_connections(int max_ssids,
1645                                 GSupplicantScanParams *scan_data)
1646 {
1647         GSequenceIter *iter;
1648         GSequence *latest_list;
1649         struct last_connected *entry;
1650         GKeyFile *keyfile;
1651         struct timeval modified;
1652         gchar **services;
1653         gchar *str;
1654         char *ssid;
1655         int i, freq;
1656         int num_ssids = 0;
1657
1658         latest_list = g_sequence_new(free_entry);
1659         if (!latest_list)
1660                 return -ENOMEM;
1661
1662         services = connman_storage_get_services();
1663         for (i = 0; services && services[i]; i++) {
1664                 if (strncmp(services[i], "wifi_", 5) != 0)
1665                         continue;
1666
1667                 keyfile = connman_storage_load_service(services[i]);
1668                 if (!keyfile)
1669                         continue;
1670
1671                 str = g_key_file_get_string(keyfile,
1672                                         services[i], "Favorite", NULL);
1673                 if (!str || g_strcmp0(str, "true")) {
1674                         g_free(str);
1675                         g_key_file_free(keyfile);
1676                         continue;
1677                 }
1678                 g_free(str);
1679
1680                 str = g_key_file_get_string(keyfile,
1681                                         services[i], "AutoConnect", NULL);
1682                 if (!str || g_strcmp0(str, "true")) {
1683                         g_free(str);
1684                         g_key_file_free(keyfile);
1685                         continue;
1686                 }
1687                 g_free(str);
1688
1689                 str = g_key_file_get_string(keyfile,
1690                                         services[i], "Modified", NULL);
1691                 if (!str) {
1692                         g_key_file_free(keyfile);
1693                         continue;
1694                 }
1695                 util_iso8601_to_timeval(str, &modified);
1696                 g_free(str);
1697
1698                 ssid = g_key_file_get_string(keyfile,
1699                                         services[i], "SSID", NULL);
1700
1701                 freq = g_key_file_get_integer(keyfile, services[i],
1702                                         "Frequency", NULL);
1703                 if (freq) {
1704                         entry = g_try_new(struct last_connected, 1);
1705                         if (!entry) {
1706                                 g_sequence_free(latest_list);
1707                                 g_key_file_free(keyfile);
1708                                 g_free(ssid);
1709                                 return -ENOMEM;
1710                         }
1711
1712                         entry->ssid = ssid;
1713                         entry->modified = modified;
1714                         entry->freq = freq;
1715
1716                         g_sequence_insert_sorted(latest_list, entry,
1717                                                 sort_entry, NULL);
1718                         num_ssids++;
1719                 } else
1720                         g_free(ssid);
1721
1722                 g_key_file_free(keyfile);
1723         }
1724
1725         g_strfreev(services);
1726
1727         num_ssids = num_ssids > max_ssids ? max_ssids : num_ssids;
1728
1729         iter = g_sequence_get_begin_iter(latest_list);
1730
1731         for (i = 0; i < num_ssids; i++) {
1732                 entry = g_sequence_get(iter);
1733
1734                 DBG("ssid %s freq %d modified %lu", entry->ssid, entry->freq,
1735                                                 entry->modified.tv_sec);
1736
1737                 add_scan_param(entry->ssid, NULL, 0, entry->freq, scan_data,
1738                                                 max_ssids, entry->ssid);
1739
1740                 iter = g_sequence_iter_next(iter);
1741         }
1742
1743         g_sequence_free(latest_list);
1744         return num_ssids;
1745 }
1746
1747 static void wifi_update_scanner_type(struct wifi_data *wifi,
1748                                         enum wifi_scanning_type new_type)
1749 {
1750         DBG("");
1751
1752         if (!wifi || wifi->scanning_type == new_type)
1753                 return;
1754
1755         wifi->scanning_type = new_type;
1756
1757         setup_autoscan(wifi);
1758 }
1759
1760 static int wifi_scan_simple(struct connman_device *device)
1761 {
1762         struct wifi_data *wifi = connman_device_get_data(device);
1763
1764         reset_autoscan(device);
1765
1766         /* Distinguish between devices performing passive and active scanning */
1767         if (wifi)
1768                 wifi_update_scanner_type(wifi, WIFI_SCANNING_PASSIVE);
1769
1770         return throw_wifi_scan(device, scan_callback_hidden);
1771 }
1772
1773 static gboolean p2p_find_stop(gpointer data)
1774 {
1775         struct connman_device *device = data;
1776         struct wifi_data *wifi = connman_device_get_data(device);
1777
1778         DBG("");
1779
1780         if (wifi) {
1781                 wifi->p2p_find_timeout = 0;
1782
1783                 g_supplicant_interface_p2p_stop_find(wifi->interface);
1784         }
1785
1786         connman_device_set_scanning(device, CONNMAN_SERVICE_TYPE_P2P, false);
1787
1788         connman_device_unref(device);
1789         start_autoscan(device);
1790
1791         return FALSE;
1792 }
1793
1794 static void p2p_find_callback(int result, GSupplicantInterface *interface,
1795                                                         void *user_data)
1796 {
1797         struct connman_device *device = user_data;
1798         struct wifi_data *wifi = connman_device_get_data(device);
1799
1800         DBG("result %d wifi %p", result, wifi);
1801
1802         if (!wifi)
1803                 goto error;
1804
1805         if (wifi->p2p_find_timeout) {
1806                 g_source_remove(wifi->p2p_find_timeout);
1807                 wifi->p2p_find_timeout = 0;
1808         }
1809
1810         if (result)
1811                 goto error;
1812
1813         wifi->p2p_find_timeout = g_timeout_add_seconds(P2P_FIND_TIMEOUT,
1814                                                         p2p_find_stop, device);
1815         if (!wifi->p2p_find_timeout)
1816                 goto error;
1817
1818         return;
1819 error:
1820         p2p_find_stop(device);
1821 }
1822
1823 static int p2p_find(struct connman_device *device)
1824 {
1825         struct wifi_data *wifi;
1826         int ret;
1827
1828         DBG("");
1829
1830         if (!p2p_technology)
1831                 return -ENOTSUP;
1832
1833         wifi = connman_device_get_data(device);
1834
1835         if (g_supplicant_interface_is_p2p_finding(wifi->interface))
1836                 return -EALREADY;
1837
1838         reset_autoscan(device);
1839         connman_device_ref(device);
1840
1841         ret = g_supplicant_interface_p2p_find(wifi->interface,
1842                                                 p2p_find_callback, device);
1843         if (ret) {
1844                 connman_device_unref(device);
1845                 start_autoscan(device);
1846         } else {
1847                 connman_device_set_scanning(device,
1848                                 CONNMAN_SERVICE_TYPE_P2P, true);
1849         }
1850
1851         return ret;
1852 }
1853
1854 /*
1855  * Note that the hidden scan is only used when connecting to this specific
1856  * hidden AP first time. It is not used when system autoconnects to hidden AP.
1857  */
1858 static int wifi_scan(struct connman_device *device,
1859                         struct connman_device_scan_params *params)
1860 {
1861         struct wifi_data *wifi = connman_device_get_data(device);
1862         GSupplicantScanParams *scan_params = NULL;
1863         struct scan_ssid *scan_ssid;
1864         struct hidden_params *hidden;
1865         int ret;
1866         int driver_max_ssids = 0;
1867         bool do_hidden;
1868         bool scanning;
1869
1870         if (!wifi)
1871                 return -ENODEV;
1872
1873         if (wifi->p2p_device)
1874                 return -EBUSY;
1875
1876         if (wifi->tethering)
1877                 return -EBUSY;
1878
1879         if (params->type == CONNMAN_SERVICE_TYPE_P2P)
1880                 return p2p_find(device);
1881
1882         DBG("device %p wifi %p hidden ssid %s", device, wifi->interface,
1883                 params->ssid);
1884
1885         scanning = connman_device_get_scanning(device, CONNMAN_SERVICE_TYPE_WIFI);
1886
1887         if (!params->ssid || params->ssid_len == 0 || params->ssid_len > 32) {
1888                 if (scanning)
1889                         return -EALREADY;
1890
1891                 driver_max_ssids = g_supplicant_interface_get_max_scan_ssids(
1892                                                         wifi->interface);
1893                 DBG("max ssids %d", driver_max_ssids);
1894                 if (driver_max_ssids == 0)
1895                         return wifi_scan_simple(device);
1896
1897                 do_hidden = false;
1898         } else {
1899                 if (scanning && wifi->hidden && wifi->postpone_hidden)
1900                         return -EALREADY;
1901
1902                 do_hidden = true;
1903         }
1904
1905         scan_params = g_try_malloc0(sizeof(GSupplicantScanParams));
1906         if (!scan_params)
1907                 return -ENOMEM;
1908
1909         if (do_hidden) {
1910                 scan_ssid = g_try_new(struct scan_ssid, 1);
1911                 if (!scan_ssid) {
1912                         g_free(scan_params);
1913                         return -ENOMEM;
1914                 }
1915
1916                 memcpy(scan_ssid->ssid, params->ssid, params->ssid_len);
1917                 scan_ssid->ssid_len = params->ssid_len;
1918                 scan_params->ssids = g_slist_prepend(scan_params->ssids,
1919                                                                 scan_ssid);
1920                 scan_params->num_ssids = 1;
1921
1922                 hidden = g_try_new0(struct hidden_params, 1);
1923                 if (!hidden) {
1924                         g_supplicant_free_scan_params(scan_params);
1925                         return -ENOMEM;
1926                 }
1927
1928                 if (wifi->hidden) {
1929                         hidden_free(wifi->hidden);
1930                         wifi->hidden = NULL;
1931                 }
1932
1933                 memcpy(hidden->ssid, params->ssid, params->ssid_len);
1934                 hidden->ssid_len = params->ssid_len;
1935                 hidden->identity = g_strdup(params->identity);
1936                 hidden->passphrase = g_strdup(params->passphrase);
1937                 hidden->security = g_strdup(params->security);
1938                 hidden->user_data = params->user_data;
1939                 wifi->hidden = hidden;
1940
1941                 if (scanning) {
1942                         /* Let's keep this active scan for later,
1943                          * when current scan will be over. */
1944                         wifi->postpone_hidden = TRUE;
1945                         hidden->scan_params = scan_params;
1946
1947                         return 0;
1948                 }
1949         } else if (wifi->connected) {
1950                 g_supplicant_free_scan_params(scan_params);
1951                 return wifi_scan_simple(device);
1952         } else if (!params->force_full_scan) {
1953                 ret = get_latest_connections(driver_max_ssids, scan_params);
1954                 if (ret <= 0) {
1955                         g_supplicant_free_scan_params(scan_params);
1956                         return wifi_scan_simple(device);
1957                 }
1958         }
1959
1960         /* Distinguish between devices performing passive and active scanning */
1961         wifi_update_scanner_type(wifi, WIFI_SCANNING_ACTIVE);
1962
1963         connman_device_ref(device);
1964
1965         reset_autoscan(device);
1966
1967         ret = g_supplicant_interface_scan(wifi->interface, scan_params,
1968                                                 scan_callback, device);
1969         if (ret == 0) {
1970                 connman_device_set_scanning(device,
1971                                 CONNMAN_SERVICE_TYPE_WIFI, true);
1972         } else {
1973                 g_supplicant_free_scan_params(scan_params);
1974                 connman_device_unref(device);
1975
1976                 if (do_hidden) {
1977                         hidden_free(wifi->hidden);
1978                         wifi->hidden = NULL;
1979                 }
1980         }
1981
1982         return ret;
1983 }
1984
1985 static void wifi_stop_scan(enum connman_service_type type,
1986                         struct connman_device *device)
1987 {
1988         struct wifi_data *wifi = connman_device_get_data(device);
1989
1990         DBG("device %p wifi %p", device, wifi);
1991
1992         if (!wifi)
1993                 return;
1994
1995         if (type == CONNMAN_SERVICE_TYPE_P2P) {
1996                 if (connman_device_get_scanning(device, CONNMAN_SERVICE_TYPE_P2P)) {
1997                         g_source_remove(wifi->p2p_find_timeout);
1998                         p2p_find_stop(device);
1999                 }
2000         }
2001 }
2002
2003 static void wifi_regdom_callback(int result,
2004                                         const char *alpha2,
2005                                                 void *user_data)
2006 {
2007         struct connman_device *device = user_data;
2008
2009         connman_device_regdom_notify(device, result, alpha2);
2010
2011         connman_device_unref(device);
2012 }
2013
2014 static int wifi_set_regdom(struct connman_device *device, const char *alpha2)
2015 {
2016         struct wifi_data *wifi = connman_device_get_data(device);
2017         int ret;
2018
2019         if (!wifi)
2020                 return -EINVAL;
2021
2022         connman_device_ref(device);
2023
2024         ret = g_supplicant_interface_set_country(wifi->interface,
2025                                                 wifi_regdom_callback,
2026                                                         alpha2, device);
2027         if (ret != 0)
2028                 connman_device_unref(device);
2029
2030         return ret;
2031 }
2032
2033 static struct connman_device_driver wifi_ng_driver = {
2034         .name           = "wifi",
2035         .type           = CONNMAN_DEVICE_TYPE_WIFI,
2036         .priority       = CONNMAN_DEVICE_PRIORITY_LOW,
2037         .probe          = wifi_probe,
2038         .remove         = wifi_remove,
2039         .enable         = wifi_enable,
2040         .disable        = wifi_disable,
2041         .scan           = wifi_scan,
2042         .stop_scan      = wifi_stop_scan,
2043         .set_regdom     = wifi_set_regdom,
2044 };
2045
2046 static void system_ready(void)
2047 {
2048         DBG("");
2049
2050         if (connman_device_driver_register(&wifi_ng_driver) < 0)
2051                 connman_error("Failed to register WiFi driver");
2052 }
2053
2054 static void system_killed(void)
2055 {
2056         DBG("");
2057
2058         connman_device_driver_unregister(&wifi_ng_driver);
2059 }
2060
2061 static int network_probe(struct connman_network *network)
2062 {
2063         DBG("network %p", network);
2064
2065         return 0;
2066 }
2067
2068 static void network_remove(struct connman_network *network)
2069 {
2070         struct connman_device *device = connman_network_get_device(network);
2071         struct wifi_data *wifi;
2072
2073         DBG("network %p", network);
2074
2075         wifi = connman_device_get_data(device);
2076         if (!wifi)
2077                 return;
2078
2079         if (wifi->network != network)
2080                 return;
2081
2082         wifi->network = NULL;
2083 }
2084
2085 static void connect_callback(int result, GSupplicantInterface *interface,
2086                                                         void *user_data)
2087 {
2088         struct connman_network *network = user_data;
2089
2090         DBG("network %p result %d", network, result);
2091
2092         if (result == -ENOKEY) {
2093                 connman_network_set_error(network,
2094                                         CONNMAN_NETWORK_ERROR_INVALID_KEY);
2095         } else if (result < 0) {
2096                 connman_network_set_error(network,
2097                                         CONNMAN_NETWORK_ERROR_CONFIGURE_FAIL);
2098         }
2099
2100         connman_network_unref(network);
2101 }
2102
2103 static GSupplicantSecurity network_security(const char *security)
2104 {
2105         if (g_str_equal(security, "none"))
2106                 return G_SUPPLICANT_SECURITY_NONE;
2107         else if (g_str_equal(security, "wep"))
2108                 return G_SUPPLICANT_SECURITY_WEP;
2109         else if (g_str_equal(security, "psk"))
2110                 return G_SUPPLICANT_SECURITY_PSK;
2111         else if (g_str_equal(security, "wpa"))
2112                 return G_SUPPLICANT_SECURITY_PSK;
2113         else if (g_str_equal(security, "rsn"))
2114                 return G_SUPPLICANT_SECURITY_PSK;
2115         else if (g_str_equal(security, "ieee8021x"))
2116                 return G_SUPPLICANT_SECURITY_IEEE8021X;
2117
2118         return G_SUPPLICANT_SECURITY_UNKNOWN;
2119 }
2120
2121 static void ssid_init(GSupplicantSSID *ssid, struct connman_network *network)
2122 {
2123         const char *security;
2124
2125         memset(ssid, 0, sizeof(*ssid));
2126         ssid->mode = G_SUPPLICANT_MODE_INFRA;
2127         ssid->ssid = connman_network_get_blob(network, "WiFi.SSID",
2128                                                 &ssid->ssid_len);
2129         ssid->scan_ssid = 1;
2130         security = connman_network_get_string(network, "WiFi.Security");
2131         ssid->security = network_security(security);
2132         ssid->passphrase = connman_network_get_string(network,
2133                                                 "WiFi.Passphrase");
2134
2135         ssid->eap = connman_network_get_string(network, "WiFi.EAP");
2136
2137         /*
2138          * If our private key password is unset,
2139          * we use the supplied passphrase. That is needed
2140          * for PEAP where 2 passphrases (identity and client
2141          * cert may have to be provided.
2142          */
2143         if (!connman_network_get_string(network, "WiFi.PrivateKeyPassphrase"))
2144                 connman_network_set_string(network,
2145                                                 "WiFi.PrivateKeyPassphrase",
2146                                                 ssid->passphrase);
2147         /* We must have an identity for both PEAP and TLS */
2148         ssid->identity = connman_network_get_string(network, "WiFi.Identity");
2149
2150         /* Use agent provided identity as a fallback */
2151         if (!ssid->identity || strlen(ssid->identity) == 0)
2152                 ssid->identity = connman_network_get_string(network,
2153                                                         "WiFi.AgentIdentity");
2154
2155         ssid->anonymous_identity = connman_network_get_string(network,
2156                                                 "WiFi.AnonymousIdentity");
2157         ssid->ca_cert_path = connman_network_get_string(network,
2158                                                         "WiFi.CACertFile");
2159         ssid->subject_match = connman_network_get_string(network,
2160                                                         "WiFi.SubjectMatch");
2161         ssid->altsubject_match = connman_network_get_string(network,
2162                                                         "WiFi.AltSubjectMatch");
2163         ssid->domain_suffix_match = connman_network_get_string(network,
2164                                                         "WiFi.DomainSuffixMatch");
2165         ssid->domain_match = connman_network_get_string(network,
2166                                                         "WiFi.DomainMatch");
2167         ssid->client_cert_path = connman_network_get_string(network,
2168                                                         "WiFi.ClientCertFile");
2169         ssid->private_key_path = connman_network_get_string(network,
2170                                                         "WiFi.PrivateKeyFile");
2171         ssid->private_key_passphrase = connman_network_get_string(network,
2172                                                 "WiFi.PrivateKeyPassphrase");
2173         ssid->phase2_auth = connman_network_get_string(network, "WiFi.Phase2");
2174
2175         ssid->use_wps = connman_network_get_bool(network, "WiFi.UseWPS");
2176         ssid->pin_wps = connman_network_get_string(network, "WiFi.PinWPS");
2177
2178         if (connman_setting_get_bool("BackgroundScanning"))
2179                 ssid->bgscan = BGSCAN_DEFAULT;
2180 }
2181
2182 static int network_connect(struct connman_network *network)
2183 {
2184         struct connman_device *device = connman_network_get_device(network);
2185         struct wifi_data *wifi;
2186         GSupplicantInterface *interface;
2187         GSupplicantSSID *ssid;
2188
2189         DBG("network %p", network);
2190
2191         if (!device)
2192                 return -ENODEV;
2193
2194         wifi = connman_device_get_data(device);
2195         if (!wifi)
2196                 return -ENODEV;
2197
2198         ssid = g_try_malloc0(sizeof(GSupplicantSSID));
2199         if (!ssid)
2200                 return -ENOMEM;
2201
2202         interface = wifi->interface;
2203
2204         ssid_init(ssid, network);
2205
2206         if (wifi->disconnecting) {
2207                 wifi->pending_network = network;
2208                 g_free(ssid);
2209         } else {
2210                 wifi->network = connman_network_ref(network);
2211                 wifi->retries = 0;
2212
2213                 return g_supplicant_interface_connect(interface, ssid,
2214                                                 connect_callback, network);
2215         }
2216
2217         return -EINPROGRESS;
2218 }
2219
2220 static void disconnect_callback(int result, GSupplicantInterface *interface,
2221                                                                 void *user_data)
2222 {
2223         struct wifi_data *wifi = user_data;
2224
2225         DBG("result %d supplicant interface %p wifi %p",
2226                         result, interface, wifi);
2227
2228         if (result == -ECONNABORTED) {
2229                 DBG("wifi interface no longer available");
2230                 return;
2231         }
2232
2233         if (wifi->network && wifi->network != wifi->pending_network)
2234                 connman_network_set_connected(wifi->network, false);
2235         wifi->network = NULL;
2236
2237         wifi->disconnecting = false;
2238         wifi->connected = false;
2239
2240         if (wifi->pending_network) {
2241                 network_connect(wifi->pending_network);
2242                 wifi->pending_network = NULL;
2243         }
2244
2245         start_autoscan(wifi->device);
2246 }
2247
2248 static int network_disconnect(struct connman_network *network)
2249 {
2250         struct connman_device *device = connman_network_get_device(network);
2251         struct wifi_data *wifi;
2252         int err;
2253
2254         DBG("network %p", network);
2255
2256         wifi = connman_device_get_data(device);
2257         if (!wifi || !wifi->interface)
2258                 return -ENODEV;
2259
2260         connman_network_set_associating(network, false);
2261
2262         if (wifi->disconnecting)
2263                 return -EALREADY;
2264
2265         wifi->disconnecting = true;
2266
2267         err = g_supplicant_interface_disconnect(wifi->interface,
2268                                                 disconnect_callback, wifi);
2269         if (err < 0)
2270                 wifi->disconnecting = false;
2271
2272         return err;
2273 }
2274
2275 static struct connman_network_driver network_driver = {
2276         .name           = "wifi",
2277         .type           = CONNMAN_NETWORK_TYPE_WIFI,
2278         .priority       = CONNMAN_NETWORK_PRIORITY_LOW,
2279         .probe          = network_probe,
2280         .remove         = network_remove,
2281         .connect        = network_connect,
2282         .disconnect     = network_disconnect,
2283 };
2284
2285 static void interface_added(GSupplicantInterface *interface)
2286 {
2287         const char *ifname = g_supplicant_interface_get_ifname(interface);
2288         const char *driver = g_supplicant_interface_get_driver(interface);
2289         struct wifi_data *wifi;
2290
2291         wifi = g_supplicant_interface_get_data(interface);
2292         if (!wifi) {
2293                 wifi = get_pending_wifi_data(ifname);
2294                 if (!wifi)
2295                         return;
2296
2297                 wifi->interface = interface;
2298                 g_supplicant_interface_set_data(interface, wifi);
2299                 p2p_iface_list = g_list_append(p2p_iface_list, wifi);
2300                 wifi->p2p_device = true;
2301         }
2302
2303         DBG("ifname %s driver %s wifi %p tethering %d",
2304                         ifname, driver, wifi, wifi->tethering);
2305
2306         if (!wifi->device) {
2307                 connman_error("WiFi device not set");
2308                 return;
2309         }
2310
2311         connman_device_set_powered(wifi->device, true);
2312 }
2313
2314 static bool is_idle(struct wifi_data *wifi)
2315 {
2316         DBG("state %d", wifi->state);
2317
2318         switch (wifi->state) {
2319         case G_SUPPLICANT_STATE_UNKNOWN:
2320         case G_SUPPLICANT_STATE_DISABLED:
2321         case G_SUPPLICANT_STATE_DISCONNECTED:
2322         case G_SUPPLICANT_STATE_INACTIVE:
2323         case G_SUPPLICANT_STATE_SCANNING:
2324                 return true;
2325
2326         case G_SUPPLICANT_STATE_AUTHENTICATING:
2327         case G_SUPPLICANT_STATE_ASSOCIATING:
2328         case G_SUPPLICANT_STATE_ASSOCIATED:
2329         case G_SUPPLICANT_STATE_4WAY_HANDSHAKE:
2330         case G_SUPPLICANT_STATE_GROUP_HANDSHAKE:
2331         case G_SUPPLICANT_STATE_COMPLETED:
2332                 return false;
2333         }
2334
2335         return false;
2336 }
2337
2338 static bool is_idle_wps(GSupplicantInterface *interface,
2339                                                 struct wifi_data *wifi)
2340 {
2341         /* First, let's check if WPS processing did not went wrong */
2342         if (g_supplicant_interface_get_wps_state(interface) ==
2343                 G_SUPPLICANT_WPS_STATE_FAIL)
2344                 return false;
2345
2346         /* Unlike normal connection, being associated while processing wps
2347          * actually means that we are idling. */
2348         switch (wifi->state) {
2349         case G_SUPPLICANT_STATE_UNKNOWN:
2350         case G_SUPPLICANT_STATE_DISABLED:
2351         case G_SUPPLICANT_STATE_DISCONNECTED:
2352         case G_SUPPLICANT_STATE_INACTIVE:
2353         case G_SUPPLICANT_STATE_SCANNING:
2354         case G_SUPPLICANT_STATE_ASSOCIATED:
2355                 return true;
2356         case G_SUPPLICANT_STATE_AUTHENTICATING:
2357         case G_SUPPLICANT_STATE_ASSOCIATING:
2358         case G_SUPPLICANT_STATE_4WAY_HANDSHAKE:
2359         case G_SUPPLICANT_STATE_GROUP_HANDSHAKE:
2360         case G_SUPPLICANT_STATE_COMPLETED:
2361                 return false;
2362         }
2363
2364         return false;
2365 }
2366
2367 static bool handle_wps_completion(GSupplicantInterface *interface,
2368                                         struct connman_network *network,
2369                                         struct connman_device *device,
2370                                         struct wifi_data *wifi)
2371 {
2372         bool wps;
2373
2374         wps = connman_network_get_bool(network, "WiFi.UseWPS");
2375         if (wps) {
2376                 const unsigned char *ssid, *wps_ssid;
2377                 unsigned int ssid_len, wps_ssid_len;
2378                 const char *wps_key;
2379
2380                 /* Checking if we got associated with requested
2381                  * network */
2382                 ssid = connman_network_get_blob(network, "WiFi.SSID",
2383                                                 &ssid_len);
2384
2385                 wps_ssid = g_supplicant_interface_get_wps_ssid(
2386                         interface, &wps_ssid_len);
2387
2388                 if (!wps_ssid || wps_ssid_len != ssid_len ||
2389                                 memcmp(ssid, wps_ssid, ssid_len) != 0) {
2390                         connman_network_set_associating(network, false);
2391                         g_supplicant_interface_disconnect(wifi->interface,
2392                                                 disconnect_callback, wifi);
2393                         return false;
2394                 }
2395
2396                 wps_key = g_supplicant_interface_get_wps_key(interface);
2397                 connman_network_set_string(network, "WiFi.Passphrase",
2398                                         wps_key);
2399
2400                 connman_network_set_string(network, "WiFi.PinWPS", NULL);
2401         }
2402
2403         return true;
2404 }
2405
2406 static bool handle_assoc_status_code(GSupplicantInterface *interface,
2407                                      struct wifi_data *wifi)
2408 {
2409         if (wifi->state == G_SUPPLICANT_STATE_ASSOCIATING &&
2410                         wifi->assoc_code == ASSOC_STATUS_NO_CLIENT &&
2411                         wifi->load_shaping_retries < LOAD_SHAPING_MAX_RETRIES) {
2412                 wifi->load_shaping_retries ++;
2413                 return TRUE;
2414         }
2415         wifi->load_shaping_retries = 0;
2416         return FALSE;
2417 }
2418
2419 static bool handle_4way_handshake_failure(GSupplicantInterface *interface,
2420                                         struct connman_network *network,
2421                                         struct wifi_data *wifi)
2422 {
2423         struct connman_service *service;
2424
2425         if (wifi->state != G_SUPPLICANT_STATE_4WAY_HANDSHAKE)
2426                 return false;
2427
2428         if (wifi->connected)
2429                 return false;
2430
2431         service = connman_service_lookup_from_network(network);
2432         if (!service)
2433                 return false;
2434
2435         wifi->retries++;
2436
2437         if (connman_service_get_favorite(service)) {
2438                 if (wifi->retries < FAVORITE_MAXIMUM_RETRIES)
2439                         return true;
2440         }
2441
2442         wifi->retries = 0;
2443         connman_network_set_error(network, CONNMAN_NETWORK_ERROR_INVALID_KEY);
2444
2445         return false;
2446 }
2447
2448 static void interface_state(GSupplicantInterface *interface)
2449 {
2450         struct connman_network *network;
2451         struct connman_device *device;
2452         struct wifi_data *wifi;
2453         GSupplicantState state = g_supplicant_interface_get_state(interface);
2454         bool wps;
2455         bool old_connected;
2456
2457         wifi = g_supplicant_interface_get_data(interface);
2458
2459         DBG("wifi %p interface state %d", wifi, state);
2460
2461         if (!wifi)
2462                 return;
2463
2464         device = wifi->device;
2465         if (!device)
2466                 return;
2467
2468         if (state == G_SUPPLICANT_STATE_COMPLETED) {
2469                 if (wifi->tethering_param) {
2470                         g_free(wifi->tethering_param->ssid);
2471                         g_free(wifi->tethering_param);
2472                         wifi->tethering_param = NULL;
2473                 }
2474
2475                 if (wifi->tethering)
2476                         stop_autoscan(device);
2477         }
2478
2479         if (g_supplicant_interface_get_ready(interface) &&
2480                                         !wifi->interface_ready) {
2481                 wifi->interface_ready = true;
2482                 finalize_interface_creation(wifi);
2483         }
2484
2485         network = wifi->network;
2486         if (!network)
2487                 return;
2488
2489         switch (state) {
2490         case G_SUPPLICANT_STATE_SCANNING:
2491                 if (wifi->connected)
2492                         connman_network_set_connected(network, false);
2493
2494                 break;
2495
2496         case G_SUPPLICANT_STATE_AUTHENTICATING:
2497         case G_SUPPLICANT_STATE_ASSOCIATING:
2498                 stop_autoscan(device);
2499
2500                 if (!wifi->connected)
2501                         connman_network_set_associating(network, true);
2502
2503                 break;
2504
2505         case G_SUPPLICANT_STATE_COMPLETED:
2506                 /* though it should be already stopped: */
2507                 stop_autoscan(device);
2508
2509                 if (!handle_wps_completion(interface, network, device, wifi))
2510                         break;
2511
2512                 connman_network_set_connected(network, true);
2513
2514                 wifi->disconnect_code = 0;
2515                 wifi->assoc_code = 0;
2516                 wifi->load_shaping_retries = 0;
2517                 break;
2518
2519         case G_SUPPLICANT_STATE_DISCONNECTED:
2520                 /*
2521                  * If we're in one of the idle modes, we have
2522                  * not started association yet and thus setting
2523                  * those ones to FALSE could cancel an association
2524                  * in progress.
2525                  */
2526                 wps = connman_network_get_bool(network, "WiFi.UseWPS");
2527                 if (wps)
2528                         if (is_idle_wps(interface, wifi))
2529                                 break;
2530
2531                 if (is_idle(wifi))
2532                         break;
2533
2534                 if (handle_assoc_status_code(interface, wifi))
2535                         break;
2536
2537                 /* If previous state was 4way-handshake, then
2538                  * it's either: psk was incorrect and thus we retry
2539                  * or if we reach the maximum retries we declare the
2540                  * psk as wrong */
2541                 if (handle_4way_handshake_failure(interface,
2542                                                 network, wifi))
2543                         break;
2544
2545                 /* See table 8-36 Reason codes in IEEE Std 802.11 */
2546                 switch (wifi->disconnect_code) {
2547                 case 1: /* Unspecified reason */
2548                         /* Let's assume it's because we got blocked */
2549
2550                 case 6: /* Class 2 frame received from nonauthenticated STA */
2551                         connman_network_set_error(network,
2552                                                 CONNMAN_NETWORK_ERROR_BLOCKED);
2553                         break;
2554
2555                 default:
2556                         break;
2557                 }
2558
2559                 if (network != wifi->pending_network) {
2560                         connman_network_set_connected(network, false);
2561                         connman_network_set_associating(network, false);
2562                 }
2563                 wifi->disconnecting = false;
2564
2565                 start_autoscan(device);
2566
2567                 break;
2568
2569         case G_SUPPLICANT_STATE_INACTIVE:
2570                 connman_network_set_associating(network, false);
2571                 start_autoscan(device);
2572
2573                 break;
2574
2575         case G_SUPPLICANT_STATE_UNKNOWN:
2576         case G_SUPPLICANT_STATE_DISABLED:
2577         case G_SUPPLICANT_STATE_ASSOCIATED:
2578         case G_SUPPLICANT_STATE_4WAY_HANDSHAKE:
2579         case G_SUPPLICANT_STATE_GROUP_HANDSHAKE:
2580                 break;
2581         }
2582
2583         old_connected = wifi->connected;
2584         wifi->state = state;
2585
2586         /* Saving wpa_s state policy:
2587          * If connected and if the state changes are roaming related:
2588          * --> We stay connected
2589          * If completed
2590          * --> We are connected
2591          * All other case:
2592          * --> We are not connected
2593          * */
2594         switch (state) {
2595         case G_SUPPLICANT_STATE_AUTHENTICATING:
2596         case G_SUPPLICANT_STATE_ASSOCIATING:
2597         case G_SUPPLICANT_STATE_ASSOCIATED:
2598         case G_SUPPLICANT_STATE_4WAY_HANDSHAKE:
2599         case G_SUPPLICANT_STATE_GROUP_HANDSHAKE:
2600                 if (wifi->connected)
2601                         connman_warn("Probably roaming right now!"
2602                                                 " Staying connected...");
2603                 break;
2604         case G_SUPPLICANT_STATE_SCANNING:
2605                 wifi->connected = false;
2606
2607                 if (old_connected)
2608                         start_autoscan(device);
2609                 break;
2610         case G_SUPPLICANT_STATE_COMPLETED:
2611                 wifi->connected = true;
2612                 break;
2613         default:
2614                 wifi->connected = false;
2615                 break;
2616         }
2617
2618         DBG("DONE");
2619 }
2620
2621 static void interface_removed(GSupplicantInterface *interface)
2622 {
2623         const char *ifname = g_supplicant_interface_get_ifname(interface);
2624         struct wifi_data *wifi;
2625
2626         DBG("ifname %s", ifname);
2627
2628         wifi = g_supplicant_interface_get_data(interface);
2629
2630         if (wifi)
2631                 wifi->interface = NULL;
2632
2633         if (wifi && wifi->tethering)
2634                 return;
2635
2636         if (!wifi || !wifi->device) {
2637                 DBG("wifi interface already removed");
2638                 return;
2639         }
2640
2641         connman_device_set_powered(wifi->device, false);
2642
2643         check_p2p_technology();
2644 }
2645
2646 static void set_device_type(const char *type, char dev_type[17])
2647 {
2648         const char *oui = "0050F204";
2649         const char *category = "0001";
2650         const char *sub_category = "0000";
2651
2652         if (!g_strcmp0(type, "handset")) {
2653                 category = "000A";
2654                 sub_category = "0005";
2655         } else if (!g_strcmp0(type, "vm") || !g_strcmp0(type, "container"))
2656                 sub_category = "0001";
2657         else if (!g_strcmp0(type, "server"))
2658                 sub_category = "0002";
2659         else if (!g_strcmp0(type, "laptop"))
2660                 sub_category = "0005";
2661         else if (!g_strcmp0(type, "desktop"))
2662                 sub_category = "0006";
2663         else if (!g_strcmp0(type, "tablet"))
2664                 sub_category = "0009";
2665         else if (!g_strcmp0(type, "watch"))
2666                 category = "00FF";
2667
2668         snprintf(dev_type, 17, "%s%s%s", category, oui, sub_category);
2669 }
2670
2671 static void p2p_support(GSupplicantInterface *interface)
2672 {
2673         char dev_type[17] = {};
2674         const char *hostname;
2675
2676         DBG("");
2677
2678         if (!interface)
2679                 return;
2680
2681         if (!g_supplicant_interface_has_p2p(interface))
2682                 return;
2683
2684         if (connman_technology_driver_register(&p2p_tech_driver) < 0) {
2685                 DBG("Could not register P2P technology driver");
2686                 return;
2687         }
2688
2689         hostname = connman_utsname_get_hostname();
2690         if (!hostname)
2691                 hostname = "ConnMan";
2692
2693         set_device_type(connman_machine_get_type(), dev_type);
2694         g_supplicant_interface_set_p2p_device_config(interface,
2695                                                         hostname, dev_type);
2696         connman_peer_driver_register(&peer_driver);
2697 }
2698
2699 static void scan_started(GSupplicantInterface *interface)
2700 {
2701         DBG("");
2702 }
2703
2704 static void scan_finished(GSupplicantInterface *interface)
2705 {
2706         DBG("");
2707 }
2708
2709 static void ap_create_fail(GSupplicantInterface *interface)
2710 {
2711         struct wifi_data *wifi = g_supplicant_interface_get_data(interface);
2712         int ret;
2713
2714         if ((wifi->tethering) && (wifi->tethering_param)) {
2715                 DBG("%s create AP fail \n",
2716                                 g_supplicant_interface_get_ifname(wifi->interface));
2717
2718                 connman_inet_remove_from_bridge(wifi->index, wifi->bridge);
2719                 wifi->ap_supported = WIFI_AP_NOT_SUPPORTED;
2720                 wifi->tethering = false;
2721
2722                 ret = tech_set_tethering(wifi->tethering_param->technology,
2723                                 wifi->tethering_param->ssid->ssid,
2724                                 wifi->tethering_param->ssid->passphrase,
2725                                 wifi->bridge, true);
2726
2727                 if ((ret == -EOPNOTSUPP) && (wifi_technology)) {
2728                         connman_technology_tethering_notify(wifi_technology,false);
2729                 }
2730
2731                 g_free(wifi->tethering_param->ssid);
2732                 g_free(wifi->tethering_param);
2733                 wifi->tethering_param = NULL;
2734         }
2735 }
2736
2737 static unsigned char calculate_strength(GSupplicantNetwork *supplicant_network)
2738 {
2739         unsigned char strength;
2740
2741         strength = 120 + g_supplicant_network_get_signal(supplicant_network);
2742         if (strength > 100)
2743                 strength = 100;
2744
2745         return strength;
2746 }
2747
2748 static void network_added(GSupplicantNetwork *supplicant_network)
2749 {
2750         struct connman_network *network;
2751         GSupplicantInterface *interface;
2752         struct wifi_data *wifi;
2753         const char *name, *identifier, *security, *group, *mode;
2754         const unsigned char *ssid;
2755         unsigned int ssid_len;
2756         bool wps;
2757         bool wps_pbc;
2758         bool wps_ready;
2759         bool wps_advertizing;
2760
2761         mode = g_supplicant_network_get_mode(supplicant_network);
2762         identifier = g_supplicant_network_get_identifier(supplicant_network);
2763
2764         DBG("%s", identifier);
2765
2766         if (!g_strcmp0(mode, "adhoc"))
2767                 return;
2768
2769         interface = g_supplicant_network_get_interface(supplicant_network);
2770         wifi = g_supplicant_interface_get_data(interface);
2771         name = g_supplicant_network_get_name(supplicant_network);
2772         security = g_supplicant_network_get_security(supplicant_network);
2773         group = g_supplicant_network_get_identifier(supplicant_network);
2774         wps = g_supplicant_network_get_wps(supplicant_network);
2775         wps_pbc = g_supplicant_network_is_wps_pbc(supplicant_network);
2776         wps_ready = g_supplicant_network_is_wps_active(supplicant_network);
2777         wps_advertizing = g_supplicant_network_is_wps_advertizing(
2778                                                         supplicant_network);
2779
2780         if (!wifi)
2781                 return;
2782
2783         ssid = g_supplicant_network_get_ssid(supplicant_network, &ssid_len);
2784
2785         network = connman_device_get_network(wifi->device, identifier);
2786
2787         if (!network) {
2788                 network = connman_network_create(identifier,
2789                                                 CONNMAN_NETWORK_TYPE_WIFI);
2790                 if (!network)
2791                         return;
2792
2793                 connman_network_set_index(network, wifi->index);
2794
2795                 if (connman_device_add_network(wifi->device, network) < 0) {
2796                         connman_network_unref(network);
2797                         return;
2798                 }
2799
2800                 wifi->networks = g_slist_prepend(wifi->networks, network);
2801         }
2802
2803         if (name && name[0] != '\0')
2804                 connman_network_set_name(network, name);
2805
2806         connman_network_set_blob(network, "WiFi.SSID",
2807                                                 ssid, ssid_len);
2808         connman_network_set_string(network, "WiFi.Security", security);
2809         connman_network_set_strength(network,
2810                                 calculate_strength(supplicant_network));
2811         connman_network_set_bool(network, "WiFi.WPS", wps);
2812         connman_network_set_bool(network, "WiFi.WPSAdvertising",
2813                                 wps_advertizing);
2814
2815         if (wps) {
2816                 /* Is AP advertizing for WPS association?
2817                  * If so, we decide to use WPS by default */
2818                 if (wps_ready && wps_pbc &&
2819                                                 wps_advertizing)
2820                         connman_network_set_bool(network, "WiFi.UseWPS", true);
2821         }
2822
2823         connman_network_set_frequency(network,
2824                         g_supplicant_network_get_frequency(supplicant_network));
2825
2826         connman_network_set_available(network, true);
2827         connman_network_set_string(network, "WiFi.Mode", mode);
2828
2829         if (ssid)
2830                 connman_network_set_group(network, group);
2831
2832         if (wifi->hidden && ssid) {
2833                 if (!g_strcmp0(wifi->hidden->security, security) &&
2834                                 wifi->hidden->ssid_len == ssid_len &&
2835                                 !memcmp(wifi->hidden->ssid, ssid, ssid_len)) {
2836                         connman_network_connect_hidden(network,
2837                                         wifi->hidden->identity,
2838                                         wifi->hidden->passphrase,
2839                                         wifi->hidden->user_data);
2840                         wifi->hidden->user_data = NULL;
2841                         hidden_free(wifi->hidden);
2842                         wifi->hidden = NULL;
2843                 }
2844         }
2845 }
2846
2847 static void network_removed(GSupplicantNetwork *network)
2848 {
2849         GSupplicantInterface *interface;
2850         struct wifi_data *wifi;
2851         const char *name, *identifier;
2852         struct connman_network *connman_network;
2853
2854         interface = g_supplicant_network_get_interface(network);
2855         wifi = g_supplicant_interface_get_data(interface);
2856         identifier = g_supplicant_network_get_identifier(network);
2857         name = g_supplicant_network_get_name(network);
2858
2859         DBG("name %s", name);
2860
2861         if (!wifi)
2862                 return;
2863
2864         connman_network = connman_device_get_network(wifi->device, identifier);
2865         if (!connman_network)
2866                 return;
2867
2868         wifi->networks = g_slist_remove(wifi->networks, connman_network);
2869
2870         connman_device_remove_network(wifi->device, connman_network);
2871         connman_network_unref(connman_network);
2872 }
2873
2874 static void network_changed(GSupplicantNetwork *network, const char *property)
2875 {
2876         GSupplicantInterface *interface;
2877         struct wifi_data *wifi;
2878         const char *name, *identifier;
2879         struct connman_network *connman_network;
2880         bool update_needed;
2881
2882         interface = g_supplicant_network_get_interface(network);
2883         wifi = g_supplicant_interface_get_data(interface);
2884         identifier = g_supplicant_network_get_identifier(network);
2885         name = g_supplicant_network_get_name(network);
2886
2887         DBG("name %s", name);
2888
2889         if (!wifi)
2890                 return;
2891
2892         connman_network = connman_device_get_network(wifi->device, identifier);
2893         if (!connman_network)
2894                 return;
2895
2896         if (g_str_equal(property, "WPSCapabilities")) {
2897                 bool wps;
2898                 bool wps_pbc;
2899                 bool wps_ready;
2900                 bool wps_advertizing;
2901
2902                 wps = g_supplicant_network_get_wps(network);
2903                 wps_pbc = g_supplicant_network_is_wps_pbc(network);
2904                 wps_ready = g_supplicant_network_is_wps_active(network);
2905                 wps_advertizing =
2906                         g_supplicant_network_is_wps_advertizing(network);
2907
2908                 connman_network_set_bool(connman_network, "WiFi.WPS", wps);
2909                 connman_network_set_bool(connman_network,
2910                                 "WiFi.WPSAdvertising", wps_advertizing);
2911
2912                 if (wps) {
2913                         /*
2914                          * Is AP advertizing for WPS association?
2915                          * If so, we decide to use WPS by default
2916                          */
2917                         if (wps_ready && wps_pbc && wps_advertizing)
2918                                 connman_network_set_bool(connman_network,
2919                                                         "WiFi.UseWPS", true);
2920                 }
2921
2922                 update_needed = true;
2923         } else if (g_str_equal(property, "Signal")) {
2924                 connman_network_set_strength(connman_network,
2925                                         calculate_strength(network));
2926                 update_needed = true;
2927         } else
2928                 update_needed = false;
2929
2930         if (update_needed)
2931                 connman_network_update(connman_network);
2932 }
2933
2934 static void network_associated(GSupplicantNetwork *network)
2935 {
2936         GSupplicantInterface *interface;
2937         struct wifi_data *wifi;
2938         struct connman_network *connman_network;
2939         const char *identifier;
2940
2941         DBG("");
2942
2943         interface = g_supplicant_network_get_interface(network);
2944         if (!interface)
2945                 return;
2946
2947         wifi = g_supplicant_interface_get_data(interface);
2948         if (!wifi)
2949                 return;
2950
2951         /* P2P networks must not be treated as WiFi networks */
2952         if (wifi->p2p_connecting || wifi->p2p_device)
2953                 return;
2954
2955         identifier = g_supplicant_network_get_identifier(network);
2956
2957         connman_network = connman_device_get_network(wifi->device, identifier);
2958         if (!connman_network)
2959                 return;
2960
2961         if (wifi->network) {
2962                 if (wifi->network == connman_network)
2963                         return;
2964
2965                 /*
2966                  * This should never happen, we got associated with
2967                  * a network different than the one we were expecting.
2968                  */
2969                 DBG("Associated to %p while expecting %p",
2970                                         connman_network, wifi->network);
2971
2972                 connman_network_set_associating(wifi->network, false);
2973         }
2974
2975         DBG("Reconnecting to previous network %p from wpa_s", connman_network);
2976
2977         wifi->network = connman_network_ref(connman_network);
2978         wifi->retries = 0;
2979
2980         /*
2981          * Interface state changes callback (interface_state) is always
2982          * called before network_associated callback thus we need to call
2983          * interface_state again in order to process the new state now that
2984          * we have the network properly set.
2985          */
2986         interface_state(interface);
2987 }
2988
2989 static void sta_authorized(GSupplicantInterface *interface,
2990                                         const char *addr)
2991 {
2992         struct wifi_data *wifi = g_supplicant_interface_get_data(interface);
2993
2994         DBG("wifi %p station %s authorized", wifi, addr);
2995
2996         if (!wifi || !wifi->tethering)
2997                 return;
2998
2999         __connman_tethering_client_register(addr);
3000 }
3001
3002 static void sta_deauthorized(GSupplicantInterface *interface,
3003                                         const char *addr)
3004 {
3005         struct wifi_data *wifi = g_supplicant_interface_get_data(interface);
3006
3007         DBG("wifi %p station %s deauthorized", wifi, addr);
3008
3009         if (!wifi || !wifi->tethering)
3010                 return;
3011
3012         __connman_tethering_client_unregister(addr);
3013 }
3014
3015 static void apply_peer_services(GSupplicantPeer *peer,
3016                                 struct connman_peer *connman_peer)
3017 {
3018         const unsigned char *data;
3019         int length;
3020
3021         DBG("");
3022
3023         connman_peer_reset_services(connman_peer);
3024
3025         data = g_supplicant_peer_get_widi_ies(peer, &length);
3026         if (data) {
3027                 connman_peer_add_service(connman_peer,
3028                         CONNMAN_PEER_SERVICE_WIFI_DISPLAY, data, length);
3029         }
3030 }
3031
3032 static void peer_found(GSupplicantPeer *peer)
3033 {
3034         GSupplicantInterface *iface = g_supplicant_peer_get_interface(peer);
3035         struct wifi_data *wifi = g_supplicant_interface_get_data(iface);
3036         struct connman_peer *connman_peer;
3037         const char *identifier, *name;
3038         int ret;
3039
3040         identifier = g_supplicant_peer_get_identifier(peer);
3041         name = g_supplicant_peer_get_name(peer);
3042
3043         DBG("ident: %s", identifier);
3044
3045         connman_peer = connman_peer_get(wifi->device, identifier);
3046         if (connman_peer)
3047                 return;
3048
3049         connman_peer = connman_peer_create(identifier);
3050         connman_peer_set_name(connman_peer, name);
3051         connman_peer_set_device(connman_peer, wifi->device);
3052         apply_peer_services(peer, connman_peer);
3053
3054         ret = connman_peer_register(connman_peer);
3055         if (ret < 0 && ret != -EALREADY)
3056                 connman_peer_unref(connman_peer);
3057         else
3058                 wifi->peers = g_slist_prepend(wifi->peers, connman_peer);
3059 }
3060
3061 static void peer_lost(GSupplicantPeer *peer)
3062 {
3063         GSupplicantInterface *iface = g_supplicant_peer_get_interface(peer);
3064         struct wifi_data *wifi = g_supplicant_interface_get_data(iface);
3065         struct connman_peer *connman_peer;
3066         const char *identifier;
3067
3068         if (!wifi)
3069                 return;
3070
3071         identifier = g_supplicant_peer_get_identifier(peer);
3072
3073         DBG("ident: %s", identifier);
3074
3075         connman_peer = connman_peer_get(wifi->device, identifier);
3076         if (connman_peer) {
3077                 if (wifi->p2p_connecting &&
3078                                 wifi->pending_peer == connman_peer) {
3079                         peer_connect_timeout(wifi);
3080                 }
3081                 connman_peer_unregister(connman_peer);
3082                 connman_peer_unref(connman_peer);
3083         }
3084
3085         wifi->peers = g_slist_remove(wifi->peers, connman_peer);
3086 }
3087
3088 static void peer_changed(GSupplicantPeer *peer, GSupplicantPeerState state)
3089 {
3090         GSupplicantInterface *iface = g_supplicant_peer_get_interface(peer);
3091         struct wifi_data *wifi = g_supplicant_interface_get_data(iface);
3092         enum connman_peer_state p_state = CONNMAN_PEER_STATE_UNKNOWN;
3093         struct connman_peer *connman_peer;
3094         const char *identifier;
3095
3096         identifier = g_supplicant_peer_get_identifier(peer);
3097
3098         DBG("ident: %s", identifier);
3099
3100         if (!wifi)
3101                 return;
3102
3103         connman_peer = connman_peer_get(wifi->device, identifier);
3104         if (!connman_peer)
3105                 return;
3106
3107         switch (state) {
3108         case G_SUPPLICANT_PEER_SERVICES_CHANGED:
3109                 apply_peer_services(peer, connman_peer);
3110                 connman_peer_services_changed(connman_peer);
3111                 return;
3112         case G_SUPPLICANT_PEER_GROUP_CHANGED:
3113                 if (!g_supplicant_peer_is_in_a_group(peer))
3114                         p_state = CONNMAN_PEER_STATE_IDLE;
3115                 else
3116                         p_state = CONNMAN_PEER_STATE_CONFIGURATION;
3117                 break;
3118         case G_SUPPLICANT_PEER_GROUP_STARTED:
3119                 break;
3120         case G_SUPPLICANT_PEER_GROUP_FINISHED:
3121                 p_state = CONNMAN_PEER_STATE_IDLE;
3122                 break;
3123         case G_SUPPLICANT_PEER_GROUP_JOINED:
3124                 connman_peer_set_iface_address(connman_peer,
3125                                 g_supplicant_peer_get_iface_address(peer));
3126                 break;
3127         case G_SUPPLICANT_PEER_GROUP_DISCONNECTED:
3128                 p_state = CONNMAN_PEER_STATE_IDLE;
3129                 break;
3130         case G_SUPPLICANT_PEER_GROUP_FAILED:
3131                 if (g_supplicant_peer_has_requested_connection(peer))
3132                         p_state = CONNMAN_PEER_STATE_IDLE;
3133                 else
3134                         p_state = CONNMAN_PEER_STATE_FAILURE;
3135                 break;
3136         }
3137
3138         if (p_state == CONNMAN_PEER_STATE_CONFIGURATION ||
3139                                         p_state == CONNMAN_PEER_STATE_FAILURE) {
3140                 if (wifi->p2p_connecting
3141                                 && connman_peer == wifi->pending_peer)
3142                         peer_cancel_timeout(wifi);
3143                 else
3144                         p_state = CONNMAN_PEER_STATE_UNKNOWN;
3145         }
3146
3147         if (p_state == CONNMAN_PEER_STATE_UNKNOWN)
3148                 return;
3149
3150         if (p_state == CONNMAN_PEER_STATE_CONFIGURATION) {
3151                 GSupplicantInterface *g_iface;
3152                 struct wifi_data *g_wifi;
3153
3154                 g_iface = g_supplicant_peer_get_group_interface(peer);
3155                 if (!g_iface)
3156                         return;
3157
3158                 g_wifi = g_supplicant_interface_get_data(g_iface);
3159                 if (!g_wifi)
3160                         return;
3161
3162                 connman_peer_set_as_master(connman_peer,
3163                                         !g_supplicant_peer_is_client(peer));
3164                 connman_peer_set_sub_device(connman_peer, g_wifi->device);
3165
3166                 /*
3167                  * If wpa_supplicant didn't create a dedicated p2p-group
3168                  * interface then mark this interface as p2p_device to avoid
3169                  * scan and auto-scan are launched on it while P2P is connected.
3170                  */
3171                 if (!g_list_find(p2p_iface_list, g_wifi))
3172                         wifi->p2p_device = true;
3173         }
3174
3175         connman_peer_set_state(connman_peer, p_state);
3176 }
3177
3178 static void peer_request(GSupplicantPeer *peer)
3179 {
3180         GSupplicantInterface *iface = g_supplicant_peer_get_interface(peer);
3181         struct wifi_data *wifi = g_supplicant_interface_get_data(iface);
3182         struct connman_peer *connman_peer;
3183         const char *identifier;
3184
3185         identifier = g_supplicant_peer_get_identifier(peer);
3186
3187         DBG("ident: %s", identifier);
3188
3189         connman_peer = connman_peer_get(wifi->device, identifier);
3190         if (!connman_peer)
3191                 return;
3192
3193         connman_peer_request_connection(connman_peer);
3194 }
3195
3196 static void debug(const char *str)
3197 {
3198         if (getenv("CONNMAN_SUPPLICANT_DEBUG"))
3199                 connman_debug("%s", str);
3200 }
3201
3202 static void disconnect_reasoncode(GSupplicantInterface *interface,
3203                                 int reasoncode)
3204 {
3205         struct wifi_data *wifi = g_supplicant_interface_get_data(interface);
3206
3207         if (wifi != NULL) {
3208                 wifi->disconnect_code = reasoncode;
3209         }
3210 }
3211
3212 static void assoc_status_code(GSupplicantInterface *interface, int status_code)
3213 {
3214         struct wifi_data *wifi = g_supplicant_interface_get_data(interface);
3215
3216         if (wifi != NULL) {
3217                 wifi->assoc_code = status_code;
3218         }
3219 }
3220
3221 static const GSupplicantCallbacks callbacks = {
3222         .system_ready           = system_ready,
3223         .system_killed          = system_killed,
3224         .interface_added        = interface_added,
3225         .interface_state        = interface_state,
3226         .interface_removed      = interface_removed,
3227         .p2p_support            = p2p_support,
3228         .scan_started           = scan_started,
3229         .scan_finished          = scan_finished,
3230         .ap_create_fail         = ap_create_fail,
3231         .network_added          = network_added,
3232         .network_removed        = network_removed,
3233         .network_changed        = network_changed,
3234         .network_associated     = network_associated,
3235         .sta_authorized         = sta_authorized,
3236         .sta_deauthorized       = sta_deauthorized,
3237         .peer_found             = peer_found,
3238         .peer_lost              = peer_lost,
3239         .peer_changed           = peer_changed,
3240         .peer_request           = peer_request,
3241         .debug                  = debug,
3242         .disconnect_reasoncode  = disconnect_reasoncode,
3243         .assoc_status_code      = assoc_status_code,
3244 };
3245
3246
3247 static int tech_probe(struct connman_technology *technology)
3248 {
3249         wifi_technology = technology;
3250
3251         return 0;
3252 }
3253
3254 static void tech_remove(struct connman_technology *technology)
3255 {
3256         wifi_technology = NULL;
3257 }
3258
3259 static GSupplicantSSID *ssid_ap_init(const char *ssid, const char *passphrase)
3260 {
3261         GSupplicantSSID *ap;
3262
3263         ap = g_try_malloc0(sizeof(GSupplicantSSID));
3264         if (!ap)
3265                 return NULL;
3266
3267         ap->mode = G_SUPPLICANT_MODE_MASTER;
3268         ap->ssid = ssid;
3269         ap->ssid_len = strlen(ssid);
3270         ap->scan_ssid = 0;
3271         ap->freq = 2412;
3272
3273         if (!passphrase || strlen(passphrase) == 0) {
3274                 ap->security = G_SUPPLICANT_SECURITY_NONE;
3275                 ap->passphrase = NULL;
3276         } else {
3277                ap->security = G_SUPPLICANT_SECURITY_PSK;
3278                ap->protocol = G_SUPPLICANT_PROTO_RSN;
3279                ap->pairwise_cipher = G_SUPPLICANT_PAIRWISE_CCMP;
3280                ap->group_cipher = G_SUPPLICANT_GROUP_CCMP;
3281                ap->passphrase = passphrase;
3282         }
3283
3284         return ap;
3285 }
3286
3287 static void ap_start_callback(int result, GSupplicantInterface *interface,
3288                                                         void *user_data)
3289 {
3290         struct wifi_tethering_info *info = user_data;
3291
3292         DBG("result %d index %d bridge %s",
3293                 result, info->wifi->index, info->wifi->bridge);
3294
3295         if ((result < 0) || (info->wifi->ap_supported != WIFI_AP_SUPPORTED)) {
3296                 connman_inet_remove_from_bridge(info->wifi->index,
3297                                                         info->wifi->bridge);
3298
3299                 if (info->wifi->ap_supported == WIFI_AP_SUPPORTED) {
3300                         connman_technology_tethering_notify(info->technology, false);
3301                         g_free(info->wifi->tethering_param->ssid);
3302                         g_free(info->wifi->tethering_param);
3303                         info->wifi->tethering_param = NULL;
3304                 }
3305         }
3306
3307         g_free(info->ifname);
3308         g_free(info);
3309 }
3310
3311 static void ap_create_callback(int result,
3312                                 GSupplicantInterface *interface,
3313                                         void *user_data)
3314 {
3315         struct wifi_tethering_info *info = user_data;
3316
3317         DBG("result %d ifname %s", result,
3318                                 g_supplicant_interface_get_ifname(interface));
3319
3320         if ((result < 0) || (info->wifi->ap_supported != WIFI_AP_SUPPORTED)) {
3321                 connman_inet_remove_from_bridge(info->wifi->index,
3322                                                         info->wifi->bridge);
3323
3324                 if (info->wifi->ap_supported == WIFI_AP_SUPPORTED) {
3325                         connman_technology_tethering_notify(info->technology, false);
3326                         g_free(info->wifi->tethering_param->ssid);
3327                         g_free(info->wifi->tethering_param);
3328                         info->wifi->tethering_param = NULL;
3329
3330                 }
3331
3332                 g_free(info->ifname);
3333                 g_free(info->ssid);
3334                 g_free(info);
3335                 return;
3336         }
3337
3338         info->wifi->interface = interface;
3339         g_supplicant_interface_set_data(interface, info->wifi);
3340
3341         if (g_supplicant_interface_set_apscan(interface, 2) < 0)
3342                 connman_error("Failed to set interface ap_scan property");
3343
3344         g_supplicant_interface_connect(interface, info->ssid,
3345                                                 ap_start_callback, info);
3346 }
3347
3348 static void sta_remove_callback(int result,
3349                                 GSupplicantInterface *interface,
3350                                         void *user_data)
3351 {
3352         struct wifi_tethering_info *info = user_data;
3353         const char *driver = connman_option_get_string("wifi");
3354
3355         DBG("ifname %s result %d ", info->ifname, result);
3356
3357         if ((result < 0) || (info->wifi->ap_supported != WIFI_AP_SUPPORTED)) {
3358                 info->wifi->tethering = false;
3359                 connman_technology_tethering_notify(info->technology, false);
3360
3361                 if (info->wifi->ap_supported == WIFI_AP_SUPPORTED) {
3362                         g_free(info->wifi->tethering_param->ssid);
3363                         g_free(info->wifi->tethering_param);
3364                         info->wifi->tethering_param = NULL;
3365                 }
3366
3367                 g_free(info->ifname);
3368                 g_free(info->ssid);
3369                 g_free(info);
3370                 return;
3371         }
3372
3373         info->wifi->interface = NULL;
3374
3375         g_supplicant_interface_create(info->ifname, driver, info->wifi->bridge,
3376                                                 ap_create_callback,
3377                                                         info);
3378 }
3379
3380 static int enable_wifi_tethering(struct connman_technology *technology,
3381                                 const char *bridge, const char *identifier,
3382                                 const char *passphrase, bool available)
3383 {
3384         GList *list;
3385         GSupplicantInterface *interface;
3386         struct wifi_data *wifi;
3387         struct wifi_tethering_info *info;
3388         const char *ifname;
3389         unsigned int mode;
3390         int err, berr = 0;
3391
3392         for (list = iface_list; list; list = list->next) {
3393                 wifi = list->data;
3394
3395                 DBG("wifi %p network %p pending_network %p", wifi,
3396                         wifi->network, wifi->pending_network);
3397
3398                 interface = wifi->interface;
3399
3400                 if (!interface)
3401                         continue;
3402
3403                 ifname = g_supplicant_interface_get_ifname(wifi->interface);
3404                 if (!ifname)
3405                         continue;
3406
3407                 if (wifi->ap_supported == WIFI_AP_NOT_SUPPORTED) {
3408                         DBG("%s does not support AP mode (detected)", ifname);
3409                         continue;
3410                 }
3411
3412                 mode = g_supplicant_interface_get_mode(interface);
3413                 if ((mode & G_SUPPLICANT_CAPABILITY_MODE_AP) == 0) {
3414                         wifi->ap_supported = WIFI_AP_NOT_SUPPORTED;
3415                         DBG("%s does not support AP mode (capability)", ifname);
3416                         continue;
3417                 }
3418
3419                 if (wifi->network && available)
3420                         continue;
3421
3422                 info = g_try_malloc0(sizeof(struct wifi_tethering_info));
3423                 if (!info)
3424                         return -ENOMEM;
3425
3426                 wifi->tethering_param = g_try_malloc0(sizeof(struct wifi_tethering_info));
3427                 if (!wifi->tethering_param) {
3428                         g_free(info);
3429                         return -ENOMEM;
3430                 }
3431
3432                 info->wifi = wifi;
3433                 info->technology = technology;
3434                 info->wifi->bridge = bridge;
3435                 info->ssid = ssid_ap_init(identifier, passphrase);
3436                 if (!info->ssid)
3437                         goto failed;
3438
3439                 info->ifname = g_strdup(ifname);
3440
3441                 wifi->tethering_param->technology = technology;
3442                 wifi->tethering_param->ssid = ssid_ap_init(identifier, passphrase);
3443                 if (!wifi->tethering_param->ssid)
3444                         goto failed;
3445
3446                 info->wifi->tethering = true;
3447                 info->wifi->ap_supported = WIFI_AP_SUPPORTED;
3448
3449                 berr = connman_technology_tethering_notify(technology, true);
3450                 if (berr < 0)
3451                         goto failed;
3452
3453                 err = g_supplicant_interface_remove(interface,
3454                                                 sta_remove_callback,
3455                                                         info);
3456                 if (err >= 0) {
3457                         DBG("tethering wifi %p ifname %s", wifi, ifname);
3458                         return 0;
3459                 }
3460
3461         failed:
3462                 g_free(info->ifname);
3463                 g_free(info->ssid);
3464                 g_free(info);
3465                 g_free(wifi->tethering_param);
3466                 wifi->tethering_param = NULL;
3467
3468                 /*
3469                  * Remove bridge if it was correctly created but remove
3470                  * operation failed. Instead, if bridge creation failed then
3471                  * break out and do not try again on another interface,
3472                  * bridge set-up does not depend on it.
3473                  */
3474                 if (berr == 0)
3475                         connman_technology_tethering_notify(technology, false);
3476                 else
3477                         break;
3478         }
3479
3480         return -EOPNOTSUPP;
3481 }
3482
3483 static int tech_set_tethering(struct connman_technology *technology,
3484                                 const char *identifier, const char *passphrase,
3485                                 const char *bridge, bool enabled)
3486 {
3487         GList *list;
3488         struct wifi_data *wifi;
3489         int err;
3490
3491         DBG("");
3492
3493         if (!enabled) {
3494                 for (list = iface_list; list; list = list->next) {
3495                         wifi = list->data;
3496
3497                         if (wifi->tethering) {
3498                                 wifi->tethering = false;
3499
3500                                 connman_inet_remove_from_bridge(wifi->index,
3501                                                                         bridge);
3502                                 wifi->bridged = false;
3503                         }
3504                 }
3505
3506                 connman_technology_tethering_notify(technology, false);
3507
3508                 return 0;
3509         }
3510
3511         DBG("trying tethering for available devices");
3512         err = enable_wifi_tethering(technology, bridge, identifier, passphrase,
3513                                 true);
3514
3515         if (err < 0) {
3516                 DBG("trying tethering for any device");
3517                 err = enable_wifi_tethering(technology, bridge, identifier,
3518                                         passphrase, false);
3519         }
3520
3521         return err;
3522 }
3523
3524 static void regdom_callback(int result, const char *alpha2, void *user_data)
3525 {
3526         DBG("");
3527
3528         if (!wifi_technology)
3529                 return;
3530
3531         if (result != 0)
3532                 alpha2 = NULL;
3533
3534         connman_technology_regdom_notify(wifi_technology, alpha2);
3535 }
3536
3537 static int tech_set_regdom(struct connman_technology *technology, const char *alpha2)
3538 {
3539         return g_supplicant_set_country(alpha2, regdom_callback, NULL);
3540 }
3541
3542 static struct connman_technology_driver tech_driver = {
3543         .name           = "wifi",
3544         .type           = CONNMAN_SERVICE_TYPE_WIFI,
3545         .probe          = tech_probe,
3546         .remove         = tech_remove,
3547         .set_tethering  = tech_set_tethering,
3548         .set_regdom     = tech_set_regdom,
3549 };
3550
3551 static int wifi_init(void)
3552 {
3553         int err;
3554
3555         err = connman_network_driver_register(&network_driver);
3556         if (err < 0)
3557                 return err;
3558
3559         err = g_supplicant_register(&callbacks);
3560         if (err < 0) {
3561                 connman_network_driver_unregister(&network_driver);
3562                 return err;
3563         }
3564
3565         err = connman_technology_driver_register(&tech_driver);
3566         if (err < 0) {
3567                 g_supplicant_unregister(&callbacks);
3568                 connman_network_driver_unregister(&network_driver);
3569                 return err;
3570         }
3571
3572         return 0;
3573 }
3574
3575 static void wifi_exit(void)
3576 {
3577         DBG();
3578
3579         connman_technology_driver_unregister(&tech_driver);
3580
3581         g_supplicant_unregister(&callbacks);
3582
3583         connman_network_driver_unregister(&network_driver);
3584 }
3585
3586 CONNMAN_PLUGIN_DEFINE(wifi, "WiFi interface plugin", VERSION,
3587                 CONNMAN_PLUGIN_PRIORITY_DEFAULT, wifi_init, wifi_exit)