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