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