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