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