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