nmcompat: D-Bus configuration file
[framework/connectivity/connman.git] / plugins / supplicant.c
1 /*
2  *
3  *  Connection Manager
4  *
5  *  Copyright (C) 2007-2010  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/wifi.h>
45 #include <connman/log.h>
46
47 #include "supplicant.h"
48
49 #define TIMEOUT 5000
50
51 #define IEEE80211_CAP_ESS       0x0001
52 #define IEEE80211_CAP_IBSS      0x0002
53 #define IEEE80211_CAP_PRIVACY   0x0010
54
55 #define SUPPLICANT_NAME  "fi.epitest.hostap.WPASupplicant"
56 #define SUPPLICANT_INTF  "fi.epitest.hostap.WPASupplicant"
57 #define SUPPLICANT_PATH  "/fi/epitest/hostap/WPASupplicant"
58
59 /* Taken from "WPA Supplicant - Common definitions" */
60 enum supplicant_state {
61         /**
62          * WPA_DISCONNECTED - Disconnected state
63          *
64          * This state indicates that client is not associated, but is likely to
65          * start looking for an access point. This state is entered when a
66          * connection is lost.
67          */
68         WPA_DISCONNECTED,
69
70         /**
71          * WPA_INACTIVE - Inactive state (wpa_supplicant disabled)
72          *
73          * This state is entered if there are no enabled networks in the
74          * configuration. wpa_supplicant is not trying to associate with a new
75          * network and external interaction (e.g., ctrl_iface call to add or
76          * enable a network) is needed to start association.
77          */
78         WPA_INACTIVE,
79
80         /**
81          * WPA_SCANNING - Scanning for a network
82          *
83          * This state is entered when wpa_supplicant starts scanning for a
84          * network.
85          */
86         WPA_SCANNING,
87
88         /**
89          * WPA_ASSOCIATING - Trying to associate with a BSS/SSID
90          *
91          * This state is entered when wpa_supplicant has found a suitable BSS
92          * to associate with and the driver is configured to try to associate
93          * with this BSS in ap_scan=1 mode. When using ap_scan=2 mode, this
94          * state is entered when the driver is configured to try to associate
95          * with a network using the configured SSID and security policy.
96          */
97         WPA_ASSOCIATING,
98
99         /**
100          * WPA_ASSOCIATED - Association completed
101          *
102          * This state is entered when the driver reports that association has
103          * been successfully completed with an AP. If IEEE 802.1X is used
104          * (with or without WPA/WPA2), wpa_supplicant remains in this state
105          * until the IEEE 802.1X/EAPOL authentication has been completed.
106          */
107         WPA_ASSOCIATED,
108
109         /**
110          * WPA_4WAY_HANDSHAKE - WPA 4-Way Key Handshake in progress
111          *
112          * This state is entered when WPA/WPA2 4-Way Handshake is started. In
113          * case of WPA-PSK, this happens when receiving the first EAPOL-Key
114          * frame after association. In case of WPA-EAP, this state is entered
115          * when the IEEE 802.1X/EAPOL authentication has been completed.
116          */
117         WPA_4WAY_HANDSHAKE,
118
119         /**
120          * WPA_GROUP_HANDSHAKE - WPA Group Key Handshake in progress
121          *
122          * This state is entered when 4-Way Key Handshake has been completed
123          * (i.e., when the supplicant sends out message 4/4) and when Group
124          * Key rekeying is started by the AP (i.e., when supplicant receives
125          * message 1/2).
126          */
127         WPA_GROUP_HANDSHAKE,
128
129         /**
130          * WPA_COMPLETED - All authentication completed
131          *
132          * This state is entered when the full authentication process is
133          * completed. In case of WPA2, this happens when the 4-Way Handshake is
134          * successfully completed. With WPA, this state is entered after the
135          * Group Key Handshake; with IEEE 802.1X (non-WPA) connection is
136          * completed after dynamic keys are received (or if not used, after
137          * the EAP authentication has been completed). With static WEP keys and
138          * plaintext connections, this state is entered when an association
139          * has been completed.
140          *
141          * This state indicates that the supplicant has completed its
142          * processing for the association phase and that data connection is
143          * fully configured.
144          */
145         WPA_COMPLETED,
146
147         /**
148          * WPA_INVALID - Invalid state (parsing error)
149          *
150          * This state is returned if the string input is invalid. It is not
151          * an official wpa_supplicant state.
152          */
153         WPA_INVALID,
154 };
155
156 struct supplicant_result {
157         char *path;
158         char *name;
159         unsigned char *addr;
160         unsigned int addr_len;
161         unsigned char *ssid;
162         unsigned int ssid_len;
163         dbus_uint16_t capabilities;
164         gboolean adhoc;
165         gboolean has_wep;
166         gboolean has_psk;
167         gboolean has_8021x;
168         gboolean has_wpa;
169         gboolean has_rsn;
170         gboolean has_wps;
171         dbus_int32_t frequency;
172         dbus_int32_t quality;
173         dbus_int32_t noise;
174         dbus_int32_t level;
175         dbus_int32_t maxrate;
176 };
177
178 struct supplicant_block {
179         unsigned char *ssid;
180         char *netpath;
181         gboolean enabled;
182         int num_scans;
183 };
184
185 struct supplicant_task {
186         int ifindex;
187         char *ifname;
188         gboolean cfg80211;
189         struct connman_device *device;
190         struct connman_network *network;
191         struct connman_network *pending_network;
192         char *path;
193         char *netpath;
194         gboolean hidden_found;
195         GHashTable *hidden_blocks;
196         gboolean created;
197         enum supplicant_state state;
198         gboolean scanning;
199         GSList *scan_results;
200         DBusPendingCall *scan_call;
201         DBusPendingCall *result_call;
202         struct iw_range *range;
203         gboolean disconnecting;
204 };
205
206 static GSList *task_list = NULL;
207
208 static DBusConnection *connection;
209
210 static void free_task(struct supplicant_task *task)
211 {
212         DBG("task %p", task);
213
214         g_free(task->ifname);
215         g_free(task->path);
216         g_free(task);
217 }
218
219 static void remove_block(gpointer user_data)
220 {
221         struct supplicant_block *block = user_data;
222
223         DBG("");
224
225         g_free(block->ssid);
226         g_free(block->netpath);
227         g_free(block);
228 }
229
230 static struct supplicant_task *find_task_by_index(int index)
231 {
232         GSList *list;
233
234         for (list = task_list; list; list = list->next) {
235                 struct supplicant_task *task = list->data;
236
237                 if (task->ifindex == index)
238                         return task;
239         }
240
241         return NULL;
242 }
243
244 static struct supplicant_task *find_task_by_path(const char *path)
245 {
246         GSList *list;
247
248         for (list = task_list; list; list = list->next) {
249                 struct supplicant_task *task = list->data;
250
251                 if (g_strcmp0(task->path, path) == 0)
252                         return task;
253         }
254
255         return NULL;
256 }
257
258 static int get_range(struct supplicant_task *task)
259 {
260         struct iwreq wrq;
261         int fd, err;
262
263         fd = socket(PF_INET, SOCK_DGRAM, 0);
264         if (fd < 0)
265                 return -1;
266
267         memset(&wrq, 0, sizeof(struct iwreq));
268         strncpy(wrq.ifr_name, task->ifname, IFNAMSIZ);
269         wrq.u.data.pointer = task->range;
270         wrq.u.data.length = sizeof(struct iw_range);
271
272         err = ioctl(fd, SIOCGIWRANGE, &wrq);
273
274         close(fd);
275
276         if (err < 0)
277                 task->range->max_qual.updated |= IW_QUAL_ALL_INVALID;
278
279         connman_info("%s {scan} capabilities 0x%02x", task->ifname,
280                                                 task->range->scan_capa);
281
282         connman_info("%s {quality} flags 0x%02x", task->ifname,
283                                         task->range->max_qual.updated);
284
285         return err;
286 }
287
288 static int get_bssid(struct connman_device *device,
289                                 unsigned char *bssid, unsigned int *bssid_len)
290 {
291         struct iwreq wrq;
292         char *ifname;
293         int ifindex;
294         int fd, err;
295
296         ifindex = connman_device_get_index(device);
297         if (ifindex < 0)
298                 return -EINVAL;
299
300         ifname = connman_inet_ifname(ifindex);
301         if (ifname == NULL)
302                 return -EINVAL;
303
304         fd = socket(PF_INET, SOCK_DGRAM, 0);
305         if (fd < 0) {
306                 g_free(ifname);
307                 return -EINVAL;
308         }
309
310         memset(&wrq, 0, sizeof(wrq));
311         strncpy(wrq.ifr_name, ifname, IFNAMSIZ);
312
313         err = ioctl(fd, SIOCGIWAP, &wrq);
314
315         g_free(ifname);
316         close(fd);
317
318         if (err < 0)
319                 return -EIO;
320
321         memcpy(bssid, wrq.u.ap_addr.sa_data, ETH_ALEN);
322         *bssid_len = ETH_ALEN;
323
324         return 0;
325 }
326
327 static int enable_network(struct supplicant_task *task, const char *netpath,
328                           connman_bool_t enable)
329 {
330         DBusMessage *message, *reply;
331         DBusError error;
332         char *enable_string;
333
334         DBG("enable %d", enable);
335
336         enable_string = enable ? "enable" : "disable";
337
338         message = dbus_message_new_method_call(SUPPLICANT_NAME, netpath,
339                                 SUPPLICANT_INTF ".Network", enable_string);
340         if (message == NULL)
341                 return -ENOMEM;
342
343         dbus_message_set_auto_start(message, FALSE);
344
345         dbus_error_init(&error);
346
347         reply = dbus_connection_send_with_reply_and_block(connection,
348                                                         message, -1, &error);
349         if (reply == NULL) {
350                 if (dbus_error_is_set(&error) == TRUE) {
351                         connman_error("%s", error.message);
352                         dbus_error_free(&error);
353                 } else
354                         connman_error("Failed to select network");
355                 dbus_message_unref(message);
356                 return -EIO;
357         }
358
359         dbus_message_unref(reply);
360
361         dbus_message_unref(message);
362
363         return 0;
364 }
365
366 static int set_hidden_network(struct supplicant_task *task, const char *netpath,
367                                 const unsigned char *ssid, int ssid_len)
368 {
369         DBusMessage *message, *reply;
370         DBusMessageIter array, dict;
371         DBusError error;
372         dbus_uint32_t scan_ssid = 1;
373         const char *invalid_address = "ff:ff:ff:ff:ff:ff";
374
375         message = dbus_message_new_method_call(SUPPLICANT_NAME, netpath,
376                                         SUPPLICANT_INTF ".Network", "set");
377         if (message == NULL)
378                 return -ENOMEM;
379
380         dbus_message_set_auto_start(message, FALSE);
381
382         dbus_message_iter_init_append(message, &array);
383
384         connman_dbus_dict_open(&array, &dict);
385
386         connman_dbus_dict_append_basic(&dict, "scan_ssid",
387                                          DBUS_TYPE_UINT32, &scan_ssid);
388
389         connman_dbus_dict_append_fixed_array(&dict, "ssid",
390                                         DBUS_TYPE_BYTE, &ssid, ssid_len);
391
392         /*
393          * We're setting an invalid BSSID to prevent wpa_s from associating
394          * automatically to this block once it's found.
395          */
396         connman_dbus_dict_append_basic(&dict, "bssid",
397                                         DBUS_TYPE_STRING, &invalid_address);
398
399         connman_dbus_dict_close(&array, &dict);
400
401         dbus_error_init(&error);
402
403         reply = dbus_connection_send_with_reply_and_block(connection,
404                                                         message, -1, &error);
405         if (reply == NULL) {
406                 if (dbus_error_is_set(&error) == TRUE) {
407                         connman_error("%s", error.message);
408                         dbus_error_free(&error);
409                 } else
410                         connman_error("Failed to set network options");
411                 dbus_message_unref(message);
412                 return -EIO;
413         }
414
415         dbus_message_unref(reply);
416
417         dbus_message_unref(message);
418
419         return 0;
420 }
421
422 static void block_reset(gpointer key, gpointer value, gpointer user_data)
423 {
424         struct supplicant_block *block = value;
425         struct supplicant_task *task = user_data;
426
427         block->num_scans = 0;
428         if (block->enabled)
429                 enable_network(task, block->netpath, FALSE);
430
431         block->enabled = FALSE;
432 }
433
434 #define MAX_BLOCK_SCANS 2
435 static void hidden_block_enable(struct supplicant_task *task)
436 {
437         GHashTableIter iter;
438         gpointer key, value;
439         struct supplicant_block *block;
440
441         DBG("network %p", task->network);
442
443         if (g_hash_table_size(task->hidden_blocks) == 0)
444                 return;
445
446         /*
447          * If we're associated or associating, we no longer need to
448          * look for hidden networks.
449          */
450         if (task->network)
451                 return;
452
453         /*
454          * We go through the block list and:
455          * - If we scanned it more than twice, we disable it and move
456          *   on to the next block.
457          * - If the next block is not enabled, we enable it, start
458          *   the scan counter, and return. This routine will be called
459          *   again when the next scan results are available.
460          * - If we're done with all the blocks there, we just reset them.
461          */
462         g_hash_table_iter_init(&iter, task->hidden_blocks);
463         while (g_hash_table_iter_next(&iter, &key, &value)) {
464                 block = value;
465
466                 DBG("%s num of scans %d enabled %d",
467                         block->ssid, block->num_scans, block->enabled);
468
469                 if (block->num_scans > MAX_BLOCK_SCANS) {
470                         if (block->enabled == FALSE)
471                                 continue;
472
473                         enable_network(task, block->netpath, FALSE);
474                         block->enabled = FALSE;
475                         continue;
476                 }
477
478                 if (block->enabled == FALSE) {
479                         enable_network(task, block->netpath, TRUE);
480                         block->enabled = TRUE;
481                 }
482
483                 block->num_scans++;
484
485                 return;
486         }
487
488         g_hash_table_foreach(task->hidden_blocks, block_reset, task);
489 }
490
491 static int add_hidden_network(struct supplicant_task *task,
492                                 const unsigned char *ssid, int ssid_len)
493 {
494         DBusMessage *message, *reply;
495         DBusError error;
496         const char *path;
497         struct supplicant_block *block;
498         char *netpath = NULL;
499         int ret, i;
500
501         DBG("task %p", task);
502
503         message = dbus_message_new_method_call(SUPPLICANT_NAME, task->path,
504                                 SUPPLICANT_INTF ".Interface", "addNetwork");
505         if (message == NULL)
506                 return -ENOMEM;
507
508         dbus_message_set_auto_start(message, FALSE);
509
510         dbus_error_init(&error);
511
512         reply = dbus_connection_send_with_reply_and_block(connection,
513                                                         message, -1, &error);
514         if (reply == NULL) {
515                 if (dbus_error_is_set(&error) == TRUE) {
516                         connman_error("%s", error.message);
517                         dbus_error_free(&error);
518                 } else
519                         connman_error("Failed to add network");
520                 dbus_message_unref(message);
521                 return -EIO;
522         }
523
524         dbus_error_init(&error);
525
526         if (dbus_message_get_args(reply, &error, DBUS_TYPE_OBJECT_PATH, &path,
527                                                 DBUS_TYPE_INVALID) == FALSE) {
528                 if (dbus_error_is_set(&error) == TRUE) {
529                         connman_error("%s", error.message);
530                         dbus_error_free(&error);
531                 } else
532                         connman_error("Wrong arguments for network");
533                 dbus_message_unref(reply);
534                 return -EIO;
535         }
536
537         netpath = g_strdup(path);
538
539         ret = set_hidden_network(task, netpath, ssid, ssid_len);
540         if (ret < 0)
541                 goto done;
542
543         block = g_try_new0(struct supplicant_block, 1);
544         if (block == NULL)
545                 goto done;
546
547         block->ssid = g_try_malloc0(ssid_len + 1);
548         if (block->ssid == NULL) {
549                 g_free(block);
550                 goto done;
551         }
552
553         for (i = 0; i < ssid_len; i++) {
554                 if (g_ascii_isprint(ssid[i]))
555                         block->ssid[i] = ssid[i];
556                 else
557                         block->ssid[i] = ' ';
558         }
559
560         block->netpath = netpath;
561         block->enabled = FALSE;
562         block->num_scans = 0;
563
564         DBG("path %s ssid %s", block->netpath, block->ssid);
565
566         g_hash_table_replace(task->hidden_blocks, block->ssid, block);
567
568         return 0;
569 done:
570         g_free(netpath);
571
572         dbus_message_unref(reply);
573
574         dbus_message_unref(message);
575
576         return ret;
577 }
578
579 static void add_interface_reply(DBusPendingCall *call, void *user_data)
580 {
581         struct supplicant_task *task = user_data;
582         DBusMessage *reply;
583         DBusError error;
584         const char *path;
585         char **hex_ssids, *hex_ssid;
586         int i;
587
588         DBG("task %p", task);
589
590         reply = dbus_pending_call_steal_reply(call);
591
592         if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR)
593                 goto failed;
594
595         dbus_error_init(&error);
596
597         if (dbus_message_get_args(reply, &error, DBUS_TYPE_OBJECT_PATH, &path,
598                                                 DBUS_TYPE_INVALID) == FALSE) {
599                 if (dbus_error_is_set(&error) == TRUE) {
600                         connman_error("%s", error.message);
601                         dbus_error_free(&error);
602                 } else
603                         connman_error("Wrong arguments for add interface");
604                 goto failed;
605         }
606
607         DBG("path %s", path);
608
609         task->path = g_strdup(path);
610         task->created = TRUE;
611
612         connman_device_set_powered(task->device, TRUE);
613
614         dbus_message_unref(reply);
615
616         dbus_pending_call_unref(call);
617
618         hex_ssids = connman_wifi_load_ssid();
619         if (hex_ssids == NULL)
620                 return;
621
622         for (i = 0; hex_ssids[i]; i++) {
623                 unsigned char *ssid;
624                 unsigned int j, k = 0, hex;
625                 size_t hex_ssid_len;
626
627                 hex_ssid = hex_ssids[i];
628                 hex_ssid_len = strlen(hex_ssid);
629
630                 ssid = g_try_malloc0(hex_ssid_len / 2 + 1);
631                 if (ssid == NULL)
632                         break;
633
634                 for (j = 0, k = 0; j < hex_ssid_len; j += 2) {
635                         sscanf(hex_ssid + j, "%02x", &hex);
636                         ssid[k++] = hex;
637                 }
638
639                 if (add_hidden_network(task, ssid, hex_ssid_len / 2) < 0) {
640                         g_free(ssid);
641                         break;
642                 }
643
644                 g_free(ssid);
645         }
646
647         g_strfreev(hex_ssids);
648
649         return;
650
651 failed:
652         dbus_message_unref(reply);
653
654         dbus_pending_call_unref(call);
655
656         task_list = g_slist_remove(task_list, task);
657
658         connman_device_unref(task->device);
659
660         free_task(task);
661 }
662
663 static int add_interface(struct supplicant_task *task)
664 {
665         const char *driver = connman_option_get_string("wifi");
666         DBusMessage *message;
667         DBusMessageIter array, dict;
668         DBusPendingCall *call;
669
670         DBG("task %p", task);
671
672         message = dbus_message_new_method_call(SUPPLICANT_NAME, SUPPLICANT_PATH,
673                                         SUPPLICANT_INTF, "addInterface");
674         if (message == NULL)
675                 return -ENOMEM;
676
677         dbus_message_set_auto_start(message, FALSE);
678
679         dbus_message_iter_init_append(message, &array);
680
681         dbus_message_iter_append_basic(&array,
682                                         DBUS_TYPE_STRING, &task->ifname);
683
684         connman_dbus_dict_open(&array, &dict);
685
686         connman_dbus_dict_append_basic(&dict, "driver",
687                                                 DBUS_TYPE_STRING, &driver);
688
689         connman_dbus_dict_close(&array, &dict);
690
691         if (dbus_connection_send_with_reply(connection, message,
692                                                 &call, TIMEOUT) == FALSE) {
693                 connman_error("Failed to add interface");
694                 dbus_message_unref(message);
695                 return -EIO;
696         }
697
698         if (call == NULL) {
699                 connman_error("D-Bus connection not available");
700                 dbus_message_unref(message);
701                 return -EIO;
702         }
703
704         dbus_pending_call_set_notify(call, add_interface_reply, task, NULL);
705
706         dbus_message_unref(message);
707
708         return -EINPROGRESS;
709 }
710
711 static void get_interface_reply(DBusPendingCall *call, void *user_data)
712 {
713         struct supplicant_task *task = user_data;
714         DBusMessage *reply;
715         DBusError error;
716         const char *path;
717
718         DBG("task %p", task);
719
720         reply = dbus_pending_call_steal_reply(call);
721
722         if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR) {
723                 add_interface(task);
724                 goto done;
725         }
726
727         dbus_error_init(&error);
728
729         if (dbus_message_get_args(reply, &error, DBUS_TYPE_OBJECT_PATH, &path,
730                                                 DBUS_TYPE_INVALID) == FALSE) {
731                 if (dbus_error_is_set(&error) == TRUE) {
732                         connman_error("%s", error.message);
733                         dbus_error_free(&error);
734                 } else
735                         connman_error("Wrong arguments for get interface");
736                 goto done;
737         }
738
739         DBG("path %s", path);
740
741         task->path = g_strdup(path);
742         task->created = FALSE;
743
744         connman_device_set_powered(task->device, TRUE);
745
746 done:
747         dbus_message_unref(reply);
748
749         dbus_pending_call_unref(call);
750 }
751
752 static int create_interface(struct supplicant_task *task)
753 {
754         DBusMessage *message;
755         DBusPendingCall *call;
756
757         DBG("task %p", task);
758
759         message = dbus_message_new_method_call(SUPPLICANT_NAME, SUPPLICANT_PATH,
760                                         SUPPLICANT_INTF, "getInterface");
761         if (message == NULL)
762                 return -ENOMEM;
763
764         dbus_message_set_auto_start(message, FALSE);
765
766         dbus_message_append_args(message, DBUS_TYPE_STRING, &task->ifname,
767                                                         DBUS_TYPE_INVALID);
768
769         if (dbus_connection_send_with_reply(connection, message,
770                                                 &call, TIMEOUT) == FALSE) {
771                 connman_error("Failed to get interface");
772                 dbus_message_unref(message);
773                 return -EIO;
774         }
775
776         if (call == NULL) {
777                 connman_error("D-Bus connection not available");
778                 dbus_message_unref(message);
779                 return -EIO;
780         }
781
782         dbus_pending_call_set_notify(call, get_interface_reply, task, NULL);
783
784         dbus_message_unref(message);
785
786         return -EINPROGRESS;
787 }
788
789 static void remove_interface_reply(DBusPendingCall *call, void *user_data)
790 {
791         struct supplicant_task *task = user_data;
792         DBusMessage *reply;
793
794         DBG("task %p", task);
795
796         reply = dbus_pending_call_steal_reply(call);
797
798         connman_device_set_powered(task->device, FALSE);
799
800         connman_device_unref(task->device);
801
802         connman_inet_ifdown(task->ifindex);
803
804         free_task(task);
805
806         dbus_message_unref(reply);
807
808         dbus_pending_call_unref(call);
809 }
810
811 static int remove_interface(struct supplicant_task *task)
812 {
813         DBusMessage *message;
814         DBusPendingCall *call;
815
816         DBG("task %p", task);
817
818         if (task->path == NULL)
819                 return 0;
820
821 #if 0
822         if (task->created == FALSE) {
823                 connman_device_set_powered(task->device, FALSE);
824                 return 0;
825         }
826 #endif
827
828         message = dbus_message_new_method_call(SUPPLICANT_NAME, SUPPLICANT_PATH,
829                                         SUPPLICANT_INTF, "removeInterface");
830         if (message == NULL)
831                 return -ENOMEM;
832
833         dbus_message_set_auto_start(message, FALSE);
834
835         dbus_message_append_args(message, DBUS_TYPE_OBJECT_PATH, &task->path,
836                                                         DBUS_TYPE_INVALID);
837
838         if (dbus_connection_send_with_reply(connection, message,
839                                                 &call, TIMEOUT) == FALSE) {
840                 connman_error("Failed to remove interface");
841                 dbus_message_unref(message);
842                 return -EIO;
843         }
844
845         if (call == NULL) {
846                 connman_error("D-Bus connection not available");
847                 dbus_message_unref(message);
848                 return -EIO;
849         }
850
851         dbus_pending_call_set_notify(call, remove_interface_reply, task, NULL);
852
853         dbus_message_unref(message);
854
855         return -EINPROGRESS;
856 }
857
858 static int set_ap_scan(struct supplicant_task *task)
859 {
860         DBusMessage *message, *reply;
861         DBusError error;
862         guint32 ap_scan = 1;
863
864         DBG("task %p", task);
865
866         message = dbus_message_new_method_call(SUPPLICANT_NAME, task->path,
867                                 SUPPLICANT_INTF ".Interface", "setAPScan");
868         if (message == NULL)
869                 return -ENOMEM;
870
871         dbus_message_set_auto_start(message, FALSE);
872
873         dbus_message_append_args(message, DBUS_TYPE_UINT32, &ap_scan,
874                                                         DBUS_TYPE_INVALID);
875
876         dbus_error_init(&error);
877
878         reply = dbus_connection_send_with_reply_and_block(connection,
879                                                         message, -1, &error);
880         if (reply == NULL) {
881                 if (dbus_error_is_set(&error) == TRUE) {
882                         connman_error("%s", error.message);
883                         dbus_error_free(&error);
884                 } else
885                         connman_error("Failed to set AP scan");
886                 dbus_message_unref(message);
887                 return -EIO;
888         }
889
890         dbus_message_unref(message);
891
892         dbus_message_unref(reply);
893
894         return 0;
895 }
896
897 static int add_network(struct supplicant_task *task)
898 {
899         DBusMessage *message, *reply;
900         DBusError error;
901         const char *path;
902
903         DBG("task %p", task);
904
905         if (task->netpath != NULL)
906                 return -EALREADY;
907
908         message = dbus_message_new_method_call(SUPPLICANT_NAME, task->path,
909                                 SUPPLICANT_INTF ".Interface", "addNetwork");
910         if (message == NULL)
911                 return -ENOMEM;
912
913         dbus_message_set_auto_start(message, FALSE);
914
915         dbus_error_init(&error);
916
917         reply = dbus_connection_send_with_reply_and_block(connection,
918                                                         message, -1, &error);
919         if (reply == NULL) {
920                 if (dbus_error_is_set(&error) == TRUE) {
921                         connman_error("%s", error.message);
922                         dbus_error_free(&error);
923                 } else
924                         connman_error("Failed to add network");
925                 dbus_message_unref(message);
926                 return -EIO;
927         }
928
929         dbus_message_unref(message);
930
931         dbus_error_init(&error);
932
933         if (dbus_message_get_args(reply, &error, DBUS_TYPE_OBJECT_PATH, &path,
934                                                 DBUS_TYPE_INVALID) == FALSE) {
935                 if (dbus_error_is_set(&error) == TRUE) {
936                         connman_error("%s", error.message);
937                         dbus_error_free(&error);
938                 } else
939                         connman_error("Wrong arguments for network");
940                 dbus_message_unref(reply);
941                 return -EIO;
942         }
943
944         DBG("path %s", path);
945
946         task->netpath = g_strdup(path);
947
948         dbus_message_unref(reply);
949
950         return 0;
951 }
952
953 static int remove_network(struct supplicant_task *task)
954 {
955         DBusMessage *message, *reply;
956         DBusError error;
957
958         DBG("task %p", task);
959
960         if (task->netpath == NULL || task->path == NULL)
961                 return -EINVAL;
962
963         message = dbus_message_new_method_call(SUPPLICANT_NAME, task->path,
964                                 SUPPLICANT_INTF ".Interface", "removeNetwork");
965         if (message == NULL)
966                 return -ENOMEM;
967
968         dbus_message_set_auto_start(message, FALSE);
969
970         dbus_message_append_args(message, DBUS_TYPE_OBJECT_PATH, &task->netpath,
971                                                         DBUS_TYPE_INVALID);
972
973         dbus_error_init(&error);
974
975         reply = dbus_connection_send_with_reply_and_block(connection,
976                                                         message, -1, &error);
977         if (reply == NULL) {
978                 if (dbus_error_is_set(&error) == TRUE) {
979                         connman_error("%s", error.message);
980                         dbus_error_free(&error);
981                 } else
982                         connman_error("Failed to remove network");
983                 dbus_message_unref(message);
984                 return -EIO;
985         }
986
987         dbus_message_unref(message);
988
989         dbus_message_unref(reply);
990
991         g_free(task->netpath);
992         task->netpath = NULL;
993
994         return 0;
995 }
996
997 static int select_network(struct supplicant_task *task)
998 {
999         DBusMessage *message, *reply;
1000         DBusError error;
1001
1002         DBG("task %p", task);
1003
1004         if (task->netpath == NULL)
1005                 return -EINVAL;
1006
1007         message = dbus_message_new_method_call(SUPPLICANT_NAME, task->path,
1008                                 SUPPLICANT_INTF ".Interface", "selectNetwork");
1009         if (message == NULL)
1010                 return -ENOMEM;
1011
1012         dbus_message_set_auto_start(message, FALSE);
1013
1014         dbus_message_append_args(message, DBUS_TYPE_OBJECT_PATH, &task->netpath,
1015                                                         DBUS_TYPE_INVALID);
1016
1017         dbus_error_init(&error);
1018
1019         reply = dbus_connection_send_with_reply_and_block(connection,
1020                                                         message, -1, &error);
1021         if (reply == NULL) {
1022                 if (dbus_error_is_set(&error) == TRUE) {
1023                         connman_error("%s", error.message);
1024                         dbus_error_free(&error);
1025                 } else
1026                         connman_error("Failed to select network");
1027                 dbus_message_unref(message);
1028                 return -EIO;
1029         }
1030
1031         dbus_message_unref(message);
1032
1033         dbus_message_unref(reply);
1034
1035         return 0;
1036 }
1037
1038 static int disconnect_network(struct supplicant_task *task)
1039 {
1040         DBusMessage *message, *reply;
1041         DBusError error;
1042
1043         DBG("task %p", task);
1044
1045         if (task->path == NULL)
1046                 return -EINVAL;
1047
1048         message = dbus_message_new_method_call(SUPPLICANT_NAME, task->path,
1049                                 SUPPLICANT_INTF ".Interface", "disconnect");
1050         if (message == NULL)
1051                 return -ENOMEM;
1052
1053         dbus_message_set_auto_start(message, FALSE);
1054
1055         dbus_error_init(&error);
1056
1057         reply = dbus_connection_send_with_reply_and_block(connection,
1058                                                         message, -1, &error);
1059         if (reply == NULL) {
1060                 if (dbus_error_is_set(&error) == TRUE) {
1061                         connman_error("%s", error.message);
1062                         dbus_error_free(&error);
1063                 } else
1064                         connman_error("Failed to disconnect network");
1065                 dbus_message_unref(message);
1066                 return -EIO;
1067         }
1068
1069         dbus_message_unref(message);
1070
1071         dbus_message_unref(reply);
1072
1073         return 0;
1074 }
1075
1076 static int set_network_tls(struct connman_network *network,
1077                            DBusMessageIter *dict)
1078 {
1079         const char *private_key, *client_cert, *ca_cert;
1080         const char *private_key_password;
1081
1082         /*
1083          * For TLS, we at least need:
1084          *              The client certificate
1085          *              The client private key file
1086          *              The client private key file password
1087          *
1088          * The Authority certificate is optional.
1089          */
1090         client_cert = connman_network_get_string(network,
1091                                                 "WiFi.ClientCertFile");
1092         if (client_cert == NULL) {
1093                 connman_error("Error in TLS authentication: "
1094                               "a ClientCertFile must be defined\n");
1095                 return -EINVAL;
1096         }
1097
1098         private_key = connman_network_get_string(network,
1099                                                 "WiFi.PrivateKeyFile");
1100         if (private_key == NULL) {
1101                 connman_error("Error in TLS authentication: "
1102                               "a PrivateKeyFile must be defined\n");
1103                 return -EINVAL;
1104         }
1105
1106         private_key_password = connman_network_get_string(network,
1107                                                 "WiFi.PrivateKeyPassphrase");
1108         if (private_key_password == NULL) {
1109                 connman_error("Error in TLS authentication: "
1110                               "a PrivateKeyPassphrase must be defined\n");
1111                 return -EINVAL;
1112         }
1113
1114         ca_cert = connman_network_get_string(network, "WiFi.CACertFile");
1115         if (ca_cert)
1116                 connman_dbus_dict_append_basic(dict, "ca_cert",
1117                                                 DBUS_TYPE_STRING, &ca_cert);
1118         else
1119                 connman_info("No CACertFile has been provided "
1120                              "to do the TLS authentication\n");
1121
1122         DBG("client cert %s private key %s", client_cert, private_key);
1123
1124         connman_dbus_dict_append_basic(dict, "private_key",
1125                                                 DBUS_TYPE_STRING, &private_key);
1126         connman_dbus_dict_append_basic(dict, "private_key_passwd",
1127                                                         DBUS_TYPE_STRING,
1128                                                         &private_key_password);
1129         connman_dbus_dict_append_basic(dict, "client_cert",
1130                                                 DBUS_TYPE_STRING, &client_cert);
1131
1132         return 0;
1133 }
1134
1135 static int set_network_peap(struct connman_network *network,
1136                             DBusMessageIter *dict, const char *passphrase)
1137 {
1138         const char *client_cert, *ca_cert, *phase2;
1139         char *phase2_auth;
1140
1141         /*
1142          * For PEAP/TTLS, we at least need
1143          *              The authority certificate
1144          *              The 2nd phase authentication method
1145          *              The 2nd phase passphrase
1146          *
1147          * The Client certificate is optional although strongly required
1148          * When setting it, we need in addition
1149          *              The Client private key file
1150          *              The Client private key file password
1151          */
1152         if (passphrase == NULL) {
1153                 connman_error("Error in PEAP/TTLS authentication: "
1154                               "a phase2 passphrase must be defined\n");
1155                 return -EINVAL;
1156         }
1157
1158         ca_cert = connman_network_get_string(network, "WiFi.CACertFile");
1159         if (ca_cert == NULL) {
1160                 connman_error("Error in PEAP/TTLS authentication: "
1161                               "CACertFile must be defined\n");
1162                 return -EINVAL;
1163         }
1164
1165         phase2 = connman_network_get_string(network, "WiFi.Phase2");
1166         if (phase2 == NULL) {
1167                 connman_error("Error in PEAP/TTLS authentication: "
1168                               "Phase2 must be defined\n");
1169                 return -EINVAL;
1170         }
1171
1172         DBG("CA cert %s phase2 auth %s", ca_cert, phase2);
1173
1174         client_cert = connman_network_get_string(network,
1175                                                         "WiFi.ClientCertFile");
1176         if (client_cert) {
1177                 const char *private_key, *private_key_password;
1178
1179                 private_key = connman_network_get_string(network,
1180                                                         "WiFi.PrivateKeyFile");
1181                 if (private_key == NULL) {
1182                         connman_error("Error in PEAP/TTLS authentication: "
1183                                       "with ClientCertFile, "
1184                                       "PrivateKeyFile must be defined\n");
1185                         return -EINVAL;
1186                 }
1187
1188                 private_key_password =
1189                         connman_network_get_string(network,
1190                                                 "WiFi.PrivateKeyPassphrase");
1191                 if (private_key_password == NULL) {
1192                         connman_error("Error in PEAP/TTLS authentication: "
1193                                       "with ClientCertFile, "
1194                                       "PrivateKeyPassphrase must be defined\n");
1195                         return -EINVAL;
1196                 }
1197
1198                 connman_dbus_dict_append_basic(dict, "client_cert",
1199                                                 DBUS_TYPE_STRING, &client_cert);
1200
1201                 connman_dbus_dict_append_basic(dict, "private_key",
1202                                                 DBUS_TYPE_STRING, &private_key);
1203
1204                 connman_dbus_dict_append_basic(dict, "private_key_passwd",
1205                                                         DBUS_TYPE_STRING,
1206                                                         &private_key_password);
1207
1208                 DBG("client cert %s private key %s", client_cert, private_key);
1209         } else
1210                 connman_info("No client certificate has been provided "
1211                              "to do the PEAP/TTLS authentication\n");
1212
1213         if (g_str_has_prefix(phase2, "EAP-") == TRUE) {
1214                 phase2_auth = g_strdup_printf("autheap=%s",
1215                                                 phase2 + strlen("EAP-"));
1216         } else
1217                 phase2_auth = g_strdup_printf("auth=%s", phase2);
1218
1219         connman_dbus_dict_append_basic(dict, "password",
1220                                                 DBUS_TYPE_STRING, &passphrase);
1221
1222         connman_dbus_dict_append_basic(dict, "ca_cert",
1223                                                 DBUS_TYPE_STRING, &ca_cert);
1224
1225         connman_dbus_dict_append_basic(dict, "phase2",
1226                                                 DBUS_TYPE_STRING, &phase2_auth);
1227
1228         g_free(phase2_auth);
1229
1230         return 0;
1231 }
1232
1233 static int set_network(struct supplicant_task *task,
1234                                 const unsigned char *network, int len,
1235                                 const char *address, const char *security,
1236                                                         const char *passphrase)
1237 {
1238         DBusMessage *message, *reply;
1239         DBusMessageIter array, dict;
1240         DBusError error;
1241         dbus_uint32_t scan_ssid = 1;
1242
1243         DBG("task %p", task);
1244
1245         if (task->netpath == NULL)
1246                 return -EINVAL;
1247
1248         message = dbus_message_new_method_call(SUPPLICANT_NAME, task->netpath,
1249                                         SUPPLICANT_INTF ".Network", "set");
1250         if (message == NULL)
1251                 return -ENOMEM;
1252
1253         dbus_message_set_auto_start(message, FALSE);
1254
1255         dbus_message_iter_init_append(message, &array);
1256
1257         connman_dbus_dict_open(&array, &dict);
1258
1259         connman_dbus_dict_append_basic(&dict, "scan_ssid",
1260                                          DBUS_TYPE_UINT32, &scan_ssid);
1261
1262         if (network)
1263                 connman_dbus_dict_append_fixed_array(&dict, "ssid",
1264                                                 DBUS_TYPE_BYTE, &network, len);
1265         else if (address)
1266                 connman_dbus_dict_append_basic(&dict, "bssid",
1267                                                 DBUS_TYPE_STRING, &address);
1268
1269         if (g_ascii_strcasecmp(security, "psk") == 0 ||
1270                                 g_ascii_strcasecmp(security, "wpa") == 0 ||
1271                                 g_ascii_strcasecmp(security, "rsn") == 0) {
1272                 const char *key_mgmt = "WPA-PSK";
1273                 connman_dbus_dict_append_basic(&dict, "key_mgmt",
1274                                                 DBUS_TYPE_STRING, &key_mgmt);
1275
1276                 if (passphrase && strlen(passphrase) > 0)
1277                         connman_dbus_dict_append_basic(&dict, "psk",
1278                                                 DBUS_TYPE_STRING, &passphrase);
1279         } else if (g_ascii_strcasecmp(security, "ieee8021x") == 0) {
1280                 struct connman_network *network = task->network;
1281                 const char *key_mgmt = "WPA-EAP", *eap, *identity;
1282                 char *eap_value;
1283
1284                 /*
1285                  * If our private key password is unset,
1286                  * we use the supplied passphrase. That is needed
1287                  * for PEAP where 2 passphrases (identity and client
1288                  * cert may have to be provided.
1289                  */
1290                 if (connman_network_get_string(network,
1291                                         "WiFi.PrivateKeyPassphrase") == NULL)
1292                         connman_network_set_string(network,
1293                                                 "WiFi.PrivateKeyPassphrase",
1294                                                                 passphrase);
1295
1296                 eap = connman_network_get_string(network, "WiFi.EAP");
1297                 if (eap == NULL)
1298                         goto invalid;
1299
1300                 /* We must have an identity for both PEAP and TLS */
1301                 identity = connman_network_get_string(network, "WiFi.Identity");
1302                 if (identity == NULL)
1303                         goto invalid;
1304
1305                 DBG("key_mgmt %s eap %s identity %s", key_mgmt, eap, identity);
1306
1307                 if (g_strcmp0(eap, "tls") == 0) {
1308                         int err;
1309
1310                         err = set_network_tls(network, &dict);
1311                         if (err < 0) {
1312                                 dbus_message_unref(message);
1313                                 return err;
1314                         }
1315                 } else if (g_strcmp0(eap, "peap") == 0 ||
1316                                    g_strcmp0(eap, "ttls") == 0) {
1317                         int err;
1318
1319                         err = set_network_peap(network, &dict, passphrase);
1320                         if (err < 0) {
1321                                 dbus_message_unref(message);
1322                                 return err;
1323                         }
1324                 } else {
1325                         connman_error("Unknown EAP %s", eap);
1326                         goto invalid;
1327                 }
1328
1329                 /* wpa_supplicant only accepts upper case EAPs */
1330                 eap_value = g_ascii_strup(eap, -1);
1331
1332                 connman_dbus_dict_append_basic(&dict, "key_mgmt",
1333                                                         DBUS_TYPE_STRING,
1334                                                         &key_mgmt);
1335                 connman_dbus_dict_append_basic(&dict, "eap",
1336                                                         DBUS_TYPE_STRING,
1337                                                         &eap_value);
1338                 connman_dbus_dict_append_basic(&dict, "identity",
1339                                                         DBUS_TYPE_STRING,
1340                                                         &identity);
1341
1342                 g_free(eap_value);
1343
1344         } else if (g_ascii_strcasecmp(security, "wep") == 0) {
1345                 const char *key_mgmt = "NONE";
1346                 const char *auth_alg = "OPEN";
1347                 const char *key_index = "0";
1348
1349                 if (task->cfg80211 == TRUE)
1350                         auth_alg = "OPEN SHARED";
1351
1352                 connman_dbus_dict_append_basic(&dict, "auth_alg",
1353                                                 DBUS_TYPE_STRING, &auth_alg);
1354
1355                 connman_dbus_dict_append_basic(&dict, "key_mgmt",
1356                                                 DBUS_TYPE_STRING, &key_mgmt);
1357
1358                 if (passphrase) {
1359                         int size = strlen(passphrase);
1360                         if (size == 10 || size == 26) {
1361                                 unsigned char *key = malloc(13);
1362                                 char tmp[3];
1363                                 int i;
1364                                 memset(tmp, 0, sizeof(tmp));
1365                                 if (key == NULL)
1366                                         size = 0;
1367                                 for (i = 0; i < size / 2; i++) {
1368                                         memcpy(tmp, passphrase + (i * 2), 2);
1369                                         key[i] = (unsigned char) strtol(tmp,
1370                                                                 NULL, 16);
1371                                 }
1372                                 connman_dbus_dict_append_fixed_array(&dict,
1373                                                 "wep_key0", DBUS_TYPE_BYTE,
1374                                                         &key, size / 2);
1375                                 free(key);
1376                         } else if (size == 5 || size == 13) {
1377                                 unsigned char *key = malloc(13);
1378                                 int i;
1379                                 if (key == NULL)
1380                                         size = 0;
1381                                 for (i = 0; i < size; i++)
1382                                         key[i] = (unsigned char) passphrase[i];
1383                                 connman_dbus_dict_append_fixed_array(&dict,
1384                                                 "wep_key0", DBUS_TYPE_BYTE,
1385                                                                 &key, size);
1386                                 free(key);
1387                         } else
1388                                 connman_dbus_dict_append_basic(&dict,
1389                                                 "wep_key0", DBUS_TYPE_STRING,
1390                                                                 &passphrase);
1391
1392                         connman_dbus_dict_append_basic(&dict, "wep_tx_keyidx",
1393                                                 DBUS_TYPE_STRING, &key_index);
1394                 }
1395         } else {
1396                 const char *key_mgmt = "NONE";
1397                 connman_dbus_dict_append_basic(&dict, "key_mgmt",
1398                                                 DBUS_TYPE_STRING, &key_mgmt);
1399         }
1400
1401         connman_dbus_dict_close(&array, &dict);
1402
1403         dbus_error_init(&error);
1404
1405         reply = dbus_connection_send_with_reply_and_block(connection,
1406                                                         message, -1, &error);
1407         if (reply == NULL) {
1408                 if (dbus_error_is_set(&error) == TRUE) {
1409                         connman_error("%s", error.message);
1410                         dbus_error_free(&error);
1411                 } else
1412                         connman_error("Failed to set network options");
1413                 dbus_message_unref(message);
1414                 return -EIO;
1415         }
1416
1417         dbus_message_unref(message);
1418
1419         dbus_message_unref(reply);
1420
1421         return 0;
1422
1423 invalid:
1424         dbus_message_unref(message);
1425         return -EINVAL;
1426 }
1427
1428 static void scan_reply(DBusPendingCall *call, void *user_data)
1429 {
1430         struct supplicant_task *task = user_data;
1431         DBusMessage *reply;
1432
1433         DBG("task %p", task);
1434
1435         task->scan_call = NULL;
1436
1437         reply = dbus_pending_call_steal_reply(call);
1438
1439         if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR) {
1440                 connman_device_set_scanning(task->device, FALSE);
1441                 goto done;
1442         }
1443
1444         if (task->scanning == TRUE)
1445                 connman_device_set_scanning(task->device, TRUE);
1446
1447 done:
1448         dbus_message_unref(reply);
1449
1450         dbus_pending_call_unref(call);
1451 }
1452
1453
1454 static int initiate_scan(struct supplicant_task *task)
1455 {
1456         DBusMessage *message;
1457
1458         DBG("task %p", task);
1459
1460         if (task->path == NULL)
1461                 return -EINVAL;
1462
1463         if (task->scan_call != NULL)
1464                 return -EALREADY;
1465
1466         connman_info("%s initiating scan", task->ifname);
1467
1468         message = dbus_message_new_method_call(SUPPLICANT_NAME, task->path,
1469                                         SUPPLICANT_INTF ".Interface", "scan");
1470         if (message == NULL)
1471                 return -ENOMEM;
1472
1473         dbus_message_set_auto_start(message, FALSE);
1474
1475         if (dbus_connection_send_with_reply(connection, message,
1476                                         &task->scan_call, TIMEOUT) == FALSE) {
1477                 connman_error("Failed to initiate scan");
1478                 dbus_message_unref(message);
1479                 return -EIO;
1480         }
1481
1482         if (task->scan_call == NULL) {
1483                 connman_error("D-Bus connection not available");
1484                 dbus_message_unref(message);
1485                 return -EIO;
1486         }
1487
1488         dbus_pending_call_set_notify(task->scan_call, scan_reply, task, NULL);
1489
1490         dbus_message_unref(message);
1491
1492         return -EINPROGRESS;
1493 }
1494
1495 static struct {
1496         char *name;
1497         char *value;
1498 } special_ssid[] = {
1499         { "<hidden>", "hidden"  },
1500         { "default",  "linksys" },
1501         { "wireless"  },
1502         { "linksys"   },
1503         { "netgear"   },
1504         { "dlink"     },
1505         { "2wire"     },
1506         { "compaq"    },
1507         { "tsunami"   },
1508         { "comcomcom", "3com"     },
1509         { "3Com",      "3com"     },
1510         { "Symbol",    "symbol"   },
1511         { "Motorola",  "motorola" },
1512         { "Wireless" , "wireless" },
1513         { "WLAN",      "wlan"     },
1514         { }
1515 };
1516
1517 static char *build_group(const char *addr, const char *name,
1518                         const unsigned char *ssid, unsigned int ssid_len,
1519                                         const char *mode, const char *security)
1520 {
1521         GString *str;
1522         unsigned int i;
1523
1524         if (addr == NULL)
1525                 return NULL;
1526
1527         str = g_string_sized_new((ssid_len * 2) + 24);
1528         if (str == NULL)
1529                 return NULL;
1530
1531         if (ssid == NULL) {
1532                 g_string_append_printf(str, "hidden_%s", addr);
1533                 goto done;
1534         }
1535
1536         for (i = 0; special_ssid[i].name; i++) {
1537                 if (g_strcmp0(special_ssid[i].name, name) == 0) {
1538                         if (special_ssid[i].value == NULL)
1539                                 g_string_append_printf(str, "%s_%s",
1540                                                                 name, addr);
1541                         else
1542                                 g_string_append_printf(str, "%s_%s",
1543                                                 special_ssid[i].value, addr);
1544                         goto done;
1545                 }
1546         }
1547
1548         if (ssid_len > 0 && ssid[0] != '\0') {
1549                 for (i = 0; i < ssid_len; i++)
1550                         g_string_append_printf(str, "%02x", ssid[i]);
1551         } else
1552                 g_string_append_printf(str, "hidden_%s", addr);
1553
1554 done:
1555         g_string_append_printf(str, "_%s_%s", mode, security);
1556
1557         return g_string_free(str, FALSE);
1558 }
1559
1560 static void extract_addr(DBusMessageIter *value,
1561                                         struct supplicant_result *result)
1562 {
1563         DBusMessageIter array;
1564         struct ether_addr eth;
1565         unsigned char *addr;
1566         int addr_len;
1567
1568         dbus_message_iter_recurse(value, &array);
1569         dbus_message_iter_get_fixed_array(&array, &addr, &addr_len);
1570
1571         if (addr_len != 6)
1572                 return;
1573
1574         result->addr = g_try_malloc(addr_len);
1575         if (result->addr == NULL)
1576                 return;
1577
1578         memcpy(result->addr, addr, addr_len);
1579         result->addr_len = addr_len;
1580
1581         result->path = g_try_malloc0(13);
1582         if (result->path == NULL)
1583                 return;
1584
1585         memcpy(&eth, addr, sizeof(eth));
1586         snprintf(result->path, 13, "%02x%02x%02x%02x%02x%02x",
1587                                                 eth.ether_addr_octet[0],
1588                                                 eth.ether_addr_octet[1],
1589                                                 eth.ether_addr_octet[2],
1590                                                 eth.ether_addr_octet[3],
1591                                                 eth.ether_addr_octet[4],
1592                                                 eth.ether_addr_octet[5]);
1593 }
1594
1595 static void extract_ssid(DBusMessageIter *value,
1596                                         struct supplicant_result *result)
1597 {
1598         DBusMessageIter array;
1599         unsigned char *ssid;
1600         int ssid_len, i;
1601
1602         dbus_message_iter_recurse(value, &array);
1603         dbus_message_iter_get_fixed_array(&array, &ssid, &ssid_len);
1604
1605         if (ssid_len < 1)
1606                 return;
1607
1608         if (ssid[0] == '\0')
1609                 return;
1610
1611         result->ssid = g_try_malloc(ssid_len);
1612         if (result->ssid == NULL)
1613                 return;
1614
1615         memcpy(result->ssid, ssid, ssid_len);
1616         result->ssid_len = ssid_len;
1617
1618         result->name = g_try_malloc0(ssid_len + 1);
1619         if (result->name == NULL)
1620                 return;
1621
1622         for (i = 0; i < ssid_len; i++) {
1623                 if (g_ascii_isprint(ssid[i]))
1624                         result->name[i] = ssid[i];
1625                 else
1626                         result->name[i] = ' ';
1627         }
1628 }
1629
1630 static unsigned char wifi_oui[3]      = { 0x00, 0x50, 0xf2 };
1631 static unsigned char ieee80211_oui[3] = { 0x00, 0x0f, 0xac };
1632
1633 static void extract_rsn(struct supplicant_result *result,
1634                                         const unsigned char *buf, int len)
1635 {
1636         uint16_t count;
1637         int i;
1638
1639         /* Version */
1640         if (len < 2)
1641                 return;
1642
1643         buf += 2;
1644         len -= 2;
1645
1646         /* Group cipher */
1647         if (len < 4)
1648                 return;
1649
1650         buf += 4;
1651         len -= 4;
1652
1653         /* Pairwise cipher */
1654         if (len < 2)
1655                 return;
1656
1657         count = buf[0] | (buf[1] << 8);
1658         if (2 + (count * 4) > len)
1659                 return;
1660
1661         buf += 2 + (count * 4);
1662         len -= 2 + (count * 4);
1663
1664         /* Authentication */
1665         if (len < 2)
1666                 return;
1667
1668         count = buf[0] | (buf[1] << 8);
1669         if (2 + (count * 4) > len)
1670                 return;
1671
1672         for (i = 0; i < count; i++) {
1673                 const unsigned char *ptr = buf + 2 + (i * 4);
1674
1675                 if (memcmp(ptr, wifi_oui, 3) == 0) {
1676                         switch (ptr[3]) {
1677                         case 1:
1678                                 result->has_8021x = TRUE;
1679                                 break;
1680                         case 2:
1681                                 result->has_psk = TRUE;
1682                                 break;
1683                         }
1684                 } else if (memcmp(ptr, ieee80211_oui, 3) == 0) {
1685                         switch (ptr[3]) {
1686                         case 1:
1687                                 result->has_8021x = TRUE;
1688                                 break;
1689                         case 2:
1690                                 result->has_psk = TRUE;
1691                                 break;
1692                         }
1693                 }
1694         }
1695
1696         buf += 2 + (count * 4);
1697         len -= 2 + (count * 4);
1698 }
1699
1700 static void extract_wpaie(DBusMessageIter *value,
1701                                         struct supplicant_result *result)
1702 {
1703         DBusMessageIter array;
1704         unsigned char *ie;
1705         int ie_len;
1706
1707         dbus_message_iter_recurse(value, &array);
1708         dbus_message_iter_get_fixed_array(&array, &ie, &ie_len);
1709
1710         if (ie_len > 6) {
1711                 result->has_wpa = TRUE;
1712                 extract_rsn(result, ie + 6, ie_len - 6);
1713         }
1714 }
1715
1716 static void extract_rsnie(DBusMessageIter *value,
1717                                         struct supplicant_result *result)
1718 {
1719         DBusMessageIter array;
1720         unsigned char *ie;
1721         int ie_len;
1722
1723         dbus_message_iter_recurse(value, &array);
1724         dbus_message_iter_get_fixed_array(&array, &ie, &ie_len);
1725
1726         if (ie_len > 2) {
1727                 result->has_rsn = TRUE;
1728                 extract_rsn(result, ie + 2, ie_len - 2);
1729         }
1730 }
1731
1732 static void extract_wpsie(DBusMessageIter *value,
1733                                         struct supplicant_result *result)
1734 {
1735         DBusMessageIter array;
1736         unsigned char *ie;
1737         int ie_len;
1738
1739         dbus_message_iter_recurse(value, &array);
1740         dbus_message_iter_get_fixed_array(&array, &ie, &ie_len);
1741
1742         if (ie_len > 0)
1743                 result->has_wps = TRUE;
1744 }
1745
1746 static void extract_capabilites(DBusMessageIter *value,
1747                                         struct supplicant_result *result)
1748 {
1749         dbus_message_iter_get_basic(value, &result->capabilities);
1750
1751         if (result->capabilities & IEEE80211_CAP_ESS)
1752                 result->adhoc = FALSE;
1753         else if (result->capabilities & IEEE80211_CAP_IBSS)
1754                 result->adhoc = TRUE;
1755
1756         if (result->capabilities & IEEE80211_CAP_PRIVACY)
1757                 result->has_wep = TRUE;
1758 }
1759
1760 static unsigned char calculate_strength(struct supplicant_task *task,
1761                                         struct supplicant_result *result)
1762 {
1763         if (result->quality == -1 || task->range->max_qual.qual == 0) {
1764                 unsigned char strength;
1765
1766                 if (result->level > 0)
1767                         strength = 100 - result->level;
1768                 else
1769                         strength = 120 + result->level;
1770
1771                 if (strength > 100)
1772                         strength = 100;
1773
1774                 return strength;
1775         }
1776
1777         return (result->quality * 100) / task->range->max_qual.qual;
1778 }
1779
1780 static unsigned short calculate_channel(struct supplicant_result *result)
1781 {
1782         if (result->frequency < 0)
1783                 return 0;
1784
1785         return (result->frequency - 2407) / 5;
1786 }
1787
1788 static void get_properties(struct supplicant_task *task);
1789
1790 static void properties_reply(DBusPendingCall *call, void *user_data)
1791 {
1792         struct supplicant_task *task = user_data;
1793         struct supplicant_result result;
1794         struct supplicant_block *block;
1795         struct connman_network *network;
1796         DBusMessage *reply;
1797         DBusMessageIter array, dict;
1798         unsigned char strength;
1799         unsigned short channel, frequency;
1800         const char *mode, *security;
1801         char *group = NULL;
1802
1803         DBG("task %p", task);
1804
1805         reply = dbus_pending_call_steal_reply(call);
1806
1807         if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR)
1808                 goto unref;
1809
1810         memset(&result, 0, sizeof(result));
1811         result.frequency = -1;
1812         result.quality = -1;
1813         result.level = 0;
1814         result.noise = 0;
1815
1816         dbus_message_iter_init(reply, &array);
1817
1818         dbus_message_iter_recurse(&array, &dict);
1819
1820         while (dbus_message_iter_get_arg_type(&dict) == DBUS_TYPE_DICT_ENTRY) {
1821                 DBusMessageIter entry, value;
1822                 const char *key;
1823
1824                 dbus_message_iter_recurse(&dict, &entry);
1825                 dbus_message_iter_get_basic(&entry, &key);
1826
1827                 dbus_message_iter_next(&entry);
1828
1829                 dbus_message_iter_recurse(&entry, &value);
1830
1831                 //type = dbus_message_iter_get_arg_type(&value);
1832                 //dbus_message_iter_get_basic(&value, &val);
1833
1834                 /* 
1835                  * bssid        : a (97)
1836                  * ssid         : a (97)
1837                  * wpaie        : a (97)
1838                  * rsnie        : a (97)
1839                  * wpsie        : a (97)
1840                  * frequency    : i (105)
1841                  * capabilities : q (113)
1842                  * quality      : i (105)
1843                  * noise        : i (105)
1844                  * level        : i (105)
1845                  * maxrate      : i (105)
1846                  */
1847
1848                 if (g_str_equal(key, "bssid") == TRUE)
1849                         extract_addr(&value, &result);
1850                 else if (g_str_equal(key, "ssid") == TRUE)
1851                         extract_ssid(&value, &result);
1852                 else if (g_str_equal(key, "wpaie") == TRUE)
1853                         extract_wpaie(&value, &result);
1854                 else if (g_str_equal(key, "rsnie") == TRUE)
1855                         extract_rsnie(&value, &result);
1856                 else if (g_str_equal(key, "wpsie") == TRUE)
1857                         extract_wpsie(&value, &result);
1858                 else if (g_str_equal(key, "capabilities") == TRUE)
1859                         extract_capabilites(&value, &result);
1860                 else if (g_str_equal(key, "frequency") == TRUE)
1861                         dbus_message_iter_get_basic(&value, &result.frequency);
1862                 else if (g_str_equal(key, "quality") == TRUE)
1863                         dbus_message_iter_get_basic(&value, &result.quality);
1864                 else if (g_str_equal(key, "noise") == TRUE)
1865                         dbus_message_iter_get_basic(&value, &result.noise);
1866                 else if (g_str_equal(key, "level") == TRUE)
1867                         dbus_message_iter_get_basic(&value, &result.level);
1868                 else if (g_str_equal(key, "maxrate") == TRUE)
1869                         dbus_message_iter_get_basic(&value, &result.maxrate);
1870
1871                 dbus_message_iter_next(&dict);
1872         }
1873
1874         DBG("capabilties %u frequency %d "
1875                         "quality %d noise %d level %d maxrate %d",
1876                                         result.capabilities, result.frequency,
1877                                                 result.quality, result.noise,
1878                                                 result.level, result.maxrate);
1879
1880         if (result.path == NULL)
1881                 goto done;
1882
1883         if (result.path[0] == '\0')
1884                 goto done;
1885
1886         if (result.name) {
1887                 block = g_hash_table_lookup(task->hidden_blocks, result.name);
1888                 if (block) {
1889                         enable_network(task, block->netpath, FALSE);
1890                         g_hash_table_remove(task->hidden_blocks, block->ssid);
1891                 }
1892         }
1893
1894         if (result.ssid == NULL)
1895                 task->hidden_found = TRUE;
1896
1897         if (result.frequency > 0 && result.frequency < 14)
1898                 result.frequency = 2407 + (5 * result.frequency);
1899         else if (result.frequency == 14)
1900                 result.frequency = 2484;
1901
1902         strength = calculate_strength(task, &result);
1903         channel  = calculate_channel(&result);
1904
1905         frequency = (result.frequency < 0) ? 0 : result.frequency;
1906
1907         if (result.has_8021x == TRUE)
1908                 security = "ieee8021x";
1909         else if (result.has_psk == TRUE)
1910                 security = "psk";
1911         else if (result.has_wep == TRUE)
1912                 security = "wep";
1913         else
1914                 security = "none";
1915
1916         mode = (result.adhoc == TRUE) ? "adhoc" : "managed";
1917
1918         group = build_group(result.path, result.name,
1919                                         result.ssid, result.ssid_len,
1920                                                         mode, security);
1921
1922         if (result.has_psk == TRUE) {
1923                 if (result.has_rsn == TRUE)
1924                         security = "rsn";
1925                 else if (result.has_wpa == TRUE)
1926                         security = "wpa";
1927         }
1928
1929         network = connman_device_get_network(task->device, result.path);
1930         if (network == NULL) {
1931                 int index;
1932
1933                 network = connman_network_create(result.path,
1934                                                 CONNMAN_NETWORK_TYPE_WIFI);
1935                 if (network == NULL)
1936                         goto done;
1937
1938                 index = connman_device_get_index(task->device);
1939                 connman_network_set_index(network, index);
1940
1941                 connman_network_set_address(network, result.addr,
1942                                                         result.addr_len);
1943
1944                 if (connman_device_add_network(task->device, network) < 0) {
1945                         connman_network_unref(network);
1946                         goto done;
1947                 }
1948         }
1949
1950         if (result.name != NULL && result.name[0] != '\0')
1951                 connman_network_set_name(network, result.name);
1952
1953         if (result.ssid_len != 0)
1954                 connman_network_set_blob(network, "WiFi.SSID",
1955                                                 result.ssid, result.ssid_len);
1956
1957         connman_network_set_string(network, "WiFi.Mode", mode);
1958
1959         DBG("%s (%s %s) strength %d (%s)",
1960                                 result.name, mode, security, strength,
1961                                 (result.has_wps == TRUE) ? "WPS" : "no WPS");
1962
1963         connman_network_set_available(network, TRUE);
1964         connman_network_set_strength(network, strength);
1965
1966         connman_network_set_uint16(network, "Frequency", frequency);
1967         connman_network_set_uint16(network, "WiFi.Channel", channel);
1968         connman_network_set_string(network, "WiFi.Security", security);
1969
1970         if (result.ssid != NULL)
1971                 connman_network_set_group(network, group);
1972
1973 done:
1974         g_free(group);
1975
1976         g_free(result.path);
1977         g_free(result.addr);
1978         g_free(result.name);
1979         g_free(result.ssid);
1980
1981 unref:
1982         dbus_message_unref(reply);
1983
1984         dbus_pending_call_unref(call);
1985
1986         get_properties(task);
1987 }
1988
1989 static void get_properties(struct supplicant_task *task)
1990 {
1991         DBusMessage *message;
1992         char *path;
1993
1994         path = g_slist_nth_data(task->scan_results, 0);
1995         if (path == NULL) {
1996                 if (task->hidden_found == TRUE) {
1997                         /*
1998                          * We're done with regular scanning, let's enable
1999                          * the missing network blocks if there are hidden
2000                          * SSIDs around.
2001                          */
2002                         hidden_block_enable(task);
2003                 }
2004                 goto noscan;
2005         }
2006
2007         message = dbus_message_new_method_call(SUPPLICANT_NAME, path,
2008                                                 SUPPLICANT_INTF ".BSSID",
2009                                                                 "properties");
2010
2011         task->scan_results = g_slist_remove(task->scan_results, path);
2012         g_free(path);
2013
2014         if (message == NULL)
2015                 goto noscan;
2016
2017         dbus_message_set_auto_start(message, FALSE);
2018
2019         if (dbus_connection_send_with_reply(connection, message,
2020                                 &task->result_call, TIMEOUT) == FALSE) {
2021                 connman_error("Failed to get network properties");
2022                 dbus_message_unref(message);
2023                 goto noscan;
2024         }
2025
2026         if (task->result_call == NULL) {
2027                 connman_error("D-Bus connection not available");
2028                 dbus_message_unref(message);
2029                 goto noscan;
2030         }
2031
2032         dbus_pending_call_set_notify(task->result_call,
2033                                         properties_reply, task, NULL);
2034
2035         dbus_message_unref(message);
2036
2037         return;
2038
2039 noscan:
2040         task->result_call = NULL;
2041
2042         if (task->scanning == TRUE) {
2043                 connman_device_set_scanning(task->device, FALSE);
2044                 task->scanning = FALSE;
2045         }
2046 }
2047
2048 static void scan_results_reply(DBusPendingCall *call, void *user_data)
2049 {
2050         struct supplicant_task *task = user_data;
2051         DBusMessage *reply;
2052         DBusError error;
2053         char **results;
2054         int i, num_results;
2055
2056         DBG("task %p", task);
2057
2058         reply = dbus_pending_call_steal_reply(call);
2059
2060         if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR)
2061                 goto done;
2062
2063         dbus_error_init(&error);
2064
2065         if (dbus_message_get_args(reply, &error,
2066                                 DBUS_TYPE_ARRAY, DBUS_TYPE_OBJECT_PATH,
2067                                                 &results, &num_results,
2068                                                 DBUS_TYPE_INVALID) == FALSE) {
2069                 if (dbus_error_is_set(&error) == TRUE) {
2070                         connman_error("%s", error.message);
2071                         dbus_error_free(&error);
2072                 } else
2073                         connman_error("Wrong arguments for scan result");
2074                 goto done;
2075         }
2076
2077         if (num_results == 0)
2078                 goto done;
2079
2080         for (i = 0; i < num_results; i++) {
2081                 char *path = g_strdup(results[i]);
2082                 if (path == NULL)
2083                         continue;
2084
2085                 task->scan_results = g_slist_append(task->scan_results, path);
2086         }
2087
2088         task->hidden_found = FALSE;
2089
2090         g_strfreev(results);
2091
2092         dbus_message_unref(reply);
2093
2094         dbus_pending_call_unref(call);
2095
2096         get_properties(task);
2097
2098         return;
2099
2100 done:
2101         dbus_message_unref(reply);
2102
2103         dbus_pending_call_unref(call);
2104
2105         task->result_call = NULL;
2106
2107         if (task->scanning == TRUE) {
2108                 connman_device_set_scanning(task->device, FALSE);
2109                 task->scanning = FALSE;
2110         }
2111 }
2112
2113 static void scan_results_available(struct supplicant_task *task)
2114 {
2115         DBusMessage *message;
2116
2117         DBG("task %p", task);
2118
2119         if (task->result_call != NULL)
2120                 return;
2121
2122         message = dbus_message_new_method_call(SUPPLICANT_NAME, task->path,
2123                                                 SUPPLICANT_INTF ".Interface",
2124                                                         "scanResults");
2125         if (message == NULL)
2126                 return;
2127
2128         dbus_message_set_auto_start(message, FALSE);
2129
2130         if (dbus_connection_send_with_reply(connection, message,
2131                                 &task->result_call, TIMEOUT) == FALSE) {
2132                 connman_error("Failed to request scan result");
2133                 goto done;
2134         }
2135
2136         if (task->result_call == NULL) {
2137                 connman_error("D-Bus connection not available");
2138                 goto done;
2139         }
2140
2141         if (task->scanning == TRUE)
2142                 connman_device_set_scanning(task->device, TRUE);
2143
2144         dbus_pending_call_set_notify(task->result_call,
2145                                         scan_results_reply, task, NULL);
2146
2147 done:
2148         dbus_message_unref(message);
2149 }
2150
2151 static enum supplicant_state string2state(const char *state)
2152 {
2153         if (g_str_equal(state, "INACTIVE") == TRUE)
2154                 return WPA_INACTIVE;
2155         else if (g_str_equal(state, "SCANNING") == TRUE)
2156                 return WPA_SCANNING;
2157         else if (g_str_equal(state, "ASSOCIATING") == TRUE)
2158                 return WPA_ASSOCIATING;
2159         else if (g_str_equal(state, "ASSOCIATED") == TRUE)
2160                 return WPA_ASSOCIATED;
2161         else if (g_str_equal(state, "GROUP_HANDSHAKE") == TRUE)
2162                 return WPA_GROUP_HANDSHAKE;
2163         else if (g_str_equal(state, "4WAY_HANDSHAKE") == TRUE)
2164                 return WPA_4WAY_HANDSHAKE;
2165         else if (g_str_equal(state, "COMPLETED") == TRUE)
2166                 return WPA_COMPLETED;
2167         else if (g_str_equal(state, "DISCONNECTED") == TRUE)
2168                 return WPA_DISCONNECTED;
2169         else
2170                 return WPA_INVALID;
2171 }
2172
2173 static int task_connect(struct supplicant_task *task)
2174 {
2175         const char *address, *security, *passphrase;
2176         const void *ssid;
2177         unsigned int ssid_len;
2178         int err;
2179
2180         g_hash_table_foreach(task->hidden_blocks, block_reset, task);
2181
2182         connman_inet_ifup(task->ifindex);
2183
2184         address = connman_network_get_string(task->network, "Address");
2185         security = connman_network_get_string(task->network, "WiFi.Security");
2186         passphrase = connman_network_get_string(task->network, "WiFi.Passphrase");
2187
2188         ssid = connman_network_get_blob(task->network, "WiFi.SSID", &ssid_len);
2189
2190         DBG("address %s security %s", address, security);
2191
2192         if (security == NULL)
2193                 return -EINVAL;
2194
2195         if (passphrase == NULL && g_str_equal(security, "none") == FALSE &&
2196                                 g_str_equal(security, "ieee8021x") == FALSE)
2197                 return -EINVAL;
2198
2199         remove_network(task);
2200
2201         set_ap_scan(task);
2202
2203         add_network(task);
2204
2205         err = set_network(task, ssid, ssid_len, address, security, passphrase);
2206         if (err < 0)
2207                 return err;
2208
2209         err = select_network(task);
2210         if (err < 0)
2211                 return err;
2212
2213         return -EINPROGRESS;
2214 }
2215
2216 static void scanning(struct supplicant_task *task, DBusMessage *msg)
2217 {
2218         DBusError error;
2219         dbus_bool_t scanning;
2220
2221         dbus_error_init(&error);
2222
2223         if (dbus_message_get_args(msg, &error, DBUS_TYPE_BOOLEAN, &scanning,
2224                                                 DBUS_TYPE_INVALID) == FALSE) {
2225                 if (dbus_error_is_set(&error) == TRUE) {
2226                         connman_error("%s", error.message);
2227                         dbus_error_free(&error);
2228                 } else
2229                         connman_error("Wrong arguments for scanning");
2230                 return;
2231         }
2232
2233         connman_info("%s scanning %s", task->ifname,
2234                                 scanning == TRUE ? "started" : "finished");
2235
2236         if (scanning == TRUE)
2237                 task->scanning = TRUE;
2238 }
2239
2240 static void state_change(struct supplicant_task *task, DBusMessage *msg)
2241 {
2242         DBusError error;
2243         const char *newstate, *oldstate;
2244         unsigned char bssid[ETH_ALEN];
2245         unsigned int bssid_len;
2246         enum supplicant_state state, prevstate;
2247
2248         dbus_error_init(&error);
2249
2250         if (dbus_message_get_args(msg, &error, DBUS_TYPE_STRING, &newstate,
2251                                                 DBUS_TYPE_STRING, &oldstate,
2252                                                 DBUS_TYPE_INVALID) == FALSE) {
2253                 if (dbus_error_is_set(&error) == TRUE) {
2254                         connman_error("%s", error.message);
2255                         dbus_error_free(&error);
2256                 } else
2257                         connman_error("Wrong arguments for state change");
2258                 return;
2259         }
2260
2261         DBG("state %s ==> %s", oldstate, newstate);
2262
2263         connman_info("%s %s%s", task->ifname, newstate,
2264                                 task->scanning == TRUE ? " (scanning)" : "");
2265
2266         state = string2state(newstate);
2267         if (state == WPA_INVALID)
2268                 return;
2269
2270         prevstate = task->state;
2271         task->state = state;
2272
2273         if (task->network == NULL)
2274                 return;
2275
2276         switch (task->state) {
2277         case WPA_COMPLETED:
2278                 switch (prevstate) {
2279                 case WPA_ASSOCIATED:
2280                 case WPA_GROUP_HANDSHAKE:
2281                         break;
2282                 default:
2283                         goto badstate;
2284                 }
2285
2286                 /* reset scan trigger and schedule background scan */
2287                 connman_device_schedule_scan(task->device);
2288
2289                 if (get_bssid(task->device, bssid, &bssid_len) == 0)
2290                         connman_network_set_address(task->network,
2291                                                         bssid, bssid_len);
2292
2293                 /* carrier on */
2294                 connman_network_set_connected(task->network, TRUE);
2295                 break;
2296
2297         case WPA_ASSOCIATING:
2298                 switch (prevstate) {
2299                 case WPA_COMPLETED:
2300                         break;
2301                 case WPA_SCANNING:
2302                         connman_network_set_associating(task->network, TRUE);
2303                         break;
2304                 default:
2305                         goto badstate;
2306                 }
2307                 break;
2308
2309         case WPA_INACTIVE:
2310                 switch (prevstate) {
2311                 case WPA_SCANNING:
2312                 case WPA_DISCONNECTED:
2313                         break;
2314                 default:
2315                         goto badstate;
2316                 }
2317                 /* fall through */
2318
2319         case WPA_DISCONNECTED:
2320                 /* carrier off */
2321                 connman_network_set_connected(task->network, FALSE);
2322
2323                 if (task->disconnecting == TRUE) {
2324                         connman_network_unref(task->network);
2325                         task->disconnecting = FALSE;
2326
2327                         if (task->pending_network != NULL) {
2328                                 task->network = task->pending_network;
2329                                 task->pending_network = NULL;
2330                                 task_connect(task);
2331                         } else
2332                                 task->network = NULL;
2333                 }
2334                 break;
2335
2336         default:
2337                 connman_network_set_associating(task->network, FALSE);
2338                 break;
2339         }
2340
2341         return;
2342
2343 badstate:
2344         connman_error("%s invalid state change %s -> %s", task->ifname,
2345                                                         oldstate, newstate);
2346 }
2347
2348 static gboolean supplicant_filter(DBusConnection *conn,
2349                                                 DBusMessage *msg, void *data)
2350 {
2351         struct supplicant_task *task;
2352         const char *member, *path;
2353
2354         member = dbus_message_get_member(msg);
2355         if (member == NULL)
2356                 return TRUE;
2357
2358         path = dbus_message_get_path(msg);
2359         if (path == NULL)
2360                 return TRUE;
2361
2362         task = find_task_by_path(path);
2363         if (task == NULL)
2364                 return TRUE;
2365
2366         DBG("task %p member %s", task, member);
2367
2368         if (g_str_equal(member, "ScanResultsAvailable") == TRUE)
2369                 scan_results_available(task);
2370         else if (g_str_equal(member, "Scanning") == TRUE)
2371                 scanning(task, msg);
2372         else if (g_str_equal(member, "StateChange") == TRUE)
2373                 state_change(task, msg);
2374
2375         return TRUE;
2376 }
2377
2378 int supplicant_start(struct connman_device *device)
2379 {
2380         struct supplicant_task *task;
2381         int err;
2382
2383         DBG("device %p", device);
2384
2385         task = g_try_new0(struct supplicant_task, 1);
2386         if (task == NULL)
2387                 return -ENOMEM;
2388
2389         task->ifindex = connman_device_get_index(device);
2390         task->ifname = connman_inet_ifname(task->ifindex);
2391
2392         if (task->ifname == NULL) {
2393                 err = -ENOMEM;
2394                 goto failed;
2395         }
2396
2397         task->cfg80211 = connman_inet_is_cfg80211(task->ifindex);
2398         if (task->cfg80211 == FALSE)
2399                 connman_warn("Enabling quirks for unsupported driver");
2400
2401         task->range = g_try_malloc0(sizeof(struct iw_range));
2402         if (task->range == NULL) {
2403                 err = -ENOMEM;
2404                 goto failed;
2405         }
2406
2407         err = get_range(task);
2408         if (err < 0)
2409                 goto failed;
2410
2411         task->device = connman_device_ref(device);
2412
2413         task->created = FALSE;
2414         task->scanning = FALSE;
2415         task->state = WPA_INVALID;
2416         task->disconnecting = FALSE;
2417         task->pending_network = NULL;
2418         task->hidden_blocks = g_hash_table_new_full(g_str_hash, g_str_equal,
2419                                                         NULL, remove_block);
2420         task_list = g_slist_append(task_list, task);
2421
2422         return create_interface(task);
2423
2424 failed:
2425         g_free(task->range);
2426         g_free(task->ifname);
2427         g_free(task);
2428
2429         return err;
2430 }
2431
2432 int supplicant_stop(struct connman_device *device)
2433 {
2434         int index = connman_device_get_index(device);
2435         struct supplicant_task *task;
2436
2437         DBG("device %p", device);
2438
2439         task = find_task_by_index(index);
2440         if (task == NULL)
2441                 return -ENODEV;
2442
2443         g_free(task->range);
2444
2445         task_list = g_slist_remove(task_list, task);
2446         g_hash_table_destroy(task->hidden_blocks);
2447
2448         if (task->scan_call != NULL) {
2449                 dbus_pending_call_cancel(task->scan_call);
2450                 task->scan_call = NULL;
2451         }
2452
2453         if (task->result_call != NULL) {
2454                 dbus_pending_call_cancel(task->result_call);
2455                 task->result_call = NULL;
2456         }
2457
2458         if (task->scanning == TRUE)
2459                 connman_device_set_scanning(task->device, FALSE);
2460
2461         remove_network(task);
2462
2463         disconnect_network(task);
2464
2465         return remove_interface(task);
2466 }
2467
2468 int supplicant_scan(struct connman_device *device)
2469 {
2470         int index = connman_device_get_index(device);
2471         struct supplicant_task *task;
2472         int err;
2473
2474         DBG("device %p", device);
2475
2476         task = find_task_by_index(index);
2477         if (task == NULL)
2478                 return -ENODEV;
2479
2480         switch (task->state) {
2481         case WPA_SCANNING:
2482                 return -EALREADY;
2483         case WPA_ASSOCIATING:
2484         case WPA_ASSOCIATED:
2485         case WPA_4WAY_HANDSHAKE:
2486         case WPA_GROUP_HANDSHAKE:
2487                 return -EBUSY;
2488         default:
2489                 break;
2490         }
2491
2492         task->scanning = TRUE;
2493
2494         err = initiate_scan(task);
2495         if (err < 0) {
2496                 if (err == -EINPROGRESS)
2497                         return 0;
2498
2499                 task->scanning = FALSE;
2500                 return err;
2501         }
2502
2503         connman_device_set_scanning(task->device, TRUE);
2504
2505         return 0;
2506 }
2507
2508 int supplicant_connect(struct connman_network *network)
2509 {
2510         struct supplicant_task *task;
2511         int index;
2512
2513         DBG("network %p", network);
2514
2515         index = connman_network_get_index(network);
2516
2517         task = find_task_by_index(index);
2518         if (task == NULL)
2519                 return -ENODEV;
2520
2521         if (task->disconnecting == TRUE)
2522                 task->pending_network = connman_network_ref(network);
2523         else {
2524                 task->network = connman_network_ref(network);
2525                 return task_connect(task);
2526         }
2527
2528         return -EINPROGRESS;
2529 }
2530
2531 int supplicant_disconnect(struct connman_network *network)
2532 {
2533         struct supplicant_task *task;
2534         int index;
2535
2536         DBG("network %p", network);
2537
2538         index = connman_network_get_index(network);
2539
2540         task = find_task_by_index(index);
2541         if (task == NULL)
2542                 return -ENODEV;
2543
2544         if (task->disconnecting == TRUE)
2545                 return -EALREADY;
2546
2547         if (task->network != network)
2548                 return -EINVAL;
2549
2550         remove_network(task);
2551
2552         disconnect_network(task);
2553
2554         task->disconnecting = TRUE;
2555
2556         return 0;
2557 }
2558
2559 void supplicant_remove_network(struct connman_network *network)
2560 {
2561         struct supplicant_task *task;
2562         int index;
2563
2564         DBG("network %p", network);
2565
2566         index = connman_network_get_index(network);
2567
2568         task = find_task_by_index(index);
2569         if (task == NULL)
2570                 return;
2571
2572         if (task->network != network)
2573                 return;
2574
2575         remove_network(task);
2576 }
2577
2578 static void supplicant_activate(DBusConnection *conn)
2579 {
2580         DBusMessage *message;
2581
2582         DBG("conn %p", conn);
2583
2584         message = dbus_message_new_method_call(SUPPLICANT_NAME, "/",
2585                                 DBUS_INTERFACE_INTROSPECTABLE, "Introspect");
2586         if (message == NULL)
2587                 return;
2588
2589         dbus_message_set_no_reply(message, TRUE);
2590
2591         dbus_connection_send(conn, message, NULL);
2592
2593         dbus_message_unref(message);
2594 }
2595
2596 static GSList *driver_list = NULL;
2597
2598 static void supplicant_probe(DBusConnection *conn, void *user_data)
2599 {
2600         GSList *list;
2601
2602         DBG("conn %p", conn);
2603
2604         for (list = driver_list; list; list = list->next) {
2605                 struct supplicant_driver *driver = list->data;
2606
2607                 DBG("driver %p name %s", driver, driver->name);
2608
2609                 if (driver->probe)
2610                         driver->probe();
2611         }
2612 }
2613
2614 static void supplicant_remove(DBusConnection *conn, void *user_data)
2615 {
2616         GSList *list;
2617
2618         DBG("conn %p", conn);
2619
2620         for (list = driver_list; list; list = list->next) {
2621                 struct supplicant_driver *driver = list->data;
2622
2623                 DBG("driver %p name %s", driver, driver->name);
2624
2625                 if (driver->remove)
2626                         driver->remove();
2627         }
2628 }
2629
2630 static guint watch;
2631 static guint iface_watch;
2632
2633 static int supplicant_create(void)
2634 {
2635         if (g_slist_length(driver_list) > 0)
2636                 return 0;
2637
2638         connection = connman_dbus_get_connection();
2639         if (connection == NULL)
2640                 return -EIO;
2641
2642         DBG("connection %p", connection);
2643
2644         watch = g_dbus_add_service_watch(connection, SUPPLICANT_NAME,
2645                         supplicant_probe, supplicant_remove, NULL, NULL);
2646
2647         iface_watch = g_dbus_add_signal_watch(connection, NULL, NULL,
2648                                                 SUPPLICANT_INTF ".Interface",
2649                                                 NULL, supplicant_filter,
2650                                                 NULL, NULL);
2651
2652         if (watch == 0 || iface_watch == 0) {
2653                 g_dbus_remove_watch(connection, watch);
2654                 g_dbus_remove_watch(connection, iface_watch);
2655                 return -EIO;
2656         }
2657
2658         return 0;
2659 }
2660
2661 static void supplicant_destroy(void)
2662 {
2663         if (g_slist_length(driver_list) > 0)
2664                 return;
2665
2666         DBG("connection %p", connection);
2667
2668         g_dbus_remove_watch(connection, watch);
2669         g_dbus_remove_watch(connection, iface_watch);
2670
2671         dbus_connection_unref(connection);
2672         connection = NULL;
2673 }
2674
2675 int supplicant_register(struct supplicant_driver *driver)
2676 {
2677         int err;
2678
2679         DBG("driver %p name %s", driver, driver->name);
2680
2681         err = supplicant_create();
2682         if (err < 0)
2683                 return err;
2684
2685         driver_list = g_slist_append(driver_list, driver);
2686
2687         supplicant_activate(connection);
2688
2689         return 0;
2690 }
2691
2692 void supplicant_unregister(struct supplicant_driver *driver)
2693 {
2694         DBG("driver %p name %s", driver, driver->name);
2695
2696         supplicant_remove(connection, NULL);
2697
2698         driver_list = g_slist_remove(driver_list, driver);
2699
2700         supplicant_destroy();
2701 }