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