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