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