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