OSDN Git Service

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