OSDN Git Service

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