Re-open ctrl_iface socket on some failure cases as a workaround
[mech_eap.git] / wpa_supplicant / ctrl_iface_unix.c
1 /*
2  * WPA Supplicant / UNIX domain socket -based control interface
3  * Copyright (c) 2004-2013, 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 ANDROID
17 #include <cutils/sockets.h>
18 #endif /* ANDROID */
19
20 #include "utils/common.h"
21 #include "utils/eloop.h"
22 #include "utils/list.h"
23 #include "eapol_supp/eapol_supp_sm.h"
24 #include "config.h"
25 #include "wpa_supplicant_i.h"
26 #include "ctrl_iface.h"
27
28 /* Per-interface ctrl_iface */
29
30 /**
31  * struct wpa_ctrl_dst - Internal data structure of control interface monitors
32  *
33  * This structure is used to store information about registered control
34  * interface monitors into struct wpa_supplicant. This data is private to
35  * ctrl_iface_unix.c and should not be touched directly from other files.
36  */
37 struct wpa_ctrl_dst {
38         struct dl_list list;
39         struct sockaddr_un addr;
40         socklen_t addrlen;
41         int debug_level;
42         int errors;
43 };
44
45
46 struct ctrl_iface_priv {
47         struct wpa_supplicant *wpa_s;
48         int sock;
49         struct dl_list ctrl_dst;
50 };
51
52
53 struct ctrl_iface_global_priv {
54         struct wpa_global *global;
55         int sock;
56         struct dl_list ctrl_dst;
57 };
58
59
60 static void wpa_supplicant_ctrl_iface_send(struct wpa_supplicant *wpa_s,
61                                            const char *ifname, int sock,
62                                            struct dl_list *ctrl_dst,
63                                            int level, const char *buf,
64                                            size_t len,
65                                            struct ctrl_iface_priv *priv,
66                                            struct ctrl_iface_global_priv *gp);
67 static int wpas_ctrl_iface_reinit(struct wpa_supplicant *wpa_s,
68                                   struct ctrl_iface_priv *priv);
69 static int wpas_ctrl_iface_global_reinit(struct wpa_global *global,
70                                          struct ctrl_iface_global_priv *priv);
71
72
73 static int wpa_supplicant_ctrl_iface_attach(struct dl_list *ctrl_dst,
74                                             struct sockaddr_un *from,
75                                             socklen_t fromlen)
76 {
77         struct wpa_ctrl_dst *dst;
78
79         dst = os_zalloc(sizeof(*dst));
80         if (dst == NULL)
81                 return -1;
82         os_memcpy(&dst->addr, from, sizeof(struct sockaddr_un));
83         dst->addrlen = fromlen;
84         dst->debug_level = MSG_INFO;
85         dl_list_add(ctrl_dst, &dst->list);
86         wpa_hexdump(MSG_DEBUG, "CTRL_IFACE monitor attached",
87                     (u8 *) from->sun_path,
88                     fromlen - offsetof(struct sockaddr_un, sun_path));
89         return 0;
90 }
91
92
93 static int wpa_supplicant_ctrl_iface_detach(struct dl_list *ctrl_dst,
94                                             struct sockaddr_un *from,
95                                             socklen_t fromlen)
96 {
97         struct wpa_ctrl_dst *dst;
98
99         dl_list_for_each(dst, ctrl_dst, struct wpa_ctrl_dst, list) {
100                 if (fromlen == dst->addrlen &&
101                     os_memcmp(from->sun_path, dst->addr.sun_path,
102                               fromlen - offsetof(struct sockaddr_un, sun_path))
103                     == 0) {
104                         wpa_hexdump(MSG_DEBUG, "CTRL_IFACE monitor detached",
105                                     (u8 *) from->sun_path,
106                                     fromlen -
107                                     offsetof(struct sockaddr_un, sun_path));
108                         dl_list_del(&dst->list);
109                         os_free(dst);
110                         return 0;
111                 }
112         }
113         return -1;
114 }
115
116
117 static int wpa_supplicant_ctrl_iface_level(struct ctrl_iface_priv *priv,
118                                            struct sockaddr_un *from,
119                                            socklen_t fromlen,
120                                            char *level)
121 {
122         struct wpa_ctrl_dst *dst;
123
124         wpa_printf(MSG_DEBUG, "CTRL_IFACE LEVEL %s", level);
125
126         dl_list_for_each(dst, &priv->ctrl_dst, struct wpa_ctrl_dst, list) {
127                 if (fromlen == dst->addrlen &&
128                     os_memcmp(from->sun_path, dst->addr.sun_path,
129                               fromlen - offsetof(struct sockaddr_un, sun_path))
130                     == 0) {
131                         wpa_hexdump(MSG_DEBUG, "CTRL_IFACE changed monitor "
132                                     "level", (u8 *) from->sun_path,
133                                     fromlen -
134                                     offsetof(struct sockaddr_un, sun_path));
135                         dst->debug_level = atoi(level);
136                         return 0;
137                 }
138         }
139
140         return -1;
141 }
142
143
144 static void wpa_supplicant_ctrl_iface_receive(int sock, void *eloop_ctx,
145                                               void *sock_ctx)
146 {
147         struct wpa_supplicant *wpa_s = eloop_ctx;
148         struct ctrl_iface_priv *priv = sock_ctx;
149         char buf[4096];
150         int res;
151         struct sockaddr_un from;
152         socklen_t fromlen = sizeof(from);
153         char *reply = NULL, *reply_buf = NULL;
154         size_t reply_len = 0;
155         int new_attached = 0;
156
157         res = recvfrom(sock, buf, sizeof(buf) - 1, 0,
158                        (struct sockaddr *) &from, &fromlen);
159         if (res < 0) {
160                 wpa_printf(MSG_ERROR, "recvfrom(ctrl_iface): %s",
161                            strerror(errno));
162                 return;
163         }
164         buf[res] = '\0';
165
166         if (os_strcmp(buf, "ATTACH") == 0) {
167                 if (wpa_supplicant_ctrl_iface_attach(&priv->ctrl_dst, &from,
168                                                      fromlen))
169                         reply_len = 1;
170                 else {
171                         new_attached = 1;
172                         reply_len = 2;
173                 }
174         } else if (os_strcmp(buf, "DETACH") == 0) {
175                 if (wpa_supplicant_ctrl_iface_detach(&priv->ctrl_dst, &from,
176                                                      fromlen))
177                         reply_len = 1;
178                 else
179                         reply_len = 2;
180         } else if (os_strncmp(buf, "LEVEL ", 6) == 0) {
181                 if (wpa_supplicant_ctrl_iface_level(priv, &from, fromlen,
182                                                     buf + 6))
183                         reply_len = 1;
184                 else
185                         reply_len = 2;
186         } else {
187                 reply_buf = wpa_supplicant_ctrl_iface_process(wpa_s, buf,
188                                                               &reply_len);
189                 reply = reply_buf;
190         }
191
192         if (!reply && reply_len == 1) {
193                 reply = "FAIL\n";
194                 reply_len = 5;
195         } else if (!reply && reply_len == 2) {
196                 reply = "OK\n";
197                 reply_len = 3;
198         }
199
200         if (reply) {
201                 if (sendto(sock, reply, reply_len, 0, (struct sockaddr *) &from,
202                            fromlen) < 0) {
203                         int _errno = errno;
204                         wpa_dbg(wpa_s, MSG_DEBUG,
205                                 "ctrl_iface sendto failed: %d - %s",
206                                 _errno, strerror(_errno));
207                         if (_errno == ENOBUFS || _errno == EAGAIN) {
208                                 /*
209                                  * The socket send buffer could be full. This
210                                  * may happen if client programs are not
211                                  * receiving their pending messages. Close and
212                                  * reopen the socket as a workaround to avoid
213                                  * getting stuck being unable to send any new
214                                  * responses.
215                                  */
216                                 sock = wpas_ctrl_iface_reinit(wpa_s, priv);
217                                 if (sock < 0) {
218                                         wpa_dbg(wpa_s, MSG_DEBUG, "Failed to reinitialize ctrl_iface socket");
219                                 }
220                         }
221                         if (new_attached) {
222                                 wpa_dbg(wpa_s, MSG_DEBUG, "Failed to send response to ATTACH - detaching");
223                                 new_attached = 0;
224                                 wpa_supplicant_ctrl_iface_detach(
225                                         &priv->ctrl_dst, &from, fromlen);
226                         }
227                 }
228         }
229         os_free(reply_buf);
230
231         if (new_attached)
232                 eapol_sm_notify_ctrl_attached(wpa_s->eapol);
233 }
234
235
236 static char * wpa_supplicant_ctrl_iface_path(struct wpa_supplicant *wpa_s)
237 {
238         char *buf;
239         size_t len;
240         char *pbuf, *dir = NULL, *gid_str = NULL;
241         int res;
242
243         if (wpa_s->conf->ctrl_interface == NULL)
244                 return NULL;
245
246         pbuf = os_strdup(wpa_s->conf->ctrl_interface);
247         if (pbuf == NULL)
248                 return NULL;
249         if (os_strncmp(pbuf, "DIR=", 4) == 0) {
250                 dir = pbuf + 4;
251                 gid_str = os_strstr(dir, " GROUP=");
252                 if (gid_str) {
253                         *gid_str = '\0';
254                         gid_str += 7;
255                 }
256         } else
257                 dir = pbuf;
258
259         len = os_strlen(dir) + os_strlen(wpa_s->ifname) + 2;
260         buf = os_malloc(len);
261         if (buf == NULL) {
262                 os_free(pbuf);
263                 return NULL;
264         }
265
266         res = os_snprintf(buf, len, "%s/%s", dir, wpa_s->ifname);
267         if (res < 0 || (size_t) res >= len) {
268                 os_free(pbuf);
269                 os_free(buf);
270                 return NULL;
271         }
272 #ifdef __CYGWIN__
273         {
274                 /* Windows/WinPcap uses interface names that are not suitable
275                  * as a file name - convert invalid chars to underscores */
276                 char *pos = buf;
277                 while (*pos) {
278                         if (*pos == '\\')
279                                 *pos = '_';
280                         pos++;
281                 }
282         }
283 #endif /* __CYGWIN__ */
284         os_free(pbuf);
285         return buf;
286 }
287
288
289 static void wpa_supplicant_ctrl_iface_msg_cb(void *ctx, int level, int global,
290                                              const char *txt, size_t len)
291 {
292         struct wpa_supplicant *wpa_s = ctx;
293
294         if (wpa_s == NULL)
295                 return;
296
297         if (global != 2 && wpa_s->global->ctrl_iface) {
298                 struct ctrl_iface_global_priv *priv = wpa_s->global->ctrl_iface;
299                 if (!dl_list_empty(&priv->ctrl_dst)) {
300                         wpa_supplicant_ctrl_iface_send(wpa_s, global ? NULL :
301                                                        wpa_s->ifname,
302                                                        priv->sock,
303                                                        &priv->ctrl_dst,
304                                                        level, txt, len, NULL,
305                                                        priv);
306                 }
307         }
308
309         if (wpa_s->ctrl_iface == NULL)
310                 return;
311         wpa_supplicant_ctrl_iface_send(wpa_s, NULL, wpa_s->ctrl_iface->sock,
312                                        &wpa_s->ctrl_iface->ctrl_dst,
313                                        level, txt, len, wpa_s->ctrl_iface,
314                                        NULL);
315 }
316
317
318 static int wpas_ctrl_iface_open_sock(struct wpa_supplicant *wpa_s,
319                                      struct ctrl_iface_priv *priv)
320 {
321         struct sockaddr_un addr;
322         char *fname = NULL;
323         gid_t gid = 0;
324         int gid_set = 0;
325         char *buf, *dir = NULL, *gid_str = NULL;
326         struct group *grp;
327         char *endp;
328         int flags;
329
330         buf = os_strdup(wpa_s->conf->ctrl_interface);
331         if (buf == NULL)
332                 goto fail;
333 #ifdef ANDROID
334         os_snprintf(addr.sun_path, sizeof(addr.sun_path), "wpa_%s",
335                     wpa_s->conf->ctrl_interface);
336         priv->sock = android_get_control_socket(addr.sun_path);
337         if (priv->sock >= 0)
338                 goto havesock;
339 #endif /* ANDROID */
340         if (os_strncmp(buf, "DIR=", 4) == 0) {
341                 dir = buf + 4;
342                 gid_str = os_strstr(dir, " GROUP=");
343                 if (gid_str) {
344                         *gid_str = '\0';
345                         gid_str += 7;
346                 }
347         } else {
348                 dir = buf;
349                 gid_str = wpa_s->conf->ctrl_interface_group;
350         }
351
352         if (mkdir(dir, S_IRWXU | S_IRWXG) < 0) {
353                 if (errno == EEXIST) {
354                         wpa_printf(MSG_DEBUG, "Using existing control "
355                                    "interface directory.");
356                 } else {
357                         wpa_printf(MSG_ERROR, "mkdir[ctrl_interface=%s]: %s",
358                                    dir, strerror(errno));
359                         goto fail;
360                 }
361         }
362
363 #ifdef ANDROID
364         /*
365          * wpa_supplicant is started from /init.*.rc on Android and that seems
366          * to be using umask 0077 which would leave the control interface
367          * directory without group access. This breaks things since Wi-Fi
368          * framework assumes that this directory can be accessed by other
369          * applications in the wifi group. Fix this by adding group access even
370          * if umask value would prevent this.
371          */
372         if (chmod(dir, S_IRWXU | S_IRWXG) < 0) {
373                 wpa_printf(MSG_ERROR, "CTRL: Could not chmod directory: %s",
374                            strerror(errno));
375                 /* Try to continue anyway */
376         }
377 #endif /* ANDROID */
378
379         if (gid_str) {
380                 grp = getgrnam(gid_str);
381                 if (grp) {
382                         gid = grp->gr_gid;
383                         gid_set = 1;
384                         wpa_printf(MSG_DEBUG, "ctrl_interface_group=%d"
385                                    " (from group name '%s')",
386                                    (int) gid, gid_str);
387                 } else {
388                         /* Group name not found - try to parse this as gid */
389                         gid = strtol(gid_str, &endp, 10);
390                         if (*gid_str == '\0' || *endp != '\0') {
391                                 wpa_printf(MSG_ERROR, "CTRL: Invalid group "
392                                            "'%s'", gid_str);
393                                 goto fail;
394                         }
395                         gid_set = 1;
396                         wpa_printf(MSG_DEBUG, "ctrl_interface_group=%d",
397                                    (int) gid);
398                 }
399         }
400
401         if (gid_set && chown(dir, -1, gid) < 0) {
402                 wpa_printf(MSG_ERROR, "chown[ctrl_interface=%s,gid=%d]: %s",
403                            dir, (int) gid, strerror(errno));
404                 goto fail;
405         }
406
407         /* Make sure the group can enter and read the directory */
408         if (gid_set &&
409             chmod(dir, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP) < 0) {
410                 wpa_printf(MSG_ERROR, "CTRL: chmod[ctrl_interface]: %s",
411                            strerror(errno));
412                 goto fail;
413         }
414
415         if (os_strlen(dir) + 1 + os_strlen(wpa_s->ifname) >=
416             sizeof(addr.sun_path)) {
417                 wpa_printf(MSG_ERROR, "ctrl_iface path limit exceeded");
418                 goto fail;
419         }
420
421         priv->sock = socket(PF_UNIX, SOCK_DGRAM, 0);
422         if (priv->sock < 0) {
423                 wpa_printf(MSG_ERROR, "socket(PF_UNIX): %s", strerror(errno));
424                 goto fail;
425         }
426
427         os_memset(&addr, 0, sizeof(addr));
428 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
429         addr.sun_len = sizeof(addr);
430 #endif /* __FreeBSD__ */
431         addr.sun_family = AF_UNIX;
432         fname = wpa_supplicant_ctrl_iface_path(wpa_s);
433         if (fname == NULL)
434                 goto fail;
435         os_strlcpy(addr.sun_path, fname, sizeof(addr.sun_path));
436         if (bind(priv->sock, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
437                 wpa_printf(MSG_DEBUG, "ctrl_iface bind(PF_UNIX) failed: %s",
438                            strerror(errno));
439                 if (connect(priv->sock, (struct sockaddr *) &addr,
440                             sizeof(addr)) < 0) {
441                         wpa_printf(MSG_DEBUG, "ctrl_iface exists, but does not"
442                                    " allow connections - assuming it was left"
443                                    "over from forced program termination");
444                         if (unlink(fname) < 0) {
445                                 wpa_printf(MSG_ERROR,
446                                            "Could not unlink existing ctrl_iface socket '%s': %s",
447                                            fname, strerror(errno));
448                                 goto fail;
449                         }
450                         if (bind(priv->sock, (struct sockaddr *) &addr,
451                                  sizeof(addr)) < 0) {
452                                 wpa_printf(MSG_ERROR, "supp-ctrl-iface-init: bind(PF_UNIX): %s",
453                                            strerror(errno));
454                                 goto fail;
455                         }
456                         wpa_printf(MSG_DEBUG, "Successfully replaced leftover "
457                                    "ctrl_iface socket '%s'", fname);
458                 } else {
459                         wpa_printf(MSG_INFO, "ctrl_iface exists and seems to "
460                                    "be in use - cannot override it");
461                         wpa_printf(MSG_INFO, "Delete '%s' manually if it is "
462                                    "not used anymore", fname);
463                         os_free(fname);
464                         fname = NULL;
465                         goto fail;
466                 }
467         }
468
469         if (gid_set && chown(fname, -1, gid) < 0) {
470                 wpa_printf(MSG_ERROR, "chown[ctrl_interface=%s,gid=%d]: %s",
471                            fname, (int) gid, strerror(errno));
472                 goto fail;
473         }
474
475         if (chmod(fname, S_IRWXU | S_IRWXG) < 0) {
476                 wpa_printf(MSG_ERROR, "chmod[ctrl_interface=%s]: %s",
477                            fname, strerror(errno));
478                 goto fail;
479         }
480         os_free(fname);
481
482 #ifdef ANDROID
483 havesock:
484 #endif /* ANDROID */
485
486         /*
487          * Make socket non-blocking so that we don't hang forever if
488          * target dies unexpectedly.
489          */
490         flags = fcntl(priv->sock, F_GETFL);
491         if (flags >= 0) {
492                 flags |= O_NONBLOCK;
493                 if (fcntl(priv->sock, F_SETFL, flags) < 0) {
494                         wpa_printf(MSG_INFO, "fcntl(ctrl, O_NONBLOCK): %s",
495                                    strerror(errno));
496                         /* Not fatal, continue on.*/
497                 }
498         }
499
500         eloop_register_read_sock(priv->sock, wpa_supplicant_ctrl_iface_receive,
501                                  wpa_s, priv);
502         wpa_msg_register_cb(wpa_supplicant_ctrl_iface_msg_cb);
503
504         os_free(buf);
505         return 0;
506
507 fail:
508         if (priv->sock >= 0) {
509                 close(priv->sock);
510                 priv->sock = -1;
511         }
512         if (fname) {
513                 unlink(fname);
514                 os_free(fname);
515         }
516         os_free(buf);
517         return -1;
518 }
519
520
521 struct ctrl_iface_priv *
522 wpa_supplicant_ctrl_iface_init(struct wpa_supplicant *wpa_s)
523 {
524         struct ctrl_iface_priv *priv;
525
526         priv = os_zalloc(sizeof(*priv));
527         if (priv == NULL)
528                 return NULL;
529         dl_list_init(&priv->ctrl_dst);
530         priv->wpa_s = wpa_s;
531         priv->sock = -1;
532
533         if (wpa_s->conf->ctrl_interface == NULL)
534                 return priv;
535
536         if (wpas_ctrl_iface_open_sock(wpa_s, priv) < 0) {
537                 os_free(priv);
538                 return NULL;
539         }
540
541         return priv;
542 }
543
544
545 static int wpas_ctrl_iface_reinit(struct wpa_supplicant *wpa_s,
546                                   struct ctrl_iface_priv *priv)
547 {
548         int res;
549
550         if (priv->sock <= 0)
551                 return -1;
552
553         eloop_unregister_read_sock(priv->sock);
554         close(priv->sock);
555         priv->sock = -1;
556         res = wpas_ctrl_iface_open_sock(wpa_s, priv);
557         if (res < 0)
558                 return -1;
559         return priv->sock;
560 }
561
562
563 void wpa_supplicant_ctrl_iface_deinit(struct ctrl_iface_priv *priv)
564 {
565         struct wpa_ctrl_dst *dst, *prev;
566
567         if (priv->sock > -1) {
568                 char *fname;
569                 char *buf, *dir = NULL, *gid_str = NULL;
570                 eloop_unregister_read_sock(priv->sock);
571                 if (!dl_list_empty(&priv->ctrl_dst)) {
572                         /*
573                          * Wait before closing the control socket if
574                          * there are any attached monitors in order to allow
575                          * them to receive any pending messages.
576                          */
577                         wpa_printf(MSG_DEBUG, "CTRL_IFACE wait for attached "
578                                    "monitors to receive messages");
579                         os_sleep(0, 100000);
580                 }
581                 close(priv->sock);
582                 priv->sock = -1;
583                 fname = wpa_supplicant_ctrl_iface_path(priv->wpa_s);
584                 if (fname) {
585                         unlink(fname);
586                         os_free(fname);
587                 }
588
589                 buf = os_strdup(priv->wpa_s->conf->ctrl_interface);
590                 if (buf == NULL)
591                         goto free_dst;
592                 if (os_strncmp(buf, "DIR=", 4) == 0) {
593                         dir = buf + 4;
594                         gid_str = os_strstr(dir, " GROUP=");
595                         if (gid_str) {
596                                 *gid_str = '\0';
597                                 gid_str += 7;
598                         }
599                 } else
600                         dir = buf;
601
602                 if (rmdir(dir) < 0) {
603                         if (errno == ENOTEMPTY) {
604                                 wpa_printf(MSG_DEBUG, "Control interface "
605                                            "directory not empty - leaving it "
606                                            "behind");
607                         } else {
608                                 wpa_printf(MSG_ERROR,
609                                            "rmdir[ctrl_interface=%s]: %s",
610                                            dir, strerror(errno));
611                         }
612                 }
613                 os_free(buf);
614         }
615
616 free_dst:
617         dl_list_for_each_safe(dst, prev, &priv->ctrl_dst, struct wpa_ctrl_dst,
618                               list)
619                 os_free(dst);
620         os_free(priv);
621 }
622
623
624 /**
625  * wpa_supplicant_ctrl_iface_send - Send a control interface packet to monitors
626  * @ifname: Interface name for global control socket or %NULL
627  * @sock: Local socket fd
628  * @ctrl_dst: List of attached listeners
629  * @level: Priority level of the message
630  * @buf: Message data
631  * @len: Message length
632  *
633  * Send a packet to all monitor programs attached to the control interface.
634  */
635 static void wpa_supplicant_ctrl_iface_send(struct wpa_supplicant *wpa_s,
636                                            const char *ifname, int sock,
637                                            struct dl_list *ctrl_dst,
638                                            int level, const char *buf,
639                                            size_t len,
640                                            struct ctrl_iface_priv *priv,
641                                            struct ctrl_iface_global_priv *gp)
642 {
643         struct wpa_ctrl_dst *dst, *next;
644         char levelstr[10];
645         int idx, res;
646         struct msghdr msg;
647         struct iovec io[5];
648
649         if (sock < 0 || dl_list_empty(ctrl_dst))
650                 return;
651
652         res = os_snprintf(levelstr, sizeof(levelstr), "<%d>", level);
653         if (res < 0 || (size_t) res >= sizeof(levelstr))
654                 return;
655         idx = 0;
656         if (ifname) {
657                 io[idx].iov_base = "IFNAME=";
658                 io[idx].iov_len = 7;
659                 idx++;
660                 io[idx].iov_base = (char *) ifname;
661                 io[idx].iov_len = os_strlen(ifname);
662                 idx++;
663                 io[idx].iov_base = " ";
664                 io[idx].iov_len = 1;
665                 idx++;
666         }
667         io[idx].iov_base = levelstr;
668         io[idx].iov_len = os_strlen(levelstr);
669         idx++;
670         io[idx].iov_base = (char *) buf;
671         io[idx].iov_len = len;
672         idx++;
673         os_memset(&msg, 0, sizeof(msg));
674         msg.msg_iov = io;
675         msg.msg_iovlen = idx;
676
677         idx = -1;
678         dl_list_for_each_safe(dst, next, ctrl_dst, struct wpa_ctrl_dst, list) {
679                 int _errno;
680
681                 idx++;
682                 if (level < dst->debug_level)
683                         continue;
684
685                 wpa_hexdump(MSG_DEBUG, "CTRL_IFACE monitor send",
686                             (u8 *) dst->addr.sun_path, dst->addrlen -
687                             offsetof(struct sockaddr_un, sun_path));
688                 msg.msg_name = (void *) &dst->addr;
689                 msg.msg_namelen = dst->addrlen;
690                 if (sendmsg(sock, &msg, MSG_DONTWAIT) >= 0) {
691                         dst->errors = 0;
692                         idx++;
693                         continue;
694                 }
695
696                 _errno = errno;
697                 wpa_printf(MSG_INFO, "CTRL_IFACE monitor[%d]: %d - %s",
698                            idx, errno, strerror(errno));
699                 dst->errors++;
700
701                 if (dst->errors > 10 || _errno == ENOENT || _errno == EPERM) {
702                         wpa_printf(MSG_INFO, "CTRL_IFACE: Detach monitor that cannot receive messages");
703                         wpa_supplicant_ctrl_iface_detach(ctrl_dst, &dst->addr,
704                                                          dst->addrlen);
705                 }
706
707                 if (_errno == ENOBUFS || _errno == EAGAIN) {
708                         /*
709                          * The socket send buffer could be full. This may happen
710                          * if client programs are not receiving their pending
711                          * messages. Close and reopen the socket as a workaround
712                          * to avoid getting stuck being unable to send any new
713                          * responses.
714                          */
715                         if (priv)
716                                 sock = wpas_ctrl_iface_reinit(wpa_s, priv);
717                         else if (gp)
718                                 sock = wpas_ctrl_iface_global_reinit(
719                                         wpa_s->global, gp);
720                         else
721                                 break;
722                         if (sock < 0) {
723                                 wpa_dbg(wpa_s, MSG_DEBUG,
724                                         "Failed to reinitialize ctrl_iface socket");
725                         }
726                 }
727         }
728 }
729
730
731 void wpa_supplicant_ctrl_iface_wait(struct ctrl_iface_priv *priv)
732 {
733         char buf[256];
734         int res;
735         struct sockaddr_un from;
736         socklen_t fromlen = sizeof(from);
737
738         for (;;) {
739                 wpa_printf(MSG_DEBUG, "CTRL_IFACE - %s - wait for monitor to "
740                            "attach", priv->wpa_s->ifname);
741                 eloop_wait_for_read_sock(priv->sock);
742
743                 res = recvfrom(priv->sock, buf, sizeof(buf) - 1, 0,
744                                (struct sockaddr *) &from, &fromlen);
745                 if (res < 0) {
746                         wpa_printf(MSG_ERROR, "recvfrom(ctrl_iface): %s",
747                                    strerror(errno));
748                         continue;
749                 }
750                 buf[res] = '\0';
751
752                 if (os_strcmp(buf, "ATTACH") == 0) {
753                         /* handle ATTACH signal of first monitor interface */
754                         if (!wpa_supplicant_ctrl_iface_attach(&priv->ctrl_dst,
755                                                               &from, fromlen)) {
756                                 if (sendto(priv->sock, "OK\n", 3, 0,
757                                            (struct sockaddr *) &from, fromlen) <
758                                     0) {
759                                         wpa_printf(MSG_DEBUG, "ctrl_iface sendto failed: %s",
760                                                    strerror(errno));
761                                 }
762                                 /* OK to continue */
763                                 return;
764                         } else {
765                                 if (sendto(priv->sock, "FAIL\n", 5, 0,
766                                            (struct sockaddr *) &from, fromlen) <
767                                     0) {
768                                         wpa_printf(MSG_DEBUG, "ctrl_iface sendto failed: %s",
769                                                    strerror(errno));
770                                 }
771                         }
772                 } else {
773                         /* return FAIL for all other signals */
774                         if (sendto(priv->sock, "FAIL\n", 5, 0,
775                                    (struct sockaddr *) &from, fromlen) < 0) {
776                                 wpa_printf(MSG_DEBUG,
777                                            "ctrl_iface sendto failed: %s",
778                                            strerror(errno));
779                         }
780                 }
781         }
782 }
783
784
785 /* Global ctrl_iface */
786
787 static void wpa_supplicant_global_ctrl_iface_receive(int sock, void *eloop_ctx,
788                                                      void *sock_ctx)
789 {
790         struct wpa_global *global = eloop_ctx;
791         struct ctrl_iface_global_priv *priv = sock_ctx;
792         char buf[256];
793         int res;
794         struct sockaddr_un from;
795         socklen_t fromlen = sizeof(from);
796         char *reply = NULL, *reply_buf = NULL;
797         size_t reply_len;
798
799         res = recvfrom(sock, buf, sizeof(buf) - 1, 0,
800                        (struct sockaddr *) &from, &fromlen);
801         if (res < 0) {
802                 wpa_printf(MSG_ERROR, "recvfrom(ctrl_iface): %s",
803                            strerror(errno));
804                 return;
805         }
806         buf[res] = '\0';
807
808         if (os_strcmp(buf, "ATTACH") == 0) {
809                 if (wpa_supplicant_ctrl_iface_attach(&priv->ctrl_dst, &from,
810                                                      fromlen))
811                         reply_len = 1;
812                 else
813                         reply_len = 2;
814         } else if (os_strcmp(buf, "DETACH") == 0) {
815                 if (wpa_supplicant_ctrl_iface_detach(&priv->ctrl_dst, &from,
816                                                      fromlen))
817                         reply_len = 1;
818                 else
819                         reply_len = 2;
820         } else {
821                 reply_buf = wpa_supplicant_global_ctrl_iface_process(
822                         global, buf, &reply_len);
823                 reply = reply_buf;
824         }
825
826         if (!reply && reply_len == 1) {
827                 reply = "FAIL\n";
828                 reply_len = 5;
829         } else if (!reply && reply_len == 2) {
830                 reply = "OK\n";
831                 reply_len = 3;
832         }
833
834         if (reply) {
835                 if (sendto(sock, reply, reply_len, 0, (struct sockaddr *) &from,
836                            fromlen) < 0) {
837                         wpa_printf(MSG_DEBUG, "ctrl_iface sendto failed: %s",
838                                 strerror(errno));
839                 }
840         }
841         os_free(reply_buf);
842 }
843
844
845 static int wpas_global_ctrl_iface_open_sock(struct wpa_global *global,
846                                             struct ctrl_iface_global_priv *priv)
847 {
848         struct sockaddr_un addr;
849         const char *ctrl = global->params.ctrl_interface;
850         int flags;
851
852         wpa_printf(MSG_DEBUG, "Global control interface '%s'", ctrl);
853
854 #ifdef ANDROID
855         if (os_strncmp(ctrl, "@android:", 9) == 0) {
856                 priv->sock = android_get_control_socket(ctrl + 9);
857                 if (priv->sock < 0) {
858                         wpa_printf(MSG_ERROR, "Failed to open Android control "
859                                    "socket '%s'", ctrl + 9);
860                         goto fail;
861                 }
862                 wpa_printf(MSG_DEBUG, "Using Android control socket '%s'",
863                            ctrl + 9);
864                 goto havesock;
865         }
866
867         if (os_strncmp(ctrl, "@abstract:", 10) != 0) {
868                 /*
869                  * Backwards compatibility - try to open an Android control
870                  * socket and if that fails, assume this was a UNIX domain
871                  * socket instead.
872                  */
873                 priv->sock = android_get_control_socket(ctrl);
874                 if (priv->sock >= 0) {
875                         wpa_printf(MSG_DEBUG,
876                                    "Using Android control socket '%s'",
877                                    ctrl);
878                         goto havesock;
879                 }
880         }
881 #endif /* ANDROID */
882
883         priv->sock = socket(PF_UNIX, SOCK_DGRAM, 0);
884         if (priv->sock < 0) {
885                 wpa_printf(MSG_ERROR, "socket(PF_UNIX): %s", strerror(errno));
886                 goto fail;
887         }
888
889         os_memset(&addr, 0, sizeof(addr));
890 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
891         addr.sun_len = sizeof(addr);
892 #endif /* __FreeBSD__ */
893         addr.sun_family = AF_UNIX;
894
895         if (os_strncmp(ctrl, "@abstract:", 10) == 0) {
896                 addr.sun_path[0] = '\0';
897                 os_strlcpy(addr.sun_path + 1, ctrl + 10,
898                            sizeof(addr.sun_path) - 1);
899                 if (bind(priv->sock, (struct sockaddr *) &addr, sizeof(addr)) <
900                     0) {
901                         wpa_printf(MSG_ERROR, "supp-global-ctrl-iface-init: "
902                                    "bind(PF_UNIX;%s) failed: %s",
903                                    ctrl, strerror(errno));
904                         goto fail;
905                 }
906                 wpa_printf(MSG_DEBUG, "Using Abstract control socket '%s'",
907                            ctrl + 10);
908                 goto havesock;
909         }
910
911         os_strlcpy(addr.sun_path, ctrl, sizeof(addr.sun_path));
912         if (bind(priv->sock, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
913                 wpa_printf(MSG_INFO, "supp-global-ctrl-iface-init(%s) (will try fixup): bind(PF_UNIX): %s",
914                            ctrl, strerror(errno));
915                 if (connect(priv->sock, (struct sockaddr *) &addr,
916                             sizeof(addr)) < 0) {
917                         wpa_printf(MSG_DEBUG, "ctrl_iface exists, but does not"
918                                    " allow connections - assuming it was left"
919                                    "over from forced program termination");
920                         if (unlink(ctrl) < 0) {
921                                 wpa_printf(MSG_ERROR,
922                                            "Could not unlink existing ctrl_iface socket '%s': %s",
923                                            ctrl, strerror(errno));
924                                 goto fail;
925                         }
926                         if (bind(priv->sock, (struct sockaddr *) &addr,
927                                  sizeof(addr)) < 0) {
928                                 wpa_printf(MSG_ERROR, "supp-glb-iface-init: bind(PF_UNIX;%s): %s",
929                                            ctrl, strerror(errno));
930                                 goto fail;
931                         }
932                         wpa_printf(MSG_DEBUG, "Successfully replaced leftover "
933                                    "ctrl_iface socket '%s'",
934                                    ctrl);
935                 } else {
936                         wpa_printf(MSG_INFO, "ctrl_iface exists and seems to "
937                                    "be in use - cannot override it");
938                         wpa_printf(MSG_INFO, "Delete '%s' manually if it is "
939                                    "not used anymore",
940                                    ctrl);
941                         goto fail;
942                 }
943         }
944
945         wpa_printf(MSG_DEBUG, "Using UNIX control socket '%s'", ctrl);
946
947         if (global->params.ctrl_interface_group) {
948                 char *gid_str = global->params.ctrl_interface_group;
949                 gid_t gid = 0;
950                 struct group *grp;
951                 char *endp;
952
953                 grp = getgrnam(gid_str);
954                 if (grp) {
955                         gid = grp->gr_gid;
956                         wpa_printf(MSG_DEBUG, "ctrl_interface_group=%d"
957                                    " (from group name '%s')",
958                                    (int) gid, gid_str);
959                 } else {
960                         /* Group name not found - try to parse this as gid */
961                         gid = strtol(gid_str, &endp, 10);
962                         if (*gid_str == '\0' || *endp != '\0') {
963                                 wpa_printf(MSG_ERROR, "CTRL: Invalid group "
964                                            "'%s'", gid_str);
965                                 goto fail;
966                         }
967                         wpa_printf(MSG_DEBUG, "ctrl_interface_group=%d",
968                                    (int) gid);
969                 }
970                 if (chown(ctrl, -1, gid) < 0) {
971                         wpa_printf(MSG_ERROR,
972                                    "chown[global_ctrl_interface=%s,gid=%d]: %s",
973                                    ctrl, (int) gid, strerror(errno));
974                         goto fail;
975                 }
976
977                 if (chmod(ctrl, S_IRWXU | S_IRWXG) < 0) {
978                         wpa_printf(MSG_ERROR,
979                                    "chmod[global_ctrl_interface=%s]: %s",
980                                    ctrl, strerror(errno));
981                         goto fail;
982                 }
983         } else {
984                 chmod(ctrl, S_IRWXU);
985         }
986
987 havesock:
988
989         /*
990          * Make socket non-blocking so that we don't hang forever if
991          * target dies unexpectedly.
992          */
993         flags = fcntl(priv->sock, F_GETFL);
994         if (flags >= 0) {
995                 flags |= O_NONBLOCK;
996                 if (fcntl(priv->sock, F_SETFL, flags) < 0) {
997                         wpa_printf(MSG_INFO, "fcntl(ctrl, O_NONBLOCK): %s",
998                                    strerror(errno));
999                         /* Not fatal, continue on.*/
1000                 }
1001         }
1002
1003         eloop_register_read_sock(priv->sock,
1004                                  wpa_supplicant_global_ctrl_iface_receive,
1005                                  global, priv);
1006
1007         return 0;
1008
1009 fail:
1010         if (priv->sock >= 0) {
1011                 close(priv->sock);
1012                 priv->sock = -1;
1013         }
1014         return -1;
1015 }
1016
1017
1018 struct ctrl_iface_global_priv *
1019 wpa_supplicant_global_ctrl_iface_init(struct wpa_global *global)
1020 {
1021         struct ctrl_iface_global_priv *priv;
1022
1023         priv = os_zalloc(sizeof(*priv));
1024         if (priv == NULL)
1025                 return NULL;
1026         dl_list_init(&priv->ctrl_dst);
1027         priv->global = global;
1028         priv->sock = -1;
1029
1030         if (global->params.ctrl_interface == NULL)
1031                 return priv;
1032
1033         if (wpas_global_ctrl_iface_open_sock(global, priv) < 0) {
1034                 os_free(priv);
1035                 return NULL;
1036         }
1037
1038         return priv;
1039 }
1040
1041
1042 static int wpas_ctrl_iface_global_reinit(struct wpa_global *global,
1043                                          struct ctrl_iface_global_priv *priv)
1044 {
1045         int res;
1046
1047         if (priv->sock <= 0)
1048                 return -1;
1049
1050         eloop_unregister_read_sock(priv->sock);
1051         close(priv->sock);
1052         priv->sock = -1;
1053         res = wpas_global_ctrl_iface_open_sock(global, priv);
1054         if (res < 0)
1055                 return -1;
1056         return priv->sock;
1057 }
1058
1059
1060 void
1061 wpa_supplicant_global_ctrl_iface_deinit(struct ctrl_iface_global_priv *priv)
1062 {
1063         struct wpa_ctrl_dst *dst, *prev;
1064
1065         if (priv->sock >= 0) {
1066                 eloop_unregister_read_sock(priv->sock);
1067                 close(priv->sock);
1068         }
1069         if (priv->global->params.ctrl_interface)
1070                 unlink(priv->global->params.ctrl_interface);
1071         dl_list_for_each_safe(dst, prev, &priv->ctrl_dst, struct wpa_ctrl_dst,
1072                               list)
1073                 os_free(dst);
1074         os_free(priv);
1075 }