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