OSDN Git Service

Merge "Fixes for concurrency support"
[android-x86/hardware-libhardware_legacy.git] / wifi / wifi.c
1 /*
2  * Copyright 2008, The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <stdlib.h>
18 #include <fcntl.h>
19 #include <errno.h>
20 #include <string.h>
21 #include <dirent.h>
22 #include <sys/socket.h>
23 #include <poll.h>
24
25 #include "hardware_legacy/wifi.h"
26 #include "libwpa_client/wpa_ctrl.h"
27
28 #define LOG_TAG "WifiHW"
29 #include "cutils/log.h"
30 #include "cutils/memory.h"
31 #include "cutils/misc.h"
32 #include "cutils/properties.h"
33 #include "private/android_filesystem_config.h"
34 #ifdef HAVE_LIBC_SYSTEM_PROPERTIES
35 #define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_
36 #include <sys/_system_properties.h>
37 #endif
38
39 /* PRIMARY refers to the connection on the primary interface
40  * SECONDARY refers to an optional connection on a p2p interface
41  *
42  * For concurrency, we only support one active p2p connection and
43  * one active STA connection at a time
44  */
45 #define PRIMARY     0
46 #define SECONDARY   1
47 #define MAX_CONNS   2
48
49 static struct wpa_ctrl *ctrl_conn[MAX_CONNS];
50 static struct wpa_ctrl *monitor_conn[MAX_CONNS];
51
52 /* socket pair used to exit from a blocking read */
53 static int exit_sockets[MAX_CONNS][2];
54
55 extern int do_dhcp();
56 extern int ifc_init();
57 extern void ifc_close();
58 extern char *dhcp_lasterror();
59 extern void get_dhcp_info();
60 extern int init_module(void *, unsigned long, const char *);
61 extern int delete_module(const char *, unsigned int);
62
63 static char primary_iface[PROPERTY_VALUE_MAX];
64 // TODO: use new ANDROID_SOCKET mechanism, once support for multiple
65 // sockets is in
66
67 #ifndef WIFI_DRIVER_MODULE_ARG
68 #define WIFI_DRIVER_MODULE_ARG          ""
69 #endif
70 #ifndef WIFI_FIRMWARE_LOADER
71 #define WIFI_FIRMWARE_LOADER            ""
72 #endif
73 #define WIFI_TEST_INTERFACE             "sta"
74
75 #ifndef WIFI_DRIVER_FW_PATH_STA
76 #define WIFI_DRIVER_FW_PATH_STA         NULL
77 #endif
78 #ifndef WIFI_DRIVER_FW_PATH_AP
79 #define WIFI_DRIVER_FW_PATH_AP          NULL
80 #endif
81 #ifndef WIFI_DRIVER_FW_PATH_P2P
82 #define WIFI_DRIVER_FW_PATH_P2P         NULL
83 #endif
84
85 #ifndef WIFI_DRIVER_FW_PATH_PARAM
86 #define WIFI_DRIVER_FW_PATH_PARAM       "/sys/module/wlan/parameters/fwpath"
87 #endif
88
89 #define WIFI_DRIVER_LOADER_DELAY        1000000
90
91 static const char IFACE_DIR[]           = "/data/system/wpa_supplicant";
92 #ifdef WIFI_DRIVER_MODULE_PATH
93 static const char DRIVER_MODULE_NAME[]  = WIFI_DRIVER_MODULE_NAME;
94 static const char DRIVER_MODULE_TAG[]   = WIFI_DRIVER_MODULE_NAME " ";
95 static const char DRIVER_MODULE_PATH[]  = WIFI_DRIVER_MODULE_PATH;
96 static const char DRIVER_MODULE_ARG[]   = WIFI_DRIVER_MODULE_ARG;
97 #endif
98 static const char FIRMWARE_LOADER[]     = WIFI_FIRMWARE_LOADER;
99 static const char DRIVER_PROP_NAME[]    = "wlan.driver.status";
100 static const char SUPPLICANT_NAME[]     = "wpa_supplicant";
101 static const char SUPP_PROP_NAME[]      = "init.svc.wpa_supplicant";
102 static const char P2P_SUPPLICANT_NAME[] = "p2p_supplicant";
103 static const char P2P_PROP_NAME[]       = "init.svc.p2p_supplicant";
104 static const char SUPP_CONFIG_TEMPLATE[]= "/system/etc/wifi/wpa_supplicant.conf";
105 static const char SUPP_CONFIG_FILE[]    = "/data/misc/wifi/wpa_supplicant.conf";
106 static const char P2P_CONFIG_FILE[]     = "/data/misc/wifi/p2p_supplicant.conf";
107 static const char CONTROL_IFACE_PATH[]  = "/data/misc/wifi/sockets";
108 static const char MODULE_FILE[]         = "/proc/modules";
109
110 static const char SUPP_ENTROPY_FILE[]   = WIFI_ENTROPY_FILE;
111 static unsigned char dummy_key[21] = { 0x02, 0x11, 0xbe, 0x33, 0x43, 0x35,
112                                        0x68, 0x47, 0x84, 0x99, 0xa9, 0x2b,
113                                        0x1c, 0xd3, 0xee, 0xff, 0xf1, 0xe2,
114                                        0xf3, 0xf4, 0xf5 };
115
116 /* Is either SUPPLICANT_NAME or P2P_SUPPLICANT_NAME */
117 static char supplicant_name[PROPERTY_VALUE_MAX];
118 /* Is either SUPP_PROP_NAME or P2P_PROP_NAME */
119 static char supplicant_prop_name[PROPERTY_KEY_MAX];
120
121 static int is_primary_interface(const char *ifname)
122 {
123     //Treat NULL as primary interface to allow control
124     //on STA without an interface
125     if (ifname == NULL || !strncmp(ifname, primary_iface, strlen(primary_iface))) {
126         return 1;
127     }
128     return 0;
129 }
130
131 static int insmod(const char *filename, const char *args)
132 {
133     void *module;
134     unsigned int size;
135     int ret;
136
137     module = load_file(filename, &size);
138     if (!module)
139         return -1;
140
141     ret = init_module(module, size, args);
142
143     free(module);
144
145     return ret;
146 }
147
148 static int rmmod(const char *modname)
149 {
150     int ret = -1;
151     int maxtry = 10;
152
153     while (maxtry-- > 0) {
154         ret = delete_module(modname, O_NONBLOCK | O_EXCL);
155         if (ret < 0 && errno == EAGAIN)
156             usleep(500000);
157         else
158             break;
159     }
160
161     if (ret != 0)
162         ALOGD("Unable to unload driver module \"%s\": %s\n",
163              modname, strerror(errno));
164     return ret;
165 }
166
167 int do_dhcp_request(int *ipaddr, int *gateway, int *mask,
168                     int *dns1, int *dns2, int *server, int *lease) {
169     /* For test driver, always report success */
170     if (strcmp(primary_iface, WIFI_TEST_INTERFACE) == 0)
171         return 0;
172
173     if (ifc_init() < 0)
174         return -1;
175
176     if (do_dhcp(primary_iface) < 0) {
177         ifc_close();
178         return -1;
179     }
180     ifc_close();
181     get_dhcp_info(ipaddr, gateway, mask, dns1, dns2, server, lease);
182     return 0;
183 }
184
185 const char *get_dhcp_error_string() {
186     return dhcp_lasterror();
187 }
188
189 int is_wifi_driver_loaded() {
190     char driver_status[PROPERTY_VALUE_MAX];
191 #ifdef WIFI_DRIVER_MODULE_PATH
192     FILE *proc;
193     char line[sizeof(DRIVER_MODULE_TAG)+10];
194 #endif
195
196     if (!property_get(DRIVER_PROP_NAME, driver_status, NULL)
197             || strcmp(driver_status, "ok") != 0) {
198         return 0;  /* driver not loaded */
199     }
200 #ifdef WIFI_DRIVER_MODULE_PATH
201     /*
202      * If the property says the driver is loaded, check to
203      * make sure that the property setting isn't just left
204      * over from a previous manual shutdown or a runtime
205      * crash.
206      */
207     if ((proc = fopen(MODULE_FILE, "r")) == NULL) {
208         ALOGW("Could not open %s: %s", MODULE_FILE, strerror(errno));
209         property_set(DRIVER_PROP_NAME, "unloaded");
210         return 0;
211     }
212     while ((fgets(line, sizeof(line), proc)) != NULL) {
213         if (strncmp(line, DRIVER_MODULE_TAG, strlen(DRIVER_MODULE_TAG)) == 0) {
214             fclose(proc);
215             return 1;
216         }
217     }
218     fclose(proc);
219     property_set(DRIVER_PROP_NAME, "unloaded");
220     return 0;
221 #else
222     return 1;
223 #endif
224 }
225
226 int wifi_load_driver()
227 {
228 #ifdef WIFI_DRIVER_MODULE_PATH
229     char driver_status[PROPERTY_VALUE_MAX];
230     int count = 100; /* wait at most 20 seconds for completion */
231
232     if (is_wifi_driver_loaded()) {
233         return 0;
234     }
235
236     if (insmod(DRIVER_MODULE_PATH, DRIVER_MODULE_ARG) < 0)
237         return -1;
238
239     if (strcmp(FIRMWARE_LOADER,"") == 0) {
240         /* usleep(WIFI_DRIVER_LOADER_DELAY); */
241         property_set(DRIVER_PROP_NAME, "ok");
242     }
243     else {
244         property_set("ctl.start", FIRMWARE_LOADER);
245     }
246     sched_yield();
247     while (count-- > 0) {
248         if (property_get(DRIVER_PROP_NAME, driver_status, NULL)) {
249             if (strcmp(driver_status, "ok") == 0)
250                 return 0;
251             else if (strcmp(DRIVER_PROP_NAME, "failed") == 0) {
252                 wifi_unload_driver();
253                 return -1;
254             }
255         }
256         usleep(200000);
257     }
258     property_set(DRIVER_PROP_NAME, "timeout");
259     wifi_unload_driver();
260     return -1;
261 #else
262     property_set(DRIVER_PROP_NAME, "ok");
263     return 0;
264 #endif
265 }
266
267 int wifi_unload_driver()
268 {
269     usleep(200000); /* allow to finish interface down */
270 #ifdef WIFI_DRIVER_MODULE_PATH
271     if (rmmod(DRIVER_MODULE_NAME) == 0) {
272         int count = 20; /* wait at most 10 seconds for completion */
273         while (count-- > 0) {
274             if (!is_wifi_driver_loaded())
275                 break;
276             usleep(500000);
277         }
278         usleep(500000); /* allow card removal */
279         if (count) {
280             return 0;
281         }
282         return -1;
283     } else
284         return -1;
285 #else
286     property_set(DRIVER_PROP_NAME, "unloaded");
287     return 0;
288 #endif
289 }
290
291 int ensure_entropy_file_exists()
292 {
293     int ret;
294     int destfd;
295
296     ret = access(SUPP_ENTROPY_FILE, R_OK|W_OK);
297     if ((ret == 0) || (errno == EACCES)) {
298         if ((ret != 0) &&
299             (chmod(SUPP_ENTROPY_FILE, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP) != 0)) {
300             ALOGE("Cannot set RW to \"%s\": %s", SUPP_ENTROPY_FILE, strerror(errno));
301             return -1;
302         }
303         return 0;
304     }
305     destfd = open(SUPP_ENTROPY_FILE, O_CREAT|O_RDWR, 0660);
306     if (destfd < 0) {
307         ALOGE("Cannot create \"%s\": %s", SUPP_ENTROPY_FILE, strerror(errno));
308         return -1;
309     }
310
311     if (write(destfd, dummy_key, sizeof(dummy_key)) != sizeof(dummy_key)) {
312         ALOGE("Error writing \"%s\": %s", SUPP_ENTROPY_FILE, strerror(errno));
313         close(destfd);
314         return -1;
315     }
316     close(destfd);
317
318     /* chmod is needed because open() didn't set permisions properly */
319     if (chmod(SUPP_ENTROPY_FILE, 0660) < 0) {
320         ALOGE("Error changing permissions of %s to 0660: %s",
321              SUPP_ENTROPY_FILE, strerror(errno));
322         unlink(SUPP_ENTROPY_FILE);
323         return -1;
324     }
325
326     if (chown(SUPP_ENTROPY_FILE, AID_SYSTEM, AID_WIFI) < 0) {
327         ALOGE("Error changing group ownership of %s to %d: %s",
328              SUPP_ENTROPY_FILE, AID_WIFI, strerror(errno));
329         unlink(SUPP_ENTROPY_FILE);
330         return -1;
331     }
332     return 0;
333 }
334
335 int update_ctrl_interface(const char *config_file) {
336
337     int srcfd, destfd;
338     int nread;
339     char ifc[PROPERTY_VALUE_MAX];
340     char *pbuf;
341     char *sptr;
342     struct stat sb;
343
344     if (stat(config_file, &sb) != 0)
345         return -1;
346
347     pbuf = malloc(sb.st_size + PROPERTY_VALUE_MAX);
348     if (!pbuf)
349         return 0;
350     srcfd = open(config_file, O_RDONLY);
351     if (srcfd < 0) {
352         ALOGE("Cannot open \"%s\": %s", config_file, strerror(errno));
353         free(pbuf);
354         return 0;
355     }
356     nread = read(srcfd, pbuf, sb.st_size);
357     close(srcfd);
358     if (nread < 0) {
359         ALOGE("Cannot read \"%s\": %s", config_file, strerror(errno));
360         free(pbuf);
361         return 0;
362     }
363
364     if (!strcmp(config_file, SUPP_CONFIG_FILE)) {
365         property_get("wifi.interface", ifc, WIFI_TEST_INTERFACE);
366     } else {
367         strcpy(ifc, CONTROL_IFACE_PATH);
368     }
369     if ((sptr = strstr(pbuf, "ctrl_interface="))) {
370         char *iptr = sptr + strlen("ctrl_interface=");
371         int ilen = 0;
372         int mlen = strlen(ifc);
373         int nwrite;
374         if (strncmp(ifc, iptr, mlen) != 0) {
375             ALOGE("ctrl_interface != %s", ifc);
376             while (((ilen + (iptr - pbuf)) < nread) && (iptr[ilen] != '\n'))
377                 ilen++;
378             mlen = ((ilen >= mlen) ? ilen : mlen) + 1;
379             memmove(iptr + mlen, iptr + ilen + 1, nread - (iptr + ilen + 1 - pbuf));
380             memset(iptr, '\n', mlen);
381             memcpy(iptr, ifc, strlen(ifc));
382             destfd = open(config_file, O_RDWR, 0660);
383             if (destfd < 0) {
384                 ALOGE("Cannot update \"%s\": %s", config_file, strerror(errno));
385                 free(pbuf);
386                 return -1;
387             }
388             write(destfd, pbuf, nread + mlen - ilen -1);
389             close(destfd);
390         }
391     }
392     free(pbuf);
393     return 0;
394 }
395
396 int ensure_config_file_exists(const char *config_file)
397 {
398     char buf[2048];
399     int srcfd, destfd;
400     struct stat sb;
401     int nread;
402     int ret;
403
404     ret = access(config_file, R_OK|W_OK);
405     if ((ret == 0) || (errno == EACCES)) {
406         if ((ret != 0) &&
407             (chmod(config_file, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP) != 0)) {
408             ALOGE("Cannot set RW to \"%s\": %s", config_file, strerror(errno));
409             return -1;
410         }
411         /* return if filesize is at least 10 bytes */
412         if (stat(config_file, &sb) == 0 && sb.st_size > 10) {
413             return update_ctrl_interface(config_file);
414         }
415     } else if (errno != ENOENT) {
416         ALOGE("Cannot access \"%s\": %s", config_file, strerror(errno));
417         return -1;
418     }
419
420     srcfd = open(SUPP_CONFIG_TEMPLATE, O_RDONLY);
421     if (srcfd < 0) {
422         ALOGE("Cannot open \"%s\": %s", SUPP_CONFIG_TEMPLATE, strerror(errno));
423         return -1;
424     }
425
426     destfd = open(config_file, O_CREAT|O_RDWR, 0660);
427     if (destfd < 0) {
428         close(srcfd);
429         ALOGE("Cannot create \"%s\": %s", config_file, strerror(errno));
430         return -1;
431     }
432
433     while ((nread = read(srcfd, buf, sizeof(buf))) != 0) {
434         if (nread < 0) {
435             ALOGE("Error reading \"%s\": %s", SUPP_CONFIG_TEMPLATE, strerror(errno));
436             close(srcfd);
437             close(destfd);
438             unlink(config_file);
439             return -1;
440         }
441         write(destfd, buf, nread);
442     }
443
444     close(destfd);
445     close(srcfd);
446
447     /* chmod is needed because open() didn't set permisions properly */
448     if (chmod(config_file, 0660) < 0) {
449         ALOGE("Error changing permissions of %s to 0660: %s",
450              config_file, strerror(errno));
451         unlink(config_file);
452         return -1;
453     }
454
455     if (chown(config_file, AID_SYSTEM, AID_WIFI) < 0) {
456         ALOGE("Error changing group ownership of %s to %d: %s",
457              config_file, AID_WIFI, strerror(errno));
458         unlink(config_file);
459         return -1;
460     }
461     return update_ctrl_interface(config_file);
462 }
463
464 /**
465  * wifi_wpa_ctrl_cleanup() - Delete any local UNIX domain socket files that
466  * may be left over from clients that were previously connected to
467  * wpa_supplicant. This keeps these files from being orphaned in the
468  * event of crashes that prevented them from being removed as part
469  * of the normal orderly shutdown.
470  */
471 void wifi_wpa_ctrl_cleanup(void)
472 {
473     DIR *dir;
474     struct dirent entry;
475     struct dirent *result;
476     size_t dirnamelen;
477     size_t maxcopy;
478     char pathname[PATH_MAX];
479     char *namep;
480     char *local_socket_dir = CONFIG_CTRL_IFACE_CLIENT_DIR;
481     char *local_socket_prefix = CONFIG_CTRL_IFACE_CLIENT_PREFIX;
482
483     if ((dir = opendir(local_socket_dir)) == NULL)
484         return;
485
486     dirnamelen = (size_t)snprintf(pathname, sizeof(pathname), "%s/", local_socket_dir);
487     if (dirnamelen >= sizeof(pathname)) {
488         closedir(dir);
489         return;
490     }
491     namep = pathname + dirnamelen;
492     maxcopy = PATH_MAX - dirnamelen;
493     while (readdir_r(dir, &entry, &result) == 0 && result != NULL) {
494         if (strncmp(entry.d_name, local_socket_prefix, strlen(local_socket_prefix)) == 0) {
495             if (strlcpy(namep, entry.d_name, maxcopy) < maxcopy) {
496                 unlink(pathname);
497             }
498         }
499     }
500     closedir(dir);
501 }
502
503 int wifi_start_supplicant(int p2p_supported)
504 {
505     char supp_status[PROPERTY_VALUE_MAX] = {'\0'};
506     int count = 200; /* wait at most 20 seconds for completion */
507 #ifdef HAVE_LIBC_SYSTEM_PROPERTIES
508     const prop_info *pi;
509     unsigned serial = 0, i;
510 #endif
511
512     if (p2p_supported) {
513         strcpy(supplicant_name, P2P_SUPPLICANT_NAME);
514         strcpy(supplicant_prop_name, P2P_PROP_NAME);
515
516         /* Ensure p2p config file is created */
517         if (ensure_config_file_exists(P2P_CONFIG_FILE) < 0) {
518             ALOGE("Failed to create a p2p config file");
519             return -1;
520         }
521
522     } else {
523         strcpy(supplicant_name, SUPPLICANT_NAME);
524         strcpy(supplicant_prop_name, SUPP_PROP_NAME);
525     }
526
527     /* Check whether already running */
528     if (property_get(supplicant_name, supp_status, NULL)
529             && strcmp(supp_status, "running") == 0) {
530         return 0;
531     }
532
533     /* Before starting the daemon, make sure its config file exists */
534     if (ensure_config_file_exists(SUPP_CONFIG_FILE) < 0) {
535         ALOGE("Wi-Fi will not be enabled");
536         return -1;
537     }
538
539     if (ensure_entropy_file_exists() < 0) {
540         ALOGE("Wi-Fi entropy file was not created");
541     }
542
543     /* Clear out any stale socket files that might be left over. */
544     wifi_wpa_ctrl_cleanup();
545
546     /* Reset sockets used for exiting from hung state */
547     for (i=0; i<MAX_CONNS; i++) {
548         exit_sockets[i][0] = exit_sockets[i][1] = -1;
549     }
550
551 #ifdef HAVE_LIBC_SYSTEM_PROPERTIES
552     /*
553      * Get a reference to the status property, so we can distinguish
554      * the case where it goes stopped => running => stopped (i.e.,
555      * it start up, but fails right away) from the case in which
556      * it starts in the stopped state and never manages to start
557      * running at all.
558      */
559     pi = __system_property_find(supplicant_prop_name);
560     if (pi != NULL) {
561         serial = pi->serial;
562     }
563 #endif
564     property_get("wifi.interface", primary_iface, WIFI_TEST_INTERFACE);
565
566     property_set("ctl.start", supplicant_name);
567     sched_yield();
568
569     while (count-- > 0) {
570 #ifdef HAVE_LIBC_SYSTEM_PROPERTIES
571         if (pi == NULL) {
572             pi = __system_property_find(supplicant_prop_name);
573         }
574         if (pi != NULL) {
575             __system_property_read(pi, NULL, supp_status);
576             if (strcmp(supp_status, "running") == 0) {
577                 return 0;
578             } else if (pi->serial != serial &&
579                     strcmp(supp_status, "stopped") == 0) {
580                 return -1;
581             }
582         }
583 #else
584         if (property_get(supplicant_prop_name, supp_status, NULL)) {
585             if (strcmp(supp_status, "running") == 0)
586                 return 0;
587         }
588 #endif
589         usleep(100000);
590     }
591     return -1;
592 }
593
594 int wifi_stop_supplicant()
595 {
596     char supp_status[PROPERTY_VALUE_MAX] = {'\0'};
597     int count = 50; /* wait at most 5 seconds for completion */
598
599     /* Check whether supplicant already stopped */
600     if (property_get(supplicant_prop_name, supp_status, NULL)
601         && strcmp(supp_status, "stopped") == 0) {
602         return 0;
603     }
604
605     property_set("ctl.stop", supplicant_name);
606     sched_yield();
607
608     while (count-- > 0) {
609         if (property_get(supplicant_prop_name, supp_status, NULL)) {
610             if (strcmp(supp_status, "stopped") == 0)
611                 return 0;
612         }
613         usleep(100000);
614     }
615     return -1;
616 }
617
618 int wifi_connect_on_socket_path(int index, const char *path)
619 {
620     char supp_status[PROPERTY_VALUE_MAX] = {'\0'};
621
622     /* Make sure supplicant is running */
623     if (!property_get(supplicant_prop_name, supp_status, NULL)
624             || strcmp(supp_status, "running") != 0) {
625         ALOGE("Supplicant not running, cannot connect");
626         return -1;
627     }
628
629     ctrl_conn[index] = wpa_ctrl_open(path);
630     if (ctrl_conn[index] == NULL) {
631         ALOGE("Unable to open connection to supplicant on \"%s\": %s",
632              path, strerror(errno));
633         return -1;
634     }
635     monitor_conn[index] = wpa_ctrl_open(path);
636     if (monitor_conn[index] == NULL) {
637         wpa_ctrl_close(ctrl_conn[index]);
638         ctrl_conn[index] = NULL;
639         return -1;
640     }
641     if (wpa_ctrl_attach(monitor_conn[index]) != 0) {
642         wpa_ctrl_close(monitor_conn[index]);
643         wpa_ctrl_close(ctrl_conn[index]);
644         ctrl_conn[index] = monitor_conn[index] = NULL;
645         return -1;
646     }
647
648     if (socketpair(AF_UNIX, SOCK_STREAM, 0, exit_sockets[index]) == -1) {
649         wpa_ctrl_close(monitor_conn[index]);
650         wpa_ctrl_close(ctrl_conn[index]);
651         ctrl_conn[index] = monitor_conn[index] = NULL;
652         return -1;
653     }
654
655     return 0;
656 }
657
658 /* Establishes the control and monitor socket connections on the interface */
659 int wifi_connect_to_supplicant(const char *ifname)
660 {
661     char path[256];
662
663     if (is_primary_interface(ifname)) {
664         if (access(IFACE_DIR, F_OK) == 0) {
665             snprintf(path, sizeof(path), "%s/%s", IFACE_DIR, primary_iface);
666         } else {
667             strlcpy(path, primary_iface, sizeof(path));
668         }
669         return wifi_connect_on_socket_path(PRIMARY, path);
670     } else {
671         sprintf(path, "%s/%s", CONTROL_IFACE_PATH, ifname);
672         return wifi_connect_on_socket_path(SECONDARY, path);
673     }
674 }
675
676 int wifi_send_command(int index, const char *cmd, char *reply, size_t *reply_len)
677 {
678     int ret;
679
680     if (ctrl_conn[index] == NULL) {
681         ALOGV("Not connected to wpa_supplicant - \"%s\" command dropped.\n", cmd);
682         return -1;
683     }
684     ret = wpa_ctrl_request(ctrl_conn[index], cmd, strlen(cmd), reply, reply_len, NULL);
685     if (ret == -2) {
686         ALOGD("'%s' command timed out.\n", cmd);
687         /* unblocks the monitor receive socket for termination */
688         write(exit_sockets[index][0], "T", 1);
689         return -2;
690     } else if (ret < 0 || strncmp(reply, "FAIL", 4) == 0) {
691         return -1;
692     }
693     if (strncmp(cmd, "PING", 4) == 0) {
694         reply[*reply_len] = '\0';
695     }
696     return 0;
697 }
698
699 int wifi_ctrl_recv(int index, char *reply, size_t *reply_len)
700 {
701     int res;
702     int ctrlfd = wpa_ctrl_get_fd(monitor_conn[index]);
703     struct pollfd rfds[2];
704
705     memset(rfds, 0, 2 * sizeof(struct pollfd));
706     rfds[0].fd = ctrlfd;
707     rfds[0].events |= POLLIN;
708     rfds[1].fd = exit_sockets[index][1];
709     rfds[1].events |= POLLIN;
710     res = poll(rfds, 2, -1);
711     if (res < 0) {
712         ALOGE("Error poll = %d", res);
713         return res;
714     }
715     if (rfds[0].revents & POLLIN) {
716         return wpa_ctrl_recv(monitor_conn[index], reply, reply_len);
717     } else {
718         return -2;
719     }
720     return 0;
721 }
722
723 int wifi_wait_on_socket(int index, char *buf, size_t buflen)
724 {
725     size_t nread = buflen - 1;
726     int fd;
727     fd_set rfds;
728     int result;
729     struct timeval tval;
730     struct timeval *tptr;
731
732     if (monitor_conn[index] == NULL) {
733         ALOGD("Connection closed\n");
734         strncpy(buf, WPA_EVENT_TERMINATING " - connection closed", buflen-1);
735         buf[buflen-1] = '\0';
736         return strlen(buf);
737     }
738
739     result = wifi_ctrl_recv(index, buf, &nread);
740
741     /* Terminate reception on exit socket */
742     if (result == -2) {
743         strncpy(buf, WPA_EVENT_TERMINATING " - connection closed", buflen-1);
744         buf[buflen-1] = '\0';
745         return strlen(buf);
746     }
747
748     if (result < 0) {
749         ALOGD("wifi_ctrl_recv failed: %s\n", strerror(errno));
750         strncpy(buf, WPA_EVENT_TERMINATING " - recv error", buflen-1);
751         buf[buflen-1] = '\0';
752         return strlen(buf);
753     }
754     buf[nread] = '\0';
755     /* Check for EOF on the socket */
756     if (result == 0 && nread == 0) {
757         /* Fabricate an event to pass up */
758         ALOGD("Received EOF on supplicant socket\n");
759         strncpy(buf, WPA_EVENT_TERMINATING " - signal 0 received", buflen-1);
760         buf[buflen-1] = '\0';
761         return strlen(buf);
762     }
763     /*
764      * Events strings are in the format
765      *
766      *     <N>CTRL-EVENT-XXX 
767      *
768      * where N is the message level in numerical form (0=VERBOSE, 1=DEBUG,
769      * etc.) and XXX is the event name. The level information is not useful
770      * to us, so strip it off.
771      */
772     if (buf[0] == '<') {
773         char *match = strchr(buf, '>');
774         if (match != NULL) {
775             nread -= (match+1-buf);
776             memmove(buf, match+1, nread+1);
777         }
778     }
779
780     return nread;
781 }
782
783 int wifi_wait_for_event(const char *ifname, char *buf, size_t buflen)
784 {
785     if (is_primary_interface(ifname)) {
786         return wifi_wait_on_socket(PRIMARY, buf, buflen);
787     } else {
788         return wifi_wait_on_socket(SECONDARY, buf, buflen);
789     }
790 }
791
792 void wifi_close_sockets(int index)
793 {
794     if (ctrl_conn[index] != NULL) {
795         wpa_ctrl_close(ctrl_conn[index]);
796         ctrl_conn[index] = NULL;
797     }
798
799     if (monitor_conn[index] != NULL) {
800         wpa_ctrl_close(monitor_conn[index]);
801         monitor_conn[index] = NULL;
802     }
803
804     if (exit_sockets[index][0] >= 0) {
805         close(exit_sockets[index][0]);
806         exit_sockets[index][0] = -1;
807     }
808
809     if (exit_sockets[index][1] >= 0) {
810         close(exit_sockets[index][1]);
811         exit_sockets[index][1] = -1;
812     }
813 }
814
815 void wifi_close_supplicant_connection(const char *ifname)
816 {
817     char supp_status[PROPERTY_VALUE_MAX] = {'\0'};
818     int count = 50; /* wait at most 5 seconds to ensure init has stopped stupplicant */
819
820     if (is_primary_interface(ifname)) {
821         wifi_close_sockets(PRIMARY);
822     } else {
823         /* p2p socket termination needs unblocking the monitor socket
824          * STA connection does not need it since supplicant gets shutdown
825          */
826         write(exit_sockets[SECONDARY][0], "T", 1);
827         wifi_close_sockets(SECONDARY);
828         //closing p2p connection does not need a wait on
829         //supplicant stop
830         return;
831     }
832
833     while (count-- > 0) {
834         if (property_get(supplicant_prop_name, supp_status, NULL)) {
835             if (strcmp(supp_status, "stopped") == 0)
836                 return;
837         }
838         usleep(100000);
839     }
840 }
841
842 int wifi_command(const char *ifname, const char *command, char *reply, size_t *reply_len)
843 {
844     if (is_primary_interface(ifname)) {
845         return wifi_send_command(PRIMARY, command, reply, reply_len);
846     } else {
847         return wifi_send_command(SECONDARY, command, reply, reply_len);
848     }
849 }
850
851 const char *wifi_get_fw_path(int fw_type)
852 {
853     switch (fw_type) {
854     case WIFI_GET_FW_PATH_STA:
855         return WIFI_DRIVER_FW_PATH_STA;
856     case WIFI_GET_FW_PATH_AP:
857         return WIFI_DRIVER_FW_PATH_AP;
858     case WIFI_GET_FW_PATH_P2P:
859         return WIFI_DRIVER_FW_PATH_P2P;
860     }
861     return NULL;
862 }
863
864 int wifi_change_fw_path(const char *fwpath)
865 {
866     int len;
867     int fd;
868     int ret = 0;
869
870     if (!fwpath)
871         return ret;
872     fd = open(WIFI_DRIVER_FW_PATH_PARAM, O_WRONLY);
873     if (fd < 0) {
874         ALOGE("Failed to open wlan fw path param (%s)", strerror(errno));
875         return -1;
876     }
877     len = strlen(fwpath) + 1;
878     if (write(fd, fwpath, len) != len) {
879         ALOGE("Failed to write wlan fw path param (%s)", strerror(errno));
880         ret = -1;
881     }
882     close(fd);
883     return ret;
884 }