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