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