276fd913be8e7fb0955b07c379352729135cd2b5
[platform/upstream/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         hex_ssids = connman_wifi_load_ssid();
614
615         for (i = 0; hex_ssids[i]; i++) {
616                 unsigned char *ssid;
617                 unsigned int j, k = 0, hex;
618                 size_t hex_ssid_len;
619
620                 hex_ssid = hex_ssids[i];
621                 hex_ssid_len = strlen(hex_ssid);
622
623                 ssid = g_try_malloc0(hex_ssid_len / 2 + 1);
624                 if (ssid == NULL)
625                         break;
626
627                 for (j = 0, k = 0; j < hex_ssid_len; j += 2) {
628                         sscanf(hex_ssid + j, "%02x", &hex);
629                         ssid[k++] = hex;
630                 }
631
632                 if (add_hidden_network(task, ssid, hex_ssid_len / 2) < 0)
633                         break;
634         }
635
636         g_strfreev(hex_ssids);
637
638         dbus_message_unref(reply);
639
640         dbus_pending_call_unref(call);
641
642         return;
643
644 failed:
645         dbus_message_unref(reply);
646
647         dbus_pending_call_unref(call);
648
649         task_list = g_slist_remove(task_list, task);
650
651         connman_device_unref(task->device);
652
653         free_task(task);
654 }
655
656 static int add_interface(struct supplicant_task *task)
657 {
658         const char *driver = connman_option_get_string("wifi");
659         DBusMessage *message;
660         DBusMessageIter array, dict;
661         DBusPendingCall *call;
662
663         DBG("task %p", task);
664
665         message = dbus_message_new_method_call(SUPPLICANT_NAME, SUPPLICANT_PATH,
666                                         SUPPLICANT_INTF, "addInterface");
667         if (message == NULL)
668                 return -ENOMEM;
669
670         dbus_message_set_auto_start(message, FALSE);
671
672         dbus_message_iter_init_append(message, &array);
673
674         dbus_message_iter_append_basic(&array,
675                                         DBUS_TYPE_STRING, &task->ifname);
676
677         connman_dbus_dict_open(&array, &dict);
678
679         connman_dbus_dict_append_basic(&dict, "driver",
680                                                 DBUS_TYPE_STRING, &driver);
681
682         connman_dbus_dict_close(&array, &dict);
683
684         if (dbus_connection_send_with_reply(connection, message,
685                                                 &call, TIMEOUT) == FALSE) {
686                 connman_error("Failed to add interface");
687                 dbus_message_unref(message);
688                 return -EIO;
689         }
690
691         if (call == NULL) {
692                 connman_error("D-Bus connection not available");
693                 dbus_message_unref(message);
694                 return -EIO;
695         }
696
697         dbus_pending_call_set_notify(call, add_interface_reply, task, NULL);
698
699         dbus_message_unref(message);
700
701         return -EINPROGRESS;
702 }
703
704 static void get_interface_reply(DBusPendingCall *call, void *user_data)
705 {
706         struct supplicant_task *task = user_data;
707         DBusMessage *reply;
708         DBusError error;
709         const char *path;
710
711         DBG("task %p", task);
712
713         reply = dbus_pending_call_steal_reply(call);
714
715         if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR) {
716                 add_interface(task);
717                 goto done;
718         }
719
720         dbus_error_init(&error);
721
722         if (dbus_message_get_args(reply, &error, DBUS_TYPE_OBJECT_PATH, &path,
723                                                 DBUS_TYPE_INVALID) == FALSE) {
724                 if (dbus_error_is_set(&error) == TRUE) {
725                         connman_error("%s", error.message);
726                         dbus_error_free(&error);
727                 } else
728                         connman_error("Wrong arguments for get interface");
729                 goto done;
730         }
731
732         DBG("path %s", path);
733
734         task->path = g_strdup(path);
735         task->created = FALSE;
736
737         connman_device_set_powered(task->device, TRUE);
738
739 done:
740         dbus_message_unref(reply);
741
742         dbus_pending_call_unref(call);
743 }
744
745 static int create_interface(struct supplicant_task *task)
746 {
747         DBusMessage *message;
748         DBusPendingCall *call;
749
750         DBG("task %p", task);
751
752         message = dbus_message_new_method_call(SUPPLICANT_NAME, SUPPLICANT_PATH,
753                                         SUPPLICANT_INTF, "getInterface");
754         if (message == NULL)
755                 return -ENOMEM;
756
757         dbus_message_set_auto_start(message, FALSE);
758
759         dbus_message_append_args(message, DBUS_TYPE_STRING, &task->ifname,
760                                                         DBUS_TYPE_INVALID);
761
762         if (dbus_connection_send_with_reply(connection, message,
763                                                 &call, TIMEOUT) == FALSE) {
764                 connman_error("Failed to get interface");
765                 dbus_message_unref(message);
766                 return -EIO;
767         }
768
769         if (call == NULL) {
770                 connman_error("D-Bus connection not available");
771                 dbus_message_unref(message);
772                 return -EIO;
773         }
774
775         dbus_pending_call_set_notify(call, get_interface_reply, task, NULL);
776
777         dbus_message_unref(message);
778
779         return -EINPROGRESS;
780 }
781
782 static void remove_interface_reply(DBusPendingCall *call, void *user_data)
783 {
784         struct supplicant_task *task = user_data;
785         DBusMessage *reply;
786
787         DBG("task %p", task);
788
789         reply = dbus_pending_call_steal_reply(call);
790
791         connman_device_set_powered(task->device, FALSE);
792
793         connman_device_unref(task->device);
794
795         connman_inet_ifdown(task->ifindex);
796
797         free_task(task);
798
799         dbus_message_unref(reply);
800
801         dbus_pending_call_unref(call);
802 }
803
804 static int remove_interface(struct supplicant_task *task)
805 {
806         DBusMessage *message;
807         DBusPendingCall *call;
808
809         DBG("task %p", task);
810
811         if (task->path == NULL)
812                 return 0;
813
814 #if 0
815         if (task->created == FALSE) {
816                 connman_device_set_powered(task->device, FALSE);
817                 return 0;
818         }
819 #endif
820
821         message = dbus_message_new_method_call(SUPPLICANT_NAME, SUPPLICANT_PATH,
822                                         SUPPLICANT_INTF, "removeInterface");
823         if (message == NULL)
824                 return -ENOMEM;
825
826         dbus_message_set_auto_start(message, FALSE);
827
828         dbus_message_append_args(message, DBUS_TYPE_OBJECT_PATH, &task->path,
829                                                         DBUS_TYPE_INVALID);
830
831         if (dbus_connection_send_with_reply(connection, message,
832                                                 &call, TIMEOUT) == FALSE) {
833                 connman_error("Failed to remove interface");
834                 dbus_message_unref(message);
835                 return -EIO;
836         }
837
838         if (call == NULL) {
839                 connman_error("D-Bus connection not available");
840                 dbus_message_unref(message);
841                 return -EIO;
842         }
843
844         dbus_pending_call_set_notify(call, remove_interface_reply, task, NULL);
845
846         dbus_message_unref(message);
847
848         return -EINPROGRESS;
849 }
850
851 static int set_ap_scan(struct supplicant_task *task)
852 {
853         DBusMessage *message, *reply;
854         DBusError error;
855         guint32 ap_scan = 1;
856
857         DBG("task %p", task);
858
859         message = dbus_message_new_method_call(SUPPLICANT_NAME, task->path,
860                                 SUPPLICANT_INTF ".Interface", "setAPScan");
861         if (message == NULL)
862                 return -ENOMEM;
863
864         dbus_message_set_auto_start(message, FALSE);
865
866         dbus_message_append_args(message, DBUS_TYPE_UINT32, &ap_scan,
867                                                         DBUS_TYPE_INVALID);
868
869         dbus_error_init(&error);
870
871         reply = dbus_connection_send_with_reply_and_block(connection,
872                                                         message, -1, &error);
873         if (reply == NULL) {
874                 if (dbus_error_is_set(&error) == TRUE) {
875                         connman_error("%s", error.message);
876                         dbus_error_free(&error);
877                 } else
878                         connman_error("Failed to set AP scan");
879                 dbus_message_unref(message);
880                 return -EIO;
881         }
882
883         dbus_message_unref(message);
884
885         dbus_message_unref(reply);
886
887         return 0;
888 }
889
890 static int add_network(struct supplicant_task *task)
891 {
892         DBusMessage *message, *reply;
893         DBusError error;
894         const char *path;
895
896         DBG("task %p", task);
897
898         if (task->netpath != NULL)
899                 return -EALREADY;
900
901         message = dbus_message_new_method_call(SUPPLICANT_NAME, task->path,
902                                 SUPPLICANT_INTF ".Interface", "addNetwork");
903         if (message == NULL)
904                 return -ENOMEM;
905
906         dbus_message_set_auto_start(message, FALSE);
907
908         dbus_error_init(&error);
909
910         reply = dbus_connection_send_with_reply_and_block(connection,
911                                                         message, -1, &error);
912         if (reply == NULL) {
913                 if (dbus_error_is_set(&error) == TRUE) {
914                         connman_error("%s", error.message);
915                         dbus_error_free(&error);
916                 } else
917                         connman_error("Failed to add network");
918                 dbus_message_unref(message);
919                 return -EIO;
920         }
921
922         dbus_message_unref(message);
923
924         dbus_error_init(&error);
925
926         if (dbus_message_get_args(reply, &error, DBUS_TYPE_OBJECT_PATH, &path,
927                                                 DBUS_TYPE_INVALID) == FALSE) {
928                 if (dbus_error_is_set(&error) == TRUE) {
929                         connman_error("%s", error.message);
930                         dbus_error_free(&error);
931                 } else
932                         connman_error("Wrong arguments for network");
933                 dbus_message_unref(reply);
934                 return -EIO;
935         }
936
937         DBG("path %s", path);
938
939         task->netpath = g_strdup(path);
940
941         dbus_message_unref(reply);
942
943         return 0;
944 }
945
946 static int remove_network(struct supplicant_task *task)
947 {
948         DBusMessage *message, *reply;
949         DBusError error;
950
951         DBG("task %p", task);
952
953         if (task->netpath == NULL || task->path == NULL)
954                 return -EINVAL;
955
956         message = dbus_message_new_method_call(SUPPLICANT_NAME, task->path,
957                                 SUPPLICANT_INTF ".Interface", "removeNetwork");
958         if (message == NULL)
959                 return -ENOMEM;
960
961         dbus_message_set_auto_start(message, FALSE);
962
963         dbus_message_append_args(message, DBUS_TYPE_OBJECT_PATH, &task->netpath,
964                                                         DBUS_TYPE_INVALID);
965
966         dbus_error_init(&error);
967
968         reply = dbus_connection_send_with_reply_and_block(connection,
969                                                         message, -1, &error);
970         if (reply == NULL) {
971                 if (dbus_error_is_set(&error) == TRUE) {
972                         connman_error("%s", error.message);
973                         dbus_error_free(&error);
974                 } else
975                         connman_error("Failed to remove network");
976                 dbus_message_unref(message);
977                 return -EIO;
978         }
979
980         dbus_message_unref(message);
981
982         dbus_message_unref(reply);
983
984         g_free(task->netpath);
985         task->netpath = NULL;
986
987         return 0;
988 }
989
990 static int select_network(struct supplicant_task *task)
991 {
992         DBusMessage *message, *reply;
993         DBusError error;
994
995         DBG("task %p", task);
996
997         if (task->netpath == NULL)
998                 return -EINVAL;
999
1000         message = dbus_message_new_method_call(SUPPLICANT_NAME, task->path,
1001                                 SUPPLICANT_INTF ".Interface", "selectNetwork");
1002         if (message == NULL)
1003                 return -ENOMEM;
1004
1005         dbus_message_set_auto_start(message, FALSE);
1006
1007         dbus_message_append_args(message, DBUS_TYPE_OBJECT_PATH, &task->netpath,
1008                                                         DBUS_TYPE_INVALID);
1009
1010         dbus_error_init(&error);
1011
1012         reply = dbus_connection_send_with_reply_and_block(connection,
1013                                                         message, -1, &error);
1014         if (reply == NULL) {
1015                 if (dbus_error_is_set(&error) == TRUE) {
1016                         connman_error("%s", error.message);
1017                         dbus_error_free(&error);
1018                 } else
1019                         connman_error("Failed to select network");
1020                 dbus_message_unref(message);
1021                 return -EIO;
1022         }
1023
1024         dbus_message_unref(message);
1025
1026         dbus_message_unref(reply);
1027
1028         return 0;
1029 }
1030
1031 static int disconnect_network(struct supplicant_task *task)
1032 {
1033         DBusMessage *message, *reply;
1034         DBusError error;
1035
1036         DBG("task %p", task);
1037
1038         if (task->path == NULL)
1039                 return -EINVAL;
1040
1041         message = dbus_message_new_method_call(SUPPLICANT_NAME, task->path,
1042                                 SUPPLICANT_INTF ".Interface", "disconnect");
1043         if (message == NULL)
1044                 return -ENOMEM;
1045
1046         dbus_message_set_auto_start(message, FALSE);
1047
1048         dbus_error_init(&error);
1049
1050         reply = dbus_connection_send_with_reply_and_block(connection,
1051                                                         message, -1, &error);
1052         if (reply == NULL) {
1053                 if (dbus_error_is_set(&error) == TRUE) {
1054                         connman_error("%s", error.message);
1055                         dbus_error_free(&error);
1056                 } else
1057                         connman_error("Failed to disconnect network");
1058                 dbus_message_unref(message);
1059                 return -EIO;
1060         }
1061
1062         dbus_message_unref(message);
1063
1064         dbus_message_unref(reply);
1065
1066         return 0;
1067 }
1068
1069 static int set_network_tls(struct connman_network *network,
1070                            DBusMessageIter *dict)
1071 {
1072         const char *private_key, *client_cert, *ca_cert;
1073         const char *private_key_password;
1074
1075         /*
1076          * For TLS, we at least need a key, the client cert,
1077          * and a passhprase.
1078          * Server cert is optional.
1079          */
1080         client_cert = connman_network_get_string(network,
1081                                                 "WiFi.ClientCertFile");
1082         if (client_cert == NULL)
1083                 return -EINVAL;
1084
1085         private_key = connman_network_get_string(network,
1086                                                 "WiFi.PrivateKeyFile");
1087         if (private_key == NULL)
1088                 return -EINVAL;
1089
1090         private_key_password = connman_network_get_string(network,
1091                                                 "WiFi.PrivateKeyPassphrase");
1092         if (private_key_password == NULL)
1093                 return -EINVAL;
1094
1095         ca_cert = connman_network_get_string(network, "WiFi.CACertFile");
1096         if (ca_cert)
1097                 connman_dbus_dict_append_basic(dict, "ca_cert",
1098                                                 DBUS_TYPE_STRING, &ca_cert);
1099
1100         DBG("client cert %s private key %s", client_cert, private_key);
1101
1102         connman_dbus_dict_append_basic(dict, "private_key",
1103                                                 DBUS_TYPE_STRING, &private_key);
1104         connman_dbus_dict_append_basic(dict, "private_key_passwd",
1105                                                         DBUS_TYPE_STRING,
1106                                                         &private_key_password);
1107         connman_dbus_dict_append_basic(dict, "client_cert",
1108                                                 DBUS_TYPE_STRING, &client_cert);
1109
1110         return 0;
1111 }
1112
1113 static int set_network_peap(struct connman_network *network,
1114                             DBusMessageIter *dict, const char *passphrase)
1115 {
1116         const char *client_cert, *ca_cert, *phase2;
1117         char *phase2_auth;
1118
1119         /*
1120          * For PEAP, we at least need the sever cert, a 2nd
1121          * phase authentication and a passhprase.
1122          * Client cert is optional although strongly required
1123          * When setting the client cert, we then need a private
1124          * key as well.
1125          */
1126         ca_cert = connman_network_get_string(network, "WiFi.CACertFile");
1127         if (ca_cert == NULL)
1128                 return -EINVAL;
1129
1130         phase2 = connman_network_get_string(network, "WiFi.Phase2");
1131         if (phase2 == NULL)
1132                 return -EINVAL;
1133
1134         DBG("CA cert %s phase2 auth %s", ca_cert, phase2);
1135
1136         client_cert = connman_network_get_string(network,
1137                                                         "WiFi.ClientCertFile");
1138         if (client_cert) {
1139                 const char *private_key, *private_key_password;
1140
1141                 private_key = connman_network_get_string(network,
1142                                                         "WiFi.PrivateKeyFile");
1143                 if (private_key == NULL)
1144                         return -EINVAL;
1145
1146                 private_key_password =
1147                         connman_network_get_string(network,
1148                                                 "WiFi.PrivateKeyPassphrase");
1149                 if (private_key_password == NULL)
1150                         return -EINVAL;
1151
1152                 connman_dbus_dict_append_basic(dict, "client_cert",
1153                                                 DBUS_TYPE_STRING, &client_cert);
1154
1155                 connman_dbus_dict_append_basic(dict, "private_key",
1156                                                 DBUS_TYPE_STRING, &private_key);
1157
1158                 connman_dbus_dict_append_basic(dict, "private_key_passwd",
1159                                                         DBUS_TYPE_STRING,
1160                                                         &private_key_password);
1161
1162                 DBG("client cert %s private key %s", client_cert, private_key);
1163         }
1164
1165         phase2_auth = g_strdup_printf("\"auth=%s\"", phase2);
1166
1167         connman_dbus_dict_append_basic(dict, "password",
1168                                                 DBUS_TYPE_STRING, &passphrase);
1169
1170         connman_dbus_dict_append_basic(dict, "ca_cert",
1171                                                 DBUS_TYPE_STRING, &ca_cert);
1172
1173         connman_dbus_dict_append_basic(dict, "phase2",
1174                                                 DBUS_TYPE_STRING, &phase2_auth);
1175
1176         g_free(phase2_auth);
1177
1178         return 0;
1179 }
1180
1181 static int set_network(struct supplicant_task *task,
1182                                 const unsigned char *network, int len,
1183                                 const char *address, const char *security,
1184                                                         const char *passphrase)
1185 {
1186         DBusMessage *message, *reply;
1187         DBusMessageIter array, dict;
1188         DBusError error;
1189         dbus_uint32_t scan_ssid = 1;
1190
1191         DBG("task %p", task);
1192
1193         if (task->netpath == NULL)
1194                 return -EINVAL;
1195
1196         message = dbus_message_new_method_call(SUPPLICANT_NAME, task->netpath,
1197                                         SUPPLICANT_INTF ".Network", "set");
1198         if (message == NULL)
1199                 return -ENOMEM;
1200
1201         dbus_message_set_auto_start(message, FALSE);
1202
1203         dbus_message_iter_init_append(message, &array);
1204
1205         connman_dbus_dict_open(&array, &dict);
1206
1207         connman_dbus_dict_append_basic(&dict, "scan_ssid",
1208                                          DBUS_TYPE_UINT32, &scan_ssid);
1209
1210         if (network)
1211                 connman_dbus_dict_append_fixed_array(&dict, "ssid",
1212                                                 DBUS_TYPE_BYTE, &network, len);
1213         else if (address)
1214                 connman_dbus_dict_append_basic(&dict, "bssid",
1215                                                 DBUS_TYPE_STRING, &address);
1216
1217         if (g_ascii_strcasecmp(security, "psk") == 0 ||
1218                                 g_ascii_strcasecmp(security, "wpa") == 0 ||
1219                                 g_ascii_strcasecmp(security, "rsn") == 0) {
1220                 const char *key_mgmt = "WPA-PSK";
1221                 connman_dbus_dict_append_basic(&dict, "key_mgmt",
1222                                                 DBUS_TYPE_STRING, &key_mgmt);
1223
1224                 if (passphrase && strlen(passphrase) > 0)
1225                         connman_dbus_dict_append_basic(&dict, "psk",
1226                                                 DBUS_TYPE_STRING, &passphrase);
1227         } else if (g_ascii_strcasecmp(security, "ieee8021x") == 0) {
1228                 struct connman_network *network = task->network;
1229                 const char *key_mgmt = "WPA-EAP", *eap, *identity;
1230                 char *eap_value;
1231
1232                 /*
1233                  * If our private key password is unset,
1234                  * we use the supplied passphrase. That is needed
1235                  * for PEAP where 2 passphrases (identity and client
1236                  * cert may have to be provided.
1237                  */
1238                 if (connman_network_get_string(network,
1239                                         "WiFi.PrivateKeyPassphrase") == NULL)
1240                         connman_network_set_string(network,
1241                                                 "WiFi.PrivateKeyPassphrase",
1242                                                                 passphrase);
1243
1244                 eap = connman_network_get_string(network, "WiFi.EAP");
1245                 if (eap == NULL)
1246                         goto invalid;
1247
1248                 /* We must have an identity for both PEAP and TLS */
1249                 identity = connman_network_get_string(network, "WiFi.Identity");
1250                 if (identity == NULL)
1251                         goto invalid;
1252
1253                 DBG("key_mgmt %s eap %s identity %s", key_mgmt, eap, identity);
1254
1255                 if (g_strcmp0(eap, "tls") == 0) {
1256                         int err;
1257
1258                         err = set_network_tls(network, &dict);
1259                         if (err < 0) {
1260                                 dbus_message_unref(message);
1261                                 return err;
1262                         }
1263                 } else if (g_strcmp0(eap, "peap") == 0) {
1264                         int err;
1265
1266                         err = set_network_peap(network, &dict, passphrase);
1267                         if (err < 0) {
1268                                 dbus_message_unref(message);
1269                                 return err;
1270                         }
1271                 } else {
1272                         connman_error("Unknown EAP %s", eap);
1273                         goto invalid;
1274                 }
1275
1276                 /* wpa_supplicant only accepts upper case EAPs */
1277                 eap_value = g_ascii_strup(eap, -1);
1278
1279                 connman_dbus_dict_append_basic(&dict, "key_mgmt",
1280                                                         DBUS_TYPE_STRING,
1281                                                         &key_mgmt);
1282                 connman_dbus_dict_append_basic(&dict, "eap",
1283                                                         DBUS_TYPE_STRING,
1284                                                         &eap_value);
1285                 connman_dbus_dict_append_basic(&dict, "identity",
1286                                                         DBUS_TYPE_STRING,
1287                                                         &identity);
1288
1289                 g_free(eap_value);
1290
1291         } else if (g_ascii_strcasecmp(security, "wep") == 0) {
1292                 const char *key_mgmt = "NONE";
1293                 const char *auth_alg = "OPEN";
1294                 const char *key_index = "0";
1295
1296                 if (task->cfg80211 == TRUE)
1297                         auth_alg = "OPEN SHARED";
1298
1299                 connman_dbus_dict_append_basic(&dict, "auth_alg",
1300                                                 DBUS_TYPE_STRING, &auth_alg);
1301
1302                 connman_dbus_dict_append_basic(&dict, "key_mgmt",
1303                                                 DBUS_TYPE_STRING, &key_mgmt);
1304
1305                 if (passphrase) {
1306                         int size = strlen(passphrase);
1307                         if (size == 10 || size == 26) {
1308                                 unsigned char *key = malloc(13);
1309                                 char tmp[3];
1310                                 int i;
1311                                 memset(tmp, 0, sizeof(tmp));
1312                                 if (key == NULL)
1313                                         size = 0;
1314                                 for (i = 0; i < size / 2; i++) {
1315                                         memcpy(tmp, passphrase + (i * 2), 2);
1316                                         key[i] = (unsigned char) strtol(tmp,
1317                                                                 NULL, 16);
1318                                 }
1319                                 connman_dbus_dict_append_fixed_array(&dict,
1320                                                 "wep_key0", DBUS_TYPE_BYTE,
1321                                                         &key, size / 2);
1322                                 free(key);
1323                         } else if (size == 5 || size == 13) {
1324                                 unsigned char *key = malloc(13);
1325                                 int i;
1326                                 if (key == NULL)
1327                                         size = 0;
1328                                 for (i = 0; i < size; i++)
1329                                         key[i] = (unsigned char) passphrase[i];
1330                                 connman_dbus_dict_append_fixed_array(&dict,
1331                                                 "wep_key0", DBUS_TYPE_BYTE,
1332                                                                 &key, size);
1333                                 free(key);
1334                         } else
1335                                 connman_dbus_dict_append_basic(&dict,
1336                                                 "wep_key0", DBUS_TYPE_STRING,
1337                                                                 &passphrase);
1338
1339                         connman_dbus_dict_append_basic(&dict, "wep_tx_keyidx",
1340                                                 DBUS_TYPE_STRING, &key_index);
1341                 }
1342         } else {
1343                 const char *key_mgmt = "NONE";
1344                 connman_dbus_dict_append_basic(&dict, "key_mgmt",
1345                                                 DBUS_TYPE_STRING, &key_mgmt);
1346         }
1347
1348         connman_dbus_dict_close(&array, &dict);
1349
1350         dbus_error_init(&error);
1351
1352         reply = dbus_connection_send_with_reply_and_block(connection,
1353                                                         message, -1, &error);
1354         if (reply == NULL) {
1355                 if (dbus_error_is_set(&error) == TRUE) {
1356                         connman_error("%s", error.message);
1357                         dbus_error_free(&error);
1358                 } else
1359                         connman_error("Failed to set network options");
1360                 dbus_message_unref(message);
1361                 return -EIO;
1362         }
1363
1364         dbus_message_unref(message);
1365
1366         dbus_message_unref(reply);
1367
1368         return 0;
1369
1370 invalid:
1371         dbus_message_unref(message);
1372         return -EINVAL;
1373 }
1374
1375 static void scan_reply(DBusPendingCall *call, void *user_data)
1376 {
1377         struct supplicant_task *task = user_data;
1378         DBusMessage *reply;
1379
1380         DBG("task %p", task);
1381
1382         task->scan_call = NULL;
1383
1384         reply = dbus_pending_call_steal_reply(call);
1385
1386         if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR) {
1387                 connman_device_set_scanning(task->device, FALSE);
1388                 goto done;
1389         }
1390
1391         if (task->scanning == TRUE)
1392                 connman_device_set_scanning(task->device, TRUE);
1393
1394 done:
1395         dbus_message_unref(reply);
1396
1397         dbus_pending_call_unref(call);
1398 }
1399
1400
1401 static int initiate_scan(struct supplicant_task *task)
1402 {
1403         DBusMessage *message;
1404
1405         DBG("task %p", task);
1406
1407         if (task->path == NULL)
1408                 return -EINVAL;
1409
1410         if (task->scan_call != NULL)
1411                 return -EALREADY;
1412
1413         message = dbus_message_new_method_call(SUPPLICANT_NAME, task->path,
1414                                         SUPPLICANT_INTF ".Interface", "scan");
1415         if (message == NULL)
1416                 return -ENOMEM;
1417
1418         dbus_message_set_auto_start(message, FALSE);
1419
1420         if (dbus_connection_send_with_reply(connection, message,
1421                                         &task->scan_call, TIMEOUT) == FALSE) {
1422                 connman_error("Failed to initiate scan");
1423                 dbus_message_unref(message);
1424                 return -EIO;
1425         }
1426
1427         if (task->scan_call == NULL) {
1428                 connman_error("D-Bus connection not available");
1429                 dbus_message_unref(message);
1430                 return -EIO;
1431         }
1432
1433         dbus_pending_call_set_notify(task->scan_call, scan_reply, task, NULL);
1434
1435         dbus_message_unref(message);
1436
1437         return -EINPROGRESS;
1438 }
1439
1440 static struct {
1441         char *name;
1442         char *value;
1443 } special_ssid[] = {
1444         { "<hidden>", "hidden"  },
1445         { "default",  "linksys" },
1446         { "wireless"  },
1447         { "linksys"   },
1448         { "netgear"   },
1449         { "dlink"     },
1450         { "2wire"     },
1451         { "compaq"    },
1452         { "tsunami"   },
1453         { "comcomcom", "3com"     },
1454         { "3Com",      "3com"     },
1455         { "Symbol",    "symbol"   },
1456         { "Motorola",  "motorola" },
1457         { "Wireless" , "wireless" },
1458         { "WLAN",      "wlan"     },
1459         { }
1460 };
1461
1462 static char *build_group(const char *addr, const char *name,
1463                         const unsigned char *ssid, unsigned int ssid_len,
1464                                         const char *mode, const char *security)
1465 {
1466         GString *str;
1467         unsigned int i;
1468
1469         if (addr == NULL)
1470                 return NULL;
1471
1472         str = g_string_sized_new((ssid_len * 2) + 24);
1473         if (str == NULL)
1474                 return NULL;
1475
1476         if (ssid == NULL) {
1477                 g_string_append_printf(str, "hidden_%s", addr);
1478                 goto done;
1479         }
1480
1481         for (i = 0; special_ssid[i].name; i++) {
1482                 if (g_strcmp0(special_ssid[i].name, name) == 0) {
1483                         if (special_ssid[i].value == NULL)
1484                                 g_string_append_printf(str, "%s_%s",
1485                                                                 name, addr);
1486                         else
1487                                 g_string_append_printf(str, "%s_%s",
1488                                                 special_ssid[i].value, addr);
1489                         goto done;
1490                 }
1491         }
1492
1493         if (ssid_len > 0 && ssid[0] != '\0') {
1494                 for (i = 0; i < ssid_len; i++)
1495                         g_string_append_printf(str, "%02x", ssid[i]);
1496         } else
1497                 g_string_append_printf(str, "hidden_%s", addr);
1498
1499 done:
1500         g_string_append_printf(str, "_%s_%s", mode, security);
1501
1502         return g_string_free(str, FALSE);
1503 }
1504
1505 static void extract_addr(DBusMessageIter *value,
1506                                         struct supplicant_result *result)
1507 {
1508         DBusMessageIter array;
1509         struct ether_addr eth;
1510         unsigned char *addr;
1511         int addr_len;
1512
1513         dbus_message_iter_recurse(value, &array);
1514         dbus_message_iter_get_fixed_array(&array, &addr, &addr_len);
1515
1516         if (addr_len != 6)
1517                 return;
1518
1519         result->addr = g_try_malloc(addr_len);
1520         if (result->addr == NULL)
1521                 return;
1522
1523         memcpy(result->addr, addr, addr_len);
1524         result->addr_len = addr_len;
1525
1526         result->path = g_try_malloc0(13);
1527         if (result->path == NULL)
1528                 return;
1529
1530         memcpy(&eth, addr, sizeof(eth));
1531         snprintf(result->path, 13, "%02x%02x%02x%02x%02x%02x",
1532                                                 eth.ether_addr_octet[0],
1533                                                 eth.ether_addr_octet[1],
1534                                                 eth.ether_addr_octet[2],
1535                                                 eth.ether_addr_octet[3],
1536                                                 eth.ether_addr_octet[4],
1537                                                 eth.ether_addr_octet[5]);
1538 }
1539
1540 static void extract_ssid(DBusMessageIter *value,
1541                                         struct supplicant_result *result)
1542 {
1543         DBusMessageIter array;
1544         unsigned char *ssid;
1545         int ssid_len, i;
1546
1547         dbus_message_iter_recurse(value, &array);
1548         dbus_message_iter_get_fixed_array(&array, &ssid, &ssid_len);
1549
1550         if (ssid_len < 1)
1551                 return;
1552
1553         if (ssid[0] == '\0')
1554                 return;
1555
1556         result->ssid = g_try_malloc(ssid_len);
1557         if (result->ssid == NULL)
1558                 return;
1559
1560         memcpy(result->ssid, ssid, ssid_len);
1561         result->ssid_len = ssid_len;
1562
1563         result->name = g_try_malloc0(ssid_len + 1);
1564         if (result->name == NULL)
1565                 return;
1566
1567         for (i = 0; i < ssid_len; i++) {
1568                 if (g_ascii_isprint(ssid[i]))
1569                         result->name[i] = ssid[i];
1570                 else
1571                         result->name[i] = ' ';
1572         }
1573 }
1574
1575 static unsigned char wifi_oui[3]      = { 0x00, 0x50, 0xf2 };
1576 static unsigned char ieee80211_oui[3] = { 0x00, 0x0f, 0xac };
1577
1578 static void extract_rsn(struct supplicant_result *result,
1579                                         const unsigned char *buf, int len)
1580 {
1581         uint16_t count;
1582         int i;
1583
1584         /* Version */
1585         if (len < 2)
1586                 return;
1587
1588         buf += 2;
1589         len -= 2;
1590
1591         /* Group cipher */
1592         if (len < 4)
1593                 return;
1594
1595         buf += 4;
1596         len -= 4;
1597
1598         /* Pairwise cipher */
1599         if (len < 2)
1600                 return;
1601
1602         count = buf[0] | (buf[1] << 8);
1603         if (2 + (count * 4) > len)
1604                 return;
1605
1606         buf += 2 + (count * 4);
1607         len -= 2 + (count * 4);
1608
1609         /* Authentication */
1610         if (len < 2)
1611                 return;
1612
1613         count = buf[0] | (buf[1] << 8);
1614         if (2 + (count * 4) > len)
1615                 return;
1616
1617         for (i = 0; i < count; i++) {
1618                 const unsigned char *ptr = buf + 2 + (i * 4);
1619
1620                 if (memcmp(ptr, wifi_oui, 3) == 0) {
1621                         switch (ptr[3]) {
1622                         case 1:
1623                                 result->has_8021x = TRUE;
1624                                 break;
1625                         case 2:
1626                                 result->has_psk = TRUE;
1627                                 break;
1628                         }
1629                 } else if (memcmp(ptr, ieee80211_oui, 3) == 0) {
1630                         switch (ptr[3]) {
1631                         case 1:
1632                                 result->has_8021x = TRUE;
1633                                 break;
1634                         case 2:
1635                                 result->has_psk = TRUE;
1636                                 break;
1637                         }
1638                 }
1639         }
1640
1641         buf += 2 + (count * 4);
1642         len -= 2 + (count * 4);
1643 }
1644
1645 static void extract_wpaie(DBusMessageIter *value,
1646                                         struct supplicant_result *result)
1647 {
1648         DBusMessageIter array;
1649         unsigned char *ie;
1650         int ie_len;
1651
1652         dbus_message_iter_recurse(value, &array);
1653         dbus_message_iter_get_fixed_array(&array, &ie, &ie_len);
1654
1655         if (ie_len > 6) {
1656                 result->has_wpa = TRUE;
1657                 extract_rsn(result, ie + 6, ie_len - 6);
1658         }
1659 }
1660
1661 static void extract_rsnie(DBusMessageIter *value,
1662                                         struct supplicant_result *result)
1663 {
1664         DBusMessageIter array;
1665         unsigned char *ie;
1666         int ie_len;
1667
1668         dbus_message_iter_recurse(value, &array);
1669         dbus_message_iter_get_fixed_array(&array, &ie, &ie_len);
1670
1671         if (ie_len > 2) {
1672                 result->has_rsn = TRUE;
1673                 extract_rsn(result, ie + 2, ie_len - 2);
1674         }
1675 }
1676
1677 static void extract_wpsie(DBusMessageIter *value,
1678                                         struct supplicant_result *result)
1679 {
1680         DBusMessageIter array;
1681         unsigned char *ie;
1682         int ie_len;
1683
1684         dbus_message_iter_recurse(value, &array);
1685         dbus_message_iter_get_fixed_array(&array, &ie, &ie_len);
1686
1687         if (ie_len > 0)
1688                 result->has_wps = TRUE;
1689 }
1690
1691 static void extract_capabilites(DBusMessageIter *value,
1692                                         struct supplicant_result *result)
1693 {
1694         dbus_message_iter_get_basic(value, &result->capabilities);
1695
1696         if (result->capabilities & IEEE80211_CAP_ESS)
1697                 result->adhoc = FALSE;
1698         else if (result->capabilities & IEEE80211_CAP_IBSS)
1699                 result->adhoc = TRUE;
1700
1701         if (result->capabilities & IEEE80211_CAP_PRIVACY)
1702                 result->has_wep = TRUE;
1703 }
1704
1705 static unsigned char calculate_strength(struct supplicant_task *task,
1706                                         struct supplicant_result *result)
1707 {
1708         if (result->quality == -1 || task->range->max_qual.qual == 0) {
1709                 unsigned char strength;
1710
1711                 if (result->level > 0)
1712                         strength = 100 - result->level;
1713                 else
1714                         strength = 120 + result->level;
1715
1716                 if (strength > 100)
1717                         strength = 100;
1718
1719                 return strength;
1720         }
1721
1722         return (result->quality * 100) / task->range->max_qual.qual;
1723 }
1724
1725 static unsigned short calculate_channel(struct supplicant_result *result)
1726 {
1727         if (result->frequency < 0)
1728                 return 0;
1729
1730         return (result->frequency - 2407) / 5;
1731 }
1732
1733 static void get_properties(struct supplicant_task *task);
1734
1735 static void properties_reply(DBusPendingCall *call, void *user_data)
1736 {
1737         struct supplicant_task *task = user_data;
1738         struct supplicant_result result;
1739         struct supplicant_block *block;
1740         struct connman_network *network;
1741         DBusMessage *reply;
1742         DBusMessageIter array, dict;
1743         unsigned char strength;
1744         unsigned short channel, frequency;
1745         const char *mode, *security;
1746         char *group = NULL;
1747
1748         DBG("task %p", task);
1749
1750         reply = dbus_pending_call_steal_reply(call);
1751
1752         if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR)
1753                 goto unref;
1754
1755         memset(&result, 0, sizeof(result));
1756         result.frequency = -1;
1757         result.quality = -1;
1758         result.level = 0;
1759         result.noise = 0;
1760
1761         dbus_message_iter_init(reply, &array);
1762
1763         dbus_message_iter_recurse(&array, &dict);
1764
1765         while (dbus_message_iter_get_arg_type(&dict) == DBUS_TYPE_DICT_ENTRY) {
1766                 DBusMessageIter entry, value;
1767                 const char *key;
1768
1769                 dbus_message_iter_recurse(&dict, &entry);
1770                 dbus_message_iter_get_basic(&entry, &key);
1771
1772                 dbus_message_iter_next(&entry);
1773
1774                 dbus_message_iter_recurse(&entry, &value);
1775
1776                 //type = dbus_message_iter_get_arg_type(&value);
1777                 //dbus_message_iter_get_basic(&value, &val);
1778
1779                 /* 
1780                  * bssid        : a (97)
1781                  * ssid         : a (97)
1782                  * wpaie        : a (97)
1783                  * rsnie        : a (97)
1784                  * wpsie        : a (97)
1785                  * frequency    : i (105)
1786                  * capabilities : q (113)
1787                  * quality      : i (105)
1788                  * noise        : i (105)
1789                  * level        : i (105)
1790                  * maxrate      : i (105)
1791                  */
1792
1793                 if (g_str_equal(key, "bssid") == TRUE)
1794                         extract_addr(&value, &result);
1795                 else if (g_str_equal(key, "ssid") == TRUE)
1796                         extract_ssid(&value, &result);
1797                 else if (g_str_equal(key, "wpaie") == TRUE)
1798                         extract_wpaie(&value, &result);
1799                 else if (g_str_equal(key, "rsnie") == TRUE)
1800                         extract_rsnie(&value, &result);
1801                 else if (g_str_equal(key, "wpsie") == TRUE)
1802                         extract_wpsie(&value, &result);
1803                 else if (g_str_equal(key, "capabilities") == TRUE)
1804                         extract_capabilites(&value, &result);
1805                 else if (g_str_equal(key, "frequency") == TRUE)
1806                         dbus_message_iter_get_basic(&value, &result.frequency);
1807                 else if (g_str_equal(key, "quality") == TRUE)
1808                         dbus_message_iter_get_basic(&value, &result.quality);
1809                 else if (g_str_equal(key, "noise") == TRUE)
1810                         dbus_message_iter_get_basic(&value, &result.noise);
1811                 else if (g_str_equal(key, "level") == TRUE)
1812                         dbus_message_iter_get_basic(&value, &result.level);
1813                 else if (g_str_equal(key, "maxrate") == TRUE)
1814                         dbus_message_iter_get_basic(&value, &result.maxrate);
1815
1816                 dbus_message_iter_next(&dict);
1817         }
1818
1819         DBG("capabilties %u frequency %d "
1820                         "quality %d noise %d level %d maxrate %d",
1821                                         result.capabilities, result.frequency,
1822                                                 result.quality, result.noise,
1823                                                 result.level, result.maxrate);
1824
1825         if (result.path == NULL)
1826                 goto done;
1827
1828         if (result.path[0] == '\0')
1829                 goto done;
1830
1831         if (result.name) {
1832                 block = g_hash_table_lookup(task->hidden_blocks, result.name);
1833                 if (block) {
1834                         enable_network(task, block->netpath, FALSE);
1835                         g_hash_table_remove(task->hidden_blocks, block->ssid);
1836                 }
1837         }
1838
1839         if (result.ssid == NULL)
1840                 task->hidden_found = TRUE;
1841
1842         if (result.frequency > 0 && result.frequency < 14)
1843                 result.frequency = 2407 + (5 * result.frequency);
1844         else if (result.frequency == 14)
1845                 result.frequency = 2484;
1846
1847         strength = calculate_strength(task, &result);
1848         channel  = calculate_channel(&result);
1849
1850         frequency = (result.frequency < 0) ? 0 : result.frequency;
1851
1852         if (result.has_8021x == TRUE)
1853                 security = "ieee8021x";
1854         else if (result.has_psk == TRUE)
1855                 security = "psk";
1856         else if (result.has_wep == TRUE)
1857                 security = "wep";
1858         else
1859                 security = "none";
1860
1861         mode = (result.adhoc == TRUE) ? "adhoc" : "managed";
1862
1863         group = build_group(result.path, result.name,
1864                                         result.ssid, result.ssid_len,
1865                                                         mode, security);
1866
1867         if (result.has_psk == TRUE) {
1868                 if (result.has_rsn == TRUE)
1869                         security = "rsn";
1870                 else if (result.has_wpa == TRUE)
1871                         security = "wpa";
1872         }
1873
1874         network = connman_device_get_network(task->device, result.path);
1875         if (network == NULL) {
1876                 int index;
1877
1878                 network = connman_network_create(result.path,
1879                                                 CONNMAN_NETWORK_TYPE_WIFI);
1880                 if (network == NULL)
1881                         goto done;
1882
1883                 index = connman_device_get_index(task->device);
1884                 connman_network_set_index(network, index);
1885
1886                 connman_network_set_protocol(network,
1887                                                 CONNMAN_NETWORK_PROTOCOL_IP);
1888
1889                 connman_network_set_address(network, result.addr,
1890                                                         result.addr_len);
1891
1892                 if (connman_device_add_network(task->device, network) < 0) {
1893                         connman_network_unref(network);
1894                         goto done;
1895                 }
1896         }
1897
1898         if (result.name != NULL && result.name[0] != '\0')
1899                 connman_network_set_name(network, result.name);
1900
1901         if (result.ssid_len != 0)
1902                 connman_network_set_blob(network, "WiFi.SSID",
1903                                                 result.ssid, result.ssid_len);
1904
1905         connman_network_set_string(network, "WiFi.Mode", mode);
1906
1907         DBG("%s (%s %s) strength %d (%s)",
1908                                 result.name, mode, security, strength,
1909                                 (result.has_wps == TRUE) ? "WPS" : "no WPS");
1910
1911         connman_network_set_available(network, TRUE);
1912         connman_network_set_strength(network, strength);
1913
1914         connman_network_set_uint16(network, "Frequency", frequency);
1915         connman_network_set_uint16(network, "WiFi.Channel", channel);
1916         connman_network_set_string(network, "WiFi.Security", security);
1917
1918         if (result.ssid != NULL)
1919                 connman_network_set_group(network, group);
1920
1921 done:
1922         g_free(group);
1923
1924         g_free(result.path);
1925         g_free(result.addr);
1926         g_free(result.name);
1927         g_free(result.ssid);
1928
1929 unref:
1930         dbus_message_unref(reply);
1931
1932         dbus_pending_call_unref(call);
1933
1934         get_properties(task);
1935 }
1936
1937 static void get_properties(struct supplicant_task *task)
1938 {
1939         DBusMessage *message;
1940         char *path;
1941
1942         path = g_slist_nth_data(task->scan_results, 0);
1943         if (path == NULL) {
1944                 if (task->hidden_found == TRUE) {
1945                         /*
1946                          * We're done with regular scanning, let's enable
1947                          * the missing network blocks if there are hidden
1948                          * SSIDs around.
1949                          */
1950                         hidden_block_enable(task);
1951                 }
1952                 goto noscan;
1953         }
1954
1955         message = dbus_message_new_method_call(SUPPLICANT_NAME, path,
1956                                                 SUPPLICANT_INTF ".BSSID",
1957                                                                 "properties");
1958
1959         task->scan_results = g_slist_remove(task->scan_results, path);
1960         g_free(path);
1961
1962         if (message == NULL)
1963                 goto noscan;
1964
1965         dbus_message_set_auto_start(message, FALSE);
1966
1967         if (dbus_connection_send_with_reply(connection, message,
1968                                 &task->result_call, TIMEOUT) == FALSE) {
1969                 connman_error("Failed to get network properties");
1970                 dbus_message_unref(message);
1971                 goto noscan;
1972         }
1973
1974         if (task->result_call == NULL) {
1975                 connman_error("D-Bus connection not available");
1976                 dbus_message_unref(message);
1977                 goto noscan;
1978         }
1979
1980         dbus_pending_call_set_notify(task->result_call,
1981                                         properties_reply, task, NULL);
1982
1983         dbus_message_unref(message);
1984
1985         return;
1986
1987 noscan:
1988         task->result_call = NULL;
1989
1990         if (task->scanning == TRUE) {
1991                 connman_device_set_scanning(task->device, FALSE);
1992                 task->scanning = FALSE;
1993         }
1994 }
1995
1996 static void scan_results_reply(DBusPendingCall *call, void *user_data)
1997 {
1998         struct supplicant_task *task = user_data;
1999         DBusMessage *reply;
2000         DBusError error;
2001         char **results;
2002         int i, num_results;
2003
2004         DBG("task %p", task);
2005
2006         reply = dbus_pending_call_steal_reply(call);
2007
2008         if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR)
2009                 goto done;
2010
2011         dbus_error_init(&error);
2012
2013         if (dbus_message_get_args(reply, &error,
2014                                 DBUS_TYPE_ARRAY, DBUS_TYPE_OBJECT_PATH,
2015                                                 &results, &num_results,
2016                                                 DBUS_TYPE_INVALID) == FALSE) {
2017                 if (dbus_error_is_set(&error) == TRUE) {
2018                         connman_error("%s", error.message);
2019                         dbus_error_free(&error);
2020                 } else
2021                         connman_error("Wrong arguments for scan result");
2022                 goto done;
2023         }
2024
2025         if (num_results == 0)
2026                 goto done;
2027
2028         for (i = 0; i < num_results; i++) {
2029                 char *path = g_strdup(results[i]);
2030                 if (path == NULL)
2031                         continue;
2032
2033                 task->scan_results = g_slist_append(task->scan_results, path);
2034         }
2035
2036         task->hidden_found = FALSE;
2037
2038         g_strfreev(results);
2039
2040         dbus_message_unref(reply);
2041
2042         dbus_pending_call_unref(call);
2043
2044         get_properties(task);
2045
2046         return;
2047
2048 done:
2049         dbus_message_unref(reply);
2050
2051         dbus_pending_call_unref(call);
2052
2053         task->result_call = NULL;
2054
2055         if (task->scanning == TRUE) {
2056                 connman_device_set_scanning(task->device, FALSE);
2057                 task->scanning = FALSE;
2058         }
2059 }
2060
2061 static void scan_results_available(struct supplicant_task *task)
2062 {
2063         DBusMessage *message;
2064
2065         DBG("task %p", task);
2066
2067         if (task->result_call != NULL)
2068                 return;
2069
2070         message = dbus_message_new_method_call(SUPPLICANT_NAME, task->path,
2071                                                 SUPPLICANT_INTF ".Interface",
2072                                                         "scanResults");
2073         if (message == NULL)
2074                 return;
2075
2076         dbus_message_set_auto_start(message, FALSE);
2077
2078         if (dbus_connection_send_with_reply(connection, message,
2079                                 &task->result_call, TIMEOUT) == FALSE) {
2080                 connman_error("Failed to request scan result");
2081                 goto done;
2082         }
2083
2084         if (task->result_call == NULL) {
2085                 connman_error("D-Bus connection not available");
2086                 goto done;
2087         }
2088
2089         if (task->scanning == TRUE)
2090                 connman_device_set_scanning(task->device, TRUE);
2091
2092         dbus_pending_call_set_notify(task->result_call,
2093                                         scan_results_reply, task, NULL);
2094
2095 done:
2096         dbus_message_unref(message);
2097 }
2098
2099 static enum supplicant_state string2state(const char *state)
2100 {
2101         if (g_str_equal(state, "INACTIVE") == TRUE)
2102                 return WPA_INACTIVE;
2103         else if (g_str_equal(state, "SCANNING") == TRUE)
2104                 return WPA_SCANNING;
2105         else if (g_str_equal(state, "ASSOCIATING") == TRUE)
2106                 return WPA_ASSOCIATING;
2107         else if (g_str_equal(state, "ASSOCIATED") == TRUE)
2108                 return WPA_ASSOCIATED;
2109         else if (g_str_equal(state, "GROUP_HANDSHAKE") == TRUE)
2110                 return WPA_GROUP_HANDSHAKE;
2111         else if (g_str_equal(state, "4WAY_HANDSHAKE") == TRUE)
2112                 return WPA_4WAY_HANDSHAKE;
2113         else if (g_str_equal(state, "COMPLETED") == TRUE)
2114                 return WPA_COMPLETED;
2115         else if (g_str_equal(state, "DISCONNECTED") == TRUE)
2116                 return WPA_DISCONNECTED;
2117         else
2118                 return WPA_INVALID;
2119 }
2120
2121 static int task_connect(struct supplicant_task *task)
2122 {
2123         const char *address, *security, *passphrase;
2124         const void *ssid;
2125         unsigned int ssid_len;
2126         int err;
2127
2128         g_hash_table_foreach(task->hidden_blocks, block_reset, task);
2129
2130         connman_inet_ifup(task->ifindex);
2131
2132         address = connman_network_get_string(task->network, "Address");
2133         security = connman_network_get_string(task->network, "WiFi.Security");
2134         passphrase = connman_network_get_string(task->network, "WiFi.Passphrase");
2135
2136         ssid = connman_network_get_blob(task->network, "WiFi.SSID", &ssid_len);
2137
2138         DBG("address %s security %s", address, security);
2139
2140         if (security == NULL)
2141                 return -EINVAL;
2142
2143         if (passphrase == NULL && g_str_equal(security, "none") == FALSE &&
2144                                 g_str_equal(security, "ieee8021x") == FALSE)
2145                 return -EINVAL;
2146
2147         remove_network(task);
2148
2149         set_ap_scan(task);
2150
2151         add_network(task);
2152
2153         err = set_network(task, ssid, ssid_len, address, security, passphrase);
2154         if (err < 0)
2155                 return err;
2156
2157         err = select_network(task);
2158         if (err < 0)
2159                 return err;
2160
2161         return -EINPROGRESS;
2162 }
2163
2164 static void scanning(struct supplicant_task *task, DBusMessage *msg)
2165 {
2166         DBusError error;
2167         dbus_bool_t scanning;
2168
2169         dbus_error_init(&error);
2170
2171         if (dbus_message_get_args(msg, &error, DBUS_TYPE_BOOLEAN, &scanning,
2172                                                 DBUS_TYPE_INVALID) == FALSE) {
2173                 if (dbus_error_is_set(&error) == TRUE) {
2174                         connman_error("%s", error.message);
2175                         dbus_error_free(&error);
2176                 } else
2177                         connman_error("Wrong arguments for scanning");
2178                 return;
2179         }
2180
2181         connman_info("%s scanning %s", task->ifname,
2182                                 scanning == TRUE ? "started" : "finished");
2183 }
2184
2185 static void state_change(struct supplicant_task *task, DBusMessage *msg)
2186 {
2187         DBusError error;
2188         const char *newstate, *oldstate;
2189         unsigned char bssid[ETH_ALEN];
2190         unsigned int bssid_len;
2191         enum supplicant_state state, prevstate;
2192
2193         dbus_error_init(&error);
2194
2195         if (dbus_message_get_args(msg, &error, DBUS_TYPE_STRING, &newstate,
2196                                                 DBUS_TYPE_STRING, &oldstate,
2197                                                 DBUS_TYPE_INVALID) == FALSE) {
2198                 if (dbus_error_is_set(&error) == TRUE) {
2199                         connman_error("%s", error.message);
2200                         dbus_error_free(&error);
2201                 } else
2202                         connman_error("Wrong arguments for state change");
2203                 return;
2204         }
2205
2206         DBG("state %s ==> %s", oldstate, newstate);
2207
2208         connman_info("%s %s%s", task->ifname, newstate,
2209                                 task->scanning == TRUE ? " (scanning)" : "");
2210
2211         state = string2state(newstate);
2212         if (state == WPA_INVALID)
2213                 return;
2214
2215         prevstate = task->state;
2216         task->state = state;
2217
2218         if (task->network == NULL)
2219                 return;
2220
2221         switch (task->state) {
2222         case WPA_COMPLETED:
2223                 switch (prevstate) {
2224                 case WPA_ASSOCIATED:
2225                 case WPA_GROUP_HANDSHAKE:
2226                         break;
2227                 default:
2228                         goto badstate;
2229                 }
2230
2231                 /* reset scan trigger and schedule background scan */
2232                 connman_device_schedule_scan(task->device);
2233
2234                 if (get_bssid(task->device, bssid, &bssid_len) == 0)
2235                         connman_network_set_address(task->network,
2236                                                         bssid, bssid_len);
2237
2238                 /* carrier on */
2239                 connman_network_set_connected(task->network, TRUE);
2240                 break;
2241
2242         case WPA_ASSOCIATING:
2243                 switch (prevstate) {
2244                 case WPA_COMPLETED:
2245                         break;
2246                 case WPA_SCANNING:
2247                         connman_network_set_associating(task->network, TRUE);
2248                         break;
2249                 default:
2250                         goto badstate;
2251                 }
2252                 break;
2253
2254         case WPA_INACTIVE:
2255                 switch (prevstate) {
2256                 case WPA_SCANNING:
2257                 case WPA_DISCONNECTED:
2258                         break;
2259                 default:
2260                         goto badstate;
2261                 }
2262                 /* fall through */
2263
2264         case WPA_DISCONNECTED:
2265                 /* carrier off */
2266                 connman_network_set_connected(task->network, FALSE);
2267
2268                 if (task->disconnecting == TRUE) {
2269                         connman_network_unref(task->network);
2270                         task->disconnecting = FALSE;
2271
2272                         if (task->pending_network != NULL) {
2273                                 task->network = task->pending_network;
2274                                 task->pending_network = NULL;
2275                                 task_connect(task);
2276                         } else
2277                                 task->network = NULL;
2278                 }
2279                 break;
2280
2281         default:
2282                 connman_network_set_associating(task->network, FALSE);
2283                 break;
2284         }
2285
2286         return;
2287
2288 badstate:
2289         connman_error("%s invalid state change %s -> %s", task->ifname,
2290                                                         oldstate, newstate);
2291 }
2292
2293 static gboolean supplicant_filter(DBusConnection *conn,
2294                                                 DBusMessage *msg, void *data)
2295 {
2296         struct supplicant_task *task;
2297         const char *member, *path;
2298
2299         member = dbus_message_get_member(msg);
2300         if (member == NULL)
2301                 return TRUE;
2302
2303         path = dbus_message_get_path(msg);
2304         if (path == NULL)
2305                 return TRUE;
2306
2307         task = find_task_by_path(path);
2308         if (task == NULL)
2309                 return TRUE;
2310
2311         DBG("task %p member %s", task, member);
2312
2313         if (g_str_equal(member, "ScanResultsAvailable") == TRUE)
2314                 scan_results_available(task);
2315         else if (g_str_equal(member, "Scanning") == TRUE)
2316                 scanning(task, msg);
2317         else if (g_str_equal(member, "StateChange") == TRUE)
2318                 state_change(task, msg);
2319
2320         return TRUE;
2321 }
2322
2323 int supplicant_start(struct connman_device *device)
2324 {
2325         struct supplicant_task *task;
2326         int err;
2327
2328         DBG("device %p", device);
2329
2330         task = g_try_new0(struct supplicant_task, 1);
2331         if (task == NULL)
2332                 return -ENOMEM;
2333
2334         task->ifindex = connman_device_get_index(device);
2335         task->ifname = connman_inet_ifname(task->ifindex);
2336
2337         if (task->ifname == NULL) {
2338                 err = -ENOMEM;
2339                 goto failed;
2340         }
2341
2342         task->cfg80211 = connman_inet_is_cfg80211(task->ifindex);
2343         if (task->cfg80211 == FALSE)
2344                 connman_warn("Enabling quirks for unsupported driver");
2345
2346         task->range = g_try_malloc0(sizeof(struct iw_range));
2347         if (task->range == NULL) {
2348                 err = -ENOMEM;
2349                 goto failed;
2350         }
2351
2352         err = get_range(task);
2353         if (err < 0)
2354                 goto failed;
2355
2356         task->device = connman_device_ref(device);
2357
2358         task->created = FALSE;
2359         task->scanning = FALSE;
2360         task->state = WPA_INVALID;
2361         task->disconnecting = FALSE;
2362         task->pending_network = NULL;
2363         task->hidden_blocks = g_hash_table_new_full(g_str_hash, g_str_equal,
2364                                                         NULL, remove_block);
2365         task_list = g_slist_append(task_list, task);
2366
2367         return create_interface(task);
2368
2369 failed:
2370         g_free(task->range);
2371         g_free(task->ifname);
2372         g_free(task);
2373
2374         return err;
2375 }
2376
2377 int supplicant_stop(struct connman_device *device)
2378 {
2379         int index = connman_device_get_index(device);
2380         struct supplicant_task *task;
2381
2382         DBG("device %p", device);
2383
2384         task = find_task_by_index(index);
2385         if (task == NULL)
2386                 return -ENODEV;
2387
2388         g_free(task->range);
2389
2390         task_list = g_slist_remove(task_list, task);
2391         g_hash_table_destroy(task->hidden_blocks);
2392
2393         if (task->scan_call != NULL) {
2394                 dbus_pending_call_cancel(task->scan_call);
2395                 task->scan_call = NULL;
2396         }
2397
2398         if (task->result_call != NULL) {
2399                 dbus_pending_call_cancel(task->result_call);
2400                 task->result_call = NULL;
2401         }
2402
2403         if (task->scanning == TRUE)
2404                 connman_device_set_scanning(task->device, FALSE);
2405
2406         remove_network(task);
2407
2408         disconnect_network(task);
2409
2410         return remove_interface(task);
2411 }
2412
2413 int supplicant_scan(struct connman_device *device)
2414 {
2415         int index = connman_device_get_index(device);
2416         struct supplicant_task *task;
2417         int err;
2418
2419         DBG("device %p", device);
2420
2421         task = find_task_by_index(index);
2422         if (task == NULL)
2423                 return -ENODEV;
2424
2425         switch (task->state) {
2426         case WPA_SCANNING:
2427                 return -EALREADY;
2428         case WPA_ASSOCIATING:
2429         case WPA_ASSOCIATED:
2430         case WPA_4WAY_HANDSHAKE:
2431         case WPA_GROUP_HANDSHAKE:
2432                 return -EBUSY;
2433         default:
2434                 break;
2435         }
2436
2437         task->scanning = TRUE;
2438
2439         err = initiate_scan(task);
2440         if (err < 0) {
2441                 if (err == -EINPROGRESS)
2442                         return 0;
2443
2444                 task->scanning = FALSE;
2445                 return err;
2446         }
2447
2448         connman_device_set_scanning(task->device, TRUE);
2449
2450         return 0;
2451 }
2452
2453 int supplicant_connect(struct connman_network *network)
2454 {
2455         struct supplicant_task *task;
2456         int index;
2457
2458         DBG("network %p", network);
2459
2460         index = connman_network_get_index(network);
2461
2462         task = find_task_by_index(index);
2463         if (task == NULL)
2464                 return -ENODEV;
2465
2466         if (task->disconnecting == TRUE)
2467                 task->pending_network = connman_network_ref(network);
2468         else {
2469                 task->network = connman_network_ref(network);
2470                 return task_connect(task);
2471         }
2472
2473         return -EINPROGRESS;
2474 }
2475
2476 int supplicant_disconnect(struct connman_network *network)
2477 {
2478         struct supplicant_task *task;
2479         int index;
2480
2481         DBG("network %p", network);
2482
2483         index = connman_network_get_index(network);
2484
2485         task = find_task_by_index(index);
2486         if (task == NULL)
2487                 return -ENODEV;
2488
2489         if (task->disconnecting == TRUE)
2490                 return -EALREADY;
2491
2492         remove_network(task);
2493
2494         disconnect_network(task);
2495
2496         task->disconnecting = TRUE;
2497
2498         return 0;
2499 }
2500
2501 static void supplicant_activate(DBusConnection *conn)
2502 {
2503         DBusMessage *message;
2504
2505         DBG("conn %p", conn);
2506
2507         message = dbus_message_new_method_call(SUPPLICANT_NAME, "/",
2508                                 DBUS_INTERFACE_INTROSPECTABLE, "Introspect");
2509         if (message == NULL)
2510                 return;
2511
2512         dbus_message_set_no_reply(message, TRUE);
2513
2514         dbus_connection_send(conn, message, NULL);
2515
2516         dbus_message_unref(message);
2517 }
2518
2519 static GSList *driver_list = NULL;
2520
2521 static void supplicant_probe(DBusConnection *conn, void *user_data)
2522 {
2523         GSList *list;
2524
2525         DBG("conn %p", conn);
2526
2527         for (list = driver_list; list; list = list->next) {
2528                 struct supplicant_driver *driver = list->data;
2529
2530                 DBG("driver %p name %s", driver, driver->name);
2531
2532                 if (driver->probe)
2533                         driver->probe();
2534         }
2535 }
2536
2537 static void supplicant_remove(DBusConnection *conn, void *user_data)
2538 {
2539         GSList *list;
2540
2541         DBG("conn %p", conn);
2542
2543         for (list = driver_list; list; list = list->next) {
2544                 struct supplicant_driver *driver = list->data;
2545
2546                 DBG("driver %p name %s", driver, driver->name);
2547
2548                 if (driver->remove)
2549                         driver->remove();
2550         }
2551 }
2552
2553 static guint watch;
2554 static guint iface_watch;
2555
2556 static int supplicant_create(void)
2557 {
2558         if (g_slist_length(driver_list) > 0)
2559                 return 0;
2560
2561         connection = connman_dbus_get_connection();
2562         if (connection == NULL)
2563                 return -EIO;
2564
2565         DBG("connection %p", connection);
2566
2567         watch = g_dbus_add_service_watch(connection, SUPPLICANT_NAME,
2568                         supplicant_probe, supplicant_remove, NULL, NULL);
2569
2570         iface_watch = g_dbus_add_signal_watch(connection, NULL, NULL,
2571                                                 SUPPLICANT_INTF ".Interface",
2572                                                 NULL, supplicant_filter,
2573                                                 NULL, NULL);
2574
2575         if (watch == 0 || iface_watch == 0) {
2576                 g_dbus_remove_watch(connection, watch);
2577                 g_dbus_remove_watch(connection, iface_watch);
2578                 return -EIO;
2579         }
2580
2581         return 0;
2582 }
2583
2584 static void supplicant_destroy(void)
2585 {
2586         if (g_slist_length(driver_list) > 0)
2587                 return;
2588
2589         DBG("connection %p", connection);
2590
2591         g_dbus_remove_watch(connection, watch);
2592         g_dbus_remove_watch(connection, iface_watch);
2593
2594         dbus_connection_unref(connection);
2595         connection = NULL;
2596 }
2597
2598 int supplicant_register(struct supplicant_driver *driver)
2599 {
2600         int err;
2601
2602         DBG("driver %p name %s", driver, driver->name);
2603
2604         err = supplicant_create();
2605         if (err < 0)
2606                 return err;
2607
2608         driver_list = g_slist_append(driver_list, driver);
2609
2610         supplicant_activate(connection);
2611
2612         return 0;
2613 }
2614
2615 void supplicant_unregister(struct supplicant_driver *driver)
2616 {
2617         DBG("driver %p name %s", driver, driver->name);
2618
2619         supplicant_remove(connection, NULL);
2620
2621         driver_list = g_slist_remove(driver_list, driver);
2622
2623         supplicant_destroy();
2624 }