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