OSDN Git Service

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