Do not wait for monitor to attach if no control interface
[mech_eap.git] / wpa_supplicant / ctrl_iface_unix.c
1 /*
2  * WPA Supplicant / UNIX domain socket -based control interface
3  * Copyright (c) 2004-2014, Jouni Malinen <j@w1.fi>
4  *
5  * This software may be distributed under the terms of the BSD license.
6  * See README for more details.
7  */
8
9 #include "includes.h"
10 #include <sys/un.h>
11 #include <sys/stat.h>
12 #include <grp.h>
13 #include <stddef.h>
14 #include <unistd.h>
15 #include <fcntl.h>
16 #ifdef __linux__
17 #include <sys/ioctl.h>
18 #include <linux/sockios.h>
19 #endif /* __linux__ */
20 #ifdef ANDROID
21 #include <cutils/sockets.h>
22 #endif /* ANDROID */
23
24 #include "utils/common.h"
25 #include "utils/eloop.h"
26 #include "utils/list.h"
27 #include "eapol_supp/eapol_supp_sm.h"
28 #include "config.h"
29 #include "wpa_supplicant_i.h"
30 #include "ctrl_iface.h"
31
32 /* Per-interface ctrl_iface */
33
34 /**
35  * struct wpa_ctrl_dst - Internal data structure of control interface monitors
36  *
37  * This structure is used to store information about registered control
38  * interface monitors into struct wpa_supplicant. This data is private to
39  * ctrl_iface_unix.c and should not be touched directly from other files.
40  */
41 struct wpa_ctrl_dst {
42         struct dl_list list;
43         struct sockaddr_un addr;
44         socklen_t addrlen;
45         int debug_level;
46         int errors;
47 };
48
49
50 struct ctrl_iface_priv {
51         struct wpa_supplicant *wpa_s;
52         int sock;
53         struct dl_list ctrl_dst;
54         int android_control_socket;
55         struct dl_list msg_queue;
56         unsigned int throttle_count;
57 };
58
59
60 struct ctrl_iface_global_priv {
61         struct wpa_global *global;
62         int sock;
63         struct dl_list ctrl_dst;
64         int android_control_socket;
65         struct dl_list msg_queue;
66         unsigned int throttle_count;
67 };
68
69 struct ctrl_iface_msg {
70         struct dl_list list;
71         struct wpa_supplicant *wpa_s;
72         int level;
73         enum wpa_msg_type type;
74         const char *txt;
75         size_t len;
76 };
77
78
79 static void wpa_supplicant_ctrl_iface_send(struct wpa_supplicant *wpa_s,
80                                            const char *ifname, int sock,
81                                            struct dl_list *ctrl_dst,
82                                            int level, const char *buf,
83                                            size_t len,
84                                            struct ctrl_iface_priv *priv,
85                                            struct ctrl_iface_global_priv *gp);
86 static int wpas_ctrl_iface_reinit(struct wpa_supplicant *wpa_s,
87                                   struct ctrl_iface_priv *priv);
88 static int wpas_ctrl_iface_global_reinit(struct wpa_global *global,
89                                          struct ctrl_iface_global_priv *priv);
90
91
92 static void wpas_ctrl_sock_debug(const char *title, int sock, const char *buf,
93                                  size_t len)
94 {
95 #ifdef __linux__
96         socklen_t optlen;
97         int sndbuf, outq;
98         int level = MSG_MSGDUMP;
99
100         if (len >= 5 && os_strncmp(buf, "PONG\n", 5) == 0)
101                 level = MSG_EXCESSIVE;
102
103         optlen = sizeof(sndbuf);
104         sndbuf = 0;
105         if (getsockopt(sock, SOL_SOCKET, SO_SNDBUF, &sndbuf, &optlen) < 0)
106                 sndbuf = -1;
107
108         if (ioctl(sock, SIOCOUTQ, &outq) < 0)
109                 outq = -1;
110
111         wpa_printf(level,
112                    "CTRL-DEBUG: %s: sock=%d sndbuf=%d outq=%d send_len=%d",
113                    title, sock, sndbuf, outq, (int) len);
114 #endif /* __linux__ */
115 }
116
117
118 static int wpa_supplicant_ctrl_iface_attach(struct dl_list *ctrl_dst,
119                                             struct sockaddr_un *from,
120                                             socklen_t fromlen, int global)
121 {
122         struct wpa_ctrl_dst *dst;
123         char addr_txt[200];
124
125         dst = os_zalloc(sizeof(*dst));
126         if (dst == NULL)
127                 return -1;
128         os_memcpy(&dst->addr, from, sizeof(struct sockaddr_un));
129         dst->addrlen = fromlen;
130         dst->debug_level = MSG_INFO;
131         dl_list_add(ctrl_dst, &dst->list);
132         printf_encode(addr_txt, sizeof(addr_txt),
133                       (u8 *) from->sun_path,
134                       fromlen - offsetof(struct sockaddr_un, sun_path));
135         wpa_printf(MSG_DEBUG, "CTRL_IFACE %smonitor attached %s",
136                    global ? "global " : "", addr_txt);
137         return 0;
138 }
139
140
141 static int wpa_supplicant_ctrl_iface_detach(struct dl_list *ctrl_dst,
142                                             struct sockaddr_un *from,
143                                             socklen_t fromlen)
144 {
145         struct wpa_ctrl_dst *dst;
146
147         dl_list_for_each(dst, ctrl_dst, struct wpa_ctrl_dst, list) {
148                 if (fromlen == dst->addrlen &&
149                     os_memcmp(from->sun_path, dst->addr.sun_path,
150                               fromlen - offsetof(struct sockaddr_un, sun_path))
151                     == 0) {
152                         char addr_txt[200];
153                         printf_encode(addr_txt, sizeof(addr_txt),
154                                       (u8 *) from->sun_path,
155                                       fromlen -
156                                       offsetof(struct sockaddr_un, sun_path));
157                         wpa_printf(MSG_DEBUG, "CTRL_IFACE monitor detached %s",
158                                    addr_txt);
159                         dl_list_del(&dst->list);
160                         os_free(dst);
161                         return 0;
162                 }
163         }
164         return -1;
165 }
166
167
168 static int wpa_supplicant_ctrl_iface_level(struct ctrl_iface_priv *priv,
169                                            struct sockaddr_un *from,
170                                            socklen_t fromlen,
171                                            char *level)
172 {
173         struct wpa_ctrl_dst *dst;
174
175         wpa_printf(MSG_DEBUG, "CTRL_IFACE LEVEL %s", level);
176
177         dl_list_for_each(dst, &priv->ctrl_dst, struct wpa_ctrl_dst, list) {
178                 if (fromlen == dst->addrlen &&
179                     os_memcmp(from->sun_path, dst->addr.sun_path,
180                               fromlen - offsetof(struct sockaddr_un, sun_path))
181                     == 0) {
182                         char addr_txt[200];
183                         dst->debug_level = atoi(level);
184                         printf_encode(addr_txt, sizeof(addr_txt),
185                                       (u8 *) from->sun_path, fromlen -
186                                       offsetof(struct sockaddr_un, sun_path));
187                         wpa_printf(MSG_DEBUG, "CTRL_IFACE changed monitor level to %d for %s",
188                                    dst->debug_level, addr_txt);
189                         return 0;
190                 }
191         }
192
193         return -1;
194 }
195
196
197 static void wpa_supplicant_ctrl_iface_receive(int sock, void *eloop_ctx,
198                                               void *sock_ctx)
199 {
200         struct wpa_supplicant *wpa_s = eloop_ctx;
201         struct ctrl_iface_priv *priv = sock_ctx;
202         char buf[4096];
203         int res;
204         struct sockaddr_un from;
205         socklen_t fromlen = sizeof(from);
206         char *reply = NULL, *reply_buf = NULL;
207         size_t reply_len = 0;
208         int new_attached = 0;
209
210         res = recvfrom(sock, buf, sizeof(buf) - 1, 0,
211                        (struct sockaddr *) &from, &fromlen);
212         if (res < 0) {
213                 wpa_printf(MSG_ERROR, "recvfrom(ctrl_iface): %s",
214                            strerror(errno));
215                 return;
216         }
217         buf[res] = '\0';
218
219         if (os_strcmp(buf, "ATTACH") == 0) {
220                 if (wpa_supplicant_ctrl_iface_attach(&priv->ctrl_dst, &from,
221                                                      fromlen, 0))
222                         reply_len = 1;
223                 else {
224                         new_attached = 1;
225                         reply_len = 2;
226                 }
227         } else if (os_strcmp(buf, "DETACH") == 0) {
228                 if (wpa_supplicant_ctrl_iface_detach(&priv->ctrl_dst, &from,
229                                                      fromlen))
230                         reply_len = 1;
231                 else
232                         reply_len = 2;
233         } else if (os_strncmp(buf, "LEVEL ", 6) == 0) {
234                 if (wpa_supplicant_ctrl_iface_level(priv, &from, fromlen,
235                                                     buf + 6))
236                         reply_len = 1;
237                 else
238                         reply_len = 2;
239         } else {
240                 reply_buf = wpa_supplicant_ctrl_iface_process(wpa_s, buf,
241                                                               &reply_len);
242                 reply = reply_buf;
243
244                 /*
245                  * There could be some password/key material in the command, so
246                  * clear the buffer explicitly now that it is not needed
247                  * anymore.
248                  */
249                 os_memset(buf, 0, res);
250         }
251
252         if (!reply && reply_len == 1) {
253                 reply = "FAIL\n";
254                 reply_len = 5;
255         } else if (!reply && reply_len == 2) {
256                 reply = "OK\n";
257                 reply_len = 3;
258         }
259
260         if (reply) {
261                 wpas_ctrl_sock_debug("ctrl_sock-sendto", sock, reply,
262                                      reply_len);
263                 if (sendto(sock, reply, reply_len, 0, (struct sockaddr *) &from,
264                            fromlen) < 0) {
265                         int _errno = errno;
266                         wpa_dbg(wpa_s, MSG_DEBUG,
267                                 "ctrl_iface sendto failed: %d - %s",
268                                 _errno, strerror(_errno));
269                         if (_errno == ENOBUFS || _errno == EAGAIN) {
270                                 /*
271                                  * The socket send buffer could be full. This
272                                  * may happen if client programs are not
273                                  * receiving their pending messages. Close and
274                                  * reopen the socket as a workaround to avoid
275                                  * getting stuck being unable to send any new
276                                  * responses.
277                                  */
278                                 sock = wpas_ctrl_iface_reinit(wpa_s, priv);
279                                 if (sock < 0) {
280                                         wpa_dbg(wpa_s, MSG_DEBUG, "Failed to reinitialize ctrl_iface socket");
281                                 }
282                         }
283                         if (new_attached) {
284                                 wpa_dbg(wpa_s, MSG_DEBUG, "Failed to send response to ATTACH - detaching");
285                                 new_attached = 0;
286                                 wpa_supplicant_ctrl_iface_detach(
287                                         &priv->ctrl_dst, &from, fromlen);
288                         }
289                 }
290         }
291         os_free(reply_buf);
292
293         if (new_attached)
294                 eapol_sm_notify_ctrl_attached(wpa_s->eapol);
295 }
296
297
298 static char * wpa_supplicant_ctrl_iface_path(struct wpa_supplicant *wpa_s)
299 {
300         char *buf;
301         size_t len;
302         char *pbuf, *dir = NULL;
303         int res;
304
305         if (wpa_s->conf->ctrl_interface == NULL)
306                 return NULL;
307
308         pbuf = os_strdup(wpa_s->conf->ctrl_interface);
309         if (pbuf == NULL)
310                 return NULL;
311         if (os_strncmp(pbuf, "DIR=", 4) == 0) {
312                 char *gid_str;
313                 dir = pbuf + 4;
314                 gid_str = os_strstr(dir, " GROUP=");
315                 if (gid_str)
316                         *gid_str = '\0';
317         } else
318                 dir = pbuf;
319
320         len = os_strlen(dir) + os_strlen(wpa_s->ifname) + 2;
321         buf = os_malloc(len);
322         if (buf == NULL) {
323                 os_free(pbuf);
324                 return NULL;
325         }
326
327         res = os_snprintf(buf, len, "%s/%s", dir, wpa_s->ifname);
328         if (os_snprintf_error(len, res)) {
329                 os_free(pbuf);
330                 os_free(buf);
331                 return NULL;
332         }
333 #ifdef __CYGWIN__
334         {
335                 /* Windows/WinPcap uses interface names that are not suitable
336                  * as a file name - convert invalid chars to underscores */
337                 char *pos = buf;
338                 while (*pos) {
339                         if (*pos == '\\')
340                                 *pos = '_';
341                         pos++;
342                 }
343         }
344 #endif /* __CYGWIN__ */
345         os_free(pbuf);
346         return buf;
347 }
348
349
350 static int wpas_ctrl_iface_throttle(int sock)
351 {
352 #ifdef __linux__
353         socklen_t optlen;
354         int sndbuf, outq;
355
356         optlen = sizeof(sndbuf);
357         sndbuf = 0;
358         if (getsockopt(sock, SOL_SOCKET, SO_SNDBUF, &sndbuf, &optlen) < 0 ||
359             ioctl(sock, SIOCOUTQ, &outq) < 0 ||
360             sndbuf <= 0 || outq < 0)
361                 return 0;
362         return outq > sndbuf / 2;
363 #else /* __linux__ */
364         return 0;
365 #endif /* __linux__ */
366 }
367
368
369 static void wpas_ctrl_msg_send_pending_global(struct wpa_global *global)
370 {
371         struct ctrl_iface_global_priv *gpriv;
372         struct ctrl_iface_msg *msg;
373
374         gpriv = global->ctrl_iface;
375         while (gpriv && !dl_list_empty(&gpriv->msg_queue) &&
376                !wpas_ctrl_iface_throttle(gpriv->sock)) {
377                 msg = dl_list_first(&gpriv->msg_queue, struct ctrl_iface_msg,
378                                     list);
379                 if (!msg)
380                         break;
381                 dl_list_del(&msg->list);
382                 wpa_supplicant_ctrl_iface_send(
383                         msg->wpa_s,
384                         msg->type != WPA_MSG_PER_INTERFACE ?
385                         NULL : msg->wpa_s->ifname,
386                         gpriv->sock, &gpriv->ctrl_dst, msg->level,
387                         msg->txt, msg->len, NULL, gpriv);
388                 os_free(msg);
389         }
390 }
391
392
393 static void wpas_ctrl_msg_send_pending_iface(struct wpa_supplicant *wpa_s)
394 {
395         struct ctrl_iface_priv *priv;
396         struct ctrl_iface_msg *msg;
397
398         priv = wpa_s->ctrl_iface;
399         while (priv && !dl_list_empty(&priv->msg_queue) &&
400                !wpas_ctrl_iface_throttle(priv->sock)) {
401                 msg = dl_list_first(&priv->msg_queue, struct ctrl_iface_msg,
402                                     list);
403                 if (!msg)
404                         break;
405                 dl_list_del(&msg->list);
406                 wpa_supplicant_ctrl_iface_send(wpa_s, NULL, priv->sock,
407                                                &priv->ctrl_dst, msg->level,
408                                                msg->txt, msg->len, priv, NULL);
409                 os_free(msg);
410         }
411 }
412
413
414 static void wpas_ctrl_msg_queue_timeout(void *eloop_ctx, void *timeout_ctx)
415 {
416         struct wpa_supplicant *wpa_s = eloop_ctx;
417         struct ctrl_iface_priv *priv;
418         struct ctrl_iface_global_priv *gpriv;
419         int sock = -1, gsock = -1;
420
421         wpas_ctrl_msg_send_pending_global(wpa_s->global);
422         wpas_ctrl_msg_send_pending_iface(wpa_s);
423
424         priv = wpa_s->ctrl_iface;
425         if (priv && !dl_list_empty(&priv->msg_queue))
426                 sock = priv->sock;
427
428         gpriv = wpa_s->global->ctrl_iface;
429         if (gpriv && !dl_list_empty(&gpriv->msg_queue))
430                 gsock = gpriv->sock;
431
432         if (sock > -1 || gsock > -1) {
433                 /* Continue pending message transmission from a timeout */
434                 wpa_printf(MSG_MSGDUMP,
435                            "CTRL: Had to throttle pending event message transmission for (sock %d gsock %d)",
436                            sock, gsock);
437                 eloop_register_timeout(0, 20000, wpas_ctrl_msg_queue_timeout,
438                                        wpa_s, NULL);
439         }
440 }
441
442
443 static void wpas_ctrl_msg_queue(struct dl_list *queue,
444                                 struct wpa_supplicant *wpa_s, int level,
445                                 enum wpa_msg_type type,
446                                 const char *txt, size_t len)
447 {
448         struct ctrl_iface_msg *msg;
449
450         msg = os_zalloc(sizeof(*msg) + len);
451         if (!msg)
452                 return;
453
454         msg->wpa_s = wpa_s;
455         msg->level = level;
456         msg->type = type;
457         os_memcpy(msg + 1, txt, len);
458         msg->txt = (const char *) (msg + 1);
459         msg->len = len;
460         dl_list_add_tail(queue, &msg->list);
461         eloop_cancel_timeout(wpas_ctrl_msg_queue_timeout, wpa_s, NULL);
462         eloop_register_timeout(0, 0, wpas_ctrl_msg_queue_timeout, wpa_s, NULL);
463 }
464
465
466 static void wpas_ctrl_msg_queue_limit(unsigned int throttle_count,
467                                       struct dl_list *queue)
468 {
469         struct ctrl_iface_msg *msg;
470
471         if (throttle_count < 2000)
472                 return;
473
474         msg = dl_list_first(queue, struct ctrl_iface_msg, list);
475         if (msg) {
476                 wpa_printf(MSG_DEBUG, "CTRL: Dropped oldest pending message");
477                 dl_list_del(&msg->list);
478                 os_free(msg);
479         }
480 }
481
482
483 static void wpa_supplicant_ctrl_iface_msg_cb(void *ctx, int level,
484                                              enum wpa_msg_type type,
485                                              const char *txt, size_t len)
486 {
487         struct wpa_supplicant *wpa_s = ctx;
488         struct ctrl_iface_priv *priv;
489         struct ctrl_iface_global_priv *gpriv;
490
491         if (wpa_s == NULL)
492                 return;
493
494         gpriv = wpa_s->global->ctrl_iface;
495
496         if (type != WPA_MSG_NO_GLOBAL && gpriv &&
497             !dl_list_empty(&gpriv->ctrl_dst)) {
498                 if (!dl_list_empty(&gpriv->msg_queue) ||
499                     wpas_ctrl_iface_throttle(gpriv->sock)) {
500                         if (gpriv->throttle_count == 0) {
501                                 wpa_printf(MSG_MSGDUMP,
502                                            "CTRL: Had to throttle global event message for sock %d",
503                                            gpriv->sock);
504                         }
505                         gpriv->throttle_count++;
506                         wpas_ctrl_msg_queue_limit(gpriv->throttle_count,
507                                                   &gpriv->msg_queue);
508                         wpas_ctrl_msg_queue(&gpriv->msg_queue, wpa_s, level,
509                                             type, txt, len);
510                 } else {
511                         if (gpriv->throttle_count) {
512                                 wpa_printf(MSG_MSGDUMP,
513                                            "CTRL: Had to throttle %u global event message(s) for sock %d",
514                                            gpriv->throttle_count, gpriv->sock);
515                         }
516                         gpriv->throttle_count = 0;
517                         wpa_supplicant_ctrl_iface_send(
518                                 wpa_s,
519                                 type != WPA_MSG_PER_INTERFACE ?
520                                 NULL : wpa_s->ifname,
521                                 gpriv->sock, &gpriv->ctrl_dst, level,
522                                 txt, len, NULL, gpriv);
523                 }
524         }
525
526         priv = wpa_s->ctrl_iface;
527
528         if (type != WPA_MSG_ONLY_GLOBAL && priv) {
529                 if (!dl_list_empty(&priv->msg_queue) ||
530                     wpas_ctrl_iface_throttle(priv->sock)) {
531                         if (priv->throttle_count == 0) {
532                                 wpa_printf(MSG_MSGDUMP,
533                                            "CTRL: Had to throttle event message for sock %d",
534                                            priv->sock);
535                         }
536                         priv->throttle_count++;
537                         wpas_ctrl_msg_queue_limit(priv->throttle_count,
538                                                   &priv->msg_queue);
539                         wpas_ctrl_msg_queue(&priv->msg_queue, wpa_s, level,
540                                             type, txt, len);
541                 } else {
542                         if (priv->throttle_count) {
543                                 wpa_printf(MSG_MSGDUMP,
544                                            "CTRL: Had to throttle %u event message(s) for sock %d",
545                                            priv->throttle_count, priv->sock);
546                         }
547                         priv->throttle_count = 0;
548                         wpa_supplicant_ctrl_iface_send(wpa_s, NULL, priv->sock,
549                                                        &priv->ctrl_dst, level,
550                                                        txt, len, priv, NULL);
551                 }
552         }
553 }
554
555
556 static int wpas_ctrl_iface_open_sock(struct wpa_supplicant *wpa_s,
557                                      struct ctrl_iface_priv *priv)
558 {
559         struct sockaddr_un addr;
560         char *fname = NULL;
561         gid_t gid = 0;
562         int gid_set = 0;
563         char *buf, *dir = NULL, *gid_str = NULL;
564         struct group *grp;
565         char *endp;
566         int flags;
567
568         buf = os_strdup(wpa_s->conf->ctrl_interface);
569         if (buf == NULL)
570                 goto fail;
571 #ifdef ANDROID
572         os_snprintf(addr.sun_path, sizeof(addr.sun_path), "wpa_%s",
573                     wpa_s->conf->ctrl_interface);
574         priv->sock = android_get_control_socket(addr.sun_path);
575         if (priv->sock >= 0) {
576                 priv->android_control_socket = 1;
577                 goto havesock;
578         }
579 #endif /* ANDROID */
580         if (os_strncmp(buf, "DIR=", 4) == 0) {
581                 dir = buf + 4;
582                 gid_str = os_strstr(dir, " GROUP=");
583                 if (gid_str) {
584                         *gid_str = '\0';
585                         gid_str += 7;
586                 }
587         } else {
588                 dir = buf;
589                 gid_str = wpa_s->conf->ctrl_interface_group;
590         }
591
592         if (mkdir(dir, S_IRWXU | S_IRWXG) < 0) {
593                 if (errno == EEXIST) {
594                         wpa_printf(MSG_DEBUG, "Using existing control "
595                                    "interface directory.");
596                 } else {
597                         wpa_printf(MSG_ERROR, "mkdir[ctrl_interface=%s]: %s",
598                                    dir, strerror(errno));
599                         goto fail;
600                 }
601         }
602
603 #ifdef ANDROID
604         /*
605          * wpa_supplicant is started from /init.*.rc on Android and that seems
606          * to be using umask 0077 which would leave the control interface
607          * directory without group access. This breaks things since Wi-Fi
608          * framework assumes that this directory can be accessed by other
609          * applications in the wifi group. Fix this by adding group access even
610          * if umask value would prevent this.
611          */
612         if (chmod(dir, S_IRWXU | S_IRWXG) < 0) {
613                 wpa_printf(MSG_ERROR, "CTRL: Could not chmod directory: %s",
614                            strerror(errno));
615                 /* Try to continue anyway */
616         }
617 #endif /* ANDROID */
618
619         if (gid_str) {
620                 grp = getgrnam(gid_str);
621                 if (grp) {
622                         gid = grp->gr_gid;
623                         gid_set = 1;
624                         wpa_printf(MSG_DEBUG, "ctrl_interface_group=%d"
625                                    " (from group name '%s')",
626                                    (int) gid, gid_str);
627                 } else {
628                         /* Group name not found - try to parse this as gid */
629                         gid = strtol(gid_str, &endp, 10);
630                         if (*gid_str == '\0' || *endp != '\0') {
631                                 wpa_printf(MSG_ERROR, "CTRL: Invalid group "
632                                            "'%s'", gid_str);
633                                 goto fail;
634                         }
635                         gid_set = 1;
636                         wpa_printf(MSG_DEBUG, "ctrl_interface_group=%d",
637                                    (int) gid);
638                 }
639         }
640
641         if (gid_set && chown(dir, -1, gid) < 0) {
642                 wpa_printf(MSG_ERROR, "chown[ctrl_interface=%s,gid=%d]: %s",
643                            dir, (int) gid, strerror(errno));
644                 goto fail;
645         }
646
647         /* Make sure the group can enter and read the directory */
648         if (gid_set &&
649             chmod(dir, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP) < 0) {
650                 wpa_printf(MSG_ERROR, "CTRL: chmod[ctrl_interface]: %s",
651                            strerror(errno));
652                 goto fail;
653         }
654
655         if (os_strlen(dir) + 1 + os_strlen(wpa_s->ifname) >=
656             sizeof(addr.sun_path)) {
657                 wpa_printf(MSG_ERROR, "ctrl_iface path limit exceeded");
658                 goto fail;
659         }
660
661         priv->sock = socket(PF_UNIX, SOCK_DGRAM, 0);
662         if (priv->sock < 0) {
663                 wpa_printf(MSG_ERROR, "socket(PF_UNIX): %s", strerror(errno));
664                 goto fail;
665         }
666
667         os_memset(&addr, 0, sizeof(addr));
668 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
669         addr.sun_len = sizeof(addr);
670 #endif /* __FreeBSD__ */
671         addr.sun_family = AF_UNIX;
672         fname = wpa_supplicant_ctrl_iface_path(wpa_s);
673         if (fname == NULL)
674                 goto fail;
675         os_strlcpy(addr.sun_path, fname, sizeof(addr.sun_path));
676         if (bind(priv->sock, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
677                 wpa_printf(MSG_DEBUG, "ctrl_iface bind(PF_UNIX) failed: %s",
678                            strerror(errno));
679                 if (connect(priv->sock, (struct sockaddr *) &addr,
680                             sizeof(addr)) < 0) {
681                         wpa_printf(MSG_DEBUG, "ctrl_iface exists, but does not"
682                                    " allow connections - assuming it was left"
683                                    "over from forced program termination");
684                         if (unlink(fname) < 0) {
685                                 wpa_printf(MSG_ERROR,
686                                            "Could not unlink existing ctrl_iface socket '%s': %s",
687                                            fname, strerror(errno));
688                                 goto fail;
689                         }
690                         if (bind(priv->sock, (struct sockaddr *) &addr,
691                                  sizeof(addr)) < 0) {
692                                 wpa_printf(MSG_ERROR, "supp-ctrl-iface-init: bind(PF_UNIX): %s",
693                                            strerror(errno));
694                                 goto fail;
695                         }
696                         wpa_printf(MSG_DEBUG, "Successfully replaced leftover "
697                                    "ctrl_iface socket '%s'", fname);
698                 } else {
699                         wpa_printf(MSG_INFO, "ctrl_iface exists and seems to "
700                                    "be in use - cannot override it");
701                         wpa_printf(MSG_INFO, "Delete '%s' manually if it is "
702                                    "not used anymore", fname);
703                         os_free(fname);
704                         fname = NULL;
705                         goto fail;
706                 }
707         }
708
709         if (gid_set && chown(fname, -1, gid) < 0) {
710                 wpa_printf(MSG_ERROR, "chown[ctrl_interface=%s,gid=%d]: %s",
711                            fname, (int) gid, strerror(errno));
712                 goto fail;
713         }
714
715         if (chmod(fname, S_IRWXU | S_IRWXG) < 0) {
716                 wpa_printf(MSG_ERROR, "chmod[ctrl_interface=%s]: %s",
717                            fname, strerror(errno));
718                 goto fail;
719         }
720         os_free(fname);
721
722 #ifdef ANDROID
723 havesock:
724 #endif /* ANDROID */
725
726         /*
727          * Make socket non-blocking so that we don't hang forever if
728          * target dies unexpectedly.
729          */
730         flags = fcntl(priv->sock, F_GETFL);
731         if (flags >= 0) {
732                 flags |= O_NONBLOCK;
733                 if (fcntl(priv->sock, F_SETFL, flags) < 0) {
734                         wpa_printf(MSG_INFO, "fcntl(ctrl, O_NONBLOCK): %s",
735                                    strerror(errno));
736                         /* Not fatal, continue on.*/
737                 }
738         }
739
740         eloop_register_read_sock(priv->sock, wpa_supplicant_ctrl_iface_receive,
741                                  wpa_s, priv);
742         wpa_msg_register_cb(wpa_supplicant_ctrl_iface_msg_cb);
743
744         os_free(buf);
745         return 0;
746
747 fail:
748         if (priv->sock >= 0) {
749                 close(priv->sock);
750                 priv->sock = -1;
751         }
752         if (fname) {
753                 unlink(fname);
754                 os_free(fname);
755         }
756         os_free(buf);
757         return -1;
758 }
759
760
761 struct ctrl_iface_priv *
762 wpa_supplicant_ctrl_iface_init(struct wpa_supplicant *wpa_s)
763 {
764         struct ctrl_iface_priv *priv;
765
766         priv = os_zalloc(sizeof(*priv));
767         if (priv == NULL)
768                 return NULL;
769         dl_list_init(&priv->ctrl_dst);
770         dl_list_init(&priv->msg_queue);
771         priv->wpa_s = wpa_s;
772         priv->sock = -1;
773
774         if (wpa_s->conf->ctrl_interface == NULL)
775                 return priv;
776
777 #ifdef ANDROID
778         if (wpa_s->global->params.ctrl_interface) {
779                 int same = 0;
780
781                 if (wpa_s->global->params.ctrl_interface[0] == '/') {
782                         if (os_strcmp(wpa_s->global->params.ctrl_interface,
783                                       wpa_s->conf->ctrl_interface) == 0)
784                                 same = 1;
785                 } else if (os_strncmp(wpa_s->global->params.ctrl_interface,
786                                       "@android:", 9) == 0 ||
787                            os_strncmp(wpa_s->global->params.ctrl_interface,
788                                       "@abstract:", 10) == 0) {
789                         char *pos;
790
791                         /*
792                          * Currently, Android uses @android:wpa_* as the naming
793                          * convention for the global ctrl interface. This logic
794                          * needs to be revisited if the above naming convention
795                          * is modified.
796                          */
797                         pos = os_strchr(wpa_s->global->params.ctrl_interface,
798                                         '_');
799                         if (pos &&
800                             os_strcmp(pos + 1,
801                                       wpa_s->conf->ctrl_interface) == 0)
802                                 same = 1;
803                 }
804
805                 if (same) {
806                         /*
807                          * The invalid configuration combination might be
808                          * possible to hit in an Android OTA upgrade case, so
809                          * instead of refusing to start the wpa_supplicant
810                          * process, do not open the per-interface ctrl_iface
811                          * and continue with the global control interface that
812                          * was set from the command line since the Wi-Fi
813                          * framework will use it for operations.
814                          */
815                         wpa_printf(MSG_ERROR,
816                                    "global ctrl interface %s matches ctrl interface %s - do not open per-interface ctrl interface",
817                                    wpa_s->global->params.ctrl_interface,
818                                    wpa_s->conf->ctrl_interface);
819                         return priv;
820                 }
821         }
822 #endif /* ANDROID */
823
824         if (wpas_ctrl_iface_open_sock(wpa_s, priv) < 0) {
825                 os_free(priv);
826                 return NULL;
827         }
828
829         return priv;
830 }
831
832
833 static int wpas_ctrl_iface_reinit(struct wpa_supplicant *wpa_s,
834                                   struct ctrl_iface_priv *priv)
835 {
836         int res;
837
838         if (priv->sock <= 0)
839                 return -1;
840
841         /*
842          * On Android, the control socket being used may be the socket
843          * that is created when wpa_supplicant is started as a /init.*.rc
844          * service. Such a socket is maintained as a key-value pair in
845          * Android's environment. Closing this control socket would leave us
846          * in a bad state with an invalid socket descriptor.
847          */
848         if (priv->android_control_socket)
849                 return priv->sock;
850
851         eloop_unregister_read_sock(priv->sock);
852         close(priv->sock);
853         priv->sock = -1;
854         res = wpas_ctrl_iface_open_sock(wpa_s, priv);
855         if (res < 0)
856                 return -1;
857         return priv->sock;
858 }
859
860
861 void wpa_supplicant_ctrl_iface_deinit(struct ctrl_iface_priv *priv)
862 {
863         struct wpa_ctrl_dst *dst, *prev;
864         struct ctrl_iface_msg *msg, *prev_msg;
865         struct ctrl_iface_global_priv *gpriv;
866
867         if (priv->sock > -1) {
868                 char *fname;
869                 char *buf, *dir = NULL;
870                 eloop_unregister_read_sock(priv->sock);
871                 if (!dl_list_empty(&priv->ctrl_dst)) {
872                         /*
873                          * Wait before closing the control socket if
874                          * there are any attached monitors in order to allow
875                          * them to receive any pending messages.
876                          */
877                         wpa_printf(MSG_DEBUG, "CTRL_IFACE wait for attached "
878                                    "monitors to receive messages");
879                         os_sleep(0, 100000);
880                 }
881                 close(priv->sock);
882                 priv->sock = -1;
883                 fname = wpa_supplicant_ctrl_iface_path(priv->wpa_s);
884                 if (fname) {
885                         unlink(fname);
886                         os_free(fname);
887                 }
888
889                 if (priv->wpa_s->conf->ctrl_interface == NULL)
890                         goto free_dst;
891                 buf = os_strdup(priv->wpa_s->conf->ctrl_interface);
892                 if (buf == NULL)
893                         goto free_dst;
894                 if (os_strncmp(buf, "DIR=", 4) == 0) {
895                         char *gid_str;
896                         dir = buf + 4;
897                         gid_str = os_strstr(dir, " GROUP=");
898                         if (gid_str)
899                                 *gid_str = '\0';
900                 } else
901                         dir = buf;
902
903                 if (rmdir(dir) < 0) {
904                         if (errno == ENOTEMPTY) {
905                                 wpa_printf(MSG_DEBUG, "Control interface "
906                                            "directory not empty - leaving it "
907                                            "behind");
908                         } else {
909                                 wpa_printf(MSG_ERROR,
910                                            "rmdir[ctrl_interface=%s]: %s",
911                                            dir, strerror(errno));
912                         }
913                 }
914                 os_free(buf);
915         }
916
917 free_dst:
918         dl_list_for_each_safe(dst, prev, &priv->ctrl_dst, struct wpa_ctrl_dst,
919                               list) {
920                 dl_list_del(&dst->list);
921                 os_free(dst);
922         }
923         dl_list_for_each_safe(msg, prev_msg, &priv->msg_queue,
924                               struct ctrl_iface_msg, list) {
925                 dl_list_del(&msg->list);
926                 os_free(msg);
927         }
928         gpriv = priv->wpa_s->global->ctrl_iface;
929         if (gpriv) {
930                 dl_list_for_each_safe(msg, prev_msg, &gpriv->msg_queue,
931                                       struct ctrl_iface_msg, list) {
932                         if (msg->wpa_s == priv->wpa_s) {
933                                 dl_list_del(&msg->list);
934                                 os_free(msg);
935                         }
936                 }
937         }
938         eloop_cancel_timeout(wpas_ctrl_msg_queue_timeout, priv->wpa_s, NULL);
939         os_free(priv);
940 }
941
942
943 /**
944  * wpa_supplicant_ctrl_iface_send - Send a control interface packet to monitors
945  * @ifname: Interface name for global control socket or %NULL
946  * @sock: Local socket fd
947  * @ctrl_dst: List of attached listeners
948  * @level: Priority level of the message
949  * @buf: Message data
950  * @len: Message length
951  *
952  * Send a packet to all monitor programs attached to the control interface.
953  */
954 static void wpa_supplicant_ctrl_iface_send(struct wpa_supplicant *wpa_s,
955                                            const char *ifname, int sock,
956                                            struct dl_list *ctrl_dst,
957                                            int level, const char *buf,
958                                            size_t len,
959                                            struct ctrl_iface_priv *priv,
960                                            struct ctrl_iface_global_priv *gp)
961 {
962         struct wpa_ctrl_dst *dst, *next;
963         char levelstr[10];
964         int idx, res;
965         struct msghdr msg;
966         struct iovec io[5];
967
968         if (sock < 0 || dl_list_empty(ctrl_dst))
969                 return;
970
971         res = os_snprintf(levelstr, sizeof(levelstr), "<%d>", level);
972         if (os_snprintf_error(sizeof(levelstr), res))
973                 return;
974         idx = 0;
975         if (ifname) {
976                 io[idx].iov_base = "IFNAME=";
977                 io[idx].iov_len = 7;
978                 idx++;
979                 io[idx].iov_base = (char *) ifname;
980                 io[idx].iov_len = os_strlen(ifname);
981                 idx++;
982                 io[idx].iov_base = " ";
983                 io[idx].iov_len = 1;
984                 idx++;
985         }
986         io[idx].iov_base = levelstr;
987         io[idx].iov_len = os_strlen(levelstr);
988         idx++;
989         io[idx].iov_base = (char *) buf;
990         io[idx].iov_len = len;
991         idx++;
992         os_memset(&msg, 0, sizeof(msg));
993         msg.msg_iov = io;
994         msg.msg_iovlen = idx;
995
996         dl_list_for_each_safe(dst, next, ctrl_dst, struct wpa_ctrl_dst, list) {
997                 int _errno;
998                 char addr_txt[200];
999
1000                 if (level < dst->debug_level)
1001                         continue;
1002
1003                 printf_encode(addr_txt, sizeof(addr_txt),
1004                               (u8 *) dst->addr.sun_path, dst->addrlen -
1005                               offsetof(struct sockaddr_un, sun_path));
1006                 msg.msg_name = (void *) &dst->addr;
1007                 msg.msg_namelen = dst->addrlen;
1008                 wpas_ctrl_sock_debug("ctrl_sock-sendmsg", sock, buf, len);
1009                 if (sendmsg(sock, &msg, MSG_DONTWAIT) >= 0) {
1010                         wpa_printf(MSG_MSGDUMP,
1011                                    "CTRL_IFACE monitor sent successfully to %s",
1012                                    addr_txt);
1013                         dst->errors = 0;
1014                         continue;
1015                 }
1016
1017                 _errno = errno;
1018                 wpa_printf(MSG_DEBUG, "CTRL_IFACE monitor[%s]: %d - %s",
1019                            addr_txt, errno, strerror(errno));
1020                 dst->errors++;
1021
1022                 if (dst->errors > 10 || _errno == ENOENT || _errno == EPERM) {
1023                         wpa_printf(MSG_INFO, "CTRL_IFACE: Detach monitor %s that cannot receive messages",
1024                                 addr_txt);
1025                         wpa_supplicant_ctrl_iface_detach(ctrl_dst, &dst->addr,
1026                                                          dst->addrlen);
1027                 }
1028
1029                 if (_errno == ENOBUFS || _errno == EAGAIN) {
1030                         /*
1031                          * The socket send buffer could be full. This may happen
1032                          * if client programs are not receiving their pending
1033                          * messages. Close and reopen the socket as a workaround
1034                          * to avoid getting stuck being unable to send any new
1035                          * responses.
1036                          */
1037                         if (priv)
1038                                 sock = wpas_ctrl_iface_reinit(wpa_s, priv);
1039                         else if (gp)
1040                                 sock = wpas_ctrl_iface_global_reinit(
1041                                         wpa_s->global, gp);
1042                         else
1043                                 break;
1044                         if (sock < 0) {
1045                                 wpa_dbg(wpa_s, MSG_DEBUG,
1046                                         "Failed to reinitialize ctrl_iface socket");
1047                                 break;
1048                         }
1049                 }
1050         }
1051 }
1052
1053
1054 void wpa_supplicant_ctrl_iface_wait(struct ctrl_iface_priv *priv)
1055 {
1056         char buf[256];
1057         int res;
1058         struct sockaddr_un from;
1059         socklen_t fromlen = sizeof(from);
1060
1061         if (priv->sock == -1)
1062                 return;
1063
1064         for (;;) {
1065                 wpa_printf(MSG_DEBUG, "CTRL_IFACE - %s - wait for monitor to "
1066                            "attach", priv->wpa_s->ifname);
1067                 eloop_wait_for_read_sock(priv->sock);
1068
1069                 res = recvfrom(priv->sock, buf, sizeof(buf) - 1, 0,
1070                                (struct sockaddr *) &from, &fromlen);
1071                 if (res < 0) {
1072                         wpa_printf(MSG_ERROR, "recvfrom(ctrl_iface): %s",
1073                                    strerror(errno));
1074                         continue;
1075                 }
1076                 buf[res] = '\0';
1077
1078                 if (os_strcmp(buf, "ATTACH") == 0) {
1079                         /* handle ATTACH signal of first monitor interface */
1080                         if (!wpa_supplicant_ctrl_iface_attach(&priv->ctrl_dst,
1081                                                               &from, fromlen,
1082                                                               0)) {
1083                                 if (sendto(priv->sock, "OK\n", 3, 0,
1084                                            (struct sockaddr *) &from, fromlen) <
1085                                     0) {
1086                                         wpa_printf(MSG_DEBUG, "ctrl_iface sendto failed: %s",
1087                                                    strerror(errno));
1088                                 }
1089                                 /* OK to continue */
1090                                 return;
1091                         } else {
1092                                 if (sendto(priv->sock, "FAIL\n", 5, 0,
1093                                            (struct sockaddr *) &from, fromlen) <
1094                                     0) {
1095                                         wpa_printf(MSG_DEBUG, "ctrl_iface sendto failed: %s",
1096                                                    strerror(errno));
1097                                 }
1098                         }
1099                 } else {
1100                         /* return FAIL for all other signals */
1101                         if (sendto(priv->sock, "FAIL\n", 5, 0,
1102                                    (struct sockaddr *) &from, fromlen) < 0) {
1103                                 wpa_printf(MSG_DEBUG,
1104                                            "ctrl_iface sendto failed: %s",
1105                                            strerror(errno));
1106                         }
1107                 }
1108         }
1109 }
1110
1111
1112 /* Global ctrl_iface */
1113
1114 static void wpa_supplicant_global_ctrl_iface_receive(int sock, void *eloop_ctx,
1115                                                      void *sock_ctx)
1116 {
1117         struct wpa_global *global = eloop_ctx;
1118         struct ctrl_iface_global_priv *priv = sock_ctx;
1119         char buf[4096];
1120         int res;
1121         struct sockaddr_un from;
1122         socklen_t fromlen = sizeof(from);
1123         char *reply = NULL, *reply_buf = NULL;
1124         size_t reply_len;
1125
1126         res = recvfrom(sock, buf, sizeof(buf) - 1, 0,
1127                        (struct sockaddr *) &from, &fromlen);
1128         if (res < 0) {
1129                 wpa_printf(MSG_ERROR, "recvfrom(ctrl_iface): %s",
1130                            strerror(errno));
1131                 return;
1132         }
1133         buf[res] = '\0';
1134
1135         if (os_strcmp(buf, "ATTACH") == 0) {
1136                 if (wpa_supplicant_ctrl_iface_attach(&priv->ctrl_dst, &from,
1137                                                      fromlen, 1))
1138                         reply_len = 1;
1139                 else
1140                         reply_len = 2;
1141         } else if (os_strcmp(buf, "DETACH") == 0) {
1142                 if (wpa_supplicant_ctrl_iface_detach(&priv->ctrl_dst, &from,
1143                                                      fromlen))
1144                         reply_len = 1;
1145                 else
1146                         reply_len = 2;
1147         } else {
1148                 reply_buf = wpa_supplicant_global_ctrl_iface_process(
1149                         global, buf, &reply_len);
1150                 reply = reply_buf;
1151
1152                 /*
1153                  * There could be some password/key material in the command, so
1154                  * clear the buffer explicitly now that it is not needed
1155                  * anymore.
1156                  */
1157                 os_memset(buf, 0, res);
1158         }
1159
1160         if (!reply && reply_len == 1) {
1161                 reply = "FAIL\n";
1162                 reply_len = 5;
1163         } else if (!reply && reply_len == 2) {
1164                 reply = "OK\n";
1165                 reply_len = 3;
1166         }
1167
1168         if (reply) {
1169                 wpas_ctrl_sock_debug("global_ctrl_sock-sendto",
1170                                      sock, reply, reply_len);
1171                 if (sendto(sock, reply, reply_len, 0, (struct sockaddr *) &from,
1172                            fromlen) < 0) {
1173                         wpa_printf(MSG_DEBUG, "ctrl_iface sendto failed: %s",
1174                                 strerror(errno));
1175                 }
1176         }
1177         os_free(reply_buf);
1178 }
1179
1180
1181 static int wpas_global_ctrl_iface_open_sock(struct wpa_global *global,
1182                                             struct ctrl_iface_global_priv *priv)
1183 {
1184         struct sockaddr_un addr;
1185         const char *ctrl = global->params.ctrl_interface;
1186         int flags;
1187
1188         wpa_printf(MSG_DEBUG, "Global control interface '%s'", ctrl);
1189
1190 #ifdef ANDROID
1191         if (os_strncmp(ctrl, "@android:", 9) == 0) {
1192                 priv->sock = android_get_control_socket(ctrl + 9);
1193                 if (priv->sock < 0) {
1194                         wpa_printf(MSG_ERROR, "Failed to open Android control "
1195                                    "socket '%s'", ctrl + 9);
1196                         goto fail;
1197                 }
1198                 wpa_printf(MSG_DEBUG, "Using Android control socket '%s'",
1199                            ctrl + 9);
1200                 priv->android_control_socket = 1;
1201                 goto havesock;
1202         }
1203
1204         if (os_strncmp(ctrl, "@abstract:", 10) != 0) {
1205                 /*
1206                  * Backwards compatibility - try to open an Android control
1207                  * socket and if that fails, assume this was a UNIX domain
1208                  * socket instead.
1209                  */
1210                 priv->sock = android_get_control_socket(ctrl);
1211                 if (priv->sock >= 0) {
1212                         wpa_printf(MSG_DEBUG,
1213                                    "Using Android control socket '%s'",
1214                                    ctrl);
1215                         priv->android_control_socket = 1;
1216                         goto havesock;
1217                 }
1218         }
1219 #endif /* ANDROID */
1220
1221         priv->sock = socket(PF_UNIX, SOCK_DGRAM, 0);
1222         if (priv->sock < 0) {
1223                 wpa_printf(MSG_ERROR, "socket(PF_UNIX): %s", strerror(errno));
1224                 goto fail;
1225         }
1226
1227         os_memset(&addr, 0, sizeof(addr));
1228 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1229         addr.sun_len = sizeof(addr);
1230 #endif /* __FreeBSD__ */
1231         addr.sun_family = AF_UNIX;
1232
1233         if (os_strncmp(ctrl, "@abstract:", 10) == 0) {
1234                 addr.sun_path[0] = '\0';
1235                 os_strlcpy(addr.sun_path + 1, ctrl + 10,
1236                            sizeof(addr.sun_path) - 1);
1237                 if (bind(priv->sock, (struct sockaddr *) &addr, sizeof(addr)) <
1238                     0) {
1239                         wpa_printf(MSG_ERROR, "supp-global-ctrl-iface-init: "
1240                                    "bind(PF_UNIX;%s) failed: %s",
1241                                    ctrl, strerror(errno));
1242                         goto fail;
1243                 }
1244                 wpa_printf(MSG_DEBUG, "Using Abstract control socket '%s'",
1245                            ctrl + 10);
1246                 goto havesock;
1247         }
1248
1249         os_strlcpy(addr.sun_path, ctrl, sizeof(addr.sun_path));
1250         if (bind(priv->sock, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
1251                 wpa_printf(MSG_INFO, "supp-global-ctrl-iface-init(%s) (will try fixup): bind(PF_UNIX): %s",
1252                            ctrl, strerror(errno));
1253                 if (connect(priv->sock, (struct sockaddr *) &addr,
1254                             sizeof(addr)) < 0) {
1255                         wpa_printf(MSG_DEBUG, "ctrl_iface exists, but does not"
1256                                    " allow connections - assuming it was left"
1257                                    "over from forced program termination");
1258                         if (unlink(ctrl) < 0) {
1259                                 wpa_printf(MSG_ERROR,
1260                                            "Could not unlink existing ctrl_iface socket '%s': %s",
1261                                            ctrl, strerror(errno));
1262                                 goto fail;
1263                         }
1264                         if (bind(priv->sock, (struct sockaddr *) &addr,
1265                                  sizeof(addr)) < 0) {
1266                                 wpa_printf(MSG_ERROR, "supp-glb-iface-init: bind(PF_UNIX;%s): %s",
1267                                            ctrl, strerror(errno));
1268                                 goto fail;
1269                         }
1270                         wpa_printf(MSG_DEBUG, "Successfully replaced leftover "
1271                                    "ctrl_iface socket '%s'",
1272                                    ctrl);
1273                 } else {
1274                         wpa_printf(MSG_INFO, "ctrl_iface exists and seems to "
1275                                    "be in use - cannot override it");
1276                         wpa_printf(MSG_INFO, "Delete '%s' manually if it is "
1277                                    "not used anymore",
1278                                    ctrl);
1279                         goto fail;
1280                 }
1281         }
1282
1283         wpa_printf(MSG_DEBUG, "Using UNIX control socket '%s'", ctrl);
1284
1285         if (global->params.ctrl_interface_group) {
1286                 char *gid_str = global->params.ctrl_interface_group;
1287                 gid_t gid = 0;
1288                 struct group *grp;
1289                 char *endp;
1290
1291                 grp = getgrnam(gid_str);
1292                 if (grp) {
1293                         gid = grp->gr_gid;
1294                         wpa_printf(MSG_DEBUG, "ctrl_interface_group=%d"
1295                                    " (from group name '%s')",
1296                                    (int) gid, gid_str);
1297                 } else {
1298                         /* Group name not found - try to parse this as gid */
1299                         gid = strtol(gid_str, &endp, 10);
1300                         if (*gid_str == '\0' || *endp != '\0') {
1301                                 wpa_printf(MSG_ERROR, "CTRL: Invalid group "
1302                                            "'%s'", gid_str);
1303                                 goto fail;
1304                         }
1305                         wpa_printf(MSG_DEBUG, "ctrl_interface_group=%d",
1306                                    (int) gid);
1307                 }
1308                 if (chown(ctrl, -1, gid) < 0) {
1309                         wpa_printf(MSG_ERROR,
1310                                    "chown[global_ctrl_interface=%s,gid=%d]: %s",
1311                                    ctrl, (int) gid, strerror(errno));
1312                         goto fail;
1313                 }
1314
1315                 if (chmod(ctrl, S_IRWXU | S_IRWXG) < 0) {
1316                         wpa_printf(MSG_ERROR,
1317                                    "chmod[global_ctrl_interface=%s]: %s",
1318                                    ctrl, strerror(errno));
1319                         goto fail;
1320                 }
1321         } else {
1322                 if (chmod(ctrl, S_IRWXU) < 0) {
1323                         wpa_printf(MSG_DEBUG,
1324                                    "chmod[global_ctrl_interface=%s](S_IRWXU): %s",
1325                                    ctrl, strerror(errno));
1326                         /* continue anyway since group change was not required
1327                          */
1328                 }
1329         }
1330
1331 havesock:
1332
1333         /*
1334          * Make socket non-blocking so that we don't hang forever if
1335          * target dies unexpectedly.
1336          */
1337         flags = fcntl(priv->sock, F_GETFL);
1338         if (flags >= 0) {
1339                 flags |= O_NONBLOCK;
1340                 if (fcntl(priv->sock, F_SETFL, flags) < 0) {
1341                         wpa_printf(MSG_INFO, "fcntl(ctrl, O_NONBLOCK): %s",
1342                                    strerror(errno));
1343                         /* Not fatal, continue on.*/
1344                 }
1345         }
1346
1347         eloop_register_read_sock(priv->sock,
1348                                  wpa_supplicant_global_ctrl_iface_receive,
1349                                  global, priv);
1350
1351         return 0;
1352
1353 fail:
1354         if (priv->sock >= 0) {
1355                 close(priv->sock);
1356                 priv->sock = -1;
1357         }
1358         return -1;
1359 }
1360
1361
1362 struct ctrl_iface_global_priv *
1363 wpa_supplicant_global_ctrl_iface_init(struct wpa_global *global)
1364 {
1365         struct ctrl_iface_global_priv *priv;
1366
1367         priv = os_zalloc(sizeof(*priv));
1368         if (priv == NULL)
1369                 return NULL;
1370         dl_list_init(&priv->ctrl_dst);
1371         dl_list_init(&priv->msg_queue);
1372         priv->global = global;
1373         priv->sock = -1;
1374
1375         if (global->params.ctrl_interface == NULL)
1376                 return priv;
1377
1378         if (wpas_global_ctrl_iface_open_sock(global, priv) < 0) {
1379                 os_free(priv);
1380                 return NULL;
1381         }
1382
1383         wpa_msg_register_cb(wpa_supplicant_ctrl_iface_msg_cb);
1384
1385         return priv;
1386 }
1387
1388
1389 static int wpas_ctrl_iface_global_reinit(struct wpa_global *global,
1390                                          struct ctrl_iface_global_priv *priv)
1391 {
1392         int res;
1393
1394         if (priv->sock <= 0)
1395                 return -1;
1396
1397         /*
1398          * On Android, the control socket being used may be the socket
1399          * that is created when wpa_supplicant is started as a /init.*.rc
1400          * service. Such a socket is maintained as a key-value pair in
1401          * Android's environment. Closing this control socket would leave us
1402          * in a bad state with an invalid socket descriptor.
1403          */
1404         if (priv->android_control_socket)
1405                 return priv->sock;
1406
1407         eloop_unregister_read_sock(priv->sock);
1408         close(priv->sock);
1409         priv->sock = -1;
1410         res = wpas_global_ctrl_iface_open_sock(global, priv);
1411         if (res < 0)
1412                 return -1;
1413         return priv->sock;
1414 }
1415
1416
1417 void
1418 wpa_supplicant_global_ctrl_iface_deinit(struct ctrl_iface_global_priv *priv)
1419 {
1420         struct wpa_ctrl_dst *dst, *prev;
1421         struct ctrl_iface_msg *msg, *prev_msg;
1422
1423         if (priv->sock >= 0) {
1424                 eloop_unregister_read_sock(priv->sock);
1425                 close(priv->sock);
1426         }
1427         if (priv->global->params.ctrl_interface)
1428                 unlink(priv->global->params.ctrl_interface);
1429         dl_list_for_each_safe(dst, prev, &priv->ctrl_dst, struct wpa_ctrl_dst,
1430                               list) {
1431                 dl_list_del(&dst->list);
1432                 os_free(dst);
1433         }
1434         dl_list_for_each_safe(msg, prev_msg, &priv->msg_queue,
1435                               struct ctrl_iface_msg, list) {
1436                 dl_list_del(&msg->list);
1437                 os_free(msg);
1438         }
1439         os_free(priv);
1440 }