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