Implement WiFi network driver remove hook
[framework/connectivity/connman.git] / plugins / supplicant.c
1 /*
2  *
3  *  Connection Manager
4  *
5  *  Copyright (C) 2007-2010  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 <stdio.h>
27 #include <unistd.h>
28 #include <errno.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <sys/ioctl.h>
32 #include <sys/socket.h>
33 #include <linux/if_arp.h>
34 #include <linux/wireless.h>
35 #include <net/ethernet.h>
36
37 #include <gdbus.h>
38
39 #define CONNMAN_API_SUBJECT_TO_CHANGE
40 #include <connman/device.h>
41 #include <connman/option.h>
42 #include <connman/inet.h>
43 #include <connman/dbus.h>
44 #include <connman/wifi.h>
45 #include <connman/log.h>
46
47 #include "supplicant.h"
48
49 #define TIMEOUT 5000
50
51 #define IEEE80211_CAP_ESS       0x0001
52 #define IEEE80211_CAP_IBSS      0x0002
53 #define IEEE80211_CAP_PRIVACY   0x0010
54
55 #define SUPPLICANT_NAME  "fi.epitest.hostap.WPASupplicant"
56 #define SUPPLICANT_INTF  "fi.epitest.hostap.WPASupplicant"
57 #define SUPPLICANT_PATH  "/fi/epitest/hostap/WPASupplicant"
58
59 /* Taken from "WPA Supplicant - Common definitions" */
60 enum supplicant_state {
61         /**
62          * WPA_DISCONNECTED - Disconnected state
63          *
64          * This state indicates that client is not associated, but is likely to
65          * start looking for an access point. This state is entered when a
66          * connection is lost.
67          */
68         WPA_DISCONNECTED,
69
70         /**
71          * WPA_INACTIVE - Inactive state (wpa_supplicant disabled)
72          *
73          * This state is entered if there are no enabled networks in the
74          * configuration. wpa_supplicant is not trying to associate with a new
75          * network and external interaction (e.g., ctrl_iface call to add or
76          * enable a network) is needed to start association.
77          */
78         WPA_INACTIVE,
79
80         /**
81          * WPA_SCANNING - Scanning for a network
82          *
83          * This state is entered when wpa_supplicant starts scanning for a
84          * network.
85          */
86         WPA_SCANNING,
87
88         /**
89          * WPA_ASSOCIATING - Trying to associate with a BSS/SSID
90          *
91          * This state is entered when wpa_supplicant has found a suitable BSS
92          * to associate with and the driver is configured to try to associate
93          * with this BSS in ap_scan=1 mode. When using ap_scan=2 mode, this
94          * state is entered when the driver is configured to try to associate
95          * with a network using the configured SSID and security policy.
96          */
97         WPA_ASSOCIATING,
98
99         /**
100          * WPA_ASSOCIATED - Association completed
101          *
102          * This state is entered when the driver reports that association has
103          * been successfully completed with an AP. If IEEE 802.1X is used
104          * (with or without WPA/WPA2), wpa_supplicant remains in this state
105          * until the IEEE 802.1X/EAPOL authentication has been completed.
106          */
107         WPA_ASSOCIATED,
108
109         /**
110          * WPA_4WAY_HANDSHAKE - WPA 4-Way Key Handshake in progress
111          *
112          * This state is entered when WPA/WPA2 4-Way Handshake is started. In
113          * case of WPA-PSK, this happens when receiving the first EAPOL-Key
114          * frame after association. In case of WPA-EAP, this state is entered
115          * when the IEEE 802.1X/EAPOL authentication has been completed.
116          */
117         WPA_4WAY_HANDSHAKE,
118
119         /**
120          * WPA_GROUP_HANDSHAKE - WPA Group Key Handshake in progress
121          *
122          * This state is entered when 4-Way Key Handshake has been completed
123          * (i.e., when the supplicant sends out message 4/4) and when Group
124          * Key rekeying is started by the AP (i.e., when supplicant receives
125          * message 1/2).
126          */
127         WPA_GROUP_HANDSHAKE,
128
129         /**
130          * WPA_COMPLETED - All authentication completed
131          *
132          * This state is entered when the full authentication process is
133          * completed. In case of WPA2, this happens when the 4-Way Handshake is
134          * successfully completed. With WPA, this state is entered after the
135          * Group Key Handshake; with IEEE 802.1X (non-WPA) connection is
136          * completed after dynamic keys are received (or if not used, after
137          * the EAP authentication has been completed). With static WEP keys and
138          * plaintext connections, this state is entered when an association
139          * has been completed.
140          *
141          * This state indicates that the supplicant has completed its
142          * processing for the association phase and that data connection is
143          * fully configured.
144          */
145         WPA_COMPLETED,
146
147         /**
148          * WPA_INVALID - Invalid state (parsing error)
149          *
150          * This state is returned if the string input is invalid. It is not
151          * an official wpa_supplicant state.
152          */
153         WPA_INVALID,
154 };
155
156 struct supplicant_result {
157         char *path;
158         char *name;
159         unsigned char *addr;
160         unsigned int addr_len;
161         unsigned char *ssid;
162         unsigned int ssid_len;
163         dbus_uint16_t capabilities;
164         gboolean adhoc;
165         gboolean has_wep;
166         gboolean has_psk;
167         gboolean has_8021x;
168         gboolean has_wpa;
169         gboolean has_rsn;
170         gboolean has_wps;
171         dbus_int32_t frequency;
172         dbus_int32_t quality;
173         dbus_int32_t noise;
174         dbus_int32_t level;
175         dbus_int32_t maxrate;
176 };
177
178 struct supplicant_block {
179         unsigned char *ssid;
180         char *netpath;
181         gboolean enabled;
182         int num_scans;
183 };
184
185 struct supplicant_task {
186         int ifindex;
187         char *ifname;
188         gboolean cfg80211;
189         struct connman_device *device;
190         struct connman_network *network;
191         struct connman_network *pending_network;
192         char *path;
193         char *netpath;
194         gboolean hidden_found;
195         GHashTable *hidden_blocks;
196         gboolean created;
197         enum supplicant_state state;
198         gboolean scanning;
199         GSList *scan_results;
200         DBusPendingCall *scan_call;
201         DBusPendingCall *result_call;
202         struct iw_range *range;
203         gboolean disconnecting;
204 };
205
206 static GSList *task_list = NULL;
207
208 static DBusConnection *connection;
209
210 static void free_task(struct supplicant_task *task)
211 {
212         DBG("task %p", task);
213
214         g_free(task->ifname);
215         g_free(task->path);
216         g_free(task);
217 }
218
219 static void remove_block(gpointer user_data)
220 {
221         struct supplicant_block *block = user_data;
222
223         DBG("");
224
225         g_free(block->ssid);
226         g_free(block->netpath);
227 }
228
229 static struct supplicant_task *find_task_by_index(int index)
230 {
231         GSList *list;
232
233         for (list = task_list; list; list = list->next) {
234                 struct supplicant_task *task = list->data;
235
236                 if (task->ifindex == index)
237                         return task;
238         }
239
240         return NULL;
241 }
242
243 static struct supplicant_task *find_task_by_path(const char *path)
244 {
245         GSList *list;
246
247         for (list = task_list; list; list = list->next) {
248                 struct supplicant_task *task = list->data;
249
250                 if (g_strcmp0(task->path, path) == 0)
251                         return task;
252         }
253
254         return NULL;
255 }
256
257 static int get_range(struct supplicant_task *task)
258 {
259         struct iwreq wrq;
260         int fd, err;
261
262         fd = socket(PF_INET, SOCK_DGRAM, 0);
263         if (fd < 0)
264                 return -1;
265
266         memset(&wrq, 0, sizeof(struct iwreq));
267         strncpy(wrq.ifr_name, task->ifname, IFNAMSIZ);
268         wrq.u.data.pointer = task->range;
269         wrq.u.data.length = sizeof(struct iw_range);
270
271         err = ioctl(fd, SIOCGIWRANGE, &wrq);
272
273         close(fd);
274
275         if (err < 0)
276                 task->range->max_qual.updated |= IW_QUAL_ALL_INVALID;
277
278         connman_info("%s {scan} capabilities 0x%02x", task->ifname,
279                                                 task->range->scan_capa);
280
281         connman_info("%s {quality} flags 0x%02x", task->ifname,
282                                         task->range->max_qual.updated);
283
284         return err;
285 }
286
287 static int get_bssid(struct connman_device *device,
288                                 unsigned char *bssid, unsigned int *bssid_len)
289 {
290         struct iwreq wrq;
291         char *ifname;
292         int ifindex;
293         int fd, err;
294
295         ifindex = connman_device_get_index(device);
296         if (ifindex < 0)
297                 return -EINVAL;
298
299         ifname = connman_inet_ifname(ifindex);
300         if (ifname == NULL)
301                 return -EINVAL;
302
303         fd = socket(PF_INET, SOCK_DGRAM, 0);
304         if (fd < 0) {
305                 g_free(ifname);
306                 return -EINVAL;
307         }
308
309         memset(&wrq, 0, sizeof(wrq));
310         strncpy(wrq.ifr_name, ifname, IFNAMSIZ);
311
312         err = ioctl(fd, SIOCGIWAP, &wrq);
313
314         g_free(ifname);
315         close(fd);
316
317         if (err < 0)
318                 return -EIO;
319
320         memcpy(bssid, wrq.u.ap_addr.sa_data, ETH_ALEN);
321         *bssid_len = ETH_ALEN;
322
323         return 0;
324 }
325
326 static int enable_network(struct supplicant_task *task, const char *netpath,
327                           connman_bool_t enable)
328 {
329         DBusMessage *message, *reply;
330         DBusError error;
331         char *enable_string;
332
333         DBG("enable %d", enable);
334
335         enable_string = enable ? "enable" : "disable";
336
337         message = dbus_message_new_method_call(SUPPLICANT_NAME, netpath,
338                                 SUPPLICANT_INTF ".Network", enable_string);
339         if (message == NULL)
340                 return -ENOMEM;
341
342         dbus_message_set_auto_start(message, FALSE);
343
344         dbus_error_init(&error);
345
346         reply = dbus_connection_send_with_reply_and_block(connection,
347                                                         message, -1, &error);
348         if (reply == NULL) {
349                 if (dbus_error_is_set(&error) == TRUE) {
350                         connman_error("%s", error.message);
351                         dbus_error_free(&error);
352                 } else
353                         connman_error("Failed to select network");
354                 dbus_message_unref(message);
355                 return -EIO;
356         }
357
358         dbus_message_unref(reply);
359
360         dbus_message_unref(message);
361
362         return 0;
363 }
364
365 static int set_hidden_network(struct supplicant_task *task, const char *netpath,
366                                 const unsigned char *ssid, int ssid_len)
367 {
368         DBusMessage *message, *reply;
369         DBusMessageIter array, dict;
370         DBusError error;
371         dbus_uint32_t scan_ssid = 1;
372         const char *invalid_address = "ff:ff:ff:ff:ff:ff";
373
374         message = dbus_message_new_method_call(SUPPLICANT_NAME, netpath,
375                                         SUPPLICANT_INTF ".Network", "set");
376         if (message == NULL)
377                 return -ENOMEM;
378
379         dbus_message_set_auto_start(message, FALSE);
380
381         dbus_message_iter_init_append(message, &array);
382
383         connman_dbus_dict_open(&array, &dict);
384
385         connman_dbus_dict_append_basic(&dict, "scan_ssid",
386                                          DBUS_TYPE_UINT32, &scan_ssid);
387
388         connman_dbus_dict_append_fixed_array(&dict, "ssid",
389                                         DBUS_TYPE_BYTE, &ssid, ssid_len);
390
391         /*
392          * We're setting an invalid BSSID to prevent wpa_s from associating
393          * automatically to this block once it's found.
394          */
395         connman_dbus_dict_append_basic(&dict, "bssid",
396                                         DBUS_TYPE_STRING, &invalid_address);
397
398         connman_dbus_dict_close(&array, &dict);
399
400         dbus_error_init(&error);
401
402         reply = dbus_connection_send_with_reply_and_block(connection,
403                                                         message, -1, &error);
404         if (reply == NULL) {
405                 if (dbus_error_is_set(&error) == TRUE) {
406                         connman_error("%s", error.message);
407                         dbus_error_free(&error);
408                 } else
409                         connman_error("Failed to set network options");
410                 dbus_message_unref(message);
411                 return -EIO;
412         }
413
414         dbus_message_unref(reply);
415
416         dbus_message_unref(message);
417
418         return 0;
419 }
420
421 static void block_reset(gpointer key, gpointer value, gpointer user_data)
422 {
423         struct supplicant_block *block = value;
424         struct supplicant_task *task = user_data;
425
426         block->num_scans = 0;
427         if (block->enabled)
428                 enable_network(task, block->netpath, FALSE);
429
430         block->enabled = FALSE;
431 }
432
433 #define MAX_BLOCK_SCANS 2
434 static void hidden_block_enable(struct supplicant_task *task)
435 {
436         GHashTableIter iter;
437         gpointer key, value;
438         struct supplicant_block *block;
439
440         DBG("network %p", task->network);
441
442         if (g_hash_table_size(task->hidden_blocks) == 0)
443                 return;
444
445         /*
446          * If we're associated or associating, we no longer need to
447          * look for hidden networks.
448          */
449         if (task->network)
450                 return;
451
452         /*
453          * We go through the block list and:
454          * - If we scanned it more than twice, we disable it and move
455          *   on to the next block.
456          * - If the next block is not enabled, we enable it, start
457          *   the scan counter, and return. This routine will be called
458          *   again when the next scan results are available.
459          * - If we're done with all the blocks there, we just reset them.
460          */
461         g_hash_table_iter_init(&iter, task->hidden_blocks);
462         while (g_hash_table_iter_next(&iter, &key, &value)) {
463                 block = value;
464
465                 DBG("%s num of scans %d enabled %d",
466                         block->ssid, block->num_scans, block->enabled);
467
468                 if (block->num_scans > MAX_BLOCK_SCANS) {
469                         if (block->enabled == FALSE)
470                                 continue;
471
472                         enable_network(task, block->netpath, FALSE);
473                         block->enabled = FALSE;
474                         continue;
475                 }
476
477                 if (block->enabled == FALSE) {
478                         enable_network(task, block->netpath, TRUE);
479                         block->enabled = TRUE;
480                 }
481
482                 block->num_scans++;
483
484                 return;
485         }
486
487         g_hash_table_foreach(task->hidden_blocks, block_reset, task);
488 }
489
490 static int add_hidden_network(struct supplicant_task *task,
491                                 const unsigned char *ssid, int ssid_len)
492 {
493         DBusMessage *message, *reply;
494         DBusError error;
495         const char *path;
496         struct supplicant_block *block;
497         char *netpath = NULL;
498         int ret, i;
499
500         DBG("task %p", task);
501
502         message = dbus_message_new_method_call(SUPPLICANT_NAME, task->path,
503                                 SUPPLICANT_INTF ".Interface", "addNetwork");
504         if (message == NULL)
505                 return -ENOMEM;
506
507         dbus_message_set_auto_start(message, FALSE);
508
509         dbus_error_init(&error);
510
511         reply = dbus_connection_send_with_reply_and_block(connection,
512                                                         message, -1, &error);
513         if (reply == NULL) {
514                 if (dbus_error_is_set(&error) == TRUE) {
515                         connman_error("%s", error.message);
516                         dbus_error_free(&error);
517                 } else
518                         connman_error("Failed to add network");
519                 dbus_message_unref(message);
520                 return -EIO;
521         }
522
523         dbus_error_init(&error);
524
525         if (dbus_message_get_args(reply, &error, DBUS_TYPE_OBJECT_PATH, &path,
526                                                 DBUS_TYPE_INVALID) == FALSE) {
527                 if (dbus_error_is_set(&error) == TRUE) {
528                         connman_error("%s", error.message);
529                         dbus_error_free(&error);
530                 } else
531                         connman_error("Wrong arguments for network");
532                 dbus_message_unref(reply);
533                 return -EIO;
534         }
535
536         netpath = g_strdup(path);
537
538         ret = set_hidden_network(task, netpath, ssid, ssid_len);
539         if (ret < 0)
540                 goto done;
541
542         block = g_try_new0(struct supplicant_block, 1);
543         if (block == NULL)
544                 goto done;
545
546         block->ssid = g_try_malloc0(ssid_len + 1);
547         if (block->ssid == NULL) {
548                 g_free(block);
549                 goto done;
550         }
551
552         for (i = 0; i < ssid_len; i++) {
553                 if (g_ascii_isprint(ssid[i]))
554                         block->ssid[i] = ssid[i];
555                 else
556                         block->ssid[i] = ' ';
557         }
558
559         block->netpath = netpath;
560         block->enabled = FALSE;
561         block->num_scans = 0;
562
563         DBG("path %s ssid %s", block->netpath, block->ssid);
564
565         g_hash_table_replace(task->hidden_blocks, block->ssid, block);
566
567         return 0;
568 done:
569         g_free(netpath);
570
571         dbus_message_unref(reply);
572
573         dbus_message_unref(message);
574
575         return ret;
576 }
577
578 static void add_interface_reply(DBusPendingCall *call, void *user_data)
579 {
580         struct supplicant_task *task = user_data;
581         DBusMessage *reply;
582         DBusError error;
583         const char *path;
584         char **hex_ssids, *hex_ssid;
585         int i;
586
587         DBG("task %p", task);
588
589         reply = dbus_pending_call_steal_reply(call);
590
591         if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR)
592                 goto failed;
593
594         dbus_error_init(&error);
595
596         if (dbus_message_get_args(reply, &error, DBUS_TYPE_OBJECT_PATH, &path,
597                                                 DBUS_TYPE_INVALID) == FALSE) {
598                 if (dbus_error_is_set(&error) == TRUE) {
599                         connman_error("%s", error.message);
600                         dbus_error_free(&error);
601                 } else
602                         connman_error("Wrong arguments for add interface");
603                 goto failed;
604         }
605
606         DBG("path %s", path);
607
608         task->path = g_strdup(path);
609         task->created = TRUE;
610
611         connman_device_set_powered(task->device, TRUE);
612
613         dbus_message_unref(reply);
614
615         dbus_pending_call_unref(call);
616
617         hex_ssids = connman_wifi_load_ssid();
618         if (hex_ssids == NULL)
619                 return;
620
621         for (i = 0; hex_ssids[i]; i++) {
622                 unsigned char *ssid;
623                 unsigned int j, k = 0, hex;
624                 size_t hex_ssid_len;
625
626                 hex_ssid = hex_ssids[i];
627                 hex_ssid_len = strlen(hex_ssid);
628
629                 ssid = g_try_malloc0(hex_ssid_len / 2 + 1);
630                 if (ssid == NULL)
631                         break;
632
633                 for (j = 0, k = 0; j < hex_ssid_len; j += 2) {
634                         sscanf(hex_ssid + j, "%02x", &hex);
635                         ssid[k++] = hex;
636                 }
637
638                 if (add_hidden_network(task, ssid, hex_ssid_len / 2) < 0)
639                         break;
640         }
641
642         g_strfreev(hex_ssids);
643
644         return;
645
646 failed:
647         dbus_message_unref(reply);
648
649         dbus_pending_call_unref(call);
650
651         task_list = g_slist_remove(task_list, task);
652
653         connman_device_unref(task->device);
654
655         free_task(task);
656 }
657
658 static int add_interface(struct supplicant_task *task)
659 {
660         const char *driver = connman_option_get_string("wifi");
661         DBusMessage *message;
662         DBusMessageIter array, dict;
663         DBusPendingCall *call;
664
665         DBG("task %p", task);
666
667         message = dbus_message_new_method_call(SUPPLICANT_NAME, SUPPLICANT_PATH,
668                                         SUPPLICANT_INTF, "addInterface");
669         if (message == NULL)
670                 return -ENOMEM;
671
672         dbus_message_set_auto_start(message, FALSE);
673
674         dbus_message_iter_init_append(message, &array);
675
676         dbus_message_iter_append_basic(&array,
677                                         DBUS_TYPE_STRING, &task->ifname);
678
679         connman_dbus_dict_open(&array, &dict);
680
681         connman_dbus_dict_append_basic(&dict, "driver",
682                                                 DBUS_TYPE_STRING, &driver);
683
684         connman_dbus_dict_close(&array, &dict);
685
686         if (dbus_connection_send_with_reply(connection, message,
687                                                 &call, TIMEOUT) == FALSE) {
688                 connman_error("Failed to add interface");
689                 dbus_message_unref(message);
690                 return -EIO;
691         }
692
693         if (call == NULL) {
694                 connman_error("D-Bus connection not available");
695                 dbus_message_unref(message);
696                 return -EIO;
697         }
698
699         dbus_pending_call_set_notify(call, add_interface_reply, task, NULL);
700
701         dbus_message_unref(message);
702
703         return -EINPROGRESS;
704 }
705
706 static void get_interface_reply(DBusPendingCall *call, void *user_data)
707 {
708         struct supplicant_task *task = user_data;
709         DBusMessage *reply;
710         DBusError error;
711         const char *path;
712
713         DBG("task %p", task);
714
715         reply = dbus_pending_call_steal_reply(call);
716
717         if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR) {
718                 add_interface(task);
719                 goto done;
720         }
721
722         dbus_error_init(&error);
723
724         if (dbus_message_get_args(reply, &error, DBUS_TYPE_OBJECT_PATH, &path,
725                                                 DBUS_TYPE_INVALID) == FALSE) {
726                 if (dbus_error_is_set(&error) == TRUE) {
727                         connman_error("%s", error.message);
728                         dbus_error_free(&error);
729                 } else
730                         connman_error("Wrong arguments for get interface");
731                 goto done;
732         }
733
734         DBG("path %s", path);
735
736         task->path = g_strdup(path);
737         task->created = FALSE;
738
739         connman_device_set_powered(task->device, TRUE);
740
741 done:
742         dbus_message_unref(reply);
743
744         dbus_pending_call_unref(call);
745 }
746
747 static int create_interface(struct supplicant_task *task)
748 {
749         DBusMessage *message;
750         DBusPendingCall *call;
751
752         DBG("task %p", task);
753
754         message = dbus_message_new_method_call(SUPPLICANT_NAME, SUPPLICANT_PATH,
755                                         SUPPLICANT_INTF, "getInterface");
756         if (message == NULL)
757                 return -ENOMEM;
758
759         dbus_message_set_auto_start(message, FALSE);
760
761         dbus_message_append_args(message, DBUS_TYPE_STRING, &task->ifname,
762                                                         DBUS_TYPE_INVALID);
763
764         if (dbus_connection_send_with_reply(connection, message,
765                                                 &call, TIMEOUT) == FALSE) {
766                 connman_error("Failed to get interface");
767                 dbus_message_unref(message);
768                 return -EIO;
769         }
770
771         if (call == NULL) {
772                 connman_error("D-Bus connection not available");
773                 dbus_message_unref(message);
774                 return -EIO;
775         }
776
777         dbus_pending_call_set_notify(call, get_interface_reply, task, NULL);
778
779         dbus_message_unref(message);
780
781         return -EINPROGRESS;
782 }
783
784 static void remove_interface_reply(DBusPendingCall *call, void *user_data)
785 {
786         struct supplicant_task *task = user_data;
787         DBusMessage *reply;
788
789         DBG("task %p", task);
790
791         reply = dbus_pending_call_steal_reply(call);
792
793         connman_device_set_powered(task->device, FALSE);
794
795         connman_device_unref(task->device);
796
797         connman_inet_ifdown(task->ifindex);
798
799         free_task(task);
800
801         dbus_message_unref(reply);
802
803         dbus_pending_call_unref(call);
804 }
805
806 static int remove_interface(struct supplicant_task *task)
807 {
808         DBusMessage *message;
809         DBusPendingCall *call;
810
811         DBG("task %p", task);
812
813         if (task->path == NULL)
814                 return 0;
815
816 #if 0
817         if (task->created == FALSE) {
818                 connman_device_set_powered(task->device, FALSE);
819                 return 0;
820         }
821 #endif
822
823         message = dbus_message_new_method_call(SUPPLICANT_NAME, SUPPLICANT_PATH,
824                                         SUPPLICANT_INTF, "removeInterface");
825         if (message == NULL)
826                 return -ENOMEM;
827
828         dbus_message_set_auto_start(message, FALSE);
829
830         dbus_message_append_args(message, DBUS_TYPE_OBJECT_PATH, &task->path,
831                                                         DBUS_TYPE_INVALID);
832
833         if (dbus_connection_send_with_reply(connection, message,
834                                                 &call, TIMEOUT) == FALSE) {
835                 connman_error("Failed to remove interface");
836                 dbus_message_unref(message);
837                 return -EIO;
838         }
839
840         if (call == NULL) {
841                 connman_error("D-Bus connection not available");
842                 dbus_message_unref(message);
843                 return -EIO;
844         }
845
846         dbus_pending_call_set_notify(call, remove_interface_reply, task, NULL);
847
848         dbus_message_unref(message);
849
850         return -EINPROGRESS;
851 }
852
853 static int set_ap_scan(struct supplicant_task *task)
854 {
855         DBusMessage *message, *reply;
856         DBusError error;
857         guint32 ap_scan = 1;
858
859         DBG("task %p", task);
860
861         message = dbus_message_new_method_call(SUPPLICANT_NAME, task->path,
862                                 SUPPLICANT_INTF ".Interface", "setAPScan");
863         if (message == NULL)
864                 return -ENOMEM;
865
866         dbus_message_set_auto_start(message, FALSE);
867
868         dbus_message_append_args(message, DBUS_TYPE_UINT32, &ap_scan,
869                                                         DBUS_TYPE_INVALID);
870
871         dbus_error_init(&error);
872
873         reply = dbus_connection_send_with_reply_and_block(connection,
874                                                         message, -1, &error);
875         if (reply == NULL) {
876                 if (dbus_error_is_set(&error) == TRUE) {
877                         connman_error("%s", error.message);
878                         dbus_error_free(&error);
879                 } else
880                         connman_error("Failed to set AP scan");
881                 dbus_message_unref(message);
882                 return -EIO;
883         }
884
885         dbus_message_unref(message);
886
887         dbus_message_unref(reply);
888
889         return 0;
890 }
891
892 static int add_network(struct supplicant_task *task)
893 {
894         DBusMessage *message, *reply;
895         DBusError error;
896         const char *path;
897
898         DBG("task %p", task);
899
900         if (task->netpath != NULL)
901                 return -EALREADY;
902
903         message = dbus_message_new_method_call(SUPPLICANT_NAME, task->path,
904                                 SUPPLICANT_INTF ".Interface", "addNetwork");
905         if (message == NULL)
906                 return -ENOMEM;
907
908         dbus_message_set_auto_start(message, FALSE);
909
910         dbus_error_init(&error);
911
912         reply = dbus_connection_send_with_reply_and_block(connection,
913                                                         message, -1, &error);
914         if (reply == NULL) {
915                 if (dbus_error_is_set(&error) == TRUE) {
916                         connman_error("%s", error.message);
917                         dbus_error_free(&error);
918                 } else
919                         connman_error("Failed to add network");
920                 dbus_message_unref(message);
921                 return -EIO;
922         }
923
924         dbus_message_unref(message);
925
926         dbus_error_init(&error);
927
928         if (dbus_message_get_args(reply, &error, DBUS_TYPE_OBJECT_PATH, &path,
929                                                 DBUS_TYPE_INVALID) == FALSE) {
930                 if (dbus_error_is_set(&error) == TRUE) {
931                         connman_error("%s", error.message);
932                         dbus_error_free(&error);
933                 } else
934                         connman_error("Wrong arguments for network");
935                 dbus_message_unref(reply);
936                 return -EIO;
937         }
938
939         DBG("path %s", path);
940
941         task->netpath = g_strdup(path);
942
943         dbus_message_unref(reply);
944
945         return 0;
946 }
947
948 static int remove_network(struct supplicant_task *task)
949 {
950         DBusMessage *message, *reply;
951         DBusError error;
952
953         DBG("task %p", task);
954
955         if (task->netpath == NULL || task->path == NULL)
956                 return -EINVAL;
957
958         message = dbus_message_new_method_call(SUPPLICANT_NAME, task->path,
959                                 SUPPLICANT_INTF ".Interface", "removeNetwork");
960         if (message == NULL)
961                 return -ENOMEM;
962
963         dbus_message_set_auto_start(message, FALSE);
964
965         dbus_message_append_args(message, DBUS_TYPE_OBJECT_PATH, &task->netpath,
966                                                         DBUS_TYPE_INVALID);
967
968         dbus_error_init(&error);
969
970         reply = dbus_connection_send_with_reply_and_block(connection,
971                                                         message, -1, &error);
972         if (reply == NULL) {
973                 if (dbus_error_is_set(&error) == TRUE) {
974                         connman_error("%s", error.message);
975                         dbus_error_free(&error);
976                 } else
977                         connman_error("Failed to remove network");
978                 dbus_message_unref(message);
979                 return -EIO;
980         }
981
982         dbus_message_unref(message);
983
984         dbus_message_unref(reply);
985
986         g_free(task->netpath);
987         task->netpath = NULL;
988
989         return 0;
990 }
991
992 static int select_network(struct supplicant_task *task)
993 {
994         DBusMessage *message, *reply;
995         DBusError error;
996
997         DBG("task %p", task);
998
999         if (task->netpath == NULL)
1000                 return -EINVAL;
1001
1002         message = dbus_message_new_method_call(SUPPLICANT_NAME, task->path,
1003                                 SUPPLICANT_INTF ".Interface", "selectNetwork");
1004         if (message == NULL)
1005                 return -ENOMEM;
1006
1007         dbus_message_set_auto_start(message, FALSE);
1008
1009         dbus_message_append_args(message, DBUS_TYPE_OBJECT_PATH, &task->netpath,
1010                                                         DBUS_TYPE_INVALID);
1011
1012         dbus_error_init(&error);
1013
1014         reply = dbus_connection_send_with_reply_and_block(connection,
1015                                                         message, -1, &error);
1016         if (reply == NULL) {
1017                 if (dbus_error_is_set(&error) == TRUE) {
1018                         connman_error("%s", error.message);
1019                         dbus_error_free(&error);
1020                 } else
1021                         connman_error("Failed to select network");
1022                 dbus_message_unref(message);
1023                 return -EIO;
1024         }
1025
1026         dbus_message_unref(message);
1027
1028         dbus_message_unref(reply);
1029
1030         return 0;
1031 }
1032
1033 static int disconnect_network(struct supplicant_task *task)
1034 {
1035         DBusMessage *message, *reply;
1036         DBusError error;
1037
1038         DBG("task %p", task);
1039
1040         if (task->path == NULL)
1041                 return -EINVAL;
1042
1043         message = dbus_message_new_method_call(SUPPLICANT_NAME, task->path,
1044                                 SUPPLICANT_INTF ".Interface", "disconnect");
1045         if (message == NULL)
1046                 return -ENOMEM;
1047
1048         dbus_message_set_auto_start(message, FALSE);
1049
1050         dbus_error_init(&error);
1051
1052         reply = dbus_connection_send_with_reply_and_block(connection,
1053                                                         message, -1, &error);
1054         if (reply == NULL) {
1055                 if (dbus_error_is_set(&error) == TRUE) {
1056                         connman_error("%s", error.message);
1057                         dbus_error_free(&error);
1058                 } else
1059                         connman_error("Failed to disconnect network");
1060                 dbus_message_unref(message);
1061                 return -EIO;
1062         }
1063
1064         dbus_message_unref(message);
1065
1066         dbus_message_unref(reply);
1067
1068         return 0;
1069 }
1070
1071 static int set_network_tls(struct connman_network *network,
1072                            DBusMessageIter *dict)
1073 {
1074         const char *private_key, *client_cert, *ca_cert;
1075         const char *private_key_password;
1076
1077         /*
1078          * For TLS, we at least need:
1079          *              The client certificate
1080          *              The client private key file
1081          *              The client private key file password
1082          *
1083          * The Authority certificate is optional.
1084          */
1085         client_cert = connman_network_get_string(network,
1086                                                 "WiFi.ClientCertFile");
1087         if (client_cert == NULL) {
1088                 connman_error("Error in TLS authentication: "
1089                               "a ClientCertFile must be defined\n");
1090                 return -EINVAL;
1091         }
1092
1093         private_key = connman_network_get_string(network,
1094                                                 "WiFi.PrivateKeyFile");
1095         if (private_key == NULL) {
1096                 connman_error("Error in TLS authentication: "
1097                               "a PrivateKeyFile must be defined\n");
1098                 return -EINVAL;
1099         }
1100
1101         private_key_password = connman_network_get_string(network,
1102                                                 "WiFi.PrivateKeyPassphrase");
1103         if (private_key_password == NULL) {
1104                 connman_error("Error in TLS authentication: "
1105                               "a PrivateKeyPassphrase must be defined\n");
1106                 return -EINVAL;
1107         }
1108
1109         ca_cert = connman_network_get_string(network, "WiFi.CACertFile");
1110         if (ca_cert)
1111                 connman_dbus_dict_append_basic(dict, "ca_cert",
1112                                                 DBUS_TYPE_STRING, &ca_cert);
1113         else
1114                 connman_info("No CACertFile has been provided "
1115                              "to do the TLS authentication\n");
1116
1117         DBG("client cert %s private key %s", client_cert, private_key);
1118
1119         connman_dbus_dict_append_basic(dict, "private_key",
1120                                                 DBUS_TYPE_STRING, &private_key);
1121         connman_dbus_dict_append_basic(dict, "private_key_passwd",
1122                                                         DBUS_TYPE_STRING,
1123                                                         &private_key_password);
1124         connman_dbus_dict_append_basic(dict, "client_cert",
1125                                                 DBUS_TYPE_STRING, &client_cert);
1126
1127         return 0;
1128 }
1129
1130 static int set_network_peap(struct connman_network *network,
1131                             DBusMessageIter *dict, const char *passphrase)
1132 {
1133         const char *client_cert, *ca_cert, *phase2;
1134         char *phase2_auth;
1135
1136         /*
1137          * For PEAP/TTLS, we at least need
1138          *              The authority certificate
1139          *              The 2nd phase authentication method
1140          *              The 2nd phase passphrase
1141          *
1142          * The Client certificate is optional although strongly required
1143          * When setting it, we need in addition
1144          *              The Client private key file
1145          *              The Client private key file password
1146          */
1147         if (passphrase == NULL) {
1148                 connman_error("Error in PEAP/TTLS authentication: "
1149                               "a phase2 passphrase must be defined\n");
1150                 return -EINVAL;
1151         }
1152
1153         ca_cert = connman_network_get_string(network, "WiFi.CACertFile");
1154         if (ca_cert == NULL) {
1155                 connman_error("Error in PEAP/TTLS authentication: "
1156                               "CACertFile must be defined\n");
1157                 return -EINVAL;
1158         }
1159
1160         phase2 = connman_network_get_string(network, "WiFi.Phase2");
1161         if (phase2 == NULL) {
1162                 connman_error("Error in PEAP/TTLS authentication: "
1163                               "Phase2 must be defined\n");
1164                 return -EINVAL;
1165         }
1166
1167         DBG("CA cert %s phase2 auth %s", ca_cert, phase2);
1168
1169         client_cert = connman_network_get_string(network,
1170                                                         "WiFi.ClientCertFile");
1171         if (client_cert) {
1172                 const char *private_key, *private_key_password;
1173
1174                 private_key = connman_network_get_string(network,
1175                                                         "WiFi.PrivateKeyFile");
1176                 if (private_key == NULL) {
1177                         connman_error("Error in PEAP/TTLS authentication: "
1178                                       "with ClientCertFile, "
1179                                       "PrivateKeyFile must be defined\n");
1180                         return -EINVAL;
1181                 }
1182
1183                 private_key_password =
1184                         connman_network_get_string(network,
1185                                                 "WiFi.PrivateKeyPassphrase");
1186                 if (private_key_password == NULL) {
1187                         connman_error("Error in PEAP/TTLS authentication: "
1188                                       "with ClientCertFile, "
1189                                       "PrivateKeyPassphrase must be defined\n");
1190                         return -EINVAL;
1191                 }
1192
1193                 connman_dbus_dict_append_basic(dict, "client_cert",
1194                                                 DBUS_TYPE_STRING, &client_cert);
1195
1196                 connman_dbus_dict_append_basic(dict, "private_key",
1197                                                 DBUS_TYPE_STRING, &private_key);
1198
1199                 connman_dbus_dict_append_basic(dict, "private_key_passwd",
1200                                                         DBUS_TYPE_STRING,
1201                                                         &private_key_password);
1202
1203                 DBG("client cert %s private key %s", client_cert, private_key);
1204         } else
1205                 connman_info("No client certificate has been provided "
1206                              "to do the PEAP/TTLS authentication\n");
1207
1208         phase2_auth = g_strdup_printf("\"auth=%s\"", phase2);
1209
1210         connman_dbus_dict_append_basic(dict, "password",
1211                                                 DBUS_TYPE_STRING, &passphrase);
1212
1213         connman_dbus_dict_append_basic(dict, "ca_cert",
1214                                                 DBUS_TYPE_STRING, &ca_cert);
1215
1216         connman_dbus_dict_append_basic(dict, "phase2",
1217                                                 DBUS_TYPE_STRING, &phase2_auth);
1218
1219         g_free(phase2_auth);
1220
1221         return 0;
1222 }
1223
1224 static int set_network(struct supplicant_task *task,
1225                                 const unsigned char *network, int len,
1226                                 const char *address, const char *security,
1227                                                         const char *passphrase)
1228 {
1229         DBusMessage *message, *reply;
1230         DBusMessageIter array, dict;
1231         DBusError error;
1232         dbus_uint32_t scan_ssid = 1;
1233
1234         DBG("task %p", task);
1235
1236         if (task->netpath == NULL)
1237                 return -EINVAL;
1238
1239         message = dbus_message_new_method_call(SUPPLICANT_NAME, task->netpath,
1240                                         SUPPLICANT_INTF ".Network", "set");
1241         if (message == NULL)
1242                 return -ENOMEM;
1243
1244         dbus_message_set_auto_start(message, FALSE);
1245
1246         dbus_message_iter_init_append(message, &array);
1247
1248         connman_dbus_dict_open(&array, &dict);
1249
1250         connman_dbus_dict_append_basic(&dict, "scan_ssid",
1251                                          DBUS_TYPE_UINT32, &scan_ssid);
1252
1253         if (network)
1254                 connman_dbus_dict_append_fixed_array(&dict, "ssid",
1255                                                 DBUS_TYPE_BYTE, &network, len);
1256         else if (address)
1257                 connman_dbus_dict_append_basic(&dict, "bssid",
1258                                                 DBUS_TYPE_STRING, &address);
1259
1260         if (g_ascii_strcasecmp(security, "psk") == 0 ||
1261                                 g_ascii_strcasecmp(security, "wpa") == 0 ||
1262                                 g_ascii_strcasecmp(security, "rsn") == 0) {
1263                 const char *key_mgmt = "WPA-PSK";
1264                 connman_dbus_dict_append_basic(&dict, "key_mgmt",
1265                                                 DBUS_TYPE_STRING, &key_mgmt);
1266
1267                 if (passphrase && strlen(passphrase) > 0)
1268                         connman_dbus_dict_append_basic(&dict, "psk",
1269                                                 DBUS_TYPE_STRING, &passphrase);
1270         } else if (g_ascii_strcasecmp(security, "ieee8021x") == 0) {
1271                 struct connman_network *network = task->network;
1272                 const char *key_mgmt = "WPA-EAP", *eap, *identity;
1273                 char *eap_value;
1274
1275                 /*
1276                  * If our private key password is unset,
1277                  * we use the supplied passphrase. That is needed
1278                  * for PEAP where 2 passphrases (identity and client
1279                  * cert may have to be provided.
1280                  */
1281                 if (connman_network_get_string(network,
1282                                         "WiFi.PrivateKeyPassphrase") == NULL)
1283                         connman_network_set_string(network,
1284                                                 "WiFi.PrivateKeyPassphrase",
1285                                                                 passphrase);
1286
1287                 eap = connman_network_get_string(network, "WiFi.EAP");
1288                 if (eap == NULL)
1289                         goto invalid;
1290
1291                 /* We must have an identity for both PEAP and TLS */
1292                 identity = connman_network_get_string(network, "WiFi.Identity");
1293                 if (identity == NULL)
1294                         goto invalid;
1295
1296                 DBG("key_mgmt %s eap %s identity %s", key_mgmt, eap, identity);
1297
1298                 if (g_strcmp0(eap, "tls") == 0) {
1299                         int err;
1300
1301                         err = set_network_tls(network, &dict);
1302                         if (err < 0) {
1303                                 dbus_message_unref(message);
1304                                 return err;
1305                         }
1306                 } else if (g_strcmp0(eap, "peap") == 0 ||
1307                                    g_strcmp0(eap, "ttls") == 0) {
1308                         int err;
1309
1310                         err = set_network_peap(network, &dict, passphrase);
1311                         if (err < 0) {
1312                                 dbus_message_unref(message);
1313                                 return err;
1314                         }
1315                 } else {
1316                         connman_error("Unknown EAP %s", eap);
1317                         goto invalid;
1318                 }
1319
1320                 /* wpa_supplicant only accepts upper case EAPs */
1321                 eap_value = g_ascii_strup(eap, -1);
1322
1323                 connman_dbus_dict_append_basic(&dict, "key_mgmt",
1324                                                         DBUS_TYPE_STRING,
1325                                                         &key_mgmt);
1326                 connman_dbus_dict_append_basic(&dict, "eap",
1327                                                         DBUS_TYPE_STRING,
1328                                                         &eap_value);
1329                 connman_dbus_dict_append_basic(&dict, "identity",
1330                                                         DBUS_TYPE_STRING,
1331                                                         &identity);
1332
1333                 g_free(eap_value);
1334
1335         } else if (g_ascii_strcasecmp(security, "wep") == 0) {
1336                 const char *key_mgmt = "NONE";
1337                 const char *auth_alg = "OPEN";
1338                 const char *key_index = "0";
1339
1340                 if (task->cfg80211 == TRUE)
1341                         auth_alg = "OPEN SHARED";
1342
1343                 connman_dbus_dict_append_basic(&dict, "auth_alg",
1344                                                 DBUS_TYPE_STRING, &auth_alg);
1345
1346                 connman_dbus_dict_append_basic(&dict, "key_mgmt",
1347                                                 DBUS_TYPE_STRING, &key_mgmt);
1348
1349                 if (passphrase) {
1350                         int size = strlen(passphrase);
1351                         if (size == 10 || size == 26) {
1352                                 unsigned char *key = malloc(13);
1353                                 char tmp[3];
1354                                 int i;
1355                                 memset(tmp, 0, sizeof(tmp));
1356                                 if (key == NULL)
1357                                         size = 0;
1358                                 for (i = 0; i < size / 2; i++) {
1359                                         memcpy(tmp, passphrase + (i * 2), 2);
1360                                         key[i] = (unsigned char) strtol(tmp,
1361                                                                 NULL, 16);
1362                                 }
1363                                 connman_dbus_dict_append_fixed_array(&dict,
1364                                                 "wep_key0", DBUS_TYPE_BYTE,
1365                                                         &key, size / 2);
1366                                 free(key);
1367                         } else if (size == 5 || size == 13) {
1368                                 unsigned char *key = malloc(13);
1369                                 int i;
1370                                 if (key == NULL)
1371                                         size = 0;
1372                                 for (i = 0; i < size; i++)
1373                                         key[i] = (unsigned char) passphrase[i];
1374                                 connman_dbus_dict_append_fixed_array(&dict,
1375                                                 "wep_key0", DBUS_TYPE_BYTE,
1376                                                                 &key, size);
1377                                 free(key);
1378                         } else
1379                                 connman_dbus_dict_append_basic(&dict,
1380                                                 "wep_key0", DBUS_TYPE_STRING,
1381                                                                 &passphrase);
1382
1383                         connman_dbus_dict_append_basic(&dict, "wep_tx_keyidx",
1384                                                 DBUS_TYPE_STRING, &key_index);
1385                 }
1386         } else {
1387                 const char *key_mgmt = "NONE";
1388                 connman_dbus_dict_append_basic(&dict, "key_mgmt",
1389                                                 DBUS_TYPE_STRING, &key_mgmt);
1390         }
1391
1392         connman_dbus_dict_close(&array, &dict);
1393
1394         dbus_error_init(&error);
1395
1396         reply = dbus_connection_send_with_reply_and_block(connection,
1397                                                         message, -1, &error);
1398         if (reply == NULL) {
1399                 if (dbus_error_is_set(&error) == TRUE) {
1400                         connman_error("%s", error.message);
1401                         dbus_error_free(&error);
1402                 } else
1403                         connman_error("Failed to set network options");
1404                 dbus_message_unref(message);
1405                 return -EIO;
1406         }
1407
1408         dbus_message_unref(message);
1409
1410         dbus_message_unref(reply);
1411
1412         return 0;
1413
1414 invalid:
1415         dbus_message_unref(message);
1416         return -EINVAL;
1417 }
1418
1419 static void scan_reply(DBusPendingCall *call, void *user_data)
1420 {
1421         struct supplicant_task *task = user_data;
1422         DBusMessage *reply;
1423
1424         DBG("task %p", task);
1425
1426         task->scan_call = NULL;
1427
1428         reply = dbus_pending_call_steal_reply(call);
1429
1430         if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR) {
1431                 connman_device_set_scanning(task->device, FALSE);
1432                 goto done;
1433         }
1434
1435         if (task->scanning == TRUE)
1436                 connman_device_set_scanning(task->device, TRUE);
1437
1438 done:
1439         dbus_message_unref(reply);
1440
1441         dbus_pending_call_unref(call);
1442 }
1443
1444
1445 static int initiate_scan(struct supplicant_task *task)
1446 {
1447         DBusMessage *message;
1448
1449         DBG("task %p", task);
1450
1451         if (task->path == NULL)
1452                 return -EINVAL;
1453
1454         if (task->scan_call != NULL)
1455                 return -EALREADY;
1456
1457         message = dbus_message_new_method_call(SUPPLICANT_NAME, task->path,
1458                                         SUPPLICANT_INTF ".Interface", "scan");
1459         if (message == NULL)
1460                 return -ENOMEM;
1461
1462         dbus_message_set_auto_start(message, FALSE);
1463
1464         if (dbus_connection_send_with_reply(connection, message,
1465                                         &task->scan_call, TIMEOUT) == FALSE) {
1466                 connman_error("Failed to initiate scan");
1467                 dbus_message_unref(message);
1468                 return -EIO;
1469         }
1470
1471         if (task->scan_call == NULL) {
1472                 connman_error("D-Bus connection not available");
1473                 dbus_message_unref(message);
1474                 return -EIO;
1475         }
1476
1477         dbus_pending_call_set_notify(task->scan_call, scan_reply, task, NULL);
1478
1479         dbus_message_unref(message);
1480
1481         return -EINPROGRESS;
1482 }
1483
1484 static struct {
1485         char *name;
1486         char *value;
1487 } special_ssid[] = {
1488         { "<hidden>", "hidden"  },
1489         { "default",  "linksys" },
1490         { "wireless"  },
1491         { "linksys"   },
1492         { "netgear"   },
1493         { "dlink"     },
1494         { "2wire"     },
1495         { "compaq"    },
1496         { "tsunami"   },
1497         { "comcomcom", "3com"     },
1498         { "3Com",      "3com"     },
1499         { "Symbol",    "symbol"   },
1500         { "Motorola",  "motorola" },
1501         { "Wireless" , "wireless" },
1502         { "WLAN",      "wlan"     },
1503         { }
1504 };
1505
1506 static char *build_group(const char *addr, const char *name,
1507                         const unsigned char *ssid, unsigned int ssid_len,
1508                                         const char *mode, const char *security)
1509 {
1510         GString *str;
1511         unsigned int i;
1512
1513         if (addr == NULL)
1514                 return NULL;
1515
1516         str = g_string_sized_new((ssid_len * 2) + 24);
1517         if (str == NULL)
1518                 return NULL;
1519
1520         if (ssid == NULL) {
1521                 g_string_append_printf(str, "hidden_%s", addr);
1522                 goto done;
1523         }
1524
1525         for (i = 0; special_ssid[i].name; i++) {
1526                 if (g_strcmp0(special_ssid[i].name, name) == 0) {
1527                         if (special_ssid[i].value == NULL)
1528                                 g_string_append_printf(str, "%s_%s",
1529                                                                 name, addr);
1530                         else
1531                                 g_string_append_printf(str, "%s_%s",
1532                                                 special_ssid[i].value, addr);
1533                         goto done;
1534                 }
1535         }
1536
1537         if (ssid_len > 0 && ssid[0] != '\0') {
1538                 for (i = 0; i < ssid_len; i++)
1539                         g_string_append_printf(str, "%02x", ssid[i]);
1540         } else
1541                 g_string_append_printf(str, "hidden_%s", addr);
1542
1543 done:
1544         g_string_append_printf(str, "_%s_%s", mode, security);
1545
1546         return g_string_free(str, FALSE);
1547 }
1548
1549 static void extract_addr(DBusMessageIter *value,
1550                                         struct supplicant_result *result)
1551 {
1552         DBusMessageIter array;
1553         struct ether_addr eth;
1554         unsigned char *addr;
1555         int addr_len;
1556
1557         dbus_message_iter_recurse(value, &array);
1558         dbus_message_iter_get_fixed_array(&array, &addr, &addr_len);
1559
1560         if (addr_len != 6)
1561                 return;
1562
1563         result->addr = g_try_malloc(addr_len);
1564         if (result->addr == NULL)
1565                 return;
1566
1567         memcpy(result->addr, addr, addr_len);
1568         result->addr_len = addr_len;
1569
1570         result->path = g_try_malloc0(13);
1571         if (result->path == NULL)
1572                 return;
1573
1574         memcpy(&eth, addr, sizeof(eth));
1575         snprintf(result->path, 13, "%02x%02x%02x%02x%02x%02x",
1576                                                 eth.ether_addr_octet[0],
1577                                                 eth.ether_addr_octet[1],
1578                                                 eth.ether_addr_octet[2],
1579                                                 eth.ether_addr_octet[3],
1580                                                 eth.ether_addr_octet[4],
1581                                                 eth.ether_addr_octet[5]);
1582 }
1583
1584 static void extract_ssid(DBusMessageIter *value,
1585                                         struct supplicant_result *result)
1586 {
1587         DBusMessageIter array;
1588         unsigned char *ssid;
1589         int ssid_len, i;
1590
1591         dbus_message_iter_recurse(value, &array);
1592         dbus_message_iter_get_fixed_array(&array, &ssid, &ssid_len);
1593
1594         if (ssid_len < 1)
1595                 return;
1596
1597         if (ssid[0] == '\0')
1598                 return;
1599
1600         result->ssid = g_try_malloc(ssid_len);
1601         if (result->ssid == NULL)
1602                 return;
1603
1604         memcpy(result->ssid, ssid, ssid_len);
1605         result->ssid_len = ssid_len;
1606
1607         result->name = g_try_malloc0(ssid_len + 1);
1608         if (result->name == NULL)
1609                 return;
1610
1611         for (i = 0; i < ssid_len; i++) {
1612                 if (g_ascii_isprint(ssid[i]))
1613                         result->name[i] = ssid[i];
1614                 else
1615                         result->name[i] = ' ';
1616         }
1617 }
1618
1619 static unsigned char wifi_oui[3]      = { 0x00, 0x50, 0xf2 };
1620 static unsigned char ieee80211_oui[3] = { 0x00, 0x0f, 0xac };
1621
1622 static void extract_rsn(struct supplicant_result *result,
1623                                         const unsigned char *buf, int len)
1624 {
1625         uint16_t count;
1626         int i;
1627
1628         /* Version */
1629         if (len < 2)
1630                 return;
1631
1632         buf += 2;
1633         len -= 2;
1634
1635         /* Group cipher */
1636         if (len < 4)
1637                 return;
1638
1639         buf += 4;
1640         len -= 4;
1641
1642         /* Pairwise cipher */
1643         if (len < 2)
1644                 return;
1645
1646         count = buf[0] | (buf[1] << 8);
1647         if (2 + (count * 4) > len)
1648                 return;
1649
1650         buf += 2 + (count * 4);
1651         len -= 2 + (count * 4);
1652
1653         /* Authentication */
1654         if (len < 2)
1655                 return;
1656
1657         count = buf[0] | (buf[1] << 8);
1658         if (2 + (count * 4) > len)
1659                 return;
1660
1661         for (i = 0; i < count; i++) {
1662                 const unsigned char *ptr = buf + 2 + (i * 4);
1663
1664                 if (memcmp(ptr, wifi_oui, 3) == 0) {
1665                         switch (ptr[3]) {
1666                         case 1:
1667                                 result->has_8021x = TRUE;
1668                                 break;
1669                         case 2:
1670                                 result->has_psk = TRUE;
1671                                 break;
1672                         }
1673                 } else if (memcmp(ptr, ieee80211_oui, 3) == 0) {
1674                         switch (ptr[3]) {
1675                         case 1:
1676                                 result->has_8021x = TRUE;
1677                                 break;
1678                         case 2:
1679                                 result->has_psk = TRUE;
1680                                 break;
1681                         }
1682                 }
1683         }
1684
1685         buf += 2 + (count * 4);
1686         len -= 2 + (count * 4);
1687 }
1688
1689 static void extract_wpaie(DBusMessageIter *value,
1690                                         struct supplicant_result *result)
1691 {
1692         DBusMessageIter array;
1693         unsigned char *ie;
1694         int ie_len;
1695
1696         dbus_message_iter_recurse(value, &array);
1697         dbus_message_iter_get_fixed_array(&array, &ie, &ie_len);
1698
1699         if (ie_len > 6) {
1700                 result->has_wpa = TRUE;
1701                 extract_rsn(result, ie + 6, ie_len - 6);
1702         }
1703 }
1704
1705 static void extract_rsnie(DBusMessageIter *value,
1706                                         struct supplicant_result *result)
1707 {
1708         DBusMessageIter array;
1709         unsigned char *ie;
1710         int ie_len;
1711
1712         dbus_message_iter_recurse(value, &array);
1713         dbus_message_iter_get_fixed_array(&array, &ie, &ie_len);
1714
1715         if (ie_len > 2) {
1716                 result->has_rsn = TRUE;
1717                 extract_rsn(result, ie + 2, ie_len - 2);
1718         }
1719 }
1720
1721 static void extract_wpsie(DBusMessageIter *value,
1722                                         struct supplicant_result *result)
1723 {
1724         DBusMessageIter array;
1725         unsigned char *ie;
1726         int ie_len;
1727
1728         dbus_message_iter_recurse(value, &array);
1729         dbus_message_iter_get_fixed_array(&array, &ie, &ie_len);
1730
1731         if (ie_len > 0)
1732                 result->has_wps = TRUE;
1733 }
1734
1735 static void extract_capabilites(DBusMessageIter *value,
1736                                         struct supplicant_result *result)
1737 {
1738         dbus_message_iter_get_basic(value, &result->capabilities);
1739
1740         if (result->capabilities & IEEE80211_CAP_ESS)
1741                 result->adhoc = FALSE;
1742         else if (result->capabilities & IEEE80211_CAP_IBSS)
1743                 result->adhoc = TRUE;
1744
1745         if (result->capabilities & IEEE80211_CAP_PRIVACY)
1746                 result->has_wep = TRUE;
1747 }
1748
1749 static unsigned char calculate_strength(struct supplicant_task *task,
1750                                         struct supplicant_result *result)
1751 {
1752         if (result->quality == -1 || task->range->max_qual.qual == 0) {
1753                 unsigned char strength;
1754
1755                 if (result->level > 0)
1756                         strength = 100 - result->level;
1757                 else
1758                         strength = 120 + result->level;
1759
1760                 if (strength > 100)
1761                         strength = 100;
1762
1763                 return strength;
1764         }
1765
1766         return (result->quality * 100) / task->range->max_qual.qual;
1767 }
1768
1769 static unsigned short calculate_channel(struct supplicant_result *result)
1770 {
1771         if (result->frequency < 0)
1772                 return 0;
1773
1774         return (result->frequency - 2407) / 5;
1775 }
1776
1777 static void get_properties(struct supplicant_task *task);
1778
1779 static void properties_reply(DBusPendingCall *call, void *user_data)
1780 {
1781         struct supplicant_task *task = user_data;
1782         struct supplicant_result result;
1783         struct supplicant_block *block;
1784         struct connman_network *network;
1785         DBusMessage *reply;
1786         DBusMessageIter array, dict;
1787         unsigned char strength;
1788         unsigned short channel, frequency;
1789         const char *mode, *security;
1790         char *group = NULL;
1791
1792         DBG("task %p", task);
1793
1794         reply = dbus_pending_call_steal_reply(call);
1795
1796         if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR)
1797                 goto unref;
1798
1799         memset(&result, 0, sizeof(result));
1800         result.frequency = -1;
1801         result.quality = -1;
1802         result.level = 0;
1803         result.noise = 0;
1804
1805         dbus_message_iter_init(reply, &array);
1806
1807         dbus_message_iter_recurse(&array, &dict);
1808
1809         while (dbus_message_iter_get_arg_type(&dict) == DBUS_TYPE_DICT_ENTRY) {
1810                 DBusMessageIter entry, value;
1811                 const char *key;
1812
1813                 dbus_message_iter_recurse(&dict, &entry);
1814                 dbus_message_iter_get_basic(&entry, &key);
1815
1816                 dbus_message_iter_next(&entry);
1817
1818                 dbus_message_iter_recurse(&entry, &value);
1819
1820                 //type = dbus_message_iter_get_arg_type(&value);
1821                 //dbus_message_iter_get_basic(&value, &val);
1822
1823                 /* 
1824                  * bssid        : a (97)
1825                  * ssid         : a (97)
1826                  * wpaie        : a (97)
1827                  * rsnie        : a (97)
1828                  * wpsie        : a (97)
1829                  * frequency    : i (105)
1830                  * capabilities : q (113)
1831                  * quality      : i (105)
1832                  * noise        : i (105)
1833                  * level        : i (105)
1834                  * maxrate      : i (105)
1835                  */
1836
1837                 if (g_str_equal(key, "bssid") == TRUE)
1838                         extract_addr(&value, &result);
1839                 else if (g_str_equal(key, "ssid") == TRUE)
1840                         extract_ssid(&value, &result);
1841                 else if (g_str_equal(key, "wpaie") == TRUE)
1842                         extract_wpaie(&value, &result);
1843                 else if (g_str_equal(key, "rsnie") == TRUE)
1844                         extract_rsnie(&value, &result);
1845                 else if (g_str_equal(key, "wpsie") == TRUE)
1846                         extract_wpsie(&value, &result);
1847                 else if (g_str_equal(key, "capabilities") == TRUE)
1848                         extract_capabilites(&value, &result);
1849                 else if (g_str_equal(key, "frequency") == TRUE)
1850                         dbus_message_iter_get_basic(&value, &result.frequency);
1851                 else if (g_str_equal(key, "quality") == TRUE)
1852                         dbus_message_iter_get_basic(&value, &result.quality);
1853                 else if (g_str_equal(key, "noise") == TRUE)
1854                         dbus_message_iter_get_basic(&value, &result.noise);
1855                 else if (g_str_equal(key, "level") == TRUE)
1856                         dbus_message_iter_get_basic(&value, &result.level);
1857                 else if (g_str_equal(key, "maxrate") == TRUE)
1858                         dbus_message_iter_get_basic(&value, &result.maxrate);
1859
1860                 dbus_message_iter_next(&dict);
1861         }
1862
1863         DBG("capabilties %u frequency %d "
1864                         "quality %d noise %d level %d maxrate %d",
1865                                         result.capabilities, result.frequency,
1866                                                 result.quality, result.noise,
1867                                                 result.level, result.maxrate);
1868
1869         if (result.path == NULL)
1870                 goto done;
1871
1872         if (result.path[0] == '\0')
1873                 goto done;
1874
1875         if (result.name) {
1876                 block = g_hash_table_lookup(task->hidden_blocks, result.name);
1877                 if (block) {
1878                         enable_network(task, block->netpath, FALSE);
1879                         g_hash_table_remove(task->hidden_blocks, block->ssid);
1880                 }
1881         }
1882
1883         if (result.ssid == NULL)
1884                 task->hidden_found = TRUE;
1885
1886         if (result.frequency > 0 && result.frequency < 14)
1887                 result.frequency = 2407 + (5 * result.frequency);
1888         else if (result.frequency == 14)
1889                 result.frequency = 2484;
1890
1891         strength = calculate_strength(task, &result);
1892         channel  = calculate_channel(&result);
1893
1894         frequency = (result.frequency < 0) ? 0 : result.frequency;
1895
1896         if (result.has_8021x == TRUE)
1897                 security = "ieee8021x";
1898         else if (result.has_psk == TRUE)
1899                 security = "psk";
1900         else if (result.has_wep == TRUE)
1901                 security = "wep";
1902         else
1903                 security = "none";
1904
1905         mode = (result.adhoc == TRUE) ? "adhoc" : "managed";
1906
1907         group = build_group(result.path, result.name,
1908                                         result.ssid, result.ssid_len,
1909                                                         mode, security);
1910
1911         if (result.has_psk == TRUE) {
1912                 if (result.has_rsn == TRUE)
1913                         security = "rsn";
1914                 else if (result.has_wpa == TRUE)
1915                         security = "wpa";
1916         }
1917
1918         network = connman_device_get_network(task->device, result.path);
1919         if (network == NULL) {
1920                 int index;
1921
1922                 network = connman_network_create(result.path,
1923                                                 CONNMAN_NETWORK_TYPE_WIFI);
1924                 if (network == NULL)
1925                         goto done;
1926
1927                 index = connman_device_get_index(task->device);
1928                 connman_network_set_index(network, index);
1929
1930                 connman_network_set_protocol(network,
1931                                                 CONNMAN_NETWORK_PROTOCOL_IP);
1932
1933                 connman_network_set_address(network, result.addr,
1934                                                         result.addr_len);
1935
1936                 if (connman_device_add_network(task->device, network) < 0) {
1937                         connman_network_unref(network);
1938                         goto done;
1939                 }
1940         }
1941
1942         if (result.name != NULL && result.name[0] != '\0')
1943                 connman_network_set_name(network, result.name);
1944
1945         if (result.ssid_len != 0)
1946                 connman_network_set_blob(network, "WiFi.SSID",
1947                                                 result.ssid, result.ssid_len);
1948
1949         connman_network_set_string(network, "WiFi.Mode", mode);
1950
1951         DBG("%s (%s %s) strength %d (%s)",
1952                                 result.name, mode, security, strength,
1953                                 (result.has_wps == TRUE) ? "WPS" : "no WPS");
1954
1955         connman_network_set_available(network, TRUE);
1956         connman_network_set_strength(network, strength);
1957
1958         connman_network_set_uint16(network, "Frequency", frequency);
1959         connman_network_set_uint16(network, "WiFi.Channel", channel);
1960         connman_network_set_string(network, "WiFi.Security", security);
1961
1962         if (result.ssid != NULL)
1963                 connman_network_set_group(network, group);
1964
1965 done:
1966         g_free(group);
1967
1968         g_free(result.path);
1969         g_free(result.addr);
1970         g_free(result.name);
1971         g_free(result.ssid);
1972
1973 unref:
1974         dbus_message_unref(reply);
1975
1976         dbus_pending_call_unref(call);
1977
1978         get_properties(task);
1979 }
1980
1981 static void get_properties(struct supplicant_task *task)
1982 {
1983         DBusMessage *message;
1984         char *path;
1985
1986         path = g_slist_nth_data(task->scan_results, 0);
1987         if (path == NULL) {
1988                 if (task->hidden_found == TRUE) {
1989                         /*
1990                          * We're done with regular scanning, let's enable
1991                          * the missing network blocks if there are hidden
1992                          * SSIDs around.
1993                          */
1994                         hidden_block_enable(task);
1995                 }
1996                 goto noscan;
1997         }
1998
1999         message = dbus_message_new_method_call(SUPPLICANT_NAME, path,
2000                                                 SUPPLICANT_INTF ".BSSID",
2001                                                                 "properties");
2002
2003         task->scan_results = g_slist_remove(task->scan_results, path);
2004         g_free(path);
2005
2006         if (message == NULL)
2007                 goto noscan;
2008
2009         dbus_message_set_auto_start(message, FALSE);
2010
2011         if (dbus_connection_send_with_reply(connection, message,
2012                                 &task->result_call, TIMEOUT) == FALSE) {
2013                 connman_error("Failed to get network properties");
2014                 dbus_message_unref(message);
2015                 goto noscan;
2016         }
2017
2018         if (task->result_call == NULL) {
2019                 connman_error("D-Bus connection not available");
2020                 dbus_message_unref(message);
2021                 goto noscan;
2022         }
2023
2024         dbus_pending_call_set_notify(task->result_call,
2025                                         properties_reply, task, NULL);
2026
2027         dbus_message_unref(message);
2028
2029         return;
2030
2031 noscan:
2032         task->result_call = NULL;
2033
2034         if (task->scanning == TRUE) {
2035                 connman_device_set_scanning(task->device, FALSE);
2036                 task->scanning = FALSE;
2037         }
2038 }
2039
2040 static void scan_results_reply(DBusPendingCall *call, void *user_data)
2041 {
2042         struct supplicant_task *task = user_data;
2043         DBusMessage *reply;
2044         DBusError error;
2045         char **results;
2046         int i, num_results;
2047
2048         DBG("task %p", task);
2049
2050         reply = dbus_pending_call_steal_reply(call);
2051
2052         if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR)
2053                 goto done;
2054
2055         dbus_error_init(&error);
2056
2057         if (dbus_message_get_args(reply, &error,
2058                                 DBUS_TYPE_ARRAY, DBUS_TYPE_OBJECT_PATH,
2059                                                 &results, &num_results,
2060                                                 DBUS_TYPE_INVALID) == FALSE) {
2061                 if (dbus_error_is_set(&error) == TRUE) {
2062                         connman_error("%s", error.message);
2063                         dbus_error_free(&error);
2064                 } else
2065                         connman_error("Wrong arguments for scan result");
2066                 goto done;
2067         }
2068
2069         if (num_results == 0)
2070                 goto done;
2071
2072         for (i = 0; i < num_results; i++) {
2073                 char *path = g_strdup(results[i]);
2074                 if (path == NULL)
2075                         continue;
2076
2077                 task->scan_results = g_slist_append(task->scan_results, path);
2078         }
2079
2080         task->hidden_found = FALSE;
2081
2082         g_strfreev(results);
2083
2084         dbus_message_unref(reply);
2085
2086         dbus_pending_call_unref(call);
2087
2088         get_properties(task);
2089
2090         return;
2091
2092 done:
2093         dbus_message_unref(reply);
2094
2095         dbus_pending_call_unref(call);
2096
2097         task->result_call = NULL;
2098
2099         if (task->scanning == TRUE) {
2100                 connman_device_set_scanning(task->device, FALSE);
2101                 task->scanning = FALSE;
2102         }
2103 }
2104
2105 static void scan_results_available(struct supplicant_task *task)
2106 {
2107         DBusMessage *message;
2108
2109         DBG("task %p", task);
2110
2111         if (task->result_call != NULL)
2112                 return;
2113
2114         message = dbus_message_new_method_call(SUPPLICANT_NAME, task->path,
2115                                                 SUPPLICANT_INTF ".Interface",
2116                                                         "scanResults");
2117         if (message == NULL)
2118                 return;
2119
2120         dbus_message_set_auto_start(message, FALSE);
2121
2122         if (dbus_connection_send_with_reply(connection, message,
2123                                 &task->result_call, TIMEOUT) == FALSE) {
2124                 connman_error("Failed to request scan result");
2125                 goto done;
2126         }
2127
2128         if (task->result_call == NULL) {
2129                 connman_error("D-Bus connection not available");
2130                 goto done;
2131         }
2132
2133         if (task->scanning == TRUE)
2134                 connman_device_set_scanning(task->device, TRUE);
2135
2136         dbus_pending_call_set_notify(task->result_call,
2137                                         scan_results_reply, task, NULL);
2138
2139 done:
2140         dbus_message_unref(message);
2141 }
2142
2143 static enum supplicant_state string2state(const char *state)
2144 {
2145         if (g_str_equal(state, "INACTIVE") == TRUE)
2146                 return WPA_INACTIVE;
2147         else if (g_str_equal(state, "SCANNING") == TRUE)
2148                 return WPA_SCANNING;
2149         else if (g_str_equal(state, "ASSOCIATING") == TRUE)
2150                 return WPA_ASSOCIATING;
2151         else if (g_str_equal(state, "ASSOCIATED") == TRUE)
2152                 return WPA_ASSOCIATED;
2153         else if (g_str_equal(state, "GROUP_HANDSHAKE") == TRUE)
2154                 return WPA_GROUP_HANDSHAKE;
2155         else if (g_str_equal(state, "4WAY_HANDSHAKE") == TRUE)
2156                 return WPA_4WAY_HANDSHAKE;
2157         else if (g_str_equal(state, "COMPLETED") == TRUE)
2158                 return WPA_COMPLETED;
2159         else if (g_str_equal(state, "DISCONNECTED") == TRUE)
2160                 return WPA_DISCONNECTED;
2161         else
2162                 return WPA_INVALID;
2163 }
2164
2165 static int task_connect(struct supplicant_task *task)
2166 {
2167         const char *address, *security, *passphrase;
2168         const void *ssid;
2169         unsigned int ssid_len;
2170         int err;
2171
2172         g_hash_table_foreach(task->hidden_blocks, block_reset, task);
2173
2174         connman_inet_ifup(task->ifindex);
2175
2176         address = connman_network_get_string(task->network, "Address");
2177         security = connman_network_get_string(task->network, "WiFi.Security");
2178         passphrase = connman_network_get_string(task->network, "WiFi.Passphrase");
2179
2180         ssid = connman_network_get_blob(task->network, "WiFi.SSID", &ssid_len);
2181
2182         DBG("address %s security %s", address, security);
2183
2184         if (security == NULL)
2185                 return -EINVAL;
2186
2187         if (passphrase == NULL && g_str_equal(security, "none") == FALSE &&
2188                                 g_str_equal(security, "ieee8021x") == FALSE)
2189                 return -EINVAL;
2190
2191         remove_network(task);
2192
2193         set_ap_scan(task);
2194
2195         add_network(task);
2196
2197         err = set_network(task, ssid, ssid_len, address, security, passphrase);
2198         if (err < 0)
2199                 return err;
2200
2201         err = select_network(task);
2202         if (err < 0)
2203                 return err;
2204
2205         return -EINPROGRESS;
2206 }
2207
2208 static void scanning(struct supplicant_task *task, DBusMessage *msg)
2209 {
2210         DBusError error;
2211         dbus_bool_t scanning;
2212
2213         dbus_error_init(&error);
2214
2215         if (dbus_message_get_args(msg, &error, DBUS_TYPE_BOOLEAN, &scanning,
2216                                                 DBUS_TYPE_INVALID) == FALSE) {
2217                 if (dbus_error_is_set(&error) == TRUE) {
2218                         connman_error("%s", error.message);
2219                         dbus_error_free(&error);
2220                 } else
2221                         connman_error("Wrong arguments for scanning");
2222                 return;
2223         }
2224
2225         connman_info("%s scanning %s", task->ifname,
2226                                 scanning == TRUE ? "started" : "finished");
2227 }
2228
2229 static gboolean delayed_scan(gpointer user_data)
2230 {
2231         struct supplicant_task *task = user_data;
2232
2233         supplicant_scan(task->device);
2234
2235         return FALSE;
2236 }
2237
2238 static void state_change(struct supplicant_task *task, DBusMessage *msg)
2239 {
2240         DBusError error;
2241         const char *newstate, *oldstate;
2242         unsigned char bssid[ETH_ALEN];
2243         unsigned int bssid_len;
2244         enum supplicant_state state, prevstate;
2245
2246         dbus_error_init(&error);
2247
2248         if (dbus_message_get_args(msg, &error, DBUS_TYPE_STRING, &newstate,
2249                                                 DBUS_TYPE_STRING, &oldstate,
2250                                                 DBUS_TYPE_INVALID) == FALSE) {
2251                 if (dbus_error_is_set(&error) == TRUE) {
2252                         connman_error("%s", error.message);
2253                         dbus_error_free(&error);
2254                 } else
2255                         connman_error("Wrong arguments for state change");
2256                 return;
2257         }
2258
2259         DBG("state %s ==> %s", oldstate, newstate);
2260
2261         connman_info("%s %s%s", task->ifname, newstate,
2262                                 task->scanning == TRUE ? " (scanning)" : "");
2263
2264         state = string2state(newstate);
2265         if (state == WPA_INVALID)
2266                 return;
2267
2268         prevstate = task->state;
2269         task->state = state;
2270
2271         if (task->network == NULL)
2272                 return;
2273
2274         switch (task->state) {
2275         case WPA_COMPLETED:
2276                 switch (prevstate) {
2277                 case WPA_ASSOCIATED:
2278                 case WPA_GROUP_HANDSHAKE:
2279                         break;
2280                 default:
2281                         goto badstate;
2282                 }
2283
2284                 /* reset scan trigger and schedule background scan */
2285                 connman_device_schedule_scan(task->device);
2286
2287                 if (get_bssid(task->device, bssid, &bssid_len) == 0)
2288                         connman_network_set_address(task->network,
2289                                                         bssid, bssid_len);
2290
2291                 /* carrier on */
2292                 connman_network_set_connected(task->network, TRUE);
2293                 break;
2294
2295         case WPA_ASSOCIATING:
2296                 switch (prevstate) {
2297                 case WPA_COMPLETED:
2298                         break;
2299                 case WPA_SCANNING:
2300                         connman_network_set_associating(task->network, TRUE);
2301                         break;
2302                 default:
2303                         goto badstate;
2304                 }
2305                 break;
2306
2307         case WPA_INACTIVE:
2308                 switch (prevstate) {
2309                 case WPA_SCANNING:
2310                 case WPA_DISCONNECTED:
2311                         break;
2312                 default:
2313                         goto badstate;
2314                 }
2315                 /* fall through */
2316
2317         case WPA_DISCONNECTED:
2318                 /* carrier off */
2319                 connman_network_set_connected(task->network, FALSE);
2320
2321                 /*
2322                  * Reset the passphrase if we're being disconnected before
2323                  * association/handshake completes.
2324                  */
2325                 if (prevstate != WPA_COMPLETED && state == WPA_DISCONNECTED)
2326                         connman_network_set_passphrase(task->network, NULL);
2327
2328                 if (task->disconnecting == TRUE) {
2329                         connman_network_unref(task->network);
2330                         task->disconnecting = FALSE;
2331
2332                         if (task->pending_network != NULL) {
2333                                 task->network = task->pending_network;
2334                                 task->pending_network = NULL;
2335                                 task_connect(task);
2336                         } else
2337                                 task->network = NULL;
2338                 } else {
2339                         if (task->state == WPA_DISCONNECTED)
2340                                 g_timeout_add_seconds(10, delayed_scan, task);
2341
2342                         remove_network(task);
2343                 }
2344
2345                 break;
2346
2347         default:
2348                 connman_network_set_associating(task->network, FALSE);
2349                 break;
2350         }
2351
2352         return;
2353
2354 badstate:
2355         connman_error("%s invalid state change %s -> %s", task->ifname,
2356                                                         oldstate, newstate);
2357 }
2358
2359 static gboolean supplicant_filter(DBusConnection *conn,
2360                                                 DBusMessage *msg, void *data)
2361 {
2362         struct supplicant_task *task;
2363         const char *member, *path;
2364
2365         member = dbus_message_get_member(msg);
2366         if (member == NULL)
2367                 return TRUE;
2368
2369         path = dbus_message_get_path(msg);
2370         if (path == NULL)
2371                 return TRUE;
2372
2373         task = find_task_by_path(path);
2374         if (task == NULL)
2375                 return TRUE;
2376
2377         DBG("task %p member %s", task, member);
2378
2379         if (g_str_equal(member, "ScanResultsAvailable") == TRUE)
2380                 scan_results_available(task);
2381         else if (g_str_equal(member, "Scanning") == TRUE)
2382                 scanning(task, msg);
2383         else if (g_str_equal(member, "StateChange") == TRUE)
2384                 state_change(task, msg);
2385
2386         return TRUE;
2387 }
2388
2389 int supplicant_start(struct connman_device *device)
2390 {
2391         struct supplicant_task *task;
2392         int err;
2393
2394         DBG("device %p", device);
2395
2396         task = g_try_new0(struct supplicant_task, 1);
2397         if (task == NULL)
2398                 return -ENOMEM;
2399
2400         task->ifindex = connman_device_get_index(device);
2401         task->ifname = connman_inet_ifname(task->ifindex);
2402
2403         if (task->ifname == NULL) {
2404                 err = -ENOMEM;
2405                 goto failed;
2406         }
2407
2408         task->cfg80211 = connman_inet_is_cfg80211(task->ifindex);
2409         if (task->cfg80211 == FALSE)
2410                 connman_warn("Enabling quirks for unsupported driver");
2411
2412         task->range = g_try_malloc0(sizeof(struct iw_range));
2413         if (task->range == NULL) {
2414                 err = -ENOMEM;
2415                 goto failed;
2416         }
2417
2418         err = get_range(task);
2419         if (err < 0)
2420                 goto failed;
2421
2422         task->device = connman_device_ref(device);
2423
2424         task->created = FALSE;
2425         task->scanning = FALSE;
2426         task->state = WPA_INVALID;
2427         task->disconnecting = FALSE;
2428         task->pending_network = NULL;
2429         task->hidden_blocks = g_hash_table_new_full(g_str_hash, g_str_equal,
2430                                                         NULL, remove_block);
2431         task_list = g_slist_append(task_list, task);
2432
2433         return create_interface(task);
2434
2435 failed:
2436         g_free(task->range);
2437         g_free(task->ifname);
2438         g_free(task);
2439
2440         return err;
2441 }
2442
2443 int supplicant_stop(struct connman_device *device)
2444 {
2445         int index = connman_device_get_index(device);
2446         struct supplicant_task *task;
2447
2448         DBG("device %p", device);
2449
2450         task = find_task_by_index(index);
2451         if (task == NULL)
2452                 return -ENODEV;
2453
2454         g_free(task->range);
2455
2456         task_list = g_slist_remove(task_list, task);
2457         g_hash_table_destroy(task->hidden_blocks);
2458
2459         if (task->scan_call != NULL) {
2460                 dbus_pending_call_cancel(task->scan_call);
2461                 task->scan_call = NULL;
2462         }
2463
2464         if (task->result_call != NULL) {
2465                 dbus_pending_call_cancel(task->result_call);
2466                 task->result_call = NULL;
2467         }
2468
2469         if (task->scanning == TRUE)
2470                 connman_device_set_scanning(task->device, FALSE);
2471
2472         remove_network(task);
2473
2474         disconnect_network(task);
2475
2476         return remove_interface(task);
2477 }
2478
2479 int supplicant_scan(struct connman_device *device)
2480 {
2481         int index = connman_device_get_index(device);
2482         struct supplicant_task *task;
2483         int err;
2484
2485         DBG("device %p", device);
2486
2487         task = find_task_by_index(index);
2488         if (task == NULL)
2489                 return -ENODEV;
2490
2491         switch (task->state) {
2492         case WPA_SCANNING:
2493                 return -EALREADY;
2494         case WPA_ASSOCIATING:
2495         case WPA_ASSOCIATED:
2496         case WPA_4WAY_HANDSHAKE:
2497         case WPA_GROUP_HANDSHAKE:
2498                 return -EBUSY;
2499         default:
2500                 break;
2501         }
2502
2503         task->scanning = TRUE;
2504
2505         err = initiate_scan(task);
2506         if (err < 0) {
2507                 if (err == -EINPROGRESS)
2508                         return 0;
2509
2510                 task->scanning = FALSE;
2511                 return err;
2512         }
2513
2514         connman_device_set_scanning(task->device, TRUE);
2515
2516         return 0;
2517 }
2518
2519 int supplicant_connect(struct connman_network *network)
2520 {
2521         struct supplicant_task *task;
2522         int index;
2523
2524         DBG("network %p", network);
2525
2526         index = connman_network_get_index(network);
2527
2528         task = find_task_by_index(index);
2529         if (task == NULL)
2530                 return -ENODEV;
2531
2532         if (task->disconnecting == TRUE)
2533                 task->pending_network = connman_network_ref(network);
2534         else {
2535                 task->network = connman_network_ref(network);
2536                 return task_connect(task);
2537         }
2538
2539         return -EINPROGRESS;
2540 }
2541
2542 int supplicant_disconnect(struct connman_network *network)
2543 {
2544         struct supplicant_task *task;
2545         int index;
2546
2547         DBG("network %p", network);
2548
2549         index = connman_network_get_index(network);
2550
2551         task = find_task_by_index(index);
2552         if (task == NULL)
2553                 return -ENODEV;
2554
2555         if (task->disconnecting == TRUE)
2556                 return -EALREADY;
2557
2558         remove_network(task);
2559
2560         disconnect_network(task);
2561
2562         task->disconnecting = TRUE;
2563
2564         return 0;
2565 }
2566
2567 void supplicant_remove_network(struct connman_network *network)
2568 {
2569         struct supplicant_task *task;
2570         int index;
2571
2572         DBG("network %p", network);
2573
2574         index = connman_network_get_index(network);
2575
2576         task = find_task_by_index(index);
2577         if (task == NULL)
2578                 return;
2579
2580         if (task->network != network)
2581                 return;
2582
2583         remove_network(task);
2584 }
2585
2586 static void supplicant_activate(DBusConnection *conn)
2587 {
2588         DBusMessage *message;
2589
2590         DBG("conn %p", conn);
2591
2592         message = dbus_message_new_method_call(SUPPLICANT_NAME, "/",
2593                                 DBUS_INTERFACE_INTROSPECTABLE, "Introspect");
2594         if (message == NULL)
2595                 return;
2596
2597         dbus_message_set_no_reply(message, TRUE);
2598
2599         dbus_connection_send(conn, message, NULL);
2600
2601         dbus_message_unref(message);
2602 }
2603
2604 static GSList *driver_list = NULL;
2605
2606 static void supplicant_probe(DBusConnection *conn, void *user_data)
2607 {
2608         GSList *list;
2609
2610         DBG("conn %p", conn);
2611
2612         for (list = driver_list; list; list = list->next) {
2613                 struct supplicant_driver *driver = list->data;
2614
2615                 DBG("driver %p name %s", driver, driver->name);
2616
2617                 if (driver->probe)
2618                         driver->probe();
2619         }
2620 }
2621
2622 static void supplicant_remove(DBusConnection *conn, void *user_data)
2623 {
2624         GSList *list;
2625
2626         DBG("conn %p", conn);
2627
2628         for (list = driver_list; list; list = list->next) {
2629                 struct supplicant_driver *driver = list->data;
2630
2631                 DBG("driver %p name %s", driver, driver->name);
2632
2633                 if (driver->remove)
2634                         driver->remove();
2635         }
2636 }
2637
2638 static guint watch;
2639 static guint iface_watch;
2640
2641 static int supplicant_create(void)
2642 {
2643         if (g_slist_length(driver_list) > 0)
2644                 return 0;
2645
2646         connection = connman_dbus_get_connection();
2647         if (connection == NULL)
2648                 return -EIO;
2649
2650         DBG("connection %p", connection);
2651
2652         watch = g_dbus_add_service_watch(connection, SUPPLICANT_NAME,
2653                         supplicant_probe, supplicant_remove, NULL, NULL);
2654
2655         iface_watch = g_dbus_add_signal_watch(connection, NULL, NULL,
2656                                                 SUPPLICANT_INTF ".Interface",
2657                                                 NULL, supplicant_filter,
2658                                                 NULL, NULL);
2659
2660         if (watch == 0 || iface_watch == 0) {
2661                 g_dbus_remove_watch(connection, watch);
2662                 g_dbus_remove_watch(connection, iface_watch);
2663                 return -EIO;
2664         }
2665
2666         return 0;
2667 }
2668
2669 static void supplicant_destroy(void)
2670 {
2671         if (g_slist_length(driver_list) > 0)
2672                 return;
2673
2674         DBG("connection %p", connection);
2675
2676         g_dbus_remove_watch(connection, watch);
2677         g_dbus_remove_watch(connection, iface_watch);
2678
2679         dbus_connection_unref(connection);
2680         connection = NULL;
2681 }
2682
2683 int supplicant_register(struct supplicant_driver *driver)
2684 {
2685         int err;
2686
2687         DBG("driver %p name %s", driver, driver->name);
2688
2689         err = supplicant_create();
2690         if (err < 0)
2691                 return err;
2692
2693         driver_list = g_slist_append(driver_list, driver);
2694
2695         supplicant_activate(connection);
2696
2697         return 0;
2698 }
2699
2700 void supplicant_unregister(struct supplicant_driver *driver)
2701 {
2702         DBG("driver %p name %s", driver, driver->name);
2703
2704         supplicant_remove(connection, NULL);
2705
2706         driver_list = g_slist_remove(driver_list, driver);
2707
2708         supplicant_destroy();
2709 }