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