8ae4b670df4fa6fda135a18f8376024350ca802f
[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                 char *eap_value;
922
923                 /*
924                  * If our private key password is unset,
925                  * we use the supplied passphrase. That is needed
926                  * for PEAP where 2 passphrases (identity and client
927                  * cert may have to be provided.
928                  */
929                 if (connman_network_get_string(network,
930                                         "WiFi.PrivateKeyPassphrase") == NULL)
931                         connman_network_set_string(network,
932                                                 "WiFi.PrivateKeyPassphrase",
933                                                                 passphrase);
934
935                 eap = connman_network_get_string(network, "WiFi.EAP");
936                 if (eap == NULL)
937                         goto invalid;
938
939                 /* We must have an identity for both PEAP and TLS */
940                 identity = connman_network_get_string(network, "WiFi.Identity");
941                 if (identity == NULL)
942                         goto invalid;
943
944                 DBG("key_mgmt %s eap %s identity %s", key_mgmt, eap, identity);
945
946                 if (g_strcmp0(eap, "tls") == 0) {
947                         int err;
948
949                         err = set_network_tls(network, &dict);
950                         if (err < 0) {
951                                 dbus_message_unref(message);
952                                 return err;
953                         }
954                 } else if (g_strcmp0(eap, "peap") == 0) {
955                         int err;
956
957                         err = set_network_peap(network, &dict, passphrase);
958                         if (err < 0) {
959                                 dbus_message_unref(message);
960                                 return err;
961                         }
962                 } else {
963                         connman_error("Unknown EAP %s", eap);
964                         goto invalid;
965                 }
966
967                 /* wpa_supplicant only accepts upper case EAPs */
968                 eap_value = g_ascii_strup(eap, -1);
969
970                 connman_dbus_dict_append_basic(&dict, "key_mgmt",
971                                                         DBUS_TYPE_STRING,
972                                                         &key_mgmt);
973                 connman_dbus_dict_append_basic(&dict, "eap",
974                                                         DBUS_TYPE_STRING,
975                                                         &eap_value);
976                 connman_dbus_dict_append_basic(&dict, "identity",
977                                                         DBUS_TYPE_STRING,
978                                                         &identity);
979
980                 g_free(eap_value);
981
982         } else if (g_ascii_strcasecmp(security, "wep") == 0) {
983                 const char *key_mgmt = "NONE";
984                 const char *auth_alg = "OPEN";
985                 const char *key_index = "0";
986
987                 if (task->mac80211 == TRUE)
988                         auth_alg = "OPEN SHARED";
989
990                 connman_dbus_dict_append_basic(&dict, "auth_alg",
991                                                 DBUS_TYPE_STRING, &auth_alg);
992
993                 connman_dbus_dict_append_basic(&dict, "key_mgmt",
994                                                 DBUS_TYPE_STRING, &key_mgmt);
995
996                 if (passphrase) {
997                         int size = strlen(passphrase);
998                         if (size == 10 || size == 26) {
999                                 unsigned char *key = malloc(13);
1000                                 char tmp[3];
1001                                 int i;
1002                                 memset(tmp, 0, sizeof(tmp));
1003                                 if (key == NULL)
1004                                         size = 0;
1005                                 for (i = 0; i < size / 2; i++) {
1006                                         memcpy(tmp, passphrase + (i * 2), 2);
1007                                         key[i] = (unsigned char) strtol(tmp,
1008                                                                 NULL, 16);
1009                                 }
1010                                 connman_dbus_dict_append_fixed_array(&dict,
1011                                                 "wep_key0", DBUS_TYPE_BYTE,
1012                                                         &key, size / 2);
1013                                 free(key);
1014                         } else
1015                                 connman_dbus_dict_append_basic(&dict,
1016                                                 "wep_key0", DBUS_TYPE_STRING,
1017                                                                 &passphrase);
1018
1019                         connman_dbus_dict_append_basic(&dict, "wep_tx_keyidx",
1020                                                 DBUS_TYPE_STRING, &key_index);
1021                 }
1022         } else {
1023                 const char *key_mgmt = "NONE";
1024                 connman_dbus_dict_append_basic(&dict, "key_mgmt",
1025                                                 DBUS_TYPE_STRING, &key_mgmt);
1026         }
1027
1028         connman_dbus_dict_close(&array, &dict);
1029
1030         dbus_error_init(&error);
1031
1032         reply = dbus_connection_send_with_reply_and_block(connection,
1033                                                         message, -1, &error);
1034         if (reply == NULL) {
1035                 if (dbus_error_is_set(&error) == TRUE) {
1036                         connman_error("%s", error.message);
1037                         dbus_error_free(&error);
1038                 } else
1039                         connman_error("Failed to set network options");
1040                 dbus_message_unref(message);
1041                 return -EIO;
1042         }
1043
1044         dbus_message_unref(message);
1045
1046         dbus_message_unref(reply);
1047
1048         return 0;
1049
1050 invalid:
1051         dbus_message_unref(message);
1052         return -EINVAL;
1053 }
1054
1055 static void scan_reply(DBusPendingCall *call, void *user_data)
1056 {
1057         struct supplicant_task *task = user_data;
1058         DBusMessage *reply;
1059
1060         DBG("task %p", task);
1061
1062         task->scan_call = NULL;
1063
1064         reply = dbus_pending_call_steal_reply(call);
1065         if (reply == NULL)
1066                 return;
1067
1068         if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR) {
1069                 connman_device_set_scanning(task->device, FALSE);
1070                 goto done;
1071         }
1072
1073         if (task->scanning == TRUE)
1074                 connman_device_set_scanning(task->device, TRUE);
1075
1076 done:
1077         dbus_message_unref(reply);
1078 }
1079
1080
1081 static int initiate_scan(struct supplicant_task *task)
1082 {
1083         DBusMessage *message;
1084
1085         DBG("task %p", task);
1086
1087         if (task->path == NULL)
1088                 return -EINVAL;
1089
1090         if (task->scan_call != NULL)
1091                 return -EALREADY;
1092
1093         message = dbus_message_new_method_call(SUPPLICANT_NAME, task->path,
1094                                         SUPPLICANT_INTF ".Interface", "scan");
1095         if (message == NULL)
1096                 return -ENOMEM;
1097
1098         dbus_message_set_auto_start(message, FALSE);
1099
1100         if (dbus_connection_send_with_reply(connection, message,
1101                                         &task->scan_call, TIMEOUT) == FALSE) {
1102                 connman_error("Failed to initiate scan");
1103                 dbus_message_unref(message);
1104                 return -EIO;
1105         }
1106
1107         if (task->scan_call == NULL) {
1108                 connman_error("D-Bus connection not available");
1109                 dbus_message_unref(message);
1110                 return -EIO;
1111         }
1112
1113         dbus_pending_call_set_notify(task->scan_call, scan_reply, task, NULL);
1114
1115         dbus_message_unref(message);
1116
1117         return -EINPROGRESS;
1118 }
1119
1120 static struct {
1121         char *name;
1122         char *value;
1123 } special_ssid[] = {
1124         { "<hidden>", "hidden"  },
1125         { "default",  "linksys" },
1126         { "wireless"  },
1127         { "linksys"   },
1128         { "netgear"   },
1129         { "dlink"     },
1130         { "2wire"     },
1131         { "compaq"    },
1132         { "tsunami"   },
1133         { "comcomcom", "3com"     },
1134         { "3Com",      "3com"     },
1135         { "Symbol",    "symbol"   },
1136         { "Motorola",  "motorola" },
1137         { "Wireless" , "wireless" },
1138         { "WLAN",      "wlan"     },
1139         { }
1140 };
1141
1142 static char *build_group(const char *addr, const char *name,
1143                         const unsigned char *ssid, unsigned int ssid_len,
1144                                         const char *mode, const char *security)
1145 {
1146         GString *str;
1147         unsigned int i;
1148
1149         if (addr == NULL)
1150                 return NULL;
1151
1152         str = g_string_sized_new((ssid_len * 2) + 24);
1153         if (str == NULL)
1154                 return NULL;
1155
1156         if (ssid == NULL) {
1157                 g_string_append_printf(str, "hidden_%s", addr);
1158                 goto done;
1159         }
1160
1161         for (i = 0; special_ssid[i].name; i++) {
1162                 if (g_strcmp0(special_ssid[i].name, name) == 0) {
1163                         if (special_ssid[i].value == NULL)
1164                                 g_string_append_printf(str, "%s_%s",
1165                                                                 name, addr);
1166                         else
1167                                 g_string_append_printf(str, "%s_%s",
1168                                                 special_ssid[i].value, addr);
1169                         goto done;
1170                 }
1171         }
1172
1173         if (ssid_len > 0 && ssid[0] != '\0') {
1174                 for (i = 0; i < ssid_len; i++)
1175                         g_string_append_printf(str, "%02x", ssid[i]);
1176         } else
1177                 g_string_append_printf(str, "hidden_%s", addr);
1178
1179 done:
1180         g_string_append_printf(str, "_%s_%s", mode, security);
1181
1182         return g_string_free(str, FALSE);
1183 }
1184
1185 static void extract_addr(DBusMessageIter *value,
1186                                         struct supplicant_result *result)
1187 {
1188         DBusMessageIter array;
1189         struct ether_addr eth;
1190         unsigned char *addr;
1191         int addr_len;
1192
1193         dbus_message_iter_recurse(value, &array);
1194         dbus_message_iter_get_fixed_array(&array, &addr, &addr_len);
1195
1196         if (addr_len != 6)
1197                 return;
1198
1199         result->addr = g_try_malloc(addr_len);
1200         if (result->addr == NULL)
1201                 return;
1202
1203         memcpy(result->addr, addr, addr_len);
1204         result->addr_len = addr_len;
1205
1206         result->path = g_try_malloc0(13);
1207         if (result->path == NULL)
1208                 return;
1209
1210         memcpy(&eth, addr, sizeof(eth));
1211         snprintf(result->path, 13, "%02x%02x%02x%02x%02x%02x",
1212                                                 eth.ether_addr_octet[0],
1213                                                 eth.ether_addr_octet[1],
1214                                                 eth.ether_addr_octet[2],
1215                                                 eth.ether_addr_octet[3],
1216                                                 eth.ether_addr_octet[4],
1217                                                 eth.ether_addr_octet[5]);
1218 }
1219
1220 static void extract_ssid(DBusMessageIter *value,
1221                                         struct supplicant_result *result)
1222 {
1223         DBusMessageIter array;
1224         unsigned char *ssid;
1225         int ssid_len, i;
1226
1227         dbus_message_iter_recurse(value, &array);
1228         dbus_message_iter_get_fixed_array(&array, &ssid, &ssid_len);
1229
1230         if (ssid_len < 1)
1231                 return;
1232
1233         if (ssid[0] == '\0')
1234                 return;
1235
1236         result->ssid = g_try_malloc(ssid_len);
1237         if (result->ssid == NULL)
1238                 return;
1239
1240         memcpy(result->ssid, ssid, ssid_len);
1241         result->ssid_len = ssid_len;
1242
1243         result->name = g_try_malloc0(ssid_len + 1);
1244         if (result->name == NULL)
1245                 return;
1246
1247         for (i = 0; i < ssid_len; i++) {
1248                 if (g_ascii_isprint(ssid[i]))
1249                         result->name[i] = ssid[i];
1250                 else
1251                         result->name[i] = ' ';
1252         }
1253 }
1254
1255 static unsigned char wifi_oui[3]      = { 0x00, 0x50, 0xf2 };
1256 static unsigned char ieee80211_oui[3] = { 0x00, 0x0f, 0xac };
1257
1258 static void extract_rsn(struct supplicant_result *result,
1259                                         const unsigned char *buf, int len)
1260 {
1261         uint16_t count;
1262         int i;
1263
1264         /* Version */
1265         if (len < 2)
1266                 return;
1267
1268         buf += 2;
1269         len -= 2;
1270
1271         /* Group cipher */
1272         if (len < 4)
1273                 return;
1274
1275         buf += 4;
1276         len -= 4;
1277
1278         /* Pairwise cipher */
1279         if (len < 2)
1280                 return;
1281
1282         count = buf[0] | (buf[1] << 8);
1283         if (2 + (count * 4) > len)
1284                 return;
1285
1286         buf += 2 + (count * 4);
1287         len -= 2 + (count * 4);
1288
1289         /* Authentication */
1290         if (len < 2)
1291                 return;
1292
1293         count = buf[0] | (buf[1] << 8);
1294         if (2 + (count * 4) > len)
1295                 return;
1296
1297         for (i = 0; i < count; i++) {
1298                 const unsigned char *ptr = buf + 2 + (i * 4);
1299
1300                 if (memcmp(ptr, wifi_oui, 3) == 0) {
1301                         switch (ptr[3]) {
1302                         case 1:
1303                                 result->has_8021x = TRUE;
1304                                 break;
1305                         case 2:
1306                                 result->has_psk = TRUE;
1307                                 break;
1308                         }
1309                 } else if (memcmp(ptr, ieee80211_oui, 3) == 0) {
1310                         switch (ptr[3]) {
1311                         case 1:
1312                                 result->has_8021x = TRUE;
1313                                 break;
1314                         case 2:
1315                                 result->has_psk = TRUE;
1316                                 break;
1317                         }
1318                 }
1319         }
1320
1321         buf += 2 + (count * 4);
1322         len -= 2 + (count * 4);
1323 }
1324
1325 static void extract_wpaie(DBusMessageIter *value,
1326                                         struct supplicant_result *result)
1327 {
1328         DBusMessageIter array;
1329         unsigned char *ie;
1330         int ie_len;
1331
1332         dbus_message_iter_recurse(value, &array);
1333         dbus_message_iter_get_fixed_array(&array, &ie, &ie_len);
1334
1335         if (ie_len > 6) {
1336                 result->has_wpa = TRUE;
1337                 extract_rsn(result, ie + 6, ie_len - 6);
1338         }
1339 }
1340
1341 static void extract_rsnie(DBusMessageIter *value,
1342                                         struct supplicant_result *result)
1343 {
1344         DBusMessageIter array;
1345         unsigned char *ie;
1346         int ie_len;
1347
1348         dbus_message_iter_recurse(value, &array);
1349         dbus_message_iter_get_fixed_array(&array, &ie, &ie_len);
1350
1351         if (ie_len > 2) {
1352                 result->has_rsn = TRUE;
1353                 extract_rsn(result, ie + 2, ie_len - 2);
1354         }
1355 }
1356
1357 static void extract_wpsie(DBusMessageIter *value,
1358                                         struct supplicant_result *result)
1359 {
1360         DBusMessageIter array;
1361         unsigned char *ie;
1362         int ie_len;
1363
1364         dbus_message_iter_recurse(value, &array);
1365         dbus_message_iter_get_fixed_array(&array, &ie, &ie_len);
1366
1367         if (ie_len > 0)
1368                 result->has_wps = TRUE;
1369 }
1370
1371 static void extract_capabilites(DBusMessageIter *value,
1372                                         struct supplicant_result *result)
1373 {
1374         dbus_message_iter_get_basic(value, &result->capabilities);
1375
1376         if (result->capabilities & IEEE80211_CAP_ESS)
1377                 result->adhoc = FALSE;
1378         else if (result->capabilities & IEEE80211_CAP_IBSS)
1379                 result->adhoc = TRUE;
1380
1381         if (result->capabilities & IEEE80211_CAP_PRIVACY)
1382                 result->has_wep = TRUE;
1383 }
1384
1385 static unsigned char calculate_strength(struct supplicant_task *task,
1386                                         struct supplicant_result *result)
1387 {
1388         if (result->quality == -1 || task->range->max_qual.qual == 0) {
1389                 unsigned char strength;
1390
1391                 if (result->level > 0)
1392                         strength = 100 - result->level;
1393                 else
1394                         strength = 120 + result->level;
1395
1396                 if (strength > 100)
1397                         strength = 100;
1398
1399                 return strength;
1400         }
1401
1402         return (result->quality * 100) / task->range->max_qual.qual;
1403 }
1404
1405 static unsigned short calculate_channel(struct supplicant_result *result)
1406 {
1407         if (result->frequency < 0)
1408                 return 0;
1409
1410         return (result->frequency - 2407) / 5;
1411 }
1412
1413 static void get_properties(struct supplicant_task *task);
1414
1415 static void properties_reply(DBusPendingCall *call, void *user_data)
1416 {
1417         struct supplicant_task *task = user_data;
1418         struct supplicant_result result;
1419         struct connman_network *network;
1420         DBusMessage *reply;
1421         DBusMessageIter array, dict;
1422         unsigned char strength;
1423         unsigned short channel, frequency;
1424         const char *mode, *security;
1425         char *group = NULL;
1426
1427         DBG("task %p", task);
1428
1429         reply = dbus_pending_call_steal_reply(call);
1430         if (reply == NULL) {
1431                 get_properties(task);
1432                 return;
1433         }
1434
1435         if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR) {
1436                 dbus_message_unref(reply);
1437                 get_properties(task);
1438                 return;
1439         }
1440
1441         memset(&result, 0, sizeof(result));
1442         result.frequency = -1;
1443         result.quality = -1;
1444         result.level = 0;
1445         result.noise = 0;
1446
1447         dbus_message_iter_init(reply, &array);
1448
1449         dbus_message_iter_recurse(&array, &dict);
1450
1451         while (dbus_message_iter_get_arg_type(&dict) == DBUS_TYPE_DICT_ENTRY) {
1452                 DBusMessageIter entry, value;
1453                 const char *key;
1454
1455                 dbus_message_iter_recurse(&dict, &entry);
1456                 dbus_message_iter_get_basic(&entry, &key);
1457
1458                 dbus_message_iter_next(&entry);
1459
1460                 dbus_message_iter_recurse(&entry, &value);
1461
1462                 //type = dbus_message_iter_get_arg_type(&value);
1463                 //dbus_message_iter_get_basic(&value, &val);
1464
1465                 /* 
1466                  * bssid        : a (97)
1467                  * ssid         : a (97)
1468                  * wpaie        : a (97)
1469                  * rsnie        : a (97)
1470                  * wpsie        : a (97)
1471                  * frequency    : i (105)
1472                  * capabilities : q (113)
1473                  * quality      : i (105)
1474                  * noise        : i (105)
1475                  * level        : i (105)
1476                  * maxrate      : i (105)
1477                  */
1478
1479                 if (g_str_equal(key, "bssid") == TRUE)
1480                         extract_addr(&value, &result);
1481                 else if (g_str_equal(key, "ssid") == TRUE)
1482                         extract_ssid(&value, &result);
1483                 else if (g_str_equal(key, "wpaie") == TRUE)
1484                         extract_wpaie(&value, &result);
1485                 else if (g_str_equal(key, "rsnie") == TRUE)
1486                         extract_rsnie(&value, &result);
1487                 else if (g_str_equal(key, "wpsie") == TRUE)
1488                         extract_wpsie(&value, &result);
1489                 else if (g_str_equal(key, "capabilities") == TRUE)
1490                         extract_capabilites(&value, &result);
1491                 else if (g_str_equal(key, "frequency") == TRUE)
1492                         dbus_message_iter_get_basic(&value, &result.frequency);
1493                 else if (g_str_equal(key, "quality") == TRUE)
1494                         dbus_message_iter_get_basic(&value, &result.quality);
1495                 else if (g_str_equal(key, "noise") == TRUE)
1496                         dbus_message_iter_get_basic(&value, &result.noise);
1497                 else if (g_str_equal(key, "level") == TRUE)
1498                         dbus_message_iter_get_basic(&value, &result.level);
1499                 else if (g_str_equal(key, "maxrate") == TRUE)
1500                         dbus_message_iter_get_basic(&value, &result.maxrate);
1501
1502                 dbus_message_iter_next(&dict);
1503         }
1504
1505         DBG("capabilties %u frequency %d "
1506                         "quality %d noise %d level %d maxrate %d",
1507                                         result.capabilities, result.frequency,
1508                                                 result.quality, result.noise,
1509                                                 result.level, result.maxrate);
1510
1511         if (result.path == NULL)
1512                 goto done;
1513
1514         if (result.path[0] == '\0')
1515                 goto done;
1516
1517         if (result.frequency > 0 && result.frequency < 14)
1518                 result.frequency = 2407 + (5 * result.frequency);
1519         else if (result.frequency == 14)
1520                 result.frequency = 2484;
1521
1522         strength = calculate_strength(task, &result);
1523         channel  = calculate_channel(&result);
1524
1525         frequency = (result.frequency < 0) ? 0 : result.frequency;
1526
1527         if (result.has_8021x == TRUE)
1528                 security = "ieee8021x";
1529         else if (result.has_psk == TRUE)
1530                 security = "psk";
1531         else if (result.has_wep == TRUE)
1532                 security = "wep";
1533         else
1534                 security = "none";
1535
1536         mode = (result.adhoc == TRUE) ? "adhoc" : "managed";
1537
1538         group = build_group(result.path, result.name,
1539                                         result.ssid, result.ssid_len,
1540                                                         mode, security);
1541
1542         if (result.has_psk == TRUE) {
1543                 if (result.has_rsn == TRUE)
1544                         security = "rsn";
1545                 else if (result.has_wpa == TRUE)
1546                         security = "wpa";
1547         }
1548
1549         network = connman_device_get_network(task->device, result.path);
1550         if (network == NULL) {
1551                 int index;
1552
1553                 network = connman_network_create(result.path,
1554                                                 CONNMAN_NETWORK_TYPE_WIFI);
1555                 if (network == NULL)
1556                         goto done;
1557
1558                 index = connman_device_get_index(task->device);
1559                 connman_network_set_index(network, index);
1560
1561                 connman_network_set_protocol(network,
1562                                                 CONNMAN_NETWORK_PROTOCOL_IP);
1563
1564                 connman_network_set_address(network, result.addr,
1565                                                         result.addr_len);
1566
1567                 if (connman_device_add_network(task->device, network) < 0) {
1568                         connman_network_unref(network);
1569                         goto done;
1570                 }
1571         }
1572
1573         if (result.name != NULL && result.name[0] != '\0')
1574                 connman_network_set_name(network, result.name);
1575
1576         connman_network_set_blob(network, "WiFi.SSID",
1577                                                 result.ssid, result.ssid_len);
1578
1579         connman_network_set_string(network, "WiFi.Mode", mode);
1580
1581         DBG("%s (%s %s) strength %d (%s)",
1582                                 result.name, mode, security, strength,
1583                                 (result.has_wps == TRUE) ? "WPS" : "no WPS");
1584
1585         connman_network_set_available(network, TRUE);
1586         connman_network_set_strength(network, strength);
1587
1588         connman_network_set_uint16(network, "Frequency", frequency);
1589         connman_network_set_uint16(network, "WiFi.Channel", channel);
1590         connman_network_set_string(network, "WiFi.Security", security);
1591
1592         if (result.ssid != NULL)
1593                 connman_network_set_group(network, group);
1594
1595 done:
1596         g_free(group);
1597
1598         g_free(result.path);
1599         g_free(result.addr);
1600         g_free(result.name);
1601         g_free(result.ssid);
1602
1603         dbus_message_unref(reply);
1604
1605         get_properties(task);
1606 }
1607
1608 static void get_properties(struct supplicant_task *task)
1609 {
1610         DBusMessage *message;
1611         char *path;
1612
1613         path = g_slist_nth_data(task->scan_results, 0);
1614         if (path == NULL)
1615                 goto noscan;
1616
1617         message = dbus_message_new_method_call(SUPPLICANT_NAME, path,
1618                                                 SUPPLICANT_INTF ".BSSID",
1619                                                                 "properties");
1620
1621         task->scan_results = g_slist_remove(task->scan_results, path);
1622         g_free(path);
1623
1624         if (message == NULL)
1625                 goto noscan;
1626
1627         dbus_message_set_auto_start(message, FALSE);
1628
1629         if (dbus_connection_send_with_reply(connection, message,
1630                                 &task->result_call, TIMEOUT) == FALSE) {
1631                 connman_error("Failed to get network properties");
1632                 dbus_message_unref(message);
1633                 goto noscan;
1634         }
1635
1636         if (task->result_call == NULL) {
1637                 connman_error("D-Bus connection not available");
1638                 dbus_message_unref(message);
1639                 goto noscan;
1640         }
1641
1642         dbus_pending_call_set_notify(task->result_call,
1643                                         properties_reply, task, NULL);
1644
1645         dbus_message_unref(message);
1646
1647         return;
1648
1649 noscan:
1650         task->result_call = NULL;
1651
1652         if (task->scanning == TRUE) {
1653                 connman_device_set_scanning(task->device, FALSE);
1654                 task->scanning = FALSE;
1655         }
1656 }
1657
1658 static void scan_results_reply(DBusPendingCall *call, void *user_data)
1659 {
1660         struct supplicant_task *task = user_data;
1661         DBusMessage *reply;
1662         DBusError error;
1663         char **results;
1664         int i, num_results;
1665
1666         DBG("task %p", task);
1667
1668         reply = dbus_pending_call_steal_reply(call);
1669         if (reply == NULL)
1670                 goto noscan;
1671
1672         if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR)
1673                 goto done;
1674
1675         dbus_error_init(&error);
1676
1677         if (dbus_message_get_args(reply, &error,
1678                                 DBUS_TYPE_ARRAY, DBUS_TYPE_OBJECT_PATH,
1679                                                 &results, &num_results,
1680                                                 DBUS_TYPE_INVALID) == FALSE) {
1681                 if (dbus_error_is_set(&error) == TRUE) {
1682                         connman_error("%s", error.message);
1683                         dbus_error_free(&error);
1684                 } else
1685                         connman_error("Wrong arguments for scan result");
1686                 goto done;
1687         }
1688
1689         if (num_results == 0)
1690                 goto done;
1691
1692         for (i = 0; i < num_results; i++) {
1693                 char *path = g_strdup(results[i]);
1694                 if (path == NULL)
1695                         continue;
1696
1697                 task->scan_results = g_slist_append(task->scan_results, path);
1698         }
1699
1700         g_strfreev(results);
1701
1702         dbus_message_unref(reply);
1703
1704         get_properties(task);
1705
1706         return;
1707
1708 done:
1709         dbus_message_unref(reply);
1710
1711 noscan:
1712         task->result_call = NULL;
1713
1714         if (task->scanning == TRUE) {
1715                 connman_device_set_scanning(task->device, FALSE);
1716                 task->scanning = FALSE;
1717         }
1718 }
1719
1720 static void scan_results_available(struct supplicant_task *task)
1721 {
1722         DBusMessage *message;
1723
1724         DBG("task %p", task);
1725
1726         if (task->result_call != NULL)
1727                 return;
1728
1729         message = dbus_message_new_method_call(SUPPLICANT_NAME, task->path,
1730                                                 SUPPLICANT_INTF ".Interface",
1731                                                         "scanResults");
1732         if (message == NULL)
1733                 return;
1734
1735         dbus_message_set_auto_start(message, FALSE);
1736
1737         if (dbus_connection_send_with_reply(connection, message,
1738                                 &task->result_call, TIMEOUT) == FALSE) {
1739                 connman_error("Failed to request scan result");
1740                 goto done;
1741         }
1742
1743         if (task->result_call == NULL) {
1744                 connman_error("D-Bus connection not available");
1745                 goto done;
1746         }
1747
1748         if (task->scanning == TRUE)
1749                 connman_device_set_scanning(task->device, TRUE);
1750
1751         dbus_pending_call_set_notify(task->result_call,
1752                                         scan_results_reply, task, NULL);
1753
1754 done:
1755         dbus_message_unref(message);
1756 }
1757
1758 static enum supplicant_state string2state(const char *state)
1759 {
1760         if (g_str_equal(state, "INACTIVE") == TRUE)
1761                 return WPA_INACTIVE;
1762         else if (g_str_equal(state, "SCANNING") == TRUE)
1763                 return WPA_SCANNING;
1764         else if (g_str_equal(state, "ASSOCIATING") == TRUE)
1765                 return WPA_ASSOCIATING;
1766         else if (g_str_equal(state, "ASSOCIATED") == TRUE)
1767                 return WPA_ASSOCIATED;
1768         else if (g_str_equal(state, "GROUP_HANDSHAKE") == TRUE)
1769                 return WPA_GROUP_HANDSHAKE;
1770         else if (g_str_equal(state, "4WAY_HANDSHAKE") == TRUE)
1771                 return WPA_4WAY_HANDSHAKE;
1772         else if (g_str_equal(state, "COMPLETED") == TRUE)
1773                 return WPA_COMPLETED;
1774         else if (g_str_equal(state, "DISCONNECTED") == TRUE)
1775                 return WPA_DISCONNECTED;
1776         else
1777                 return WPA_INVALID;
1778 }
1779
1780 static int task_connect(struct supplicant_task *task)
1781 {
1782         const char *address, *security, *passphrase;
1783         const void *ssid;
1784         unsigned int ssid_len;
1785         int err;
1786
1787         connman_inet_ifup(task->ifindex);
1788
1789         address = connman_network_get_string(task->network, "Address");
1790         security = connman_network_get_string(task->network, "WiFi.Security");
1791         passphrase = connman_network_get_string(task->network, "WiFi.Passphrase");
1792
1793         ssid = connman_network_get_blob(task->network, "WiFi.SSID", &ssid_len);
1794
1795         DBG("address %s security %s", address, security);
1796
1797         if (security == NULL && passphrase == NULL)
1798                 return -EINVAL;
1799
1800         if (g_str_equal(security, "none") == FALSE && passphrase == NULL)
1801                 return -EINVAL;
1802
1803         remove_network(task);
1804
1805         set_ap_scan(task);
1806
1807         add_network(task);
1808
1809         err = set_network(task, ssid, ssid_len, address, security, passphrase);
1810         if (err < 0)
1811                 return err;
1812
1813         err = select_network(task);
1814         if (err < 0)
1815                 return err;
1816
1817         return -EINPROGRESS;
1818 }
1819
1820 static void scanning(struct supplicant_task *task, DBusMessage *msg)
1821 {
1822         DBusError error;
1823         dbus_bool_t scanning;
1824
1825         dbus_error_init(&error);
1826
1827         if (dbus_message_get_args(msg, &error, DBUS_TYPE_BOOLEAN, &scanning,
1828                                                 DBUS_TYPE_INVALID) == FALSE) {
1829                 if (dbus_error_is_set(&error) == TRUE) {
1830                         connman_error("%s", error.message);
1831                         dbus_error_free(&error);
1832                 } else
1833                         connman_error("Wrong arguments for scanning");
1834                 return;
1835         }
1836
1837         connman_info("%s scanning %s", task->ifname,
1838                                 scanning == TRUE ? "started" : "finished");
1839 }
1840
1841 static void state_change(struct supplicant_task *task, DBusMessage *msg)
1842 {
1843         DBusError error;
1844         const char *newstate, *oldstate;
1845         unsigned char bssid[ETH_ALEN];
1846         unsigned int bssid_len;
1847         enum supplicant_state state, prevstate;
1848
1849         dbus_error_init(&error);
1850
1851         if (dbus_message_get_args(msg, &error, DBUS_TYPE_STRING, &newstate,
1852                                                 DBUS_TYPE_STRING, &oldstate,
1853                                                 DBUS_TYPE_INVALID) == FALSE) {
1854                 if (dbus_error_is_set(&error) == TRUE) {
1855                         connman_error("%s", error.message);
1856                         dbus_error_free(&error);
1857                 } else
1858                         connman_error("Wrong arguments for state change");
1859                 return;
1860         }
1861
1862         DBG("state %s ==> %s", oldstate, newstate);
1863
1864         connman_info("%s %s%s", task->ifname, newstate,
1865                                 task->scanning == TRUE ? " (scanning)" : "");
1866
1867         state = string2state(newstate);
1868         if (state == WPA_INVALID)
1869                 return;
1870
1871         if (task->scanning == TRUE && state != WPA_SCANNING) {
1872                 connman_device_cleanup_scanning(task->device);
1873                 task->scanning = FALSE;
1874         }
1875
1876         prevstate = task->state;
1877         task->state = state;
1878
1879         if (task->network == NULL)
1880                 return;
1881
1882         switch (task->state) {
1883         case WPA_COMPLETED:
1884                 switch (prevstate) {
1885                 case WPA_ASSOCIATED:
1886                 case WPA_GROUP_HANDSHAKE:
1887                         break;
1888                 default:
1889                         goto badstate;
1890                 }
1891
1892                 /* reset scan trigger and schedule background scan */
1893                 connman_device_schedule_scan(task->device);
1894
1895                 if (get_bssid(task->device, bssid, &bssid_len) == 0)
1896                         connman_network_set_address(task->network,
1897                                                         bssid, bssid_len);
1898
1899                 /* carrier on */
1900                 connman_network_set_connected(task->network, TRUE);
1901                 break;
1902
1903         case WPA_ASSOCIATING:
1904                 switch (prevstate) {
1905                 case WPA_COMPLETED:
1906                         break;
1907                 case WPA_SCANNING:
1908                         connman_network_set_associating(task->network, TRUE);
1909                         break;
1910                 default:
1911                         goto badstate;
1912                 }
1913                 break;
1914
1915         case WPA_INACTIVE:
1916                 switch (prevstate) {
1917                 case WPA_SCANNING:
1918                 case WPA_DISCONNECTED:
1919                         break;
1920                 default:
1921                         goto badstate;
1922                 }
1923                 /* fall through */
1924
1925         case WPA_DISCONNECTED:
1926                 /* carrier off */
1927                 connman_network_set_connected(task->network, FALSE);
1928
1929                 if (task->disconnecting == TRUE) {
1930                         connman_network_unref(task->network);
1931                         task->disconnecting = FALSE;
1932
1933                         if (task->pending_network != NULL) {
1934                                 task->network = task->pending_network;
1935                                 task->pending_network = NULL;
1936                                 task_connect(task);
1937                         } else
1938                                 task->network = NULL;
1939                 }
1940                 break;
1941
1942         default:
1943                 connman_network_set_associating(task->network, FALSE);
1944                 break;
1945         }
1946
1947         return;
1948
1949 badstate:
1950         connman_error("%s invalid state change %s -> %s", task->ifname,
1951                                                         oldstate, newstate);
1952 }
1953
1954 static DBusHandlerResult supplicant_filter(DBusConnection *conn,
1955                                                 DBusMessage *msg, void *data)
1956 {
1957         struct supplicant_task *task;
1958         const char *member, *path;
1959
1960         if (dbus_message_has_interface(msg,
1961                                 SUPPLICANT_INTF ".Interface") == FALSE)
1962                 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1963
1964         member = dbus_message_get_member(msg);
1965         if (member == NULL)
1966                 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1967
1968         path = dbus_message_get_path(msg);
1969         if (path == NULL)
1970                 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1971
1972         task = find_task_by_path(path);
1973         if (task == NULL)
1974                 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1975
1976         DBG("task %p member %s", task, member);
1977
1978         if (g_str_equal(member, "ScanResultsAvailable") == TRUE)
1979                 scan_results_available(task);
1980         else if (g_str_equal(member, "Scanning") == TRUE)
1981                 scanning(task, msg);
1982         else if (g_str_equal(member, "StateChange") == TRUE)
1983                 state_change(task, msg);
1984
1985         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1986 }
1987
1988 int supplicant_start(struct connman_device *device)
1989 {
1990         struct supplicant_task *task;
1991         int err;
1992
1993         DBG("device %p", device);
1994
1995         task = g_try_new0(struct supplicant_task, 1);
1996         if (task == NULL)
1997                 return -ENOMEM;
1998
1999         task->ifindex = connman_device_get_index(device);
2000         task->ifname = connman_inet_ifname(task->ifindex);
2001
2002         if (task->ifname == NULL) {
2003                 err = -ENOMEM;
2004                 goto failed;
2005         }
2006
2007         task->mac80211 = connman_inet_is_mac80211(task->ifindex);
2008         if (task->mac80211 == FALSE)
2009                 connman_warn("Enabling quirks for unsupported driver");
2010
2011         task->range = g_try_malloc0(sizeof(struct iw_range));
2012         if (task->range == NULL) {
2013                 err = -ENOMEM;
2014                 goto failed;
2015         }
2016
2017         err = get_range(task);
2018         if (err < 0)
2019                 goto failed;
2020
2021         task->device = connman_device_ref(device);
2022
2023         task->created = FALSE;
2024         task->scanning = FALSE;
2025         task->state = WPA_INVALID;
2026         task->disconnecting = FALSE;
2027         task->pending_network = NULL;
2028
2029         task_list = g_slist_append(task_list, task);
2030
2031         return create_interface(task);
2032
2033 failed:
2034         g_free(task->range);
2035         g_free(task->ifname);
2036         g_free(task);
2037
2038         return err;
2039 }
2040
2041 int supplicant_stop(struct connman_device *device)
2042 {
2043         int index = connman_device_get_index(device);
2044         struct supplicant_task *task;
2045
2046         DBG("device %p", device);
2047
2048         task = find_task_by_index(index);
2049         if (task == NULL)
2050                 return -ENODEV;
2051
2052         g_free(task->range);
2053
2054         task_list = g_slist_remove(task_list, task);
2055
2056         if (task->scan_call != NULL) {
2057                 dbus_pending_call_cancel(task->scan_call);
2058                 task->scan_call = NULL;
2059         }
2060
2061         if (task->result_call != NULL) {
2062                 dbus_pending_call_cancel(task->result_call);
2063                 task->result_call = NULL;
2064         }
2065
2066         if (task->scanning == TRUE)
2067                 connman_device_set_scanning(task->device, FALSE);
2068
2069         remove_network(task);
2070
2071         disconnect_network(task);
2072
2073         return remove_interface(task);
2074 }
2075
2076 int supplicant_scan(struct connman_device *device)
2077 {
2078         int index = connman_device_get_index(device);
2079         struct supplicant_task *task;
2080         int err;
2081
2082         DBG("device %p", device);
2083
2084         task = find_task_by_index(index);
2085         if (task == NULL)
2086                 return -ENODEV;
2087
2088         switch (task->state) {
2089         case WPA_SCANNING:
2090                 return -EALREADY;
2091         case WPA_ASSOCIATING:
2092         case WPA_ASSOCIATED:
2093         case WPA_4WAY_HANDSHAKE:
2094         case WPA_GROUP_HANDSHAKE:
2095                 return -EBUSY;
2096         default:
2097                 break;
2098         }
2099
2100         task->scanning = TRUE;
2101
2102         err = initiate_scan(task);
2103         if (err < 0) {
2104                 if (err == -EINPROGRESS)
2105                         return 0;
2106
2107                 task->scanning = FALSE;
2108                 return err;
2109         }
2110
2111         connman_device_set_scanning(task->device, TRUE);
2112
2113         return 0;
2114 }
2115
2116 int supplicant_connect(struct connman_network *network)
2117 {
2118         struct supplicant_task *task;
2119         int index;
2120
2121         DBG("network %p", network);
2122
2123         index = connman_network_get_index(network);
2124
2125         task = find_task_by_index(index);
2126         if (task == NULL)
2127                 return -ENODEV;
2128
2129         if (task->disconnecting == TRUE)
2130                 task->pending_network = connman_network_ref(network);
2131         else {
2132                 task->network = connman_network_ref(network);
2133                 return task_connect(task);
2134         }
2135
2136         return -EINPROGRESS;
2137 }
2138
2139 int supplicant_disconnect(struct connman_network *network)
2140 {
2141         struct supplicant_task *task;
2142         int index;
2143
2144         DBG("network %p", network);
2145
2146         index = connman_network_get_index(network);
2147
2148         task = find_task_by_index(index);
2149         if (task == NULL)
2150                 return -ENODEV;
2151
2152         if (task->disconnecting == TRUE)
2153                 return -EALREADY;
2154
2155         remove_network(task);
2156
2157         disconnect_network(task);
2158
2159         task->disconnecting = TRUE;
2160
2161         return 0;
2162 }
2163
2164 static void supplicant_activate(DBusConnection *conn)
2165 {
2166         DBusMessage *message;
2167
2168         DBG("conn %p", conn);
2169
2170         message = dbus_message_new_method_call(SUPPLICANT_NAME, "/",
2171                                 DBUS_INTERFACE_INTROSPECTABLE, "Introspect");
2172         if (message == NULL)
2173                 return;
2174
2175         dbus_message_set_no_reply(message, TRUE);
2176
2177         dbus_connection_send(conn, message, NULL);
2178
2179         dbus_message_unref(message);
2180 }
2181
2182 static GSList *driver_list = NULL;
2183
2184 static void supplicant_probe(DBusConnection *conn, void *user_data)
2185 {
2186         GSList *list;
2187
2188         DBG("conn %p", conn);
2189
2190         for (list = driver_list; list; list = list->next) {
2191                 struct supplicant_driver *driver = list->data;
2192
2193                 DBG("driver %p name %s", driver, driver->name);
2194
2195                 if (driver->probe)
2196                         driver->probe();
2197         }
2198 }
2199
2200 static void supplicant_remove(DBusConnection *conn, void *user_data)
2201 {
2202         GSList *list;
2203
2204         DBG("conn %p", conn);
2205
2206         for (list = driver_list; list; list = list->next) {
2207                 struct supplicant_driver *driver = list->data;
2208
2209                 DBG("driver %p name %s", driver, driver->name);
2210
2211                 if (driver->remove)
2212                         driver->remove();
2213         }
2214 }
2215
2216 static const char *supplicant_rule = "type=signal,"
2217                                 "interface=" SUPPLICANT_INTF ".Interface";
2218 static guint watch;
2219
2220 static int supplicant_create(void)
2221 {
2222         if (g_slist_length(driver_list) > 0)
2223                 return 0;
2224
2225         connection = connman_dbus_get_connection();
2226         if (connection == NULL)
2227                 return -EIO;
2228
2229         DBG("connection %p", connection);
2230
2231         if (dbus_connection_add_filter(connection,
2232                                 supplicant_filter, NULL, NULL) == FALSE) {
2233                 dbus_connection_unref(connection);
2234                 connection = NULL;
2235                 return -EIO;
2236         }
2237
2238         dbus_bus_add_match(connection, supplicant_rule, NULL);
2239         dbus_connection_flush(connection);
2240
2241         watch = g_dbus_add_service_watch(connection, SUPPLICANT_NAME,
2242                         supplicant_probe, supplicant_remove, NULL, NULL);
2243
2244         return 0;
2245 }
2246
2247 static void supplicant_destroy(void)
2248 {
2249         if (g_slist_length(driver_list) > 0)
2250                 return;
2251
2252         DBG("connection %p", connection);
2253
2254         if (watch > 0)
2255                 g_dbus_remove_watch(connection, watch);
2256
2257         dbus_bus_remove_match(connection, supplicant_rule, NULL);
2258         dbus_connection_flush(connection);
2259
2260         dbus_connection_remove_filter(connection, supplicant_filter, NULL);
2261
2262         dbus_connection_unref(connection);
2263         connection = NULL;
2264 }
2265
2266 int supplicant_register(struct supplicant_driver *driver)
2267 {
2268         int err;
2269
2270         DBG("driver %p name %s", driver, driver->name);
2271
2272         err = supplicant_create();
2273         if (err < 0)
2274                 return err;
2275
2276         driver_list = g_slist_append(driver_list, driver);
2277
2278         supplicant_activate(connection);
2279
2280         return 0;
2281 }
2282
2283 void supplicant_unregister(struct supplicant_driver *driver)
2284 {
2285         DBG("driver %p name %s", driver, driver->name);
2286
2287         supplicant_remove(connection, NULL);
2288
2289         driver_list = g_slist_remove(driver_list, driver);
2290
2291         supplicant_destroy();
2292 }