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