OSDN Git Service

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