Update the network address when connected
[platform/upstream/connman.git] / plugins / supplicant.c
1 /*
2  *
3  *  Connection Manager
4  *
5  *  Copyright (C) 2007-2009  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/log.h>
45
46 #include "supplicant.h"
47
48 #define TIMEOUT 5000
49
50 #define IEEE80211_CAP_ESS       0x0001
51 #define IEEE80211_CAP_IBSS      0x0002
52 #define IEEE80211_CAP_PRIVACY   0x0010
53
54 #define SUPPLICANT_NAME  "fi.epitest.hostap.WPASupplicant"
55 #define SUPPLICANT_INTF  "fi.epitest.hostap.WPASupplicant"
56 #define SUPPLICANT_PATH  "/fi/epitest/hostap/WPASupplicant"
57
58 /* Taken from "WPA Supplicant - Common definitions" */
59 enum supplicant_state {
60         /**
61          * WPA_DISCONNECTED - Disconnected state
62          *
63          * This state indicates that client is not associated, but is likely to
64          * start looking for an access point. This state is entered when a
65          * connection is lost.
66          */
67         WPA_DISCONNECTED,
68
69         /**
70          * WPA_INACTIVE - Inactive state (wpa_supplicant disabled)
71          *
72          * This state is entered if there are no enabled networks in the
73          * configuration. wpa_supplicant is not trying to associate with a new
74          * network and external interaction (e.g., ctrl_iface call to add or
75          * enable a network) is needed to start association.
76          */
77         WPA_INACTIVE,
78
79         /**
80          * WPA_SCANNING - Scanning for a network
81          *
82          * This state is entered when wpa_supplicant starts scanning for a
83          * network.
84          */
85         WPA_SCANNING,
86
87         /**
88          * WPA_ASSOCIATING - Trying to associate with a BSS/SSID
89          *
90          * This state is entered when wpa_supplicant has found a suitable BSS
91          * to associate with and the driver is configured to try to associate
92          * with this BSS in ap_scan=1 mode. When using ap_scan=2 mode, this
93          * state is entered when the driver is configured to try to associate
94          * with a network using the configured SSID and security policy.
95          */
96         WPA_ASSOCIATING,
97
98         /**
99          * WPA_ASSOCIATED - Association completed
100          *
101          * This state is entered when the driver reports that association has
102          * been successfully completed with an AP. If IEEE 802.1X is used
103          * (with or without WPA/WPA2), wpa_supplicant remains in this state
104          * until the IEEE 802.1X/EAPOL authentication has been completed.
105          */
106         WPA_ASSOCIATED,
107
108         /**
109          * WPA_4WAY_HANDSHAKE - WPA 4-Way Key Handshake in progress
110          *
111          * This state is entered when WPA/WPA2 4-Way Handshake is started. In
112          * case of WPA-PSK, this happens when receiving the first EAPOL-Key
113          * frame after association. In case of WPA-EAP, this state is entered
114          * when the IEEE 802.1X/EAPOL authentication has been completed.
115          */
116         WPA_4WAY_HANDSHAKE,
117
118         /**
119          * WPA_GROUP_HANDSHAKE - WPA Group Key Handshake in progress
120          *
121          * This state is entered when 4-Way Key Handshake has been completed
122          * (i.e., when the supplicant sends out message 4/4) and when Group
123          * Key rekeying is started by the AP (i.e., when supplicant receives
124          * message 1/2).
125          */
126         WPA_GROUP_HANDSHAKE,
127
128         /**
129          * WPA_COMPLETED - All authentication completed
130          *
131          * This state is entered when the full authentication process is
132          * completed. In case of WPA2, this happens when the 4-Way Handshake is
133          * successfully completed. With WPA, this state is entered after the
134          * Group Key Handshake; with IEEE 802.1X (non-WPA) connection is
135          * completed after dynamic keys are received (or if not used, after
136          * the EAP authentication has been completed). With static WEP keys and
137          * plaintext connections, this state is entered when an association
138          * has been completed.
139          *
140          * This state indicates that the supplicant has completed its
141          * processing for the association phase and that data connection is
142          * fully configured.
143          */
144         WPA_COMPLETED,
145
146         /**
147          * WPA_INVALID - Invalid state (parsing error)
148          *
149          * This state is returned if the string input is invalid. It is not
150          * an official wpa_supplicant state.
151          */
152         WPA_INVALID,
153 };
154
155 struct supplicant_result {
156         char *path;
157         char *name;
158         unsigned char *addr;
159         unsigned int addr_len;
160         unsigned char *ssid;
161         unsigned int ssid_len;
162         dbus_uint16_t capabilities;
163         gboolean adhoc;
164         gboolean has_wep;
165         gboolean has_wpa;
166         gboolean has_rsn;
167         gboolean has_wps;
168         dbus_int32_t frequency;
169         dbus_int32_t quality;
170         dbus_int32_t noise;
171         dbus_int32_t level;
172         dbus_int32_t maxrate;
173 };
174
175 struct supplicant_task {
176         int ifindex;
177         char *ifname;
178         struct connman_device *device;
179         struct connman_network *network;
180         struct connman_network *pending_network;
181         char *path;
182         char *netpath;
183         gboolean created;
184         enum supplicant_state state;
185         gboolean noscan;
186         GSList *scan_results;
187         struct iw_range *range;
188         gboolean disconnecting;
189 };
190
191 static GSList *task_list = NULL;
192
193 static DBusConnection *connection;
194
195 static void free_task(struct supplicant_task *task)
196 {
197         DBG("task %p", task);
198
199         g_free(task->ifname);
200         g_free(task->path);
201         g_free(task);
202 }
203
204 static struct supplicant_task *find_task_by_index(int index)
205 {
206         GSList *list;
207
208         for (list = task_list; list; list = list->next) {
209                 struct supplicant_task *task = list->data;
210
211                 if (task->ifindex == index)
212                         return task;
213         }
214
215         return NULL;
216 }
217
218 static struct supplicant_task *find_task_by_path(const char *path)
219 {
220         GSList *list;
221
222         for (list = task_list; list; list = list->next) {
223                 struct supplicant_task *task = list->data;
224
225                 if (g_strcmp0(task->path, path) == 0)
226                         return task;
227         }
228
229         return NULL;
230 }
231
232 static int get_range(struct supplicant_task *task)
233 {
234         struct iwreq wrq;
235         int fd, err;
236
237         fd = socket(PF_INET, SOCK_DGRAM, 0);
238         if (fd < 0)
239                 return -1;
240
241         memset(&wrq, 0, sizeof(struct iwreq));
242         strncpy(wrq.ifr_name, task->ifname, IFNAMSIZ);
243         wrq.u.data.pointer = task->range;
244         wrq.u.data.length = sizeof(struct iw_range);
245
246         err = ioctl(fd, SIOCGIWRANGE, &wrq);
247
248         close(fd);
249
250         return err;
251 }
252
253 static int get_bssid(struct connman_device *device,
254                                 unsigned char *bssid, unsigned int *bssid_len)
255 {
256         struct iwreq wrq;
257         char *ifname;
258         int ifindex;
259         int fd, err;
260
261         ifindex = connman_device_get_index(device);
262         if (ifindex < 0)
263                 return -EINVAL;
264
265         ifname = connman_inet_ifname(ifindex);
266         if (ifname == NULL)
267                 return -EINVAL;
268
269         fd = socket(PF_INET, SOCK_DGRAM, 0);
270         if (fd < 0) {
271                 g_free(ifname);
272                 return -EINVAL;
273         }
274
275         memset(&wrq, 0, sizeof(wrq));
276         strncpy(wrq.ifr_name, ifname, IFNAMSIZ);
277
278         err = ioctl(fd, SIOCGIWAP, &wrq);
279
280         g_free(ifname);
281         close(fd);
282
283         if (err < 0)
284                 return -EIO;
285
286         memcpy(bssid, wrq.u.ap_addr.sa_data, ETH_ALEN);
287         *bssid_len = ETH_ALEN;
288
289         return 0;
290 }
291
292 static void add_interface_reply(DBusPendingCall *call, void *user_data)
293 {
294         struct supplicant_task *task = user_data;
295         DBusMessage *reply;
296         DBusError error;
297         const char *path;
298
299         DBG("task %p", task);
300
301         reply = dbus_pending_call_steal_reply(call);
302         if (reply == NULL)
303                 return;
304
305         if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR)
306                 goto failed;
307
308         dbus_error_init(&error);
309
310         if (dbus_message_get_args(reply, &error, DBUS_TYPE_OBJECT_PATH, &path,
311                                                 DBUS_TYPE_INVALID) == FALSE) {
312                 if (dbus_error_is_set(&error) == TRUE) {
313                         connman_error("%s", error.message);
314                         dbus_error_free(&error);
315                 } else
316                         connman_error("Wrong arguments for add interface");
317                 goto failed;
318         }
319
320         DBG("path %s", path);
321
322         task->path = g_strdup(path);
323         task->created = TRUE;
324
325         connman_device_set_powered(task->device, TRUE);
326
327         dbus_message_unref(reply);
328
329         return;
330
331 failed:
332         task_list = g_slist_remove(task_list, task);
333
334         connman_device_unref(task->device);
335
336         free_task(task);
337 }
338
339 static int add_interface(struct supplicant_task *task)
340 {
341         const char *driver = connman_option_get_string("wifi");
342         DBusMessage *message;
343         DBusMessageIter array, dict;
344         DBusPendingCall *call;
345
346         DBG("task %p", task);
347
348         message = dbus_message_new_method_call(SUPPLICANT_NAME, SUPPLICANT_PATH,
349                                         SUPPLICANT_INTF, "addInterface");
350         if (message == NULL)
351                 return -ENOMEM;
352
353         dbus_message_iter_init_append(message, &array);
354
355         dbus_message_iter_append_basic(&array,
356                                         DBUS_TYPE_STRING, &task->ifname);
357
358         dbus_message_iter_open_container(&array, DBUS_TYPE_ARRAY,
359                         DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
360                         DBUS_TYPE_STRING_AS_STRING DBUS_TYPE_VARIANT_AS_STRING
361                         DBUS_DICT_ENTRY_END_CHAR_AS_STRING, &dict);
362
363         connman_dbus_dict_append_variant(&dict, "driver",
364                                                 DBUS_TYPE_STRING, &driver);
365
366         dbus_message_iter_close_container(&array, &dict);
367
368         if (dbus_connection_send_with_reply(connection, message,
369                                                 &call, TIMEOUT) == FALSE) {
370                 connman_error("Failed to add interface");
371                 dbus_message_unref(message);
372                 return -EIO;
373         }
374
375         if (call == NULL) {
376                 connman_error("D-Bus connection not available");
377                 dbus_message_unref(message);
378                 return -EIO;
379         }
380
381         dbus_pending_call_set_notify(call, add_interface_reply, task, NULL);
382
383         dbus_message_unref(message);
384
385         return -EINPROGRESS;
386 }
387
388 static void get_interface_reply(DBusPendingCall *call, void *user_data)
389 {
390         struct supplicant_task *task = user_data;
391         DBusMessage *reply;
392         DBusError error;
393         const char *path;
394
395         DBG("task %p", task);
396
397         reply = dbus_pending_call_steal_reply(call);
398         if (reply == NULL)
399                 return;
400
401         if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR) {
402                 add_interface(task);
403                 goto done;
404         }
405
406         dbus_error_init(&error);
407
408         if (dbus_message_get_args(reply, &error, DBUS_TYPE_OBJECT_PATH, &path,
409                                                 DBUS_TYPE_INVALID) == FALSE) {
410                 if (dbus_error_is_set(&error) == TRUE) {
411                         connman_error("%s", error.message);
412                         dbus_error_free(&error);
413                 } else
414                         connman_error("Wrong arguments for get interface");
415                 goto done;
416         }
417
418         DBG("path %s", path);
419
420         task->path = g_strdup(path);
421         task->created = FALSE;
422
423         connman_device_set_powered(task->device, TRUE);
424
425 done:
426         dbus_message_unref(reply);
427 }
428
429 static int create_interface(struct supplicant_task *task)
430 {
431         DBusMessage *message;
432         DBusPendingCall *call;
433
434         DBG("task %p", task);
435
436         message = dbus_message_new_method_call(SUPPLICANT_NAME, SUPPLICANT_PATH,
437                                         SUPPLICANT_INTF, "getInterface");
438         if (message == NULL)
439                 return -ENOMEM;
440
441         dbus_message_append_args(message, DBUS_TYPE_STRING, &task->ifname,
442                                                         DBUS_TYPE_INVALID);
443
444         if (dbus_connection_send_with_reply(connection, message,
445                                                 &call, TIMEOUT) == FALSE) {
446                 connman_error("Failed to get interface");
447                 dbus_message_unref(message);
448                 return -EIO;
449         }
450
451         if (call == NULL) {
452                 connman_error("D-Bus connection not available");
453                 dbus_message_unref(message);
454                 return -EIO;
455         }
456
457         dbus_pending_call_set_notify(call, get_interface_reply, task, NULL);
458
459         dbus_message_unref(message);
460
461         return -EINPROGRESS;
462 }
463
464 static void remove_interface_reply(DBusPendingCall *call, void *user_data)
465 {
466         struct supplicant_task *task = user_data;
467         DBusMessage *reply;
468
469         DBG("task %p", task);
470
471         reply = dbus_pending_call_steal_reply(call);
472
473         connman_device_set_powered(task->device, FALSE);
474
475         connman_device_unref(task->device);
476
477         connman_inet_ifdown(task->ifindex);
478
479         free_task(task);
480
481         dbus_message_unref(reply);
482 }
483
484 static int remove_interface(struct supplicant_task *task)
485 {
486         DBusMessage *message;
487         DBusPendingCall *call;
488
489         DBG("task %p", task);
490
491         if (task->created == FALSE) {
492                 connman_device_set_powered(task->device, FALSE);
493                 return 0;
494         }
495
496         message = dbus_message_new_method_call(SUPPLICANT_NAME, SUPPLICANT_PATH,
497                                         SUPPLICANT_INTF, "removeInterface");
498         if (message == NULL)
499                 return -ENOMEM;
500
501         dbus_message_append_args(message, DBUS_TYPE_OBJECT_PATH, &task->path,
502                                                         DBUS_TYPE_INVALID);
503
504         if (dbus_connection_send_with_reply(connection, message,
505                                                 &call, TIMEOUT) == FALSE) {
506                 connman_error("Failed to remove interface");
507                 dbus_message_unref(message);
508                 return -EIO;
509         }
510
511         if (call == NULL) {
512                 connman_error("D-Bus connection not available");
513                 dbus_message_unref(message);
514                 return -EIO;
515         }
516
517         dbus_pending_call_set_notify(call, remove_interface_reply, task, NULL);
518
519         dbus_message_unref(message);
520
521         return -EINPROGRESS;
522 }
523
524 #if 0
525 static int set_ap_scan(struct supplicant_task *task)
526 {
527         DBusMessage *message, *reply;
528         DBusError error;
529         guint32 ap_scan = 1;
530
531         DBG("task %p", task);
532
533         message = dbus_message_new_method_call(SUPPLICANT_NAME, task->path,
534                                 SUPPLICANT_INTF ".Interface", "setAPScan");
535         if (message == NULL)
536                 return -ENOMEM;
537
538         dbus_message_append_args(message, DBUS_TYPE_UINT32, &ap_scan,
539                                                         DBUS_TYPE_INVALID);
540
541         dbus_error_init(&error);
542
543         reply = dbus_connection_send_with_reply_and_block(connection,
544                                                         message, -1, &error);
545         if (reply == NULL) {
546                 if (dbus_error_is_set(&error) == TRUE) {
547                         connman_error("%s", error.message);
548                         dbus_error_free(&error);
549                 } else
550                         connman_error("Failed to set AP scan");
551                 dbus_message_unref(message);
552                 return -EIO;
553         }
554
555         dbus_message_unref(message);
556
557         dbus_message_unref(reply);
558
559         return 0;
560 }
561 #endif
562
563 static int add_network(struct supplicant_task *task)
564 {
565         DBusMessage *message, *reply;
566         DBusError error;
567         const char *path;
568
569         DBG("task %p", task);
570
571         if (task->netpath != NULL)
572                 return -EALREADY;
573
574         message = dbus_message_new_method_call(SUPPLICANT_NAME, task->path,
575                                 SUPPLICANT_INTF ".Interface", "addNetwork");
576         if (message == NULL)
577                 return -ENOMEM;
578
579         dbus_error_init(&error);
580
581         reply = dbus_connection_send_with_reply_and_block(connection,
582                                                         message, -1, &error);
583         if (reply == NULL) {
584                 if (dbus_error_is_set(&error) == TRUE) {
585                         connman_error("%s", error.message);
586                         dbus_error_free(&error);
587                 } else
588                         connman_error("Failed to add network");
589                 dbus_message_unref(message);
590                 return -EIO;
591         }
592
593         dbus_message_unref(message);
594
595         dbus_error_init(&error);
596
597         if (dbus_message_get_args(reply, &error, DBUS_TYPE_OBJECT_PATH, &path,
598                                                 DBUS_TYPE_INVALID) == FALSE) {
599                 if (dbus_error_is_set(&error) == TRUE) {
600                         connman_error("%s", error.message);
601                         dbus_error_free(&error);
602                 } else
603                         connman_error("Wrong arguments for network");
604                 dbus_message_unref(reply);
605                 return -EIO;
606         }
607
608         DBG("path %s", path);
609
610         task->netpath = g_strdup(path);
611
612         dbus_message_unref(reply);
613
614         return 0;
615 }
616
617 static int remove_network(struct supplicant_task *task)
618 {
619         DBusMessage *message, *reply;
620         DBusError error;
621
622         DBG("task %p", task);
623
624         if (task->netpath == NULL)
625                 return -EINVAL;
626
627         message = dbus_message_new_method_call(SUPPLICANT_NAME, task->path,
628                                 SUPPLICANT_INTF ".Interface", "removeNetwork");
629         if (message == NULL)
630                 return -ENOMEM;
631
632         dbus_message_append_args(message, DBUS_TYPE_OBJECT_PATH, &task->netpath,
633                                                         DBUS_TYPE_INVALID);
634
635         dbus_error_init(&error);
636
637         reply = dbus_connection_send_with_reply_and_block(connection,
638                                                         message, -1, &error);
639         if (reply == NULL) {
640                 if (dbus_error_is_set(&error) == TRUE) {
641                         connman_error("%s", error.message);
642                         dbus_error_free(&error);
643                 } else
644                         connman_error("Failed to remove network");
645                 dbus_message_unref(message);
646                 return -EIO;
647         }
648
649         dbus_message_unref(message);
650
651         dbus_message_unref(reply);
652
653         g_free(task->netpath);
654         task->netpath = NULL;
655
656         return 0;
657 }
658
659 static int select_network(struct supplicant_task *task)
660 {
661         DBusMessage *message, *reply;
662         DBusError error;
663
664         DBG("task %p", task);
665
666         if (task->netpath == NULL)
667                 return -EINVAL;
668
669         message = dbus_message_new_method_call(SUPPLICANT_NAME, task->path,
670                                 SUPPLICANT_INTF ".Interface", "selectNetwork");
671         if (message == NULL)
672                 return -ENOMEM;
673
674         dbus_message_append_args(message, DBUS_TYPE_OBJECT_PATH, &task->netpath,
675                                                         DBUS_TYPE_INVALID);
676
677         dbus_error_init(&error);
678
679         reply = dbus_connection_send_with_reply_and_block(connection,
680                                                         message, -1, &error);
681         if (reply == NULL) {
682                 if (dbus_error_is_set(&error) == TRUE) {
683                         connman_error("%s", error.message);
684                         dbus_error_free(&error);
685                 } else
686                         connman_error("Failed to select network");
687                 dbus_message_unref(message);
688                 return -EIO;
689         }
690
691         dbus_message_unref(message);
692
693         dbus_message_unref(reply);
694
695         return 0;
696 }
697
698 static int enable_network(struct supplicant_task *task)
699 {
700         DBusMessage *message, *reply;
701         DBusError error;
702
703         DBG("task %p", task);
704
705         if (task->netpath == NULL)
706                 return -EINVAL;
707
708         message = dbus_message_new_method_call(SUPPLICANT_NAME, task->netpath,
709                                         SUPPLICANT_INTF ".Network", "enable");
710         if (message == NULL)
711                 return -ENOMEM;
712
713         dbus_error_init(&error);
714
715         reply = dbus_connection_send_with_reply_and_block(connection,
716                                                         message, -1, &error);
717         if (reply == NULL) {
718                 if (dbus_error_is_set(&error) == TRUE) {
719                         connman_error("%s", error.message);
720                         dbus_error_free(&error);
721                 } else
722                         connman_error("Failed to enable network");
723                 dbus_message_unref(message);
724                 return -EIO;
725         }
726
727         dbus_message_unref(message);
728
729         dbus_message_unref(reply);
730
731         return 0;
732 }
733
734 static int disable_network(struct supplicant_task *task)
735 {
736         DBusMessage *message, *reply;
737         DBusError error;
738
739         DBG("task %p", task);
740
741         if (task->netpath == NULL)
742                 return -EINVAL;
743
744         message = dbus_message_new_method_call(SUPPLICANT_NAME, task->netpath,
745                                         SUPPLICANT_INTF ".Network", "disable");
746         if (message == NULL)
747                 return -ENOMEM;
748
749         dbus_error_init(&error);
750
751         reply = dbus_connection_send_with_reply_and_block(connection,
752                                                         message, -1, &error);
753         if (reply == NULL) {
754                 if (dbus_error_is_set(&error) == TRUE) {
755                         connman_error("%s", error.message);
756                         dbus_error_free(&error);
757                 } else
758                         connman_error("Failed to disable network");
759                 dbus_message_unref(message);
760                 return -EIO;
761         }
762
763         dbus_message_unref(message);
764
765         dbus_message_unref(reply);
766
767         return 0;
768 }
769
770 static int set_network(struct supplicant_task *task,
771                                 const unsigned char *network, int len,
772                                 const char *address, const char *security,
773                                                         const char *passphrase)
774 {
775         DBusMessage *message, *reply;
776         DBusMessageIter array, dict;
777         DBusError error;
778         dbus_uint32_t scan_ssid = 1;
779
780         DBG("task %p", task);
781
782         if (task->netpath == NULL)
783                 return -EINVAL;
784
785         message = dbus_message_new_method_call(SUPPLICANT_NAME, task->netpath,
786                                         SUPPLICANT_INTF ".Network", "set");
787         if (message == NULL)
788                 return -ENOMEM;
789
790         dbus_message_iter_init_append(message, &array);
791
792         dbus_message_iter_open_container(&array, DBUS_TYPE_ARRAY,
793                         DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
794                         DBUS_TYPE_STRING_AS_STRING DBUS_TYPE_VARIANT_AS_STRING
795                         DBUS_DICT_ENTRY_END_CHAR_AS_STRING, &dict);
796
797         connman_dbus_dict_append_variant(&dict, "scan_ssid",
798                                          DBUS_TYPE_UINT32, &scan_ssid);
799
800         if (address)
801                 connman_dbus_dict_append_variant(&dict, "bssid",
802                                                 DBUS_TYPE_STRING, &address);
803
804         connman_dbus_dict_append_array(&dict, "ssid",
805                                         DBUS_TYPE_BYTE, &network, len);
806
807         if (g_ascii_strcasecmp(security, "wpa") == 0 ||
808                                 g_ascii_strcasecmp(security, "rsn") == 0) {
809                 const char *key_mgmt = "WPA-PSK";
810                 connman_dbus_dict_append_variant(&dict, "key_mgmt",
811                                                 DBUS_TYPE_STRING, &key_mgmt);
812
813                 if (passphrase && strlen(passphrase) > 0)
814                         connman_dbus_dict_append_variant(&dict, "psk",
815                                                 DBUS_TYPE_STRING, &passphrase);
816         } else if (g_ascii_strcasecmp(security, "wep") == 0) {
817                 const char *key_mgmt = "NONE";
818                 const char *auth_alg = "OPEN SHARED";
819                 const char *key_index = "0";
820
821                 connman_dbus_dict_append_variant(&dict, "auth_alg",
822                                                 DBUS_TYPE_STRING, &auth_alg);
823
824                 connman_dbus_dict_append_variant(&dict, "key_mgmt",
825                                                 DBUS_TYPE_STRING, &key_mgmt);
826
827                 if (passphrase) {
828                         int size = strlen(passphrase);
829                         if (size == 10 || size == 26) {
830                                 unsigned char *key = malloc(13);
831                                 char tmp[3];
832                                 int i;
833                                 memset(tmp, 0, sizeof(tmp));
834                                 if (key == NULL)
835                                         size = 0;
836                                 for (i = 0; i < size / 2; i++) {
837                                         memcpy(tmp, passphrase + (i * 2), 2);
838                                         key[i] = (unsigned char) strtol(tmp,
839                                                                 NULL, 16);
840                                 }
841                                 connman_dbus_dict_append_array(&dict,
842                                                 "wep_key0", DBUS_TYPE_BYTE,
843                                                         &key, size / 2);
844                                 free(key);
845                         } else
846                                 connman_dbus_dict_append_variant(&dict,
847                                                 "wep_key0", DBUS_TYPE_STRING,
848                                                                 &passphrase);
849
850                         connman_dbus_dict_append_variant(&dict, "wep_tx_keyidx",
851                                                 DBUS_TYPE_STRING, &key_index);
852                 }
853         } else {
854                 const char *key_mgmt = "NONE";
855                 connman_dbus_dict_append_variant(&dict, "key_mgmt",
856                                                 DBUS_TYPE_STRING, &key_mgmt);
857         }
858
859         dbus_message_iter_close_container(&array, &dict);
860
861         dbus_error_init(&error);
862
863         reply = dbus_connection_send_with_reply_and_block(connection,
864                                                         message, -1, &error);
865         if (reply == NULL) {
866                 if (dbus_error_is_set(&error) == TRUE) {
867                         connman_error("%s", error.message);
868                         dbus_error_free(&error);
869                 } else
870                         connman_error("Failed to set network options");
871                 dbus_message_unref(message);
872                 return -EIO;
873         }
874
875         dbus_message_unref(message);
876
877         dbus_message_unref(reply);
878
879         return 0;
880 }
881
882 static int initiate_scan(struct supplicant_task *task)
883 {
884         DBusMessage *message;
885         DBusPendingCall *call;
886
887         DBG("task %p", task);
888
889         message = dbus_message_new_method_call(SUPPLICANT_NAME, task->path,
890                                         SUPPLICANT_INTF ".Interface", "scan");
891         if (message == NULL)
892                 return -ENOMEM;
893
894         if (dbus_connection_send_with_reply(connection, message,
895                                                 &call, TIMEOUT) == FALSE) {
896                 connman_error("Failed to initiate scan");
897                 dbus_message_unref(message);
898                 return -EIO;
899         }
900
901         dbus_message_unref(message);
902
903         return 0;
904 }
905
906 static struct {
907         char *name;
908         char *value;
909 } special_ssid[] = {
910         { "<hidden>", "hidden"  },
911         { "default",  "linksys" },
912         { "wireless"  },
913         { "linksys"   },
914         { "netgear"   },
915         { "dlink"     },
916         { "2wire"     },
917         { "compaq"    },
918         { "tsunami"   },
919         { "comcomcom", "3com"     },
920         { "3Com",      "3com"     },
921         { "Symbol",    "symbol"   },
922         { "Motorola",  "motorola" },
923         { "Wireless" , "wireless" },
924         { "WLAN",      "wlan"     },
925         { }
926 };
927
928 static char *build_group(const char *addr, const char *name,
929                         const unsigned char *ssid, unsigned int ssid_len,
930                                         const char *mode, const char *security)
931 {
932         GString *str;
933         unsigned int i;
934
935         if (addr == NULL)
936                 return NULL;
937
938         str = g_string_sized_new((ssid_len * 2) + 24);
939         if (str == NULL)
940                 return NULL;
941
942         if (ssid == NULL) {
943                 g_string_append_printf(str, "hidden_%s", addr);
944                 goto done;
945         }
946
947         for (i = 0; special_ssid[i].name; i++) {
948                 if (g_strcmp0(special_ssid[i].name, name) == 0) {
949                         if (special_ssid[i].value == NULL)
950                                 g_string_append_printf(str, "%s_%s",
951                                                                 name, addr);
952                         else
953                                 g_string_append_printf(str, "%s_%s",
954                                                 special_ssid[i].value, addr);
955                         goto done;
956                 }
957         }
958
959         if (ssid_len > 0 && ssid[0] != '\0') {
960                 for (i = 0; i < ssid_len; i++)
961                         g_string_append_printf(str, "%02x", ssid[i]);
962         } else
963                 g_string_append_printf(str, "hidden_%s", addr);
964
965 done:
966         g_string_append_printf(str, "_%s_%s", mode, security);
967
968         return g_string_free(str, FALSE);
969 }
970
971 static void extract_addr(DBusMessageIter *value,
972                                         struct supplicant_result *result)
973 {
974         DBusMessageIter array;
975         struct ether_addr eth;
976         unsigned char *addr;
977         int addr_len;
978
979         dbus_message_iter_recurse(value, &array);
980         dbus_message_iter_get_fixed_array(&array, &addr, &addr_len);
981
982         if (addr_len != 6)
983                 return;
984
985         result->addr = g_try_malloc(addr_len);
986         if (result->addr == NULL)
987                 return;
988
989         memcpy(result->addr, addr, addr_len);
990         result->addr_len = addr_len;
991
992         result->path = g_try_malloc0(13);
993         if (result->path == NULL)
994                 return;
995
996         memcpy(&eth, addr, sizeof(eth));
997         snprintf(result->path, 13, "%02x%02x%02x%02x%02x%02x",
998                                                 eth.ether_addr_octet[0],
999                                                 eth.ether_addr_octet[1],
1000                                                 eth.ether_addr_octet[2],
1001                                                 eth.ether_addr_octet[3],
1002                                                 eth.ether_addr_octet[4],
1003                                                 eth.ether_addr_octet[5]);
1004 }
1005
1006 static void extract_ssid(DBusMessageIter *value,
1007                                         struct supplicant_result *result)
1008 {
1009         DBusMessageIter array;
1010         unsigned char *ssid;
1011         int ssid_len, i;
1012
1013         dbus_message_iter_recurse(value, &array);
1014         dbus_message_iter_get_fixed_array(&array, &ssid, &ssid_len);
1015
1016         if (ssid_len < 1)
1017                 return;
1018
1019         if (ssid[0] == '\0')
1020                 return;
1021
1022         result->ssid = g_try_malloc(ssid_len);
1023         if (result->ssid == NULL)
1024                 return;
1025
1026         memcpy(result->ssid, ssid, ssid_len);
1027         result->ssid_len = ssid_len;
1028
1029         result->name = g_try_malloc0(ssid_len + 1);
1030         if (result->name == NULL)
1031                 return;
1032
1033         for (i = 0; i < ssid_len; i++) {
1034                 if (g_ascii_isprint(ssid[i]))
1035                         result->name[i] = ssid[i];
1036                 else
1037                         result->name[i] = ' ';
1038         }
1039 }
1040
1041 static void extract_wpaie(DBusMessageIter *value,
1042                                         struct supplicant_result *result)
1043 {
1044         DBusMessageIter array;
1045         unsigned char *ie;
1046         int ie_len;
1047
1048         dbus_message_iter_recurse(value, &array);
1049         dbus_message_iter_get_fixed_array(&array, &ie, &ie_len);
1050
1051         if (ie_len > 0)
1052                 result->has_wpa = TRUE;
1053 }
1054
1055 static void extract_rsnie(DBusMessageIter *value,
1056                                         struct supplicant_result *result)
1057 {
1058         DBusMessageIter array;
1059         unsigned char *ie;
1060         int ie_len;
1061
1062         dbus_message_iter_recurse(value, &array);
1063         dbus_message_iter_get_fixed_array(&array, &ie, &ie_len);
1064
1065         if (ie_len > 0)
1066                 result->has_rsn = TRUE;
1067 }
1068
1069 static void extract_wpsie(DBusMessageIter *value,
1070                                         struct supplicant_result *result)
1071 {
1072         DBusMessageIter array;
1073         unsigned char *ie;
1074         int ie_len;
1075
1076         dbus_message_iter_recurse(value, &array);
1077         dbus_message_iter_get_fixed_array(&array, &ie, &ie_len);
1078
1079         if (ie_len > 0)
1080                 result->has_wps = TRUE;
1081 }
1082
1083 static void extract_capabilites(DBusMessageIter *value,
1084                                         struct supplicant_result *result)
1085 {
1086         dbus_message_iter_get_basic(value, &result->capabilities);
1087
1088         if (result->capabilities & IEEE80211_CAP_ESS)
1089                 result->adhoc = FALSE;
1090         else if (result->capabilities & IEEE80211_CAP_IBSS)
1091                 result->adhoc = TRUE;
1092
1093         if (result->capabilities & IEEE80211_CAP_PRIVACY)
1094                 result->has_wep = TRUE;
1095 }
1096
1097 static unsigned char calculate_strength(struct supplicant_task *task,
1098                                         struct supplicant_result *result)
1099 {
1100         if (task->range->max_qual.qual == 0) {
1101                 unsigned char strength;
1102
1103                 if (result->level > 0)
1104                         strength = 100 - result->level;
1105                 else
1106                         strength = 120 + result->level;
1107
1108                 if (strength > 100)
1109                         strength = 100;
1110
1111                 return strength;
1112         }
1113
1114         return (result->quality * 100) / task->range->max_qual.qual;
1115 }
1116
1117 static unsigned short calculate_channel(struct supplicant_result *result)
1118 {
1119         if (result->frequency < 0)
1120                 return 0;
1121
1122         return (result->frequency - 2407) / 5;
1123 }
1124
1125 static void get_properties(struct supplicant_task *task);
1126
1127 static void properties_reply(DBusPendingCall *call, void *user_data)
1128 {
1129         struct supplicant_task *task = user_data;
1130         struct supplicant_result result;
1131         struct connman_network *network;
1132         DBusMessage *reply;
1133         DBusMessageIter array, dict;
1134         unsigned char strength;
1135         unsigned short channel, frequency;
1136         const char *mode, *security;
1137         char *group = NULL;
1138         unsigned int ssid_len;
1139
1140         DBG("task %p", task);
1141
1142         reply = dbus_pending_call_steal_reply(call);
1143         if (reply == NULL) {
1144                 get_properties(task);
1145                 return;
1146         }
1147
1148         if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR) {
1149                 dbus_message_unref(reply);
1150                 get_properties(task);
1151                 return;
1152         }
1153
1154         memset(&result, 0, sizeof(result));
1155         result.frequency = -1;
1156         result.quality = -1;
1157         result.level = 0;
1158         result.noise = 0;
1159
1160         dbus_message_iter_init(reply, &array);
1161
1162         dbus_message_iter_recurse(&array, &dict);
1163
1164         while (dbus_message_iter_get_arg_type(&dict) == DBUS_TYPE_DICT_ENTRY) {
1165                 DBusMessageIter entry, value;
1166                 const char *key;
1167
1168                 dbus_message_iter_recurse(&dict, &entry);
1169                 dbus_message_iter_get_basic(&entry, &key);
1170
1171                 dbus_message_iter_next(&entry);
1172
1173                 dbus_message_iter_recurse(&entry, &value);
1174
1175                 //type = dbus_message_iter_get_arg_type(&value);
1176                 //dbus_message_iter_get_basic(&value, &val);
1177
1178                 /* 
1179                  * bssid        : a (97)
1180                  * ssid         : a (97)
1181                  * wpaie        : a (97)
1182                  * rsnie        : a (97)
1183                  * wpsie        : a (97)
1184                  * frequency    : i (105)
1185                  * capabilities : q (113)
1186                  * quality      : i (105)
1187                  * noise        : i (105)
1188                  * level        : i (105)
1189                  * maxrate      : i (105)
1190                  */
1191
1192                 if (g_str_equal(key, "bssid") == TRUE)
1193                         extract_addr(&value, &result);
1194                 else if (g_str_equal(key, "ssid") == TRUE)
1195                         extract_ssid(&value, &result);
1196                 else if (g_str_equal(key, "wpaie") == TRUE)
1197                         extract_wpaie(&value, &result);
1198                 else if (g_str_equal(key, "rsnie") == TRUE)
1199                         extract_rsnie(&value, &result);
1200                 else if (g_str_equal(key, "wpsie") == TRUE)
1201                         extract_wpsie(&value, &result);
1202                 else if (g_str_equal(key, "capabilities") == TRUE)
1203                         extract_capabilites(&value, &result);
1204                 else if (g_str_equal(key, "frequency") == TRUE)
1205                         dbus_message_iter_get_basic(&value, &result.frequency);
1206                 else if (g_str_equal(key, "quality") == TRUE)
1207                         dbus_message_iter_get_basic(&value, &result.quality);
1208                 else if (g_str_equal(key, "noise") == TRUE)
1209                         dbus_message_iter_get_basic(&value, &result.noise);
1210                 else if (g_str_equal(key, "level") == TRUE)
1211                         dbus_message_iter_get_basic(&value, &result.level);
1212                 else if (g_str_equal(key, "maxrate") == TRUE)
1213                         dbus_message_iter_get_basic(&value, &result.maxrate);
1214
1215                 dbus_message_iter_next(&dict);
1216         }
1217
1218         if (result.path == NULL)
1219                 goto done;
1220
1221         if (result.path[0] == '\0')
1222                 goto done;
1223
1224         if (result.frequency > 0 && result.frequency < 14)
1225                 result.frequency = 2407 + (5 * result.frequency);
1226         else if (result.frequency == 14)
1227                 result.frequency = 2484;
1228
1229         strength = calculate_strength(task, &result);
1230         channel  = calculate_channel(&result);
1231
1232         frequency = (result.frequency < 0) ? 0 : result.frequency;
1233
1234         if (result.has_rsn == TRUE)
1235                 security = "rsn";
1236         else if (result.has_wpa == TRUE)
1237                 security = "wpa";
1238         else if (result.has_wep == TRUE)
1239                 security = "wep";
1240         else
1241                 security = "none";
1242
1243         mode = (result.adhoc == TRUE) ? "adhoc" : "managed";
1244
1245         group = build_group(result.path, result.name,
1246                                         result.ssid, result.ssid_len,
1247                                                         mode, security);
1248
1249         network = connman_device_get_network(task->device, result.path);
1250         if (network == NULL) {
1251                 int index;
1252
1253                 network = connman_network_create(result.path,
1254                                                 CONNMAN_NETWORK_TYPE_WIFI);
1255                 if (network == NULL)
1256                         goto done;
1257
1258                 index = connman_device_get_index(task->device);
1259                 connman_network_set_index(network, index);
1260
1261                 connman_network_set_protocol(network,
1262                                                 CONNMAN_NETWORK_PROTOCOL_IP);
1263
1264                 connman_network_set_address(network, result.addr,
1265                                                         result.addr_len);
1266
1267                 if (connman_device_add_network(task->device, network) < 0) {
1268                         connman_network_unref(network);
1269                         goto done;
1270                 }
1271         }
1272
1273         if (result.name != NULL && result.name[0] != '\0')
1274                 connman_network_set_name(network, result.name);
1275
1276         if (connman_network_get_blob(network, "WiFi.SSID", &ssid_len) == NULL) {
1277                 connman_network_set_blob(network, "WiFi.SSID",
1278                                          result.ssid, result.ssid_len);
1279         }
1280
1281         connman_network_set_string(network, "WiFi.Mode", mode);
1282
1283         DBG("%s (%s %s) strength %d (%s)",
1284                                 result.name, mode, security, strength,
1285                                 (result.has_wps == TRUE) ? "WPS" : "no WPS");
1286
1287         connman_network_set_available(network, TRUE);
1288         connman_network_set_strength(network, strength);
1289
1290         connman_network_set_uint16(network, "Frequency", frequency);
1291         connman_network_set_uint16(network, "WiFi.Channel", channel);
1292         connman_network_set_string(network, "WiFi.Security", security);
1293
1294         if (result.ssid != NULL)
1295                 connman_network_set_group(network, group);
1296
1297 done:
1298         g_free(group);
1299
1300         g_free(result.path);
1301         g_free(result.addr);
1302         g_free(result.name);
1303         g_free(result.ssid);
1304
1305         dbus_message_unref(reply);
1306
1307         get_properties(task);
1308 }
1309
1310 static void get_properties(struct supplicant_task *task)
1311 {
1312         DBusMessage *message;
1313         DBusPendingCall *call;
1314         char *path;
1315
1316         path = g_slist_nth_data(task->scan_results, 0);
1317         if (path == NULL)
1318                 goto noscan;
1319
1320         message = dbus_message_new_method_call(SUPPLICANT_NAME, path,
1321                                                 SUPPLICANT_INTF ".BSSID",
1322                                                                 "properties");
1323
1324         task->scan_results = g_slist_remove(task->scan_results, path);
1325         g_free(path);
1326
1327         if (message == NULL)
1328                 goto noscan;
1329
1330         if (dbus_connection_send_with_reply(connection, message,
1331                                                 &call, TIMEOUT) == FALSE) {
1332                 connman_error("Failed to get network properties");
1333                 dbus_message_unref(message);
1334                 goto noscan;
1335         }
1336
1337         if (call == NULL) {
1338                 connman_error("D-Bus connection not available");
1339                 dbus_message_unref(message);
1340                 goto noscan;
1341         }
1342
1343         dbus_pending_call_set_notify(call, properties_reply, task, NULL);
1344
1345         dbus_message_unref(message);
1346
1347         return;
1348
1349 noscan:
1350         connman_device_set_scanning(task->device, FALSE);
1351 }
1352
1353 static void scan_results_reply(DBusPendingCall *call, void *user_data)
1354 {
1355         struct supplicant_task *task = user_data;
1356         DBusMessage *reply;
1357         DBusError error;
1358         char **results;
1359         int i, num_results;
1360
1361         DBG("task %p", task);
1362
1363         reply = dbus_pending_call_steal_reply(call);
1364         if (reply == NULL)
1365                 goto noscan;
1366
1367         if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR)
1368                 goto done;
1369
1370         dbus_error_init(&error);
1371
1372         if (dbus_message_get_args(reply, &error,
1373                                 DBUS_TYPE_ARRAY, DBUS_TYPE_OBJECT_PATH,
1374                                                 &results, &num_results,
1375                                                 DBUS_TYPE_INVALID) == FALSE) {
1376                 if (dbus_error_is_set(&error) == TRUE) {
1377                         connman_error("%s", error.message);
1378                         dbus_error_free(&error);
1379                 } else
1380                         connman_error("Wrong arguments for scan result");
1381                 goto done;
1382         }
1383
1384         if (num_results == 0)
1385                 goto done;
1386
1387         for (i = 0; i < num_results; i++) {
1388                 char *path = g_strdup(results[i]);
1389                 if (path == NULL)
1390                         continue;
1391
1392                 task->scan_results = g_slist_append(task->scan_results, path);
1393         }
1394
1395         g_strfreev(results);
1396
1397         dbus_message_unref(reply);
1398
1399         get_properties(task);
1400
1401         return;
1402
1403 done:
1404         dbus_message_unref(reply);
1405
1406 noscan:
1407         connman_device_set_scanning(task->device, FALSE);
1408 }
1409
1410 static void scan_results_available(struct supplicant_task *task)
1411 {
1412         DBusMessage *message;
1413         DBusPendingCall *call;
1414
1415         DBG("task %p", task);
1416
1417         message = dbus_message_new_method_call(SUPPLICANT_NAME, task->path,
1418                                                 SUPPLICANT_INTF ".Interface",
1419                                                         "scanResults");
1420         if (message == NULL)
1421                 return;
1422
1423         if (dbus_connection_send_with_reply(connection, message,
1424                                                 &call, TIMEOUT) == FALSE) {
1425                 connman_error("Failed to request scan result");
1426                 goto done;
1427         }
1428
1429         if (task->noscan == FALSE)
1430                 connman_device_set_scanning(task->device, TRUE);
1431
1432         if (call == NULL) {
1433                 connman_error("D-Bus connection not available");
1434                 goto done;
1435         }
1436
1437         dbus_pending_call_set_notify(call, scan_results_reply, task, NULL);
1438
1439 done:
1440         dbus_message_unref(message);
1441 }
1442
1443 static enum supplicant_state string2state(const char *state)
1444 {
1445         if (g_str_equal(state, "INACTIVE") == TRUE)
1446                 return WPA_INACTIVE;
1447         else if (g_str_equal(state, "SCANNING") == TRUE)
1448                 return WPA_SCANNING;
1449         else if (g_str_equal(state, "ASSOCIATING") == TRUE)
1450                 return WPA_ASSOCIATING;
1451         else if (g_str_equal(state, "ASSOCIATED") == TRUE)
1452                 return WPA_ASSOCIATED;
1453         else if (g_str_equal(state, "GROUP_HANDSHAKE") == TRUE)
1454                 return WPA_GROUP_HANDSHAKE;
1455         else if (g_str_equal(state, "4WAY_HANDSHAKE") == TRUE)
1456                 return WPA_4WAY_HANDSHAKE;
1457         else if (g_str_equal(state, "COMPLETED") == TRUE)
1458                 return WPA_COMPLETED;
1459         else if (g_str_equal(state, "DISCONNECTED") == TRUE)
1460                 return WPA_DISCONNECTED;
1461         else
1462                 return WPA_INVALID;
1463 }
1464
1465 static int task_connect(struct supplicant_task *task)
1466 {
1467         const char *address, *security, *passphrase;
1468         const void *ssid;
1469         unsigned int ssid_len;
1470
1471         address = connman_network_get_string(task->network, "Address");
1472         security = connman_network_get_string(task->network, "WiFi.Security");
1473         passphrase = connman_network_get_string(task->network, "WiFi.Passphrase");
1474
1475         ssid = connman_network_get_blob(task->network, "WiFi.SSID", &ssid_len);
1476
1477         DBG("address %s security %s passphrase %s",
1478                                         address, security, passphrase);
1479
1480         if (security == NULL && passphrase == NULL)
1481                 return -EINVAL;
1482
1483         if (g_str_equal(security, "none") == FALSE && passphrase == NULL)
1484                 return -EINVAL;
1485
1486         add_network(task);
1487
1488         select_network(task);
1489         disable_network(task);
1490
1491         set_network(task, ssid, ssid_len, address, security, passphrase);
1492
1493         enable_network(task);
1494
1495         return -EINPROGRESS;
1496 }
1497
1498 static void state_change(struct supplicant_task *task, DBusMessage *msg)
1499 {
1500         DBusError error;
1501         const char *newstate, *oldstate;
1502         unsigned char bssid[ETH_ALEN];
1503         unsigned int bssid_len;
1504         enum supplicant_state state;
1505
1506         dbus_error_init(&error);
1507
1508         if (dbus_message_get_args(msg, &error, DBUS_TYPE_STRING, &newstate,
1509                                                 DBUS_TYPE_STRING, &oldstate,
1510                                                 DBUS_TYPE_INVALID) == FALSE) {
1511                 if (dbus_error_is_set(&error) == TRUE) {
1512                         connman_error("%s", error.message);
1513                         dbus_error_free(&error);
1514                 } else
1515                         connman_error("Wrong arguments for state change");
1516                 return;
1517         }
1518
1519         DBG("state %s ==> %s", oldstate, newstate);
1520
1521         state = string2state(newstate);
1522         if (state == WPA_INVALID)
1523                 return;
1524
1525         task->state = state;
1526
1527         switch (task->state) {
1528         case WPA_SCANNING:
1529                 task->noscan = TRUE;
1530                 connman_device_set_scanning(task->device, TRUE);
1531                 break;
1532         case WPA_ASSOCIATING:
1533         case WPA_ASSOCIATED:
1534         case WPA_4WAY_HANDSHAKE:
1535         case WPA_GROUP_HANDSHAKE:
1536                 task->noscan = TRUE;
1537                 break;
1538         case WPA_COMPLETED:
1539         case WPA_DISCONNECTED:
1540                 task->noscan = FALSE;
1541                 break;
1542         case WPA_INACTIVE:
1543                 task->noscan = FALSE;
1544                 connman_device_set_scanning(task->device, FALSE);
1545                 break;
1546         case WPA_INVALID:
1547                 break;
1548         }
1549
1550         if (task->network == NULL)
1551                 return;
1552
1553         switch (task->state) {
1554         case WPA_COMPLETED:
1555                 if (get_bssid(task->device, bssid, &bssid_len) == 0)
1556                         connman_network_set_address(task->network,
1557                                                         bssid, bssid_len);
1558
1559                 /* carrier on */
1560                 connman_network_set_connected(task->network, TRUE);
1561                 connman_device_set_scanning(task->device, FALSE);
1562                 break;
1563
1564         case WPA_DISCONNECTED:
1565                 disable_network(task);
1566
1567                 if (task->disconnecting == TRUE) {
1568                         connman_network_set_connected(task->network, FALSE);
1569                         connman_network_unref(task->network);
1570                         task->disconnecting = FALSE;
1571
1572                         if (task->pending_network != NULL) {
1573                                 task->network = task->pending_network;
1574                                 task->pending_network = NULL;
1575                                 task_connect(task);
1576                         }
1577                 } else {
1578                         /* carrier off */
1579                         connman_network_set_connected(task->network, FALSE);
1580                         connman_device_set_scanning(task->device, FALSE);
1581                 }
1582                 break;
1583
1584         case WPA_ASSOCIATING:
1585                 connman_network_set_associating(task->network, TRUE);
1586                 break;
1587
1588         case WPA_INACTIVE:
1589                 remove_network(task);
1590
1591                 if (task->disconnecting == TRUE) {
1592                         connman_network_set_connected(task->network, FALSE);
1593                         connman_network_unref(task->network);
1594                         task->disconnecting = FALSE;
1595
1596                         if (task->pending_network != NULL) {
1597                                 task->network = task->pending_network;
1598                                 task->pending_network = NULL;
1599                                 task_connect(task);
1600                         }
1601                 }
1602                 break;
1603
1604         default:
1605                 connman_network_set_associating(task->network, FALSE);
1606                 break;
1607         }
1608 }
1609
1610 static DBusHandlerResult supplicant_filter(DBusConnection *conn,
1611                                                 DBusMessage *msg, void *data)
1612 {
1613         struct supplicant_task *task;
1614         const char *member, *path;
1615
1616         if (dbus_message_has_interface(msg,
1617                                 SUPPLICANT_INTF ".Interface") == FALSE)
1618                 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1619
1620         member = dbus_message_get_member(msg);
1621         if (member == NULL)
1622                 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1623
1624         path = dbus_message_get_path(msg);
1625         if (path == NULL)
1626                 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1627
1628         task = find_task_by_path(path);
1629         if (task == NULL)
1630                 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1631
1632         DBG("task %p member %s", task, member);
1633
1634         if (g_str_equal(member, "ScanResultsAvailable") == TRUE)
1635                 scan_results_available(task);
1636         else if (g_str_equal(member, "StateChange") == TRUE)
1637                 state_change(task, msg);
1638
1639         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1640 }
1641
1642 int supplicant_start(struct connman_device *device)
1643 {
1644         struct supplicant_task *task;
1645         int err;
1646
1647         DBG("device %p", device);
1648
1649         task = g_try_new0(struct supplicant_task, 1);
1650         if (task == NULL)
1651                 return -ENOMEM;
1652
1653         task->ifindex = connman_device_get_index(device);
1654         task->ifname = connman_inet_ifname(task->ifindex);
1655
1656         if (task->ifname == NULL) {
1657                 err = -ENOMEM;
1658                 goto failed;
1659         }
1660
1661         task->range = g_try_malloc0(sizeof(struct iw_range));
1662         if (task->range == NULL) {
1663                 err = -ENOMEM;
1664                 goto failed;
1665         }
1666
1667         err = get_range(task);
1668         if (err < 0)
1669                 goto failed;
1670
1671         task->device = connman_device_ref(device);
1672
1673         task->created = FALSE;
1674         task->noscan = FALSE;
1675         task->state = WPA_INVALID;
1676         task->disconnecting = FALSE;
1677         task->pending_network = NULL;
1678
1679         task_list = g_slist_append(task_list, task);
1680
1681         return create_interface(task);
1682
1683 failed:
1684         g_free(task->range);
1685         g_free(task->ifname);
1686         g_free(task);
1687
1688         return err;
1689 }
1690
1691 int supplicant_stop(struct connman_device *device)
1692 {
1693         int index = connman_device_get_index(device);
1694         struct supplicant_task *task;
1695
1696         DBG("device %p", device);
1697
1698         task = find_task_by_index(index);
1699         if (task == NULL)
1700                 return -ENODEV;
1701
1702         g_free(task->range);
1703
1704         task_list = g_slist_remove(task_list, task);
1705
1706         disable_network(task);
1707
1708         remove_network(task);
1709
1710         return remove_interface(task);
1711 }
1712
1713 int supplicant_scan(struct connman_device *device)
1714 {
1715         int index = connman_device_get_index(device);
1716         struct supplicant_task *task;
1717         int err;
1718
1719         DBG("device %p", device);
1720
1721         task = find_task_by_index(index);
1722         if (task == NULL)
1723                 return -ENODEV;
1724
1725         switch (task->state) {
1726         case WPA_SCANNING:
1727                 return -EALREADY;
1728         case WPA_ASSOCIATING:
1729         case WPA_ASSOCIATED:
1730         case WPA_4WAY_HANDSHAKE:
1731         case WPA_GROUP_HANDSHAKE:
1732                 return -EBUSY;
1733         default:
1734                 break;
1735         }
1736
1737         err = initiate_scan(task);
1738
1739         return 0;
1740 }
1741
1742 int supplicant_connect(struct connman_network *network)
1743 {
1744         struct supplicant_task *task;
1745         int index;
1746
1747         DBG("network %p", network);
1748
1749         index = connman_network_get_index(network);
1750
1751         task = find_task_by_index(index);
1752         if (task == NULL)
1753                 return -ENODEV;
1754
1755         if (task->disconnecting == TRUE)
1756                 task->pending_network = connman_network_ref(network);
1757         else {
1758                 task->network = connman_network_ref(network);
1759                 return task_connect(task);
1760         }
1761
1762         return -EINPROGRESS;
1763 }
1764
1765 int supplicant_disconnect(struct connman_network *network)
1766 {
1767         struct supplicant_task *task;
1768         int index;
1769
1770         DBG("network %p", network);
1771
1772         index = connman_network_get_index(network);
1773
1774         task = find_task_by_index(index);
1775         if (task == NULL)
1776                 return -ENODEV;
1777
1778         if (task->disconnecting == TRUE)
1779                 return -EINPROGRESS;
1780
1781         disable_network(task);
1782
1783         remove_network(task);
1784
1785         task->disconnecting = TRUE;
1786
1787         return 0;
1788 }
1789
1790 static void supplicant_activate(DBusConnection *conn)
1791 {
1792         DBusMessage *message;
1793
1794         DBG("conn %p", conn);
1795
1796         message = dbus_message_new_method_call(SUPPLICANT_NAME, "/",
1797                                 DBUS_INTERFACE_INTROSPECTABLE, "Introspect");
1798         if (message == NULL)
1799                 return;
1800
1801         dbus_message_set_no_reply(message, TRUE);
1802
1803         dbus_connection_send(conn, message, NULL);
1804
1805         dbus_message_unref(message);
1806 }
1807
1808 static GSList *driver_list = NULL;
1809
1810 static void supplicant_probe(DBusConnection *conn, void *user_data)
1811 {
1812         GSList *list;
1813
1814         DBG("conn %p", conn);
1815
1816         for (list = driver_list; list; list = list->next) {
1817                 struct supplicant_driver *driver = list->data;
1818
1819                 DBG("driver %p name %s", driver, driver->name);
1820
1821                 if (driver->probe)
1822                         driver->probe();
1823         }
1824 }
1825
1826 static void supplicant_remove(DBusConnection *conn, void *user_data)
1827 {
1828         GSList *list;
1829
1830         DBG("conn %p", conn);
1831
1832         for (list = driver_list; list; list = list->next) {
1833                 struct supplicant_driver *driver = list->data;
1834
1835                 DBG("driver %p name %s", driver, driver->name);
1836
1837                 if (driver->remove)
1838                         driver->remove();
1839         }
1840 }
1841
1842 static const char *supplicant_rule = "type=signal,"
1843                                 "interface=" SUPPLICANT_INTF ".Interface";
1844 static guint watch;
1845
1846 static int supplicant_create(void)
1847 {
1848         if (g_slist_length(driver_list) > 0)
1849                 return 0;
1850
1851         connection = connman_dbus_get_connection();
1852         if (connection == NULL)
1853                 return -EIO;
1854
1855         DBG("connection %p", connection);
1856
1857         if (dbus_connection_add_filter(connection,
1858                                 supplicant_filter, NULL, NULL) == FALSE) {
1859                 connection = connman_dbus_get_connection();
1860                 return -EIO;
1861         }
1862
1863         dbus_bus_add_match(connection, supplicant_rule, NULL);
1864         dbus_connection_flush(connection);
1865
1866         watch = g_dbus_add_service_watch(connection, SUPPLICANT_NAME,
1867                         supplicant_probe, supplicant_remove, NULL, NULL);
1868
1869         return 0;
1870 }
1871
1872 static void supplicant_destroy(void)
1873 {
1874         if (g_slist_length(driver_list) > 0)
1875                 return;
1876
1877         DBG("connection %p", connection);
1878
1879         if (watch > 0)
1880                 g_dbus_remove_watch(connection, watch);
1881
1882         dbus_bus_remove_match(connection, supplicant_rule, NULL);
1883         dbus_connection_flush(connection);
1884
1885         dbus_connection_remove_filter(connection, supplicant_filter, NULL);
1886
1887         dbus_connection_unref(connection);
1888         connection = NULL;
1889 }
1890
1891 int supplicant_register(struct supplicant_driver *driver)
1892 {
1893         int err;
1894
1895         DBG("driver %p name %s", driver, driver->name);
1896
1897         err = supplicant_create();
1898         if (err < 0)
1899                 return err;
1900
1901         driver_list = g_slist_append(driver_list, driver);
1902
1903         if (g_dbus_check_service(connection, SUPPLICANT_NAME) == TRUE)
1904                 supplicant_probe(connection, NULL);
1905         else
1906                 supplicant_activate(connection);
1907
1908         return 0;
1909 }
1910
1911 void supplicant_unregister(struct supplicant_driver *driver)
1912 {
1913         DBG("driver %p name %s", driver, driver->name);
1914
1915         supplicant_remove(connection, NULL);
1916
1917         driver_list = g_slist_remove(driver_list, driver);
1918
1919         supplicant_destroy();
1920 }