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
50static struct wpa_ctrl *ctrl_conn[MAX_CONNS];
51static struct wpa_ctrl *monitor_conn[MAX_CONNS];
52
53/* socket pair used to exit from a blocking read */
54static int exit_sockets[MAX_CONNS][2];
55
56extern int do_dhcp();
57extern int ifc_init();
58extern void ifc_close();
59extern char *dhcp_lasterror();
60extern void get_dhcp_info();
61extern int init_module(void *, unsigned long, const char *);
62extern int delete_module(const char *, unsigned int);
63
64static 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
92static const char IFACE_DIR[]           = "/data/system/wpa_supplicant";
93#ifdef WIFI_DRIVER_MODULE_PATH
94static const char DRIVER_MODULE_NAME[]  = WIFI_DRIVER_MODULE_NAME;
95static const char DRIVER_MODULE_TAG[]   = WIFI_DRIVER_MODULE_NAME " ";
96static const char DRIVER_MODULE_PATH[]  = WIFI_DRIVER_MODULE_PATH;
97static const char DRIVER_MODULE_ARG[]   = WIFI_DRIVER_MODULE_ARG;
98#endif
99static const char FIRMWARE_LOADER[]     = WIFI_FIRMWARE_LOADER;
100static const char DRIVER_PROP_NAME[]    = "wlan.driver.status";
101static const char SUPPLICANT_NAME[]     = "wpa_supplicant";
102static const char SUPP_PROP_NAME[]      = "init.svc.wpa_supplicant";
103static const char P2P_SUPPLICANT_NAME[] = "p2p_supplicant";
104static const char P2P_PROP_NAME[]       = "init.svc.p2p_supplicant";
105static const char SUPP_CONFIG_TEMPLATE[]= "/system/etc/wifi/wpa_supplicant.conf";
106static const char SUPP_CONFIG_FILE[]    = "/data/misc/wifi/wpa_supplicant.conf";
107static const char P2P_CONFIG_FILE[]     = "/data/misc/wifi/p2p_supplicant.conf";
108static const char CONTROL_IFACE_PATH[]  = "/data/misc/wifi/sockets";
109static const char MODULE_FILE[]         = "/proc/modules";
110
111static const char SUPP_ENTROPY_FILE[]   = WIFI_ENTROPY_FILE;
112static 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 */
118static char supplicant_name[PROPERTY_VALUE_MAX];
119/* Is either SUPP_PROP_NAME or P2P_PROP_NAME */
120static char supplicant_prop_name[PROPERTY_KEY_MAX];
121
122static 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
132static 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
149static 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
168int 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
186const char *get_dhcp_error_string() {
187    return dhcp_lasterror();
188}
189
190int 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
227int 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
268int 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
292int 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
336int 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    /*
371     * if there is a "ctrl_interface=<value>" entry, re-write it ONLY if it is
372     * NOT a directory.  The non-directory value option is an Android add-on
373     * that allows the control interface to be exchanged through an environment
374     * variable (initialized by the "init" program when it starts a service
375     * with a "socket" option).
376     *
377     * The <value> is deemed to be a directory if the "DIR=" form is used or
378     * the value begins with "/".
379     */
380    if ((sptr = strstr(pbuf, "ctrl_interface=")) &&
381        (!strstr(pbuf, "ctrl_interface=DIR=")) &&
382        (!strstr(pbuf, "ctrl_interface=/"))) {
383        char *iptr = sptr + strlen("ctrl_interface=");
384        int ilen = 0;
385        int mlen = strlen(ifc);
386        int nwrite;
387        if (strncmp(ifc, iptr, mlen) != 0) {
388            ALOGE("ctrl_interface != %s", ifc);
389            while (((ilen + (iptr - pbuf)) < nread) && (iptr[ilen] != '\n'))
390                ilen++;
391            mlen = ((ilen >= mlen) ? ilen : mlen) + 1;
392            memmove(iptr + mlen, iptr + ilen + 1, nread - (iptr + ilen + 1 - pbuf));
393            memset(iptr, '\n', mlen);
394            memcpy(iptr, ifc, strlen(ifc));
395            destfd = TEMP_FAILURE_RETRY(open(config_file, O_RDWR, 0660));
396            if (destfd < 0) {
397                ALOGE("Cannot update \"%s\": %s", config_file, strerror(errno));
398                free(pbuf);
399                return -1;
400            }
401            TEMP_FAILURE_RETRY(write(destfd, pbuf, nread + mlen - ilen -1));
402            close(destfd);
403        }
404    }
405    free(pbuf);
406    return 0;
407}
408
409int ensure_config_file_exists(const char *config_file)
410{
411    char buf[2048];
412    int srcfd, destfd;
413    struct stat sb;
414    int nread;
415    int ret;
416
417    ret = access(config_file, R_OK|W_OK);
418    if ((ret == 0) || (errno == EACCES)) {
419        if ((ret != 0) &&
420            (chmod(config_file, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP) != 0)) {
421            ALOGE("Cannot set RW to \"%s\": %s", config_file, strerror(errno));
422            return -1;
423        }
424        /* return if filesize is at least 10 bytes */
425        if (stat(config_file, &sb) == 0 && sb.st_size > 10) {
426            return update_ctrl_interface(config_file);
427        }
428    } else if (errno != ENOENT) {
429        ALOGE("Cannot access \"%s\": %s", config_file, strerror(errno));
430        return -1;
431    }
432
433    srcfd = TEMP_FAILURE_RETRY(open(SUPP_CONFIG_TEMPLATE, O_RDONLY));
434    if (srcfd < 0) {
435        ALOGE("Cannot open \"%s\": %s", SUPP_CONFIG_TEMPLATE, strerror(errno));
436        return -1;
437    }
438
439    destfd = TEMP_FAILURE_RETRY(open(config_file, O_CREAT|O_RDWR, 0660));
440    if (destfd < 0) {
441        close(srcfd);
442        ALOGE("Cannot create \"%s\": %s", config_file, strerror(errno));
443        return -1;
444    }
445
446    while ((nread = TEMP_FAILURE_RETRY(read(srcfd, buf, sizeof(buf)))) != 0) {
447        if (nread < 0) {
448            ALOGE("Error reading \"%s\": %s", SUPP_CONFIG_TEMPLATE, strerror(errno));
449            close(srcfd);
450            close(destfd);
451            unlink(config_file);
452            return -1;
453        }
454        TEMP_FAILURE_RETRY(write(destfd, buf, nread));
455    }
456
457    close(destfd);
458    close(srcfd);
459
460    /* chmod is needed because open() didn't set permisions properly */
461    if (chmod(config_file, 0660) < 0) {
462        ALOGE("Error changing permissions of %s to 0660: %s",
463             config_file, strerror(errno));
464        unlink(config_file);
465        return -1;
466    }
467
468    if (chown(config_file, AID_SYSTEM, AID_WIFI) < 0) {
469        ALOGE("Error changing group ownership of %s to %d: %s",
470             config_file, AID_WIFI, strerror(errno));
471        unlink(config_file);
472        return -1;
473    }
474    return update_ctrl_interface(config_file);
475}
476
477/**
478 * wifi_wpa_ctrl_cleanup() - Delete any local UNIX domain socket files that
479 * may be left over from clients that were previously connected to
480 * wpa_supplicant. This keeps these files from being orphaned in the
481 * event of crashes that prevented them from being removed as part
482 * of the normal orderly shutdown.
483 */
484void wifi_wpa_ctrl_cleanup(void)
485{
486    DIR *dir;
487    struct dirent entry;
488    struct dirent *result;
489    size_t dirnamelen;
490    size_t maxcopy;
491    char pathname[PATH_MAX];
492    char *namep;
493    char *local_socket_dir = CONFIG_CTRL_IFACE_CLIENT_DIR;
494    char *local_socket_prefix = CONFIG_CTRL_IFACE_CLIENT_PREFIX;
495
496    if ((dir = opendir(local_socket_dir)) == NULL)
497        return;
498
499    dirnamelen = (size_t)snprintf(pathname, sizeof(pathname), "%s/", local_socket_dir);
500    if (dirnamelen >= sizeof(pathname)) {
501        closedir(dir);
502        return;
503    }
504    namep = pathname + dirnamelen;
505    maxcopy = PATH_MAX - dirnamelen;
506    while (readdir_r(dir, &entry, &result) == 0 && result != NULL) {
507        if (strncmp(entry.d_name, local_socket_prefix, strlen(local_socket_prefix)) == 0) {
508            if (strlcpy(namep, entry.d_name, maxcopy) < maxcopy) {
509                unlink(pathname);
510            }
511        }
512    }
513    closedir(dir);
514}
515
516int wifi_start_supplicant(int p2p_supported)
517{
518    char supp_status[PROPERTY_VALUE_MAX] = {'\0'};
519    int count = 200; /* wait at most 20 seconds for completion */
520#ifdef HAVE_LIBC_SYSTEM_PROPERTIES
521    const prop_info *pi;
522    unsigned serial = 0, i;
523#endif
524
525    if (p2p_supported) {
526        strcpy(supplicant_name, P2P_SUPPLICANT_NAME);
527        strcpy(supplicant_prop_name, P2P_PROP_NAME);
528
529        /* Ensure p2p config file is created */
530        if (ensure_config_file_exists(P2P_CONFIG_FILE) < 0) {
531            ALOGE("Failed to create a p2p config file");
532            return -1;
533        }
534
535    } else {
536        strcpy(supplicant_name, SUPPLICANT_NAME);
537        strcpy(supplicant_prop_name, SUPP_PROP_NAME);
538    }
539
540    /* Check whether already running */
541    if (property_get(supplicant_name, supp_status, NULL)
542            && strcmp(supp_status, "running") == 0) {
543        return 0;
544    }
545
546    /* Before starting the daemon, make sure its config file exists */
547    if (ensure_config_file_exists(SUPP_CONFIG_FILE) < 0) {
548        ALOGE("Wi-Fi will not be enabled");
549        return -1;
550    }
551
552    if (ensure_entropy_file_exists() < 0) {
553        ALOGE("Wi-Fi entropy file was not created");
554    }
555
556    /* Clear out any stale socket files that might be left over. */
557    wifi_wpa_ctrl_cleanup();
558
559    /* Reset sockets used for exiting from hung state */
560    for (i=0; i<MAX_CONNS; i++) {
561        exit_sockets[i][0] = exit_sockets[i][1] = -1;
562    }
563
564#ifdef HAVE_LIBC_SYSTEM_PROPERTIES
565    /*
566     * Get a reference to the status property, so we can distinguish
567     * the case where it goes stopped => running => stopped (i.e.,
568     * it start up, but fails right away) from the case in which
569     * it starts in the stopped state and never manages to start
570     * running at all.
571     */
572    pi = __system_property_find(supplicant_prop_name);
573    if (pi != NULL) {
574        serial = pi->serial;
575    }
576#endif
577    property_get("wifi.interface", primary_iface, WIFI_TEST_INTERFACE);
578
579    property_set("ctl.start", supplicant_name);
580    sched_yield();
581
582    while (count-- > 0) {
583#ifdef HAVE_LIBC_SYSTEM_PROPERTIES
584        if (pi == NULL) {
585            pi = __system_property_find(supplicant_prop_name);
586        }
587        if (pi != NULL) {
588            __system_property_read(pi, NULL, supp_status);
589            if (strcmp(supp_status, "running") == 0) {
590                return 0;
591            } else if (pi->serial != serial &&
592                    strcmp(supp_status, "stopped") == 0) {
593                return -1;
594            }
595        }
596#else
597        if (property_get(supplicant_prop_name, supp_status, NULL)) {
598            if (strcmp(supp_status, "running") == 0)
599                return 0;
600        }
601#endif
602        usleep(100000);
603    }
604    return -1;
605}
606
607int wifi_stop_supplicant(int p2p_supported)
608{
609    char supp_status[PROPERTY_VALUE_MAX] = {'\0'};
610    int count = 50; /* wait at most 5 seconds for completion */
611
612    if (p2p_supported) {
613        strcpy(supplicant_name, P2P_SUPPLICANT_NAME);
614        strcpy(supplicant_prop_name, P2P_PROP_NAME);
615    } else {
616        strcpy(supplicant_name, SUPPLICANT_NAME);
617        strcpy(supplicant_prop_name, SUPP_PROP_NAME);
618    }
619
620    /* Check whether supplicant already stopped */
621    if (property_get(supplicant_prop_name, supp_status, NULL)
622        && strcmp(supp_status, "stopped") == 0) {
623        return 0;
624    }
625
626    property_set("ctl.stop", supplicant_name);
627    sched_yield();
628
629    while (count-- > 0) {
630        if (property_get(supplicant_prop_name, supp_status, NULL)) {
631            if (strcmp(supp_status, "stopped") == 0)
632                return 0;
633        }
634        usleep(100000);
635    }
636    ALOGE("Failed to stop supplicant");
637    return -1;
638}
639
640int wifi_connect_on_socket_path(int index, const char *path)
641{
642    char supp_status[PROPERTY_VALUE_MAX] = {'\0'};
643
644    /* Make sure supplicant is running */
645    if (!property_get(supplicant_prop_name, supp_status, NULL)
646            || strcmp(supp_status, "running") != 0) {
647        ALOGE("Supplicant not running, cannot connect");
648        return -1;
649    }
650
651    ctrl_conn[index] = wpa_ctrl_open(path);
652    if (ctrl_conn[index] == NULL) {
653        ALOGE("Unable to open connection to supplicant on \"%s\": %s",
654             path, strerror(errno));
655        return -1;
656    }
657    monitor_conn[index] = wpa_ctrl_open(path);
658    if (monitor_conn[index] == NULL) {
659        wpa_ctrl_close(ctrl_conn[index]);
660        ctrl_conn[index] = NULL;
661        return -1;
662    }
663    if (wpa_ctrl_attach(monitor_conn[index]) != 0) {
664        wpa_ctrl_close(monitor_conn[index]);
665        wpa_ctrl_close(ctrl_conn[index]);
666        ctrl_conn[index] = monitor_conn[index] = NULL;
667        return -1;
668    }
669
670    if (socketpair(AF_UNIX, SOCK_STREAM, 0, exit_sockets[index]) == -1) {
671        wpa_ctrl_close(monitor_conn[index]);
672        wpa_ctrl_close(ctrl_conn[index]);
673        ctrl_conn[index] = monitor_conn[index] = NULL;
674        return -1;
675    }
676
677    return 0;
678}
679
680/* Establishes the control and monitor socket connections on the interface */
681int wifi_connect_to_supplicant(const char *ifname)
682{
683    char path[256];
684
685    if (is_primary_interface(ifname)) {
686        if (access(IFACE_DIR, F_OK) == 0) {
687            snprintf(path, sizeof(path), "%s/%s", IFACE_DIR, primary_iface);
688        } else {
689            strlcpy(path, primary_iface, sizeof(path));
690        }
691        return wifi_connect_on_socket_path(PRIMARY, path);
692    } else {
693        sprintf(path, "%s/%s", CONTROL_IFACE_PATH, ifname);
694        return wifi_connect_on_socket_path(SECONDARY, path);
695    }
696}
697
698int wifi_send_command(int index, const char *cmd, char *reply, size_t *reply_len)
699{
700    int ret;
701
702    if (ctrl_conn[index] == NULL) {
703        ALOGV("Not connected to wpa_supplicant - \"%s\" command dropped.\n", cmd);
704        return -1;
705    }
706    ret = wpa_ctrl_request(ctrl_conn[index], cmd, strlen(cmd), reply, reply_len, NULL);
707    if (ret == -2) {
708        ALOGD("'%s' command timed out.\n", cmd);
709        /* unblocks the monitor receive socket for termination */
710        TEMP_FAILURE_RETRY(write(exit_sockets[index][0], "T", 1));
711        return -2;
712    } else if (ret < 0 || strncmp(reply, "FAIL", 4) == 0) {
713        return -1;
714    }
715    if (strncmp(cmd, "PING", 4) == 0) {
716        reply[*reply_len] = '\0';
717    }
718    return 0;
719}
720
721int wifi_ctrl_recv(int index, char *reply, size_t *reply_len)
722{
723    int res;
724    int ctrlfd = wpa_ctrl_get_fd(monitor_conn[index]);
725    struct pollfd rfds[2];
726
727    memset(rfds, 0, 2 * sizeof(struct pollfd));
728    rfds[0].fd = ctrlfd;
729    rfds[0].events |= POLLIN;
730    rfds[1].fd = exit_sockets[index][1];
731    rfds[1].events |= POLLIN;
732    res = TEMP_FAILURE_RETRY(poll(rfds, 2, -1));
733    if (res < 0) {
734        ALOGE("Error poll = %d", res);
735        return res;
736    }
737    if (rfds[0].revents & POLLIN) {
738        return wpa_ctrl_recv(monitor_conn[index], reply, reply_len);
739    } else if (rfds[1].revents & POLLIN) {
740        /* Close only the p2p sockets on receive side
741         * see wifi_close_supplicant_connection()
742         */
743        if (index == SECONDARY) {
744            ALOGD("close sockets %d", index);
745            wifi_close_sockets(index);
746        }
747    }
748    return -2;
749}
750
751int wifi_wait_on_socket(int index, char *buf, size_t buflen)
752{
753    size_t nread = buflen - 1;
754    int fd;
755    fd_set rfds;
756    int result;
757    struct timeval tval;
758    struct timeval *tptr;
759
760    if (monitor_conn[index] == NULL) {
761        ALOGD("Connection closed\n");
762        strncpy(buf, WPA_EVENT_TERMINATING " - connection closed", buflen-1);
763        buf[buflen-1] = '\0';
764        return strlen(buf);
765    }
766
767    result = wifi_ctrl_recv(index, buf, &nread);
768
769    /* Terminate reception on exit socket */
770    if (result == -2) {
771        strncpy(buf, WPA_EVENT_TERMINATING " - connection closed", buflen-1);
772        buf[buflen-1] = '\0';
773        return strlen(buf);
774    }
775
776    if (result < 0) {
777        ALOGD("wifi_ctrl_recv failed: %s\n", strerror(errno));
778        strncpy(buf, WPA_EVENT_TERMINATING " - recv error", buflen-1);
779        buf[buflen-1] = '\0';
780        return strlen(buf);
781    }
782    buf[nread] = '\0';
783    /* Check for EOF on the socket */
784    if (result == 0 && nread == 0) {
785        /* Fabricate an event to pass up */
786        ALOGD("Received EOF on supplicant socket\n");
787        strncpy(buf, WPA_EVENT_TERMINATING " - signal 0 received", buflen-1);
788        buf[buflen-1] = '\0';
789        return strlen(buf);
790    }
791    /*
792     * Events strings are in the format
793     *
794     *     <N>CTRL-EVENT-XXX
795     *
796     * where N is the message level in numerical form (0=VERBOSE, 1=DEBUG,
797     * etc.) and XXX is the event name. The level information is not useful
798     * to us, so strip it off.
799     */
800    if (buf[0] == '<') {
801        char *match = strchr(buf, '>');
802        if (match != NULL) {
803            nread -= (match+1-buf);
804            memmove(buf, match+1, nread+1);
805        }
806    }
807
808    return nread;
809}
810
811int wifi_wait_for_event(const char *ifname, char *buf, size_t buflen)
812{
813    if (is_primary_interface(ifname)) {
814        return wifi_wait_on_socket(PRIMARY, buf, buflen);
815    } else {
816        return wifi_wait_on_socket(SECONDARY, buf, buflen);
817    }
818}
819
820void wifi_close_sockets(int index)
821{
822    if (ctrl_conn[index] != NULL) {
823        wpa_ctrl_close(ctrl_conn[index]);
824        ctrl_conn[index] = NULL;
825    }
826
827    if (monitor_conn[index] != NULL) {
828        wpa_ctrl_close(monitor_conn[index]);
829        monitor_conn[index] = NULL;
830    }
831
832    if (exit_sockets[index][0] >= 0) {
833        close(exit_sockets[index][0]);
834        exit_sockets[index][0] = -1;
835    }
836
837    if (exit_sockets[index][1] >= 0) {
838        close(exit_sockets[index][1]);
839        exit_sockets[index][1] = -1;
840    }
841}
842
843void wifi_close_supplicant_connection(const char *ifname)
844{
845    char supp_status[PROPERTY_VALUE_MAX] = {'\0'};
846    int count = 50; /* wait at most 5 seconds to ensure init has stopped stupplicant */
847
848    if (is_primary_interface(ifname)) {
849        wifi_close_sockets(PRIMARY);
850    } else {
851        /* p2p socket termination needs unblocking the monitor socket
852         * STA connection does not need it since supplicant gets shutdown
853         */
854        TEMP_FAILURE_RETRY(write(exit_sockets[SECONDARY][0], "T", 1));
855        /* p2p sockets are closed after the monitor thread
856         * receives the terminate on the exit socket
857         */
858        return;
859    }
860
861    while (count-- > 0) {
862        if (property_get(supplicant_prop_name, supp_status, NULL)) {
863            if (strcmp(supp_status, "stopped") == 0)
864                return;
865        }
866        usleep(100000);
867    }
868}
869
870int wifi_command(const char *ifname, const char *command, char *reply, size_t *reply_len)
871{
872    if (is_primary_interface(ifname)) {
873        return wifi_send_command(PRIMARY, command, reply, reply_len);
874    } else {
875        return wifi_send_command(SECONDARY, command, reply, reply_len);
876    }
877}
878
879const char *wifi_get_fw_path(int fw_type)
880{
881    switch (fw_type) {
882    case WIFI_GET_FW_PATH_STA:
883        return WIFI_DRIVER_FW_PATH_STA;
884    case WIFI_GET_FW_PATH_AP:
885        return WIFI_DRIVER_FW_PATH_AP;
886    case WIFI_GET_FW_PATH_P2P:
887        return WIFI_DRIVER_FW_PATH_P2P;
888    }
889    return NULL;
890}
891
892int wifi_change_fw_path(const char *fwpath)
893{
894    int len;
895    int fd;
896    int ret = 0;
897
898    if (!fwpath)
899        return ret;
900    fd = TEMP_FAILURE_RETRY(open(WIFI_DRIVER_FW_PATH_PARAM, O_WRONLY));
901    if (fd < 0) {
902        ALOGE("Failed to open wlan fw path param (%s)", strerror(errno));
903        return -1;
904    }
905    len = strlen(fwpath) + 1;
906    if (TEMP_FAILURE_RETRY(write(fd, fwpath, len)) != len) {
907        ALOGE("Failed to write wlan fw path param (%s)", strerror(errno));
908        ret = -1;
909    }
910    close(fd);
911    return ret;
912}
913