• source navigation  • diff markup  • identifier search  • freetext search  • 

Sources/iwinfo/iwinfo_nl80211.c

  1 /*
  2  * iwinfo - Wireless Information Library - NL80211 Backend
  3  *
  4  *   Copyright (C) 2010-2013 Jo-Philipp Wich <xm@subsignal.org>
  5  *
  6  * The iwinfo library is free software: you can redistribute it and/or
  7  * modify it under the terms of the GNU General Public License version 2
  8  * as published by the Free Software Foundation.
  9  *
 10  * The iwinfo library is distributed in the hope that it will be useful,
 11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
 12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 13  * See the GNU General Public License for more details.
 14  *
 15  * You should have received a copy of the GNU General Public License along
 16  * with the iwinfo library. If not, see http://www.gnu.org/licenses/.
 17  *
 18  * The signal handling code is derived from the official madwifi tools,
 19  * wlanconfig.c in particular. The encryption property handling was
 20  * inspired by the hostapd madwifi driver.
 21  *
 22  * Parts of this code are derived from the Linux iw utility.
 23  */
 24 
 25 #include <sys/stat.h>
 26 #include <limits.h>
 27 #include <glob.h>
 28 #include <fnmatch.h>
 29 #include <stdarg.h>
 30 #include <stdlib.h>
 31 
 32 #include "iwinfo_nl80211.h"
 33 
 34 #define min(x, y) ((x) < (y)) ? (x) : (y)
 35 
 36 #define BIT(x) (1ULL<<(x))
 37 
 38 static struct nl80211_state *nls = NULL;
 39 
 40 static void nl80211_close(void)
 41 {
 42         if (nls)
 43         {
 44                 if (nls->nlctrl)
 45                         genl_family_put(nls->nlctrl);
 46 
 47                 if (nls->nl80211)
 48                         genl_family_put(nls->nl80211);
 49 
 50                 if (nls->nl_sock)
 51                         nl_socket_free(nls->nl_sock);
 52 
 53                 if (nls->nl_cache)
 54                         nl_cache_free(nls->nl_cache);
 55 
 56                 free(nls);
 57                 nls = NULL;
 58         }
 59 }
 60 
 61 static int nl80211_init(void)
 62 {
 63         int err, fd;
 64 
 65         if (!nls)
 66         {
 67                 nls = malloc(sizeof(struct nl80211_state));
 68                 if (!nls) {
 69                         err = -ENOMEM;
 70                         goto err;
 71                 }
 72 
 73                 memset(nls, 0, sizeof(*nls));
 74 
 75                 nls->nl_sock = nl_socket_alloc();
 76                 if (!nls->nl_sock) {
 77                         err = -ENOMEM;
 78                         goto err;
 79                 }
 80 
 81                 if (genl_connect(nls->nl_sock)) {
 82                         err = -ENOLINK;
 83                         goto err;
 84                 }
 85 
 86                 fd = nl_socket_get_fd(nls->nl_sock);
 87                 if (fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC) < 0) {
 88                         err = -EINVAL;
 89                         goto err;
 90                 }
 91 
 92                 if (genl_ctrl_alloc_cache(nls->nl_sock, &nls->nl_cache)) {
 93                         err = -ENOMEM;
 94                         goto err;
 95                 }
 96 
 97                 nls->nl80211 = genl_ctrl_search_by_name(nls->nl_cache, "nl80211");
 98                 if (!nls->nl80211) {
 99                         err = -ENOENT;
100                         goto err;
101                 }
102 
103                 nls->nlctrl = genl_ctrl_search_by_name(nls->nl_cache, "nlctrl");
104                 if (!nls->nlctrl) {
105                         err = -ENOENT;
106                         goto err;
107                 }
108         }
109 
110         return 0;
111 
112 
113 err:
114         nl80211_close();
115         return err;
116 }
117 
118 static int nl80211_readint(const char *path)
119 {
120         int fd;
121         int rv = -1;
122         char buffer[16];
123 
124         if ((fd = open(path, O_RDONLY)) > -1)
125         {
126                 if (read(fd, buffer, sizeof(buffer)) > 0)
127                         rv = atoi(buffer);
128 
129                 close(fd);
130         }
131 
132         return rv;
133 }
134 
135 static int nl80211_readstr(const char *path, char *buffer, int length)
136 {
137         int fd;
138         int rv = -1;
139 
140         if ((fd = open(path, O_RDONLY)) > -1)
141         {
142                 if ((rv = read(fd, buffer, length - 1)) > 0)
143                 {
144                         if (buffer[rv - 1] == '\n')
145                                 rv--;
146 
147                         buffer[rv] = 0;
148                 }
149 
150                 close(fd);
151         }
152 
153         return rv;
154 }
155 
156 static int nl80211_get_band(int nla_type)
157 {
158         switch (nla_type)
159         {
160         case NL80211_BAND_2GHZ:
161                 return IWINFO_BAND_24;
162         case NL80211_BAND_5GHZ:
163                 return IWINFO_BAND_5;
164         case NL80211_BAND_6GHZ:
165                 return IWINFO_BAND_6;
166         case NL80211_BAND_60GHZ:
167                 return IWINFO_BAND_60;
168         }
169 
170         return 0;
171 }
172 
173 
174 static int nl80211_msg_error(struct sockaddr_nl *nla,
175         struct nlmsgerr *err, void *arg)
176 {
177         int *ret = arg;
178         *ret = err->error;
179         return NL_STOP;
180 }
181 
182 static int nl80211_msg_finish(struct nl_msg *msg, void *arg)
183 {
184         int *ret = arg;
185         *ret = 0;
186         return NL_SKIP;
187 }
188 
189 static int nl80211_msg_ack(struct nl_msg *msg, void *arg)
190 {
191         int *ret = arg;
192         *ret = 0;
193         return NL_STOP;
194 }
195 
196 static int nl80211_msg_response(struct nl_msg *msg, void *arg)
197 {
198         return NL_SKIP;
199 }
200 
201 static void nl80211_free(struct nl80211_msg_conveyor *cv)
202 {
203         if (cv)
204         {
205                 if (cv->cb)
206                         nl_cb_put(cv->cb);
207 
208                 if (cv->msg)
209                         nlmsg_free(cv->msg);
210 
211                 cv->cb  = NULL;
212                 cv->msg = NULL;
213         }
214 }
215 
216 static struct nl80211_msg_conveyor * nl80211_new(struct genl_family *family,
217                                                  int cmd, int flags)
218 {
219         static struct nl80211_msg_conveyor cv;
220 
221         struct nl_msg *req = NULL;
222         struct nl_cb *cb = NULL;
223 
224         req = nlmsg_alloc();
225         if (!req)
226                 goto err;
227 
228         cb = nl_cb_alloc(NL_CB_DEFAULT);
229         if (!cb)
230                 goto err;
231 
232         genlmsg_put(req, 0, 0, genl_family_get_id(family), 0, flags, cmd, 0);
233 
234         cv.msg = req;
235         cv.cb  = cb;
236 
237         return &cv;
238 
239 err:
240         if (req)
241                 nlmsg_free(req);
242 
243         return NULL;
244 }
245 
246 static struct nl80211_msg_conveyor * nl80211_ctl(int cmd, int flags)
247 {
248         if (nl80211_init() < 0)
249                 return NULL;
250 
251         return nl80211_new(nls->nlctrl, cmd, flags);
252 }
253 
254 static const char *nl80211_phy_path_str(const char *phyname)
255 {
256         static char path[PATH_MAX];
257         const char *prefix = "/sys/devices/";
258         int prefix_len = strlen(prefix);
259         int buf_len, offset;
260         struct dirent *e;
261         char buf[512], *link;
262         int phy_idx;
263         int seq = 0;
264         DIR *d;
265 
266         snprintf(buf, sizeof(buf), "/sys/class/ieee80211/%s/index", phyname);
267         phy_idx = nl80211_readint(buf);
268         if (phy_idx < 0)
269                 return NULL;
270 
271         buf_len = snprintf(buf, sizeof(buf), "/sys/class/ieee80211/%s/device", phyname);
272         link = realpath(buf, path);
273         if (!link)
274                 return NULL;
275 
276         if (strncmp(link, prefix, prefix_len) != 0)
277                 return NULL;
278 
279         link += prefix_len;
280 
281         prefix = "platform/";
282         prefix_len = strlen(prefix);
283         if (!strncmp(link, prefix, prefix_len) && strstr(link, "/pci"))
284                 link += prefix_len;
285 
286         snprintf(buf + buf_len, sizeof(buf) - buf_len, "/ieee80211");
287         d = opendir(buf);
288         if (!d)
289                 return link;
290 
291         while ((e = readdir(d)) != NULL) {
292                 int cur_idx;
293 
294                 snprintf(buf, sizeof(buf), "/sys/class/ieee80211/%s/index", e->d_name);
295                 cur_idx = nl80211_readint(buf);
296                 if (cur_idx < 0)
297                         continue;
298 
299                 if (cur_idx >= phy_idx)
300                         continue;
301 
302                 seq++;
303         }
304 
305         closedir(d);
306 
307         if (!seq)
308                 return link;
309 
310         offset = link - path + strlen(link);
311         snprintf(path + offset, sizeof(path) - offset, "+%d", seq);
312 
313         return link;
314 }
315 
316 static int nl80211_phy_idx_from_path(const char *path)
317 {
318         char buf[512];
319         struct dirent *e;
320         const char *cur_path;
321         int cur_path_len;
322         int path_len;
323         int idx = -1;
324         DIR *d;
325 
326         if (!path)
327                 return -1;
328 
329         path_len = strlen(path);
330         if (!path_len)
331                 return -1;
332 
333         d = opendir("/sys/class/ieee80211");
334         if (!d)
335                 return -1;
336 
337         while ((e = readdir(d)) != NULL) {
338                 cur_path = nl80211_phy_path_str(e->d_name);
339                 if (!cur_path)
340                         continue;
341 
342                 cur_path_len = strlen(cur_path);
343                 if (cur_path_len < path_len)
344                         continue;
345 
346                 if (strcmp(cur_path + cur_path_len - path_len, path) != 0)
347                         continue;
348 
349                 snprintf(buf, sizeof(buf), "/sys/class/ieee80211/%s/index", e->d_name);
350                 idx = nl80211_readint(buf);
351 
352                 if (idx >= 0)
353                         break;
354         }
355 
356         closedir(d);
357 
358         return idx;
359 }
360 
361 static int nl80211_phy_idx_from_macaddr(const char *opt)
362 {
363         char buf[128];
364         int i, idx = -1;
365         glob_t gl;
366 
367         if (!opt)
368                 return -1;
369 
370         snprintf(buf, sizeof(buf), "/sys/class/ieee80211/*");
371         if (glob(buf, 0, NULL, &gl))
372                 return -1;
373 
374         for (i = 0; i < gl.gl_pathc; i++)
375         {
376                 snprintf(buf, sizeof(buf), "%s/macaddress", gl.gl_pathv[i]);
377                 if (nl80211_readstr(buf, buf, sizeof(buf)) <= 0)
378                         continue;
379 
380                 if (fnmatch(opt, buf, FNM_CASEFOLD))
381                         continue;
382 
383                 snprintf(buf, sizeof(buf), "%s/index", gl.gl_pathv[i]);
384                 if ((idx = nl80211_readint(buf)) > -1)
385                         break;
386         }
387 
388         globfree(&gl);
389 
390         return idx;
391 }
392 
393 static int nl80211_phy_idx_from_phy(const char *opt)
394 {
395         char buf[128];
396 
397         if (!opt)
398                 return -1;
399 
400         snprintf(buf, sizeof(buf), "/sys/class/ieee80211/%s/index", opt);
401         return nl80211_readint(buf);
402 }
403 
404 static int nl80211_phy_idx_from_uci(const char *name)
405 {
406         struct uci_section *s;
407         const char *opt;
408         int idx = -1;
409 
410         s = iwinfo_uci_get_radio(name, "mac80211");
411         if (!s)
412                 goto out;
413 
414         opt = uci_lookup_option_string(uci_ctx, s, "path");
415         idx = nl80211_phy_idx_from_path(opt);
416         if (idx >= 0)
417                 goto out;
418 
419         opt = uci_lookup_option_string(uci_ctx, s, "macaddr");
420         idx = nl80211_phy_idx_from_macaddr(opt);
421         if (idx >= 0)
422                 goto out;
423 
424         opt = uci_lookup_option_string(uci_ctx, s, "phy");
425         idx = nl80211_phy_idx_from_phy(opt);
426 
427 out:
428         iwinfo_uci_free();
429         return idx;
430 }
431 
432 static bool nl80211_is_ifname(const char *name)
433 {
434         struct stat st;
435         char buffer[PATH_MAX];
436 
437         snprintf(buffer, sizeof(buffer), "/sys/class/net/%s", name);
438         return !lstat(buffer, &st);
439 }
440 
441 static struct nl80211_msg_conveyor * nl80211_msg(const char *ifname,
442                                                  int cmd, int flags)
443 {
444         unsigned int ifidx = 0;
445         int phyidx = -1;
446         struct nl80211_msg_conveyor *cv;
447 
448         if (ifname == NULL)
449                 return NULL;
450 
451         if (nl80211_init() < 0)
452                 return NULL;
453 
454         if (!strncmp(ifname, "mon.", 4))
455                 ifidx = if_nametoindex(&ifname[4]);
456         else if (nl80211_is_ifname(ifname))
457                 ifidx = if_nametoindex(ifname);
458         else
459         {
460                 phyidx = nl80211_phy_idx_from_phy(ifname);
461                 if (phyidx < 0)
462                         phyidx = nl80211_phy_idx_from_uci(ifname);
463         }
464 
465         /* Valid ifidx must be greater than 0 */
466         if ((ifidx <= 0) && (phyidx < 0))
467                 return NULL;
468 
469         cv = nl80211_new(nls->nl80211, cmd, flags);
470         if (!cv)
471                 return NULL;
472 
473         if (ifidx > 0)
474                 NLA_PUT_U32(cv->msg, NL80211_ATTR_IFINDEX, ifidx);
475         else if (phyidx > -1)
476                 NLA_PUT_U32(cv->msg, NL80211_ATTR_WIPHY, phyidx);
477 
478         return cv;
479 
480 nla_put_failure:
481         nl80211_free(cv);
482         return NULL;
483 }
484 
485 static int nl80211_send(struct nl80211_msg_conveyor *cv,
486                         int (*cb_func)(struct nl_msg *, void *),
487                         void *cb_arg)
488 {
489         static struct nl80211_msg_conveyor rcv;
490         int err;
491 
492         if (cb_func)
493                 nl_cb_set(cv->cb, NL_CB_VALID, NL_CB_CUSTOM, cb_func, cb_arg);
494         else
495                 nl_cb_set(cv->cb, NL_CB_VALID, NL_CB_CUSTOM, nl80211_msg_response, &rcv);
496 
497         err = nl_send_auto_complete(nls->nl_sock, cv->msg);
498 
499         if (err < 0)
500                 goto out;
501 
502         err = 1;
503 
504         nl_cb_err(cv->cb,               NL_CB_CUSTOM, nl80211_msg_error,  &err);
505         nl_cb_set(cv->cb, NL_CB_FINISH, NL_CB_CUSTOM, nl80211_msg_finish, &err);
506         nl_cb_set(cv->cb, NL_CB_ACK,    NL_CB_CUSTOM, nl80211_msg_ack,    &err);
507 
508         while (err > 0)
509                 nl_recvmsgs(nls->nl_sock, cv->cb);
510 
511 out:
512         nl80211_free(cv);
513         return err;
514 }
515 
516 static int nl80211_request(const char *ifname, int cmd, int flags,
517                            int (*cb_func)(struct nl_msg *, void *),
518                            void *cb_arg)
519 {
520         struct nl80211_msg_conveyor *cv;
521 
522         cv = nl80211_msg(ifname, cmd, flags);
523 
524         if (!cv)
525                 return -ENOMEM;
526 
527         return nl80211_send(cv, cb_func, cb_arg);
528 }
529 
530 static struct nlattr ** nl80211_parse(struct nl_msg *msg)
531 {
532         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
533         static struct nlattr *attr[NL80211_ATTR_MAX + 1];
534 
535         nla_parse(attr, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
536                   genlmsg_attrlen(gnlh, 0), NULL);
537 
538         return attr;
539 }
540 
541 static int nl80211_get_protocol_features_cb(struct nl_msg *msg, void *arg)
542 {
543         uint32_t *features = arg;
544         struct nlattr **attr = nl80211_parse(msg);
545 
546         if (attr[NL80211_ATTR_PROTOCOL_FEATURES])
547                 *features = nla_get_u32(attr[NL80211_ATTR_PROTOCOL_FEATURES]);
548 
549         return NL_SKIP;
550 }
551 
552 static int nl80211_get_protocol_features(const char *ifname)
553 {
554         struct nl80211_msg_conveyor *req;
555         uint32_t features = 0;
556 
557         req = nl80211_msg(ifname, NL80211_CMD_GET_PROTOCOL_FEATURES, 0);
558         if (req) {
559                 nl80211_send(req, nl80211_get_protocol_features_cb, &features);
560                 nl80211_free(req);
561         }
562 
563         return features;
564 }
565 
566 static int nl80211_subscribe_cb(struct nl_msg *msg, void *arg)
567 {
568         struct nl80211_group_conveyor *cv = arg;
569 
570         struct nlattr **attr = nl80211_parse(msg);
571         struct nlattr *mgrpinfo[CTRL_ATTR_MCAST_GRP_MAX + 1];
572         struct nlattr *mgrp;
573         int mgrpidx;
574 
575         if (!attr[CTRL_ATTR_MCAST_GROUPS])
576                 return NL_SKIP;
577 
578         nla_for_each_nested(mgrp, attr[CTRL_ATTR_MCAST_GROUPS], mgrpidx)
579         {
580                 nla_parse(mgrpinfo, CTRL_ATTR_MCAST_GRP_MAX,
581                           nla_data(mgrp), nla_len(mgrp), NULL);
582 
583                 if (mgrpinfo[CTRL_ATTR_MCAST_GRP_ID] &&
584                     mgrpinfo[CTRL_ATTR_MCAST_GRP_NAME] &&
585                     !strncmp(nla_data(mgrpinfo[CTRL_ATTR_MCAST_GRP_NAME]),
586                              cv->name, nla_len(mgrpinfo[CTRL_ATTR_MCAST_GRP_NAME])))
587                 {
588                         cv->id = nla_get_u32(mgrpinfo[CTRL_ATTR_MCAST_GRP_ID]);
589                         break;
590                 }
591         }
592 
593         return NL_SKIP;
594 }
595 
596 static int nl80211_subscribe(const char *family, const char *group)
597 {
598         struct nl80211_group_conveyor cv = { .name = group, .id = -ENOENT };
599         struct nl80211_msg_conveyor *req;
600         int err;
601 
602         req = nl80211_ctl(CTRL_CMD_GETFAMILY, 0);
603         if (req)
604         {
605                 NLA_PUT_STRING(req->msg, CTRL_ATTR_FAMILY_NAME, family);
606                 err = nl80211_send(req, nl80211_subscribe_cb, &cv);
607 
608                 if (err)
609                         return err;
610 
611                 return nl_socket_add_membership(nls->nl_sock, cv.id);
612 
613 nla_put_failure:
614                 nl80211_free(req);
615         }
616 
617         return -ENOMEM;
618 }
619 
620 
621 static int nl80211_wait_cb(struct nl_msg *msg, void *arg)
622 {
623         struct nl80211_event_conveyor *cv = arg;
624         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
625 
626         if (cv->wait[gnlh->cmd / 32] & (1 << (gnlh->cmd % 32)))
627                 cv->recv = gnlh->cmd;
628 
629         return NL_SKIP;
630 }
631 
632 static int nl80211_wait_seq_check(struct nl_msg *msg, void *arg)
633 {
634         return NL_OK;
635 }
636 
637 static int __nl80211_wait(const char *family, const char *group, ...)
638 {
639         struct nl80211_event_conveyor cv = { };
640         struct nl_cb *cb;
641         int err = 0;
642         int cmd;
643         va_list ap;
644 
645         if (nl80211_subscribe(family, group))
646                 return -ENOENT;
647 
648         cb = nl_cb_alloc(NL_CB_DEFAULT);
649 
650         if (!cb)
651                 return -ENOMEM;
652 
653         nl_cb_err(cb,                  NL_CB_CUSTOM, nl80211_msg_error,      &err);
654         nl_cb_set(cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM, nl80211_wait_seq_check, NULL);
655         nl_cb_set(cb, NL_CB_VALID,     NL_CB_CUSTOM, nl80211_wait_cb,        &cv );
656 
657         va_start(ap, group);
658 
659         for (cmd = va_arg(ap, int); cmd != 0; cmd = va_arg(ap, int))
660                 cv.wait[cmd / 32] |= (1 << (cmd % 32));
661 
662         va_end(ap);
663 
664         while (!cv.recv && !err)
665                 nl_recvmsgs(nls->nl_sock, cb);
666 
667         nl_cb_put(cb);
668 
669         return err;
670 }
671 
672 #define nl80211_wait(family, group, ...) \
673         __nl80211_wait(family, group, __VA_ARGS__, 0)
674 
675 /* This is linux's ieee80211_freq_khz_to_channel() which is:
676  * SPDX-License-Identifier: GPL-2.0
677  * Copyright 2007-2009 Johannes Berg <johannes@sipsolutions.net>
678  * Copyright 2013-2014 Intel Mobile Communications GmbH
679  * Copyright 2017 Intel Deutschland GmbH
680  * Copyright (C) 2018-2022 Intel Corporation
681  */
682 static int nl80211_freq2channel(int freq)
683 {
684         if (freq == 2484)
685                 return 14;
686         else if (freq < 2484)
687                 return (freq - 2407) / 5;
688         else if (freq >= 4910 && freq <= 4980)
689                 return (freq - 4000) / 5;
690         else if (freq < 5925)
691                 return (freq - 5000) / 5;
692         else if (freq == 5935)
693                 return 2;
694         else if (freq <= 45000) /* DMG band lower limit */
695                 /* see 802.11ax D6.1 27.3.22.2 */
696                 return (freq - 5950) / 5;
697         else if (freq >= 58320 && freq <= 70200)
698                 return (freq - 56160) / 2160;
699         else
700                 return 0;
701 }
702 
703 /* This is linux's ieee80211_channel_to_freq_khz() which is:
704  * SPDX-License-Identifier: GPL-2.0
705  * Copyright 2007-2009 Johannes Berg <johannes@sipsolutions.net>
706  * Copyright 2013-2014 Intel Mobile Communications GmbH
707  * Copyright 2017 Intel Deutschland GmbH
708  * Copyright (C) 2018-2022 Intel Corporation
709  */
710 static int nl80211_channel2freq(int channel, const char *band, bool ax)
711 {
712         if (channel < 1)
713                 return 0;
714 
715         if (!band || band[0] != 'a')
716         {
717                 if (channel == 14)
718                         return 2484;
719                 else if (channel < 14)
720                         return (channel * 5) + 2407;
721         }
722         else if (strcmp(band, "ad")  == 0)
723         {
724                 if (channel < 7)
725                         return 56160 + 2160 * channel;
726         }
727         else if (ax)
728         {
729                 if (channel == 2)
730                         return 5935;
731                 if (channel < 233)
732                         return (channel * 5) + 5950;
733         }
734         else
735         {
736                 if (channel >= 182 && channel <= 196)
737                         return (channel * 5) + 4000;
738                 else
739                         return (channel * 5) + 5000;
740         }
741 
742         return 0;
743 }
744 
745 static uint8_t nl80211_freq2band(int freq)
746 {
747         if (freq >= 2412 && freq <= 2484)
748                 return IWINFO_BAND_24;
749         else if (freq >= 5160 && freq <= 5885)
750                 return IWINFO_BAND_5;
751         else if (freq >= 5925 && freq <= 7125)
752                 return IWINFO_BAND_6;
753         else if (freq >= 58320 && freq <= 69120)
754                 return IWINFO_BAND_60;
755 
756         return 0;
757 }
758 
759 static int nl80211_phyname_cb(struct nl_msg *msg, void *arg)
760 {
761         char *buf = arg;
762         struct nlattr **attr = nl80211_parse(msg);
763 
764         if (attr[NL80211_ATTR_WIPHY_NAME])
765                 memcpy(buf, nla_data(attr[NL80211_ATTR_WIPHY_NAME]),
766                        nla_len(attr[NL80211_ATTR_WIPHY_NAME]));
767         else
768                 buf[0] = 0;
769 
770         return NL_SKIP;
771 }
772 
773 static char * nl80211_ifname2phy(const char *ifname)
774 {
775         static char phy[32] = { 0 };
776 
777         memset(phy, 0, sizeof(phy));
778 
779         nl80211_request(ifname, NL80211_CMD_GET_WIPHY, 0,
780                         nl80211_phyname_cb, phy);
781 
782         return phy[0] ? phy : NULL;
783 }
784 
785 static char * nl80211_phyidx2name(unsigned int idx)
786 {
787         struct nl80211_msg_conveyor *cv;
788         static char phy[32] = { 0 };
789 
790         if (nl80211_init() < 0)
791                 return NULL;
792 
793         cv = nl80211_new(nls->nl80211, NL80211_CMD_GET_WIPHY, 0);
794         if (!cv)
795                 return NULL;
796 
797         NLA_PUT_U32(cv->msg, NL80211_ATTR_WIPHY, idx);
798 
799         memset(phy, 0, sizeof(phy));
800         nl80211_send(cv, nl80211_phyname_cb, phy);
801 
802         return phy[0] ? phy : NULL;
803 
804 nla_put_failure:
805         return NULL;
806 }
807 
808 static char * nl80211_phy2ifname(const char *ifname)
809 {
810         int ifidx = -1, cifidx, lmode = 1, clmode, phyidx;
811         char buffer[512];
812         static char nif[IFNAMSIZ] = { 0 };
813         DIR *d;
814         struct dirent *e;
815 
816         /* Only accept phy name in the form of phy%d or radio%d */
817         if (!ifname)
818                 return NULL;
819 
820         phyidx = nl80211_phy_idx_from_phy(ifname);
821         if (phyidx < 0)
822                 phyidx = nl80211_phy_idx_from_uci(ifname);;
823         if (phyidx < 0)
824                 return NULL;
825 
826         memset(nif, 0, sizeof(nif));
827 
828         snprintf(buffer, sizeof(buffer),
829                  "/sys/class/ieee80211/phy%d/device/net", phyidx);
830 
831         if ((d = opendir(buffer)) != NULL)
832         {
833                 while ((e = readdir(d)) != NULL)
834                 {
835                         snprintf(buffer, sizeof(buffer),
836                                  "/sys/class/net/%s/ifindex", e->d_name);
837                         cifidx = nl80211_readint(buffer);
838 
839                         if (cifidx < 0)
840                                 continue;
841 
842                         snprintf(buffer, sizeof(buffer),
843                                  "/sys/class/net/%s/link_mode", e->d_name);
844                         clmode = nl80211_readint(buffer);
845 
846                         /* prefer non-supplicant-based devices */
847                         if ((ifidx < 0) || (cifidx < ifidx) || ((lmode == 1) && (clmode != 1)))
848                         {
849                                 ifidx = cifidx;
850                                 lmode = clmode;
851                                 strncpy(nif, e->d_name, sizeof(nif) - 1);
852                         }
853                 }
854 
855                 closedir(d);
856         }
857 
858         return nif[0] ? nif : NULL;
859 }
860 
861 static int nl80211_get_mode_cb(struct nl_msg *msg, void *arg)
862 {
863         int *mode = arg;
864         struct nlattr **tb = nl80211_parse(msg);
865         const int ifmodes[NL80211_IFTYPE_MAX + 1] = {
866                 IWINFO_OPMODE_UNKNOWN,          /* unspecified */
867                 IWINFO_OPMODE_ADHOC,            /* IBSS */
868                 IWINFO_OPMODE_CLIENT,           /* managed */
869                 IWINFO_OPMODE_MASTER,           /* AP */
870                 IWINFO_OPMODE_AP_VLAN,          /* AP/VLAN */
871                 IWINFO_OPMODE_WDS,              /* WDS */
872                 IWINFO_OPMODE_MONITOR,          /* monitor */
873                 IWINFO_OPMODE_MESHPOINT,        /* mesh point */
874                 IWINFO_OPMODE_P2P_CLIENT,       /* P2P-client */
875                 IWINFO_OPMODE_P2P_GO,           /* P2P-GO */
876         };
877 
878         if (tb[NL80211_ATTR_IFTYPE])
879                 *mode = ifmodes[nla_get_u32(tb[NL80211_ATTR_IFTYPE])];
880 
881         return NL_SKIP;
882 }
883 
884 
885 static int nl80211_get_mode(const char *ifname, int *buf)
886 {
887         char *res;
888 
889         *buf = IWINFO_OPMODE_UNKNOWN;
890 
891         res = nl80211_phy2ifname(ifname);
892 
893         nl80211_request(res ? res : ifname, NL80211_CMD_GET_INTERFACE, 0,
894                         nl80211_get_mode_cb, buf);
895 
896         return (*buf == IWINFO_OPMODE_UNKNOWN) ? -1 : 0;
897 }
898 
899 static int __nl80211_hostapd_query(const char *ifname, ...)
900 {
901         va_list ap, ap_cur;
902         char *phy, *search, *dest, *key, *val, buf[128];
903         int len, mode, found = 0, match = 1;
904         FILE *fp;
905 
906         if (nl80211_get_mode(ifname, &mode))
907                 return 0;
908 
909         if (mode != IWINFO_OPMODE_MASTER && mode != IWINFO_OPMODE_AP_VLAN)
910                 return 0;
911 
912         phy = nl80211_ifname2phy(ifname);
913 
914         if (!phy)
915                 return 0;
916 
917         snprintf(buf, sizeof(buf), "/var/run/hostapd-%s.conf", phy);
918         fp = fopen(buf, "r");
919 
920         if (!fp)
921                 return 0;
922 
923         va_start(ap, ifname);
924 
925         /* clear all destination buffers */
926         va_copy(ap_cur, ap);
927 
928         while ((search = va_arg(ap_cur, char *)) != NULL)
929         {
930                 dest = va_arg(ap_cur, char *);
931                 len  = va_arg(ap_cur, int);
932 
933                 memset(dest, 0, len);
934         }
935 
936         va_end(ap_cur);
937 
938         /* iterate applicable lines and copy found values into dest buffers */
939         while (fgets(buf, sizeof(buf), fp))
940         {
941                 key = strtok(buf, " =\t\n");
942                 val = strtok(NULL, "\n");
943 
944                 if (!key || !val || !*key || *key == '#')
945                         continue;
946 
947                 if (!strcmp(key, "interface") || !strcmp(key, "bss"))
948                         match = !strcmp(ifname, val);
949 
950                 if (!match)
951                         continue;
952 
953                 va_copy(ap_cur, ap);
954 
955                 while ((search = va_arg(ap_cur, char *)) != NULL)
956                 {
957                         dest = va_arg(ap_cur, char *);
958                         len  = va_arg(ap_cur, int);
959 
960                         if (!strcmp(search, key))
961                         {
962                                 strncpy(dest, val, len - 1);
963                                 found++;
964                                 break;
965                         }
966                 }
967 
968                 va_end(ap_cur);
969         }
970 
971         fclose(fp);
972 
973         va_end(ap);
974 
975         return found;
976 }
977 
978 #define nl80211_hostapd_query(ifname, ...) \
979         __nl80211_hostapd_query(ifname, ##__VA_ARGS__, NULL)
980 
981 
982 static inline int nl80211_wpactl_recv(int sock, char *buf, int blen)
983 {
984         fd_set rfds;
985         struct timeval tv = { 0, 256000 };
986 
987         FD_ZERO(&rfds);
988         FD_SET(sock, &rfds);
989 
990         memset(buf, 0, blen);
991 
992         if (select(sock + 1, &rfds, NULL, NULL, &tv) < 0)
993                 return -1;
994 
995         if (!FD_ISSET(sock, &rfds))
996                 return -1;
997 
998         return recv(sock, buf, blen - 1, 0);
999 }
1000 
1001 static int nl80211_wpactl_connect(const char *ifname, struct sockaddr_un *local)
1002 {
1003         struct sockaddr_un remote = { 0 };
1004         size_t remote_length, local_length;
1005 
1006         int sock = socket(PF_UNIX, SOCK_DGRAM, 0);
1007         if (sock < 0)
1008                 return sock;
1009 
1010         remote.sun_family = AF_UNIX;
1011         remote_length = sizeof(remote.sun_family) +
1012                 sprintf(remote.sun_path, "/var/run/wpa_supplicant/%s", ifname);
1013 
1014         /* Set client socket file permissions so that bind() creates the client
1015         * socket with these permissions and there is no need to try to change
1016         * them with chmod() after bind() which would have potential issues with
1017         * race conditions. These permissions are needed to make sure the server
1018         * side (wpa_supplicant or hostapd) can reply to the control interface
1019         * messages.
1020         *
1021         * The lchown() calls below after bind() are also part of the needed
1022         * operations to allow the response to go through. Those are using the
1023         * no-deference-symlinks version to avoid races. */
1024         fchmod(sock, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
1025 
1026         if (fcntl(sock, F_SETFD, fcntl(sock, F_GETFD) | FD_CLOEXEC) < 0)
1027         {
1028                 close(sock);
1029                 return -1;
1030         }
1031 
1032         if (connect(sock, (struct sockaddr *)&remote, remote_length))
1033         {
1034                 close(sock);
1035                 return -1;
1036         }
1037 
1038         local->sun_family = AF_UNIX;
1039         local_length = sizeof(local->sun_family) +
1040                 sprintf(local->sun_path, "/var/run/iwinfo-%s-%d", ifname, getpid());
1041 
1042         if (bind(sock, (struct sockaddr *)local, local_length) < 0)
1043         {
1044                 close(sock);
1045                 return -1;
1046         }
1047 
1048         /* Set group even if we do not have privileges to change owner */
1049         lchown(local->sun_path, -1, 101);
1050         lchown(local->sun_path, 101, 101);
1051 
1052         return sock;
1053 }
1054 
1055 static int __nl80211_wpactl_query(const char *ifname, ...)
1056 {
1057         va_list ap, ap_cur;
1058         struct sockaddr_un local = { 0 };
1059         int len, mode, found = 0, sock = -1;
1060         char *search, *dest, *key, *val, *line, *pos, buf[512];
1061 
1062         if (nl80211_get_mode(ifname, &mode))
1063                 return 0;
1064 
1065         if (mode != IWINFO_OPMODE_CLIENT &&
1066             mode != IWINFO_OPMODE_ADHOC &&
1067             mode != IWINFO_OPMODE_MESHPOINT)
1068                 return 0;
1069 
1070         sock = nl80211_wpactl_connect(ifname, &local);
1071 
1072         if (sock < 0)
1073                 return 0;
1074 
1075         va_start(ap, ifname);
1076 
1077         /* clear all destination buffers */
1078         va_copy(ap_cur, ap);
1079 
1080         while ((search = va_arg(ap_cur, char *)) != NULL)
1081         {
1082                 dest = va_arg(ap_cur, char *);
1083                 len  = va_arg(ap_cur, int);
1084 
1085                 memset(dest, 0, len);
1086         }
1087 
1088         va_end(ap_cur);
1089 
1090         send(sock, "STATUS", 6, 0);
1091 
1092         while (true)
1093         {
1094                 if (nl80211_wpactl_recv(sock, buf, sizeof(buf)) <= 0)
1095                         break;
1096 
1097                 if (buf[0] == '<')
1098                         continue;
1099 
1100                 for (line = strtok_r(buf, "\n", &pos);
1101                          line != NULL;
1102                          line = strtok_r(NULL, "\n", &pos))
1103                 {
1104                         key = strtok(line, "=");
1105                         val = strtok(NULL, "\n");
1106 
1107                         if (!key || !val)
1108                                 continue;
1109 
1110                         va_copy(ap_cur, ap);
1111 
1112                         while ((search = va_arg(ap_cur, char *)) != NULL)
1113                         {
1114                                 dest = va_arg(ap_cur, char *);
1115                                 len  = va_arg(ap_cur, int);
1116 
1117                                 if (!strcmp(search, key))
1118                                 {
1119                                         strncpy(dest, val, len - 1);
1120                                         found++;
1121                                         break;
1122                                 }
1123                         }
1124 
1125                         va_end(ap_cur);
1126                 }
1127 
1128                 break;
1129         }
1130 
1131         va_end(ap);
1132 
1133         close(sock);
1134         unlink(local.sun_path);
1135 
1136         return found;
1137 }
1138 
1139 #define nl80211_wpactl_query(ifname, ...) \
1140         __nl80211_wpactl_query(ifname, ##__VA_ARGS__, NULL)
1141 
1142 
1143 static char * nl80211_ifadd(const char *ifname)
1144 {
1145         char path[PATH_MAX];
1146         static char nif[IFNAMSIZ] = { 0 };
1147         struct nl80211_msg_conveyor *req;
1148         FILE *sysfs;
1149 
1150         req = nl80211_msg(ifname, NL80211_CMD_NEW_INTERFACE, 0);
1151         if (req)
1152         {
1153                 snprintf(nif, sizeof(nif), "tmp.%s", ifname);
1154 
1155                 NLA_PUT_STRING(req->msg, NL80211_ATTR_IFNAME, nif);
1156                 NLA_PUT_U32(req->msg, NL80211_ATTR_IFTYPE, NL80211_IFTYPE_STATION);
1157 
1158                 nl80211_send(req, NULL, NULL);
1159 
1160                 snprintf(path, sizeof(path) - 1,
1161                          "/proc/sys/net/ipv6/conf/%s/disable_ipv6", nif);
1162 
1163                 if ((sysfs = fopen(path, "w")) != NULL)
1164                 {
1165                         fwrite("\n", 1, 2, sysfs);
1166                         fclose(sysfs);
1167                 }
1168 
1169                 return nif;
1170 
1171         nla_put_failure:
1172                 nl80211_free(req);
1173         }
1174 
1175         return NULL;
1176 }
1177 
1178 static void nl80211_ifdel(const char *ifname)
1179 {
1180         struct nl80211_msg_conveyor *req;
1181 
1182         req = nl80211_msg(ifname, NL80211_CMD_DEL_INTERFACE, 0);
1183         if (req)
1184         {
1185                 NLA_PUT_STRING(req->msg, NL80211_ATTR_IFNAME, ifname);
1186 
1187                 nl80211_send(req, NULL, NULL);
1188                 return;
1189 
1190         nla_put_failure:
1191                 nl80211_free(req);
1192         }
1193 }
1194 
1195 static void nl80211_hostapd_hup(const char *ifname)
1196 {
1197         int fd, pid = 0;
1198         char buf[32];
1199         char *phy = nl80211_ifname2phy(ifname);
1200 
1201         if (phy)
1202         {
1203                 snprintf(buf, sizeof(buf), "/var/run/wifi-%s.pid", phy);
1204                 if ((fd = open(buf, O_RDONLY)) >= 0)
1205                 {
1206                         if (read(fd, buf, sizeof(buf)) > 0)
1207                                 pid = atoi(buf);
1208 
1209                         close(fd);
1210                 }
1211 
1212                 if (pid > 0)
1213                         kill(pid, 1);
1214         }
1215 }
1216 
1217 
1218 static int nl80211_probe(const char *ifname)
1219 {
1220         return !!nl80211_ifname2phy(ifname);
1221 }
1222 
1223 struct nl80211_ssid_bssid {
1224         unsigned char *ssid;
1225         unsigned char bssid[7];
1226 };
1227 
1228 static int nl80211_get_macaddr_cb(struct nl_msg *msg, void *arg)
1229 {
1230         struct nl80211_ssid_bssid *sb = arg;
1231         struct nlattr **tb = nl80211_parse(msg);
1232 
1233         if (tb[NL80211_ATTR_MAC]) {
1234                 sb->bssid[0] = 1;
1235                 memcpy(sb->bssid + 1, nla_data(tb[NL80211_ATTR_MAC]),
1236                        sizeof(sb->bssid) - 1);
1237         }
1238 
1239         return NL_SKIP;
1240 }
1241 
1242 static int nl80211_get_ssid_bssid_cb(struct nl_msg *msg, void *arg)
1243 {
1244         int ielen;
1245         unsigned char *ie;
1246         struct nl80211_ssid_bssid *sb = arg;
1247         struct nlattr **tb = nl80211_parse(msg);
1248         struct nlattr *bss[NL80211_BSS_MAX + 1];
1249 
1250         static struct nla_policy bss_policy[NL80211_BSS_MAX + 1] = {
1251                 [NL80211_BSS_INFORMATION_ELEMENTS] = { 0 },
1252                 [NL80211_BSS_STATUS]               = { .type = NLA_U32 },
1253         };
1254 
1255         if (!tb[NL80211_ATTR_BSS] ||
1256             nla_parse_nested(bss, NL80211_BSS_MAX, tb[NL80211_ATTR_BSS],
1257                              bss_policy) ||
1258             !bss[NL80211_BSS_BSSID] ||
1259             !bss[NL80211_BSS_STATUS] ||
1260             !bss[NL80211_BSS_INFORMATION_ELEMENTS])
1261         {
1262                 return NL_SKIP;
1263         }
1264 
1265         switch (nla_get_u32(bss[NL80211_BSS_STATUS]))
1266         {
1267         case NL80211_BSS_STATUS_ASSOCIATED:
1268         case NL80211_BSS_STATUS_AUTHENTICATED:
1269         case NL80211_BSS_STATUS_IBSS_JOINED:
1270 
1271                 if (sb->ssid)
1272                 {
1273                         ie = nla_data(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
1274                         ielen = nla_len(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
1275 
1276                         while (ielen >= 2 && ielen >= ie[1])
1277                         {
1278                                 if (ie[0] == 0)
1279                                 {
1280                                         memcpy(sb->ssid, ie + 2, min(ie[1], IWINFO_ESSID_MAX_SIZE));
1281                                         return NL_SKIP;
1282                                 }
1283 
1284                                 ielen -= ie[1] + 2;
1285                                 ie += ie[1] + 2;
1286                         }
1287                 }
1288                 else
1289                 {
1290                         sb->bssid[0] = 1;
1291                         memcpy(sb->bssid + 1, nla_data(bss[NL80211_BSS_BSSID]), 6);
1292                         return NL_SKIP;
1293                 }
1294 
1295         default:
1296                 return NL_SKIP;
1297         }
1298 }
1299 
1300 static int nl80211_get_ssid(const char *ifname, char *buf)
1301 {
1302         char *res;
1303         struct nl80211_ssid_bssid sb = { .ssid = (unsigned char *)buf };
1304 
1305         /* try to find ssid from scan dump results */
1306         res = nl80211_phy2ifname(ifname);
1307         sb.ssid[0] = 0;
1308 
1309         nl80211_request(res ? res : ifname, NL80211_CMD_GET_SCAN, NLM_F_DUMP,
1310                         nl80211_get_ssid_bssid_cb, &sb);
1311 
1312         /* failed, try to find from hostapd info */
1313         if (sb.ssid[0] == 0)
1314                 nl80211_hostapd_query(ifname, "ssid", sb.ssid,
1315                                       IWINFO_ESSID_MAX_SIZE + 1);
1316 
1317         /* failed, try to obtain Mesh ID */
1318         if (sb.ssid[0] == 0)
1319                 iwinfo_ubus_query(res ? res : ifname, "mesh_id",
1320                                   buf, IWINFO_ESSID_MAX_SIZE + 1);
1321 
1322         return (sb.ssid[0] == 0) ? -1 : 0;
1323 }
1324 
1325 static int nl80211_get_bssid(const char *ifname, char *buf)
1326 {
1327         char *res, bssid[sizeof("FF:FF:FF:FF:FF:FF\0")];
1328         struct nl80211_ssid_bssid sb = { };
1329 
1330         res = nl80211_phy2ifname(ifname);
1331 
1332         /* try to obtain mac address via NL80211_CMD_GET_INTERFACE */
1333         nl80211_request(res ? res : ifname, NL80211_CMD_GET_INTERFACE, 0,
1334                         nl80211_get_macaddr_cb, &sb);
1335 
1336         /* failed, try to find bssid from scan dump results */
1337         if (sb.bssid[0] == 0)
1338                 nl80211_request(res ? res : ifname,
1339                                 NL80211_CMD_GET_SCAN, NLM_F_DUMP,
1340                                 nl80211_get_ssid_bssid_cb, &sb);
1341 
1342         /* failed, try to find mac from hostapd info */
1343         if ((sb.bssid[0] == 0) &&
1344             nl80211_hostapd_query(ifname, "bssid", bssid, sizeof(bssid)))
1345         {
1346                 sb.bssid[0] = 1;
1347                 sb.bssid[1] = strtol(&bssid[0],  NULL, 16);
1348                 sb.bssid[2] = strtol(&bssid[3],  NULL, 16);
1349                 sb.bssid[3] = strtol(&bssid[6],  NULL, 16);
1350                 sb.bssid[4] = strtol(&bssid[9],  NULL, 16);
1351                 sb.bssid[5] = strtol(&bssid[12], NULL, 16);
1352                 sb.bssid[6] = strtol(&bssid[15], NULL, 16);
1353         }
1354 
1355         if (sb.bssid[0])
1356         {
1357                 sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X",
1358                         sb.bssid[1], sb.bssid[2], sb.bssid[3],
1359                         sb.bssid[4], sb.bssid[5], sb.bssid[6]);
1360 
1361                 return 0;
1362         }
1363 
1364         return -1;
1365 }
1366 
1367 
1368 static int nl80211_get_frequency_scan_cb(struct nl_msg *msg, void *arg)
1369 {
1370         int *freq = arg;
1371         struct nlattr **attr = nl80211_parse(msg);
1372         struct nlattr *binfo[NL80211_BSS_MAX + 1];
1373 
1374         static struct nla_policy bss_policy[NL80211_BSS_MAX + 1] = {
1375                 [NL80211_BSS_FREQUENCY] = { .type = NLA_U32 },
1376                 [NL80211_BSS_STATUS]    = { .type = NLA_U32 },
1377         };
1378 
1379         if (attr[NL80211_ATTR_BSS] &&
1380             !nla_parse_nested(binfo, NL80211_BSS_MAX,
1381                               attr[NL80211_ATTR_BSS], bss_policy))
1382         {
1383                 if (binfo[NL80211_BSS_STATUS] && binfo[NL80211_BSS_FREQUENCY])
1384                         *freq = nla_get_u32(binfo[NL80211_BSS_FREQUENCY]);
1385         }
1386 
1387         return NL_SKIP;
1388 }
1389 
1390 static int nl80211_get_frequency_info_cb(struct nl_msg *msg, void *arg)
1391 {
1392         int *freq = arg;
1393         struct nlattr **tb = nl80211_parse(msg);
1394 
1395         if (tb[NL80211_ATTR_WIPHY_FREQ])
1396                 *freq = nla_get_u32(tb[NL80211_ATTR_WIPHY_FREQ]);
1397 
1398         return NL_SKIP;
1399 }
1400 
1401 static int nl80211_get_frequency(const char *ifname, int *buf)
1402 {
1403         char *res, channel[4] = { 0 }, hwmode[3] = { 0 }, ax[2] = { 0 };
1404 
1405         /* try to find frequency from interface info */
1406         res = nl80211_phy2ifname(ifname);
1407         *buf = 0;
1408 
1409         nl80211_request(res ? res : ifname, NL80211_CMD_GET_INTERFACE, 0,
1410                         nl80211_get_frequency_info_cb, buf);
1411 
1412         /* failed, try to find frequency from hostapd info */
1413         if ((*buf == 0) &&
1414             nl80211_hostapd_query(ifname, "hw_mode", hwmode, sizeof(hwmode),
1415                                           "channel", channel, sizeof(channel),
1416                                           "ieee80211ax", ax, sizeof(ax)) >= 2)
1417         {
1418                 *buf = nl80211_channel2freq(atoi(channel), hwmode, ax[0] == '1');
1419         }
1420 
1421         /* failed, try to find frequency from scan results */
1422         if (*buf == 0)
1423         {
1424                 res = nl80211_phy2ifname(ifname);
1425 
1426                 nl80211_request(res ? res : ifname, NL80211_CMD_GET_SCAN, NLM_F_DUMP,
1427                                 nl80211_get_frequency_scan_cb, buf);
1428         }
1429 
1430         return (*buf == 0) ? -1 : 0;
1431 }
1432 
1433 static int nl80211_get_center_freq1_cb(struct nl_msg *msg, void *arg)
1434 {
1435         int *freq = arg;
1436         struct nlattr **tb = nl80211_parse(msg);
1437 
1438         if (tb[NL80211_ATTR_CENTER_FREQ1])
1439                 *freq = nla_get_u32(tb[NL80211_ATTR_CENTER_FREQ1]);
1440 
1441         return NL_SKIP;
1442 }
1443 
1444 static int nl80211_get_center_freq1(const char *ifname, int *buf)
1445 {
1446         char *res;
1447 
1448         /* try to find frequency from interface info */
1449         res = nl80211_phy2ifname(ifname);
1450         *buf = 0;
1451 
1452         nl80211_request(res ? res : ifname, NL80211_CMD_GET_INTERFACE, 0,
1453                         nl80211_get_center_freq1_cb, buf);
1454 
1455         return (*buf == 0) ? -1 : 0;
1456 }
1457 
1458 static int nl80211_get_center_freq2_cb(struct nl_msg *msg, void *arg)
1459 {
1460         int *freq = arg;
1461         struct nlattr **tb = nl80211_parse(msg);
1462 
1463         if (tb[NL80211_ATTR_CENTER_FREQ2])
1464                 *freq = nla_get_u32(tb[NL80211_ATTR_CENTER_FREQ2]);
1465 
1466         return NL_SKIP;
1467 }
1468 
1469 static int nl80211_get_center_freq2(const char *ifname, int *buf)
1470 {
1471         char *res;
1472 
1473         /* try to find frequency from interface info */
1474         res = nl80211_phy2ifname(ifname);
1475         *buf = 0;
1476 
1477         nl80211_request(res ? res : ifname, NL80211_CMD_GET_INTERFACE, 0,
1478                         nl80211_get_center_freq2_cb, buf);
1479 
1480         return (*buf == 0) ? -1 : 0;
1481 }
1482 
1483 static int nl80211_get_channel(const char *ifname, int *buf)
1484 {
1485         if (!nl80211_get_frequency(ifname, buf))
1486         {
1487                 *buf = nl80211_freq2channel(*buf);
1488                 return 0;
1489         }
1490 
1491         return -1;
1492 }
1493 
1494 static int nl80211_get_center_chan1(const char *ifname, int *buf)
1495 {
1496         if (!nl80211_get_center_freq1(ifname, buf))
1497         {
1498                 *buf = nl80211_freq2channel(*buf);
1499                 return 0;
1500         }
1501 
1502         return -1;
1503 }
1504 
1505 static int nl80211_get_center_chan2(const char *ifname, int *buf)
1506 {
1507         if (!nl80211_get_center_freq2(ifname, buf))
1508         {
1509                 *buf = nl80211_freq2channel(*buf);
1510                 return 0;
1511         }
1512 
1513         return -1;
1514 }
1515 
1516 static int nl80211_get_txpower_cb(struct nl_msg *msg, void *arg)
1517 {
1518         int *buf = arg;
1519         struct nlattr **tb = nl80211_parse(msg);
1520 
1521         if (tb[NL80211_ATTR_WIPHY_TX_POWER_LEVEL])
1522                 *buf = iwinfo_mbm2dbm(nla_get_u32(tb[NL80211_ATTR_WIPHY_TX_POWER_LEVEL]));
1523 
1524         return NL_SKIP;
1525 }
1526 
1527 static int nl80211_get_txpower(const char *ifname, int *buf)
1528 {
1529         char *res;
1530 
1531         res = nl80211_phy2ifname(ifname);
1532         *buf = 0;
1533 
1534         if (nl80211_request(res ? res : ifname, NL80211_CMD_GET_INTERFACE, 0,
1535                             nl80211_get_txpower_cb, buf))
1536                 return -1;
1537 
1538         return 0;
1539 }
1540 
1541 
1542 static int nl80211_fill_signal_cb(struct nl_msg *msg, void *arg)
1543 {
1544         int8_t dbm;
1545         int16_t mbit;
1546         struct nl80211_rssi_rate *rr = arg;
1547         struct nlattr **attr = nl80211_parse(msg);
1548         struct nlattr *sinfo[NL80211_STA_INFO_MAX + 1];
1549         struct nlattr *rinfo[NL80211_RATE_INFO_MAX + 1];
1550 
1551         static struct nla_policy stats_policy[NL80211_STA_INFO_MAX + 1] = {
1552                 [NL80211_STA_INFO_INACTIVE_TIME] = { .type = NLA_U32    },
1553                 [NL80211_STA_INFO_RX_BYTES]      = { .type = NLA_U32    },
1554                 [NL80211_STA_INFO_TX_BYTES]      = { .type = NLA_U32    },
1555                 [NL80211_STA_INFO_RX_PACKETS]    = { .type = NLA_U32    },
1556                 [NL80211_STA_INFO_TX_PACKETS]    = { .type = NLA_U32    },
1557                 [NL80211_STA_INFO_SIGNAL]        = { .type = NLA_U8     },
1558                 [NL80211_STA_INFO_TX_BITRATE]    = { .type = NLA_NESTED },
1559                 [NL80211_STA_INFO_LLID]          = { .type = NLA_U16    },
1560                 [NL80211_STA_INFO_PLID]          = { .type = NLA_U16    },
1561                 [NL80211_STA_INFO_PLINK_STATE]   = { .type = NLA_U8     },
1562         };
1563 
1564         static struct nla_policy rate_policy[NL80211_RATE_INFO_MAX + 1] = {
1565                 [NL80211_RATE_INFO_BITRATE]      = { .type = NLA_U16  },
1566                 [NL80211_RATE_INFO_MCS]          = { .type = NLA_U8   },
1567                 [NL80211_RATE_INFO_40_MHZ_WIDTH] = { .type = NLA_FLAG },
1568                 [NL80211_RATE_INFO_SHORT_GI]     = { .type = NLA_FLAG },
1569         };
1570 
1571         if (attr[NL80211_ATTR_STA_INFO])
1572         {
1573                 if (!nla_parse_nested(sinfo, NL80211_STA_INFO_MAX,
1574                                       attr[NL80211_ATTR_STA_INFO], stats_policy))
1575                 {
1576                         if (sinfo[NL80211_STA_INFO_SIGNAL])
1577                         {
1578                                 dbm = nla_get_u8(sinfo[NL80211_STA_INFO_SIGNAL]);
1579                                 rr->rssi = (rr->rssi * rr->rssi_samples + dbm) / (rr->rssi_samples + 1);
1580                                 rr->rssi_samples++;
1581                         }
1582 
1583                         if (sinfo[NL80211_STA_INFO_TX_BITRATE])
1584                         {
1585                                 if (!nla_parse_nested(rinfo, NL80211_RATE_INFO_MAX,
1586                                                       sinfo[NL80211_STA_INFO_TX_BITRATE],
1587                                                       rate_policy))
1588                                 {
1589                                         if (rinfo[NL80211_RATE_INFO_BITRATE])
1590                                         {
1591                                                 mbit = nla_get_u16(rinfo[NL80211_RATE_INFO_BITRATE]);
1592                                                 rr->rate = (rr->rate * rr->rate_samples + mbit) / (rr->rate_samples + 1);
1593                                                 rr->rate_samples++;
1594                                         }
1595                                 }
1596                         }
1597                 }
1598         }
1599 
1600         return NL_SKIP;
1601 }
1602 
1603 static void nl80211_fill_signal(const char *ifname, struct nl80211_rssi_rate *r)
1604 {
1605         DIR *d;
1606         struct dirent *de;
1607 
1608         memset(r, 0, sizeof(*r));
1609 
1610         if ((d = opendir("/sys/class/net")) != NULL)
1611         {
1612                 while ((de = readdir(d)) != NULL)
1613                 {
1614                         if (!strncmp(de->d_name, ifname, strlen(ifname)) &&
1615                             (!de->d_name[strlen(ifname)] ||
1616                              !strncmp(&de->d_name[strlen(ifname)], ".sta", 4)))
1617                         {
1618                                 nl80211_request(de->d_name, NL80211_CMD_GET_STATION,
1619                                                 NLM_F_DUMP, nl80211_fill_signal_cb, r);
1620                         }
1621                 }
1622 
1623                 closedir(d);
1624         }
1625 }
1626 
1627 static int nl80211_get_bitrate(const char *ifname, int *buf)
1628 {
1629         struct nl80211_rssi_rate rr;
1630 
1631         nl80211_fill_signal(ifname, &rr);
1632 
1633         if (rr.rate_samples)
1634         {
1635                 *buf = (rr.rate * 100);
1636                 return 0;
1637         }
1638 
1639         return -1;
1640 }
1641 
1642 static int nl80211_get_signal(const char *ifname, int *buf)
1643 {
1644         struct nl80211_rssi_rate rr;
1645 
1646         nl80211_fill_signal(ifname, &rr);
1647 
1648         if (rr.rssi_samples)
1649         {
1650                 *buf = rr.rssi;
1651                 return 0;
1652         }
1653 
1654         return -1;
1655 }
1656 
1657 static int nl80211_get_noise_cb(struct nl_msg *msg, void *arg)
1658 {
1659         int8_t *noise = arg;
1660         struct nlattr **tb = nl80211_parse(msg);
1661         struct nlattr *si[NL80211_SURVEY_INFO_MAX + 1];
1662 
1663         static struct nla_policy sp[NL80211_SURVEY_INFO_MAX + 1] = {
1664                 [NL80211_SURVEY_INFO_FREQUENCY] = { .type = NLA_U32 },
1665                 [NL80211_SURVEY_INFO_NOISE]     = { .type = NLA_U8  },
1666         };
1667 
1668         if (!tb[NL80211_ATTR_SURVEY_INFO])
1669                 return NL_SKIP;
1670 
1671         if (nla_parse_nested(si, NL80211_SURVEY_INFO_MAX,
1672                              tb[NL80211_ATTR_SURVEY_INFO], sp))
1673                 return NL_SKIP;
1674 
1675         if (!si[NL80211_SURVEY_INFO_NOISE])
1676                 return NL_SKIP;
1677 
1678         if (!*noise || si[NL80211_SURVEY_INFO_IN_USE])
1679                 *noise = (int8_t)nla_get_u8(si[NL80211_SURVEY_INFO_NOISE]);
1680 
1681         return NL_SKIP;
1682 }
1683 
1684 
1685 static int nl80211_get_noise(const char *ifname, int *buf)
1686 {
1687         int8_t noise = 0;
1688 
1689         if (nl80211_request(ifname, NL80211_CMD_GET_SURVEY, NLM_F_DUMP,
1690                             nl80211_get_noise_cb, &noise))
1691                 goto out;
1692 
1693         *buf = noise;
1694         return 0;
1695 
1696 out:
1697         *buf = 0;
1698         return -1;
1699 }
1700 
1701 static int nl80211_get_quality(const char *ifname, int *buf)
1702 {
1703         int signal;
1704 
1705         if (!nl80211_get_signal(ifname, &signal))
1706         {
1707                 /* A positive signal level is usually just a quality
1708                  * value, pass through as-is */
1709                 if (signal >= 0)
1710                 {
1711                         *buf = signal;
1712                 }
1713 
1714                 /* The cfg80211 wext compat layer assumes a signal range
1715                  * of -110 dBm to -40 dBm, the quality value is derived
1716                  * by adding 110 to the signal level */
1717                 else
1718                 {
1719                         if (signal < -110)
1720                                 signal = -110;
1721                         else if (signal > -40)
1722                                 signal = -40;
1723 
1724                         *buf = (signal + 110);
1725                 }
1726 
1727                 return 0;
1728         }
1729 
1730         return -1;
1731 }
1732 
1733 static int nl80211_get_quality_max(const char *ifname, int *buf)
1734 {
1735         /* The cfg80211 wext compat layer assumes a maximum
1736          * quality of 70 */
1737         *buf = 70;
1738 
1739         return 0;
1740 }
1741 
1742 static int nl80211_check_wepkey(const char *key)
1743 {
1744         if (key && *key)
1745         {
1746                 switch (strlen(key))
1747                 {
1748                 case 5:
1749                 case 10:
1750                         return IWINFO_CIPHER_WEP40;
1751 
1752                 case 13:
1753                 case 26:
1754                         return IWINFO_CIPHER_WEP104;
1755                 }
1756         }
1757 
1758         return 0;
1759 }
1760 
1761 static struct {
1762         const char *match;
1763         int version;
1764         int suite;
1765 } wpa_key_mgmt_strings[] = {
1766         { "IEEE 802.1X/EAP", 0, IWINFO_KMGMT_8021x },
1767         { "EAP-SUITE-B-192", 4, IWINFO_KMGMT_8021x },
1768         { "EAP-SUITE-B",     4, IWINFO_KMGMT_8021x },
1769         { "EAP-SHA384",      4, IWINFO_KMGMT_8021x },
1770         { "EAP-SHA256",      0, IWINFO_KMGMT_8021x },
1771         { "PSK-SHA256",      0, IWINFO_KMGMT_PSK },
1772         { "NONE",            0, IWINFO_KMGMT_NONE },
1773         { "None",            0, IWINFO_KMGMT_NONE },
1774         { "PSK",             0, IWINFO_KMGMT_PSK },
1775         { "EAP",             0, IWINFO_KMGMT_8021x },
1776         { "SAE",             4, IWINFO_KMGMT_SAE },
1777         { "OWE",             4, IWINFO_KMGMT_OWE }
1778 };
1779 
1780 static void parse_wpa_suites(const char *str, int defversion,
1781                              uint8_t *versions, uint8_t *suites)
1782 {
1783         size_t l;
1784         int i, version;
1785         const char *p, *q, *m, *sep = " \t\n,-+/";
1786 
1787         for (p = str; *p; )
1788         {
1789                 q = p;
1790 
1791                 for (i = 0; i < ARRAY_SIZE(wpa_key_mgmt_strings); i++)
1792                 {
1793                         m = wpa_key_mgmt_strings[i].match;
1794                         l = strlen(m);
1795 
1796                         if (!strncmp(q, m, l) && (!q[l] || strchr(sep, q[l])))
1797                         {
1798                                 if (wpa_key_mgmt_strings[i].version != 0)
1799                                         version = wpa_key_mgmt_strings[i].version;
1800                                 else
1801                                         version = defversion;
1802 
1803                                 *versions |= version;
1804                                 *suites |= wpa_key_mgmt_strings[i].suite;
1805 
1806                                 q += l;
1807                                 break;
1808                         }
1809                 }
1810 
1811                 if (q == p)
1812                         q += strcspn(q, sep);
1813 
1814                 p = q + strspn(q, sep);
1815         }
1816 }
1817 
1818 static struct {
1819         const char *match;
1820         int cipher;
1821 } wpa_cipher_strings[] = {
1822         { "WEP-104", IWINFO_CIPHER_WEP104  },
1823         { "WEP-40",  IWINFO_CIPHER_WEP40   },
1824         { "NONE",    IWINFO_CIPHER_NONE    },
1825         { "TKIP",    IWINFO_CIPHER_TKIP    },
1826         { "CCMP-256",IWINFO_CIPHER_CCMP256 },
1827         { "CCMP",    IWINFO_CIPHER_CCMP    },
1828         { "GCMP-256",IWINFO_CIPHER_GCMP256 },
1829         { "GCMP",    IWINFO_CIPHER_GCMP    }
1830 };
1831 
1832 static void parse_wpa_ciphers(const char *str, uint16_t *ciphers)
1833 {
1834         int i;
1835         size_t l;
1836         const char *m, *p, *q, *sep = " \t\n,-+/";
1837 
1838         for (p = str; *p; )
1839         {
1840                 q = p;
1841 
1842                 for (i = 0; i < ARRAY_SIZE(wpa_cipher_strings); i++)
1843                 {
1844                         m = wpa_cipher_strings[i].match;
1845                         l = strlen(m);
1846 
1847                         if (!strncmp(q, m, l) && (!q[l] || strchr(sep, q[l])))
1848                         {
1849                                 *ciphers |= wpa_cipher_strings[i].cipher;
1850 
1851                                 q += l;
1852                                 break;
1853                         }
1854                 }
1855 
1856                 if (q == p)
1857                         q += strcspn(q, sep);
1858 
1859                 p = q + strspn(q, sep);
1860         }
1861 }
1862 
1863 static int nl80211_get_encryption(const char *ifname, char *buf)
1864 {
1865         char *p;
1866         int opmode;
1867         uint8_t wpa_version = 0;
1868         char wpa[2], wpa_key_mgmt[64], wpa_pairwise[16], wpa_groupwise[16];
1869         char auth_algs[2], wep_key0[27], wep_key1[27], wep_key2[27], wep_key3[27];
1870         char mode[16];
1871 
1872         struct iwinfo_crypto_entry *c = (struct iwinfo_crypto_entry *)buf;
1873 
1874         /* WPA supplicant */
1875         if (nl80211_wpactl_query(ifname,
1876                         "pairwise_cipher", wpa_pairwise,  sizeof(wpa_pairwise),
1877                         "group_cipher",    wpa_groupwise, sizeof(wpa_groupwise),
1878                         "key_mgmt",        wpa_key_mgmt,  sizeof(wpa_key_mgmt),
1879                         "mode",            mode,          sizeof(mode)))
1880         {
1881                 /* WEP or Open */
1882                 if (!strcmp(wpa_key_mgmt, "NONE"))
1883                 {
1884                         parse_wpa_ciphers(wpa_pairwise, &c->pair_ciphers);
1885                         parse_wpa_ciphers(wpa_groupwise, &c->group_ciphers);
1886 
1887                         if (c->pair_ciphers != 0 && c->pair_ciphers != IWINFO_CIPHER_NONE) {
1888                                 c->enabled     = 1;
1889                                 c->auth_suites = IWINFO_KMGMT_NONE;
1890                                 c->auth_algs   = IWINFO_AUTH_OPEN | IWINFO_AUTH_SHARED;
1891                         }
1892                         else {
1893                                 c->pair_ciphers = 0;
1894                                 c->group_ciphers = 0;
1895                         }
1896                 }
1897 
1898                 /* MESH with SAE */
1899                 else if (!strcmp(mode, "mesh") && !strcmp(wpa_key_mgmt, "UNKNOWN"))
1900                 {
1901                         c->enabled = 1;
1902                         c->wpa_version = 4;
1903                         c->auth_suites = IWINFO_KMGMT_SAE;
1904                         c->pair_ciphers = IWINFO_CIPHER_CCMP;
1905                         c->group_ciphers = IWINFO_CIPHER_CCMP;
1906                 }
1907 
1908                 /* WPA */
1909                 else
1910                 {
1911                         parse_wpa_ciphers(wpa_pairwise, &c->pair_ciphers);
1912                         parse_wpa_ciphers(wpa_groupwise, &c->group_ciphers);
1913 
1914                         p = wpa_key_mgmt;
1915 
1916                         if (!strncmp(p, "WPA2-", 5) || !strncmp(p, "WPA2/", 5))
1917                         {
1918                                 p += 5;
1919                                 wpa_version = 2;
1920                         }
1921                         else if (!strncmp(p, "WPA-", 4))
1922                         {
1923                                 p += 4;
1924                                 wpa_version = 1;
1925                         }
1926 
1927                         parse_wpa_suites(p, wpa_version, &c->wpa_version, &c->auth_suites);
1928 
1929                         c->enabled = !!(c->wpa_version && c->auth_suites);
1930                 }
1931 
1932                 return 0;
1933         }
1934 
1935         /* Hostapd */
1936         else if (nl80211_hostapd_query(ifname,
1937                                 "wpa",          wpa,          sizeof(wpa),
1938                                 "wpa_key_mgmt", wpa_key_mgmt, sizeof(wpa_key_mgmt),
1939                                 "wpa_pairwise", wpa_pairwise, sizeof(wpa_pairwise),
1940                                 "auth_algs",    auth_algs,    sizeof(auth_algs),
1941                                 "wep_key0",     wep_key0,     sizeof(wep_key0),
1942                                 "wep_key1",     wep_key1,     sizeof(wep_key1),
1943                                 "wep_key2",     wep_key2,     sizeof(wep_key2),
1944                                 "wep_key3",     wep_key3,     sizeof(wep_key3)))
1945         {
1946                 c->wpa_version = 0;
1947 
1948                 if (wpa_key_mgmt[0])
1949                 {
1950                         for (p = strtok(wpa_key_mgmt, " \t"); p != NULL; p = strtok(NULL, " \t"))
1951                         {
1952                                 if (!strncmp(p, "WPA-", 4))
1953                                         p += 4;
1954 
1955                                 if (!strncmp(p, "FT-", 3))
1956                                         p += 3;
1957 
1958                                 parse_wpa_suites(p, atoi(wpa), &c->wpa_version, &c->auth_suites);
1959                         }
1960 
1961                         c->enabled = c->wpa_version ? 1 : 0;
1962                 }
1963 
1964                 if (wpa_pairwise[0])
1965                         parse_wpa_ciphers(wpa_pairwise, &c->pair_ciphers);
1966 
1967                 if (auth_algs[0])
1968                 {
1969                         switch (atoi(auth_algs))
1970                         {
1971                         case 1:
1972                                 c->auth_algs |= IWINFO_AUTH_OPEN;
1973                                 break;
1974 
1975                         case 2:
1976                                 c->auth_algs |= IWINFO_AUTH_SHARED;
1977                                 break;
1978 
1979                         case 3:
1980                                 c->auth_algs |= IWINFO_AUTH_OPEN;
1981                                 c->auth_algs |= IWINFO_AUTH_SHARED;
1982                                 break;
1983                         }
1984 
1985                         c->pair_ciphers |= nl80211_check_wepkey(wep_key0);
1986                         c->pair_ciphers |= nl80211_check_wepkey(wep_key1);
1987                         c->pair_ciphers |= nl80211_check_wepkey(wep_key2);
1988                         c->pair_ciphers |= nl80211_check_wepkey(wep_key3);
1989 
1990                         c->enabled = (c->auth_algs && c->pair_ciphers) ? 1 : 0;
1991                 }
1992 
1993                 c->group_ciphers = c->pair_ciphers;
1994 
1995                 return 0;
1996         }
1997 
1998         /* Ad-Hoc or Mesh interfaces without wpa_supplicant are open */
1999         else if (!nl80211_get_mode(ifname, &opmode) &&
2000                  (opmode == IWINFO_OPMODE_ADHOC ||
2001                   opmode == IWINFO_OPMODE_MESHPOINT))
2002         {
2003                 c->enabled = 0;
2004 
2005                 return 0;
2006         }
2007 
2008 
2009         return -1;
2010 }
2011 
2012 static int nl80211_get_phyname(const char *ifname, char *buf)
2013 {
2014         const char *name;
2015 
2016         name = nl80211_ifname2phy(ifname);
2017 
2018         if (name)
2019         {
2020                 strcpy(buf, name);
2021                 return 0;
2022         }
2023         else if ((name = nl80211_phy2ifname(ifname)) != NULL)
2024         {
2025                 name = nl80211_ifname2phy(name);
2026 
2027                 if (name)
2028                 {
2029                         strcpy(buf, ifname);
2030                         return 0;
2031                 }
2032         }
2033 
2034         return -1;
2035 }
2036 
2037 
2038 static void nl80211_parse_rateinfo(struct nlattr **ri,
2039                                    struct iwinfo_rate_entry *re)
2040 {
2041         if (ri[NL80211_RATE_INFO_BITRATE32])
2042                 re->rate = nla_get_u32(ri[NL80211_RATE_INFO_BITRATE32]) * 100;
2043         else if (ri[NL80211_RATE_INFO_BITRATE])
2044                 re->rate = nla_get_u16(ri[NL80211_RATE_INFO_BITRATE]) * 100;
2045 
2046         if (ri[NL80211_RATE_INFO_HE_MCS])
2047         {
2048                 re->is_he = 1;
2049                 re->mcs = nla_get_u8(ri[NL80211_RATE_INFO_HE_MCS]);
2050 
2051                 if (ri[NL80211_RATE_INFO_HE_NSS])
2052                         re->nss = nla_get_u8(ri[NL80211_RATE_INFO_HE_NSS]);
2053                 if (ri[NL80211_RATE_INFO_HE_GI])
2054                         re->he_gi = nla_get_u8(ri[NL80211_RATE_INFO_HE_GI]);
2055                 if (ri[NL80211_RATE_INFO_HE_DCM])
2056                         re->he_dcm = nla_get_u8(ri[NL80211_RATE_INFO_HE_DCM]);
2057         }
2058         else if (ri[NL80211_RATE_INFO_VHT_MCS])
2059         {
2060                 re->is_vht = 1;
2061                 re->mcs = nla_get_u8(ri[NL80211_RATE_INFO_VHT_MCS]);
2062 
2063                 if (ri[NL80211_RATE_INFO_VHT_NSS])
2064                         re->nss = nla_get_u8(ri[NL80211_RATE_INFO_VHT_NSS]);
2065         }
2066         else if (ri[NL80211_RATE_INFO_MCS])
2067         {
2068                 re->is_ht = 1;
2069                 re->mcs = nla_get_u8(ri[NL80211_RATE_INFO_MCS]);
2070         }
2071 
2072         if (ri[NL80211_RATE_INFO_5_MHZ_WIDTH])
2073                 re->mhz = 5;
2074         else if (ri[NL80211_RATE_INFO_10_MHZ_WIDTH])
2075                 re->mhz = 10;
2076         else if (ri[NL80211_RATE_INFO_40_MHZ_WIDTH])
2077                 re->mhz = 40;
2078         else if (ri[NL80211_RATE_INFO_80_MHZ_WIDTH])
2079                 re->mhz = 80;
2080         else if (ri[NL80211_RATE_INFO_80P80_MHZ_WIDTH] ||
2081                  ri[NL80211_RATE_INFO_160_MHZ_WIDTH])
2082                 re->mhz = 160;
2083         else
2084                 re->mhz = 20;
2085 
2086         if (ri[NL80211_RATE_INFO_SHORT_GI])
2087                 re->is_short_gi = 1;
2088 
2089         re->is_40mhz = (re->mhz == 40);
2090 }
2091 
2092 static int nl80211_get_survey_cb(struct nl_msg *msg, void *arg)
2093 {
2094         struct nl80211_array_buf *arr = arg;
2095         struct iwinfo_survey_entry *e = arr->buf;
2096         struct nlattr **attr = nl80211_parse(msg);
2097         struct nlattr *sinfo[NL80211_SURVEY_INFO_MAX + 1];
2098         int rc;
2099 
2100         static struct nla_policy survey_policy[NL80211_SURVEY_INFO_MAX + 1] = {
2101                 [NL80211_SURVEY_INFO_FREQUENCY] = { .type = NLA_U32 },
2102                 [NL80211_SURVEY_INFO_NOISE]  = { .type = NLA_U8     },
2103                 [NL80211_SURVEY_INFO_TIME] = { .type = NLA_U64   },
2104                 [NL80211_SURVEY_INFO_TIME_BUSY] = { .type = NLA_U64   },
2105                 [NL80211_SURVEY_INFO_TIME_EXT_BUSY] = { .type = NLA_U64   },
2106                 [NL80211_SURVEY_INFO_TIME_RX] = { .type = NLA_U64   },
2107                 [NL80211_SURVEY_INFO_TIME_TX] = { .type = NLA_U64   },
2108         };
2109 
2110         rc = nla_parse_nested(sinfo, NL80211_SURVEY_INFO_MAX,
2111                                 attr[NL80211_ATTR_SURVEY_INFO],
2112                                 survey_policy);
2113         if (rc)
2114                 return NL_SKIP;
2115 
2116         /* advance to end of array */
2117         e += arr->count;
2118         memset(e, 0, sizeof(*e));
2119 
2120         if (sinfo[NL80211_SURVEY_INFO_FREQUENCY])
2121                 e->mhz = nla_get_u32(sinfo[NL80211_SURVEY_INFO_FREQUENCY]);
2122 
2123         if (sinfo[NL80211_SURVEY_INFO_NOISE])
2124                 e->noise = nla_get_u8(sinfo[NL80211_SURVEY_INFO_NOISE]);
2125 
2126         if (sinfo[NL80211_SURVEY_INFO_TIME])
2127                 e->active_time = nla_get_u64(sinfo[NL80211_SURVEY_INFO_TIME]);
2128 
2129         if (sinfo[NL80211_SURVEY_INFO_TIME_BUSY])
2130                 e->busy_time = nla_get_u64(sinfo[NL80211_SURVEY_INFO_TIME_BUSY]);
2131 
2132         if (sinfo[NL80211_SURVEY_INFO_TIME_EXT_BUSY])
2133                 e->busy_time_ext = nla_get_u64(sinfo[NL80211_SURVEY_INFO_TIME_EXT_BUSY]);
2134 
2135         if (sinfo[NL80211_SURVEY_INFO_TIME_RX])
2136                 e->rxtime = nla_get_u64(sinfo[NL80211_SURVEY_INFO_TIME_RX]);
2137 
2138         if (sinfo[NL80211_SURVEY_INFO_TIME_TX])
2139                 e->txtime = nla_get_u64(sinfo[NL80211_SURVEY_INFO_TIME_TX]);
2140 
2141         arr->count++;
2142         return NL_SKIP;
2143 }
2144 
2145 
2146 static void plink_state_to_str(char *dst, unsigned state)
2147 {
2148         switch (state) {
2149         case NL80211_PLINK_LISTEN:
2150                 strcpy(dst, "LISTEN");
2151                 break;
2152         case NL80211_PLINK_OPN_SNT:
2153                 strcpy(dst, "OPN_SNT");
2154                 break;
2155         case NL80211_PLINK_OPN_RCVD:
2156                 strcpy(dst, "OPN_RCVD");
2157                 break;
2158         case NL80211_PLINK_CNF_RCVD:
2159                 strcpy(dst, "CNF_RCVD");
2160                 break;
2161         case NL80211_PLINK_ESTAB:
2162                 strcpy(dst, "ESTAB");
2163                 break;
2164         case NL80211_PLINK_HOLDING:
2165                 strcpy(dst, "HOLDING");
2166                 break;
2167         case NL80211_PLINK_BLOCKED:
2168                 strcpy(dst, "BLOCKED");
2169                 break;
2170         default:
2171                 strcpy(dst, "UNKNOWN");
2172                 break;
2173         }
2174 }
2175 
2176 static void power_mode_to_str(char *dst, struct nlattr *a)
2177 {
2178         enum nl80211_mesh_power_mode pm = nla_get_u32(a);
2179 
2180         switch (pm) {
2181         case NL80211_MESH_POWER_ACTIVE:
2182                 strcpy(dst, "ACTIVE");
2183                 break;
2184         case NL80211_MESH_POWER_LIGHT_SLEEP:
2185                 strcpy(dst, "LIGHT SLEEP");
2186                 break;
2187         case NL80211_MESH_POWER_DEEP_SLEEP:
2188                 strcpy(dst, "DEEP SLEEP");
2189                 break;
2190         default:
2191                 strcpy(dst, "UNKNOWN");
2192                 break;
2193         }
2194 }
2195 
2196 static int nl80211_get_assoclist_cb(struct nl_msg *msg, void *arg)
2197 {
2198         struct nl80211_array_buf *arr = arg;
2199         struct iwinfo_assoclist_entry *e = arr->buf;
2200         struct nlattr **attr = nl80211_parse(msg);
2201         struct nlattr *sinfo[NL80211_STA_INFO_MAX + 1];
2202         struct nlattr *rinfo[NL80211_RATE_INFO_MAX + 1];
2203         struct nl80211_sta_flag_update *sta_flags;
2204 
2205         static struct nla_policy stats_policy[NL80211_STA_INFO_MAX + 1] = {
2206                 [NL80211_STA_INFO_INACTIVE_TIME] = { .type = NLA_U32    },
2207                 [NL80211_STA_INFO_RX_PACKETS]    = { .type = NLA_U32    },
2208                 [NL80211_STA_INFO_TX_PACKETS]    = { .type = NLA_U32    },
2209                 [NL80211_STA_INFO_RX_BITRATE]    = { .type = NLA_NESTED },
2210                 [NL80211_STA_INFO_TX_BITRATE]    = { .type = NLA_NESTED },
2211                 [NL80211_STA_INFO_SIGNAL]        = { .type = NLA_U8     },
2212                 [NL80211_STA_INFO_SIGNAL_AVG]    = { .type = NLA_U8     },
2213                 [NL80211_STA_INFO_RX_BYTES]      = { .type = NLA_U32    },
2214                 [NL80211_STA_INFO_TX_BYTES]      = { .type = NLA_U32    },
2215                 [NL80211_STA_INFO_TX_RETRIES]    = { .type = NLA_U32    },
2216                 [NL80211_STA_INFO_TX_FAILED]     = { .type = NLA_U32    },
2217                 [NL80211_STA_INFO_CONNECTED_TIME]= { .type = NLA_U32    },
2218                 [NL80211_STA_INFO_RX_DROP_MISC]  = { .type = NLA_U64    },
2219                 [NL80211_STA_INFO_T_OFFSET]      = { .type = NLA_U64    },
2220                 [NL80211_STA_INFO_STA_FLAGS] =
2221                         { .minlen = sizeof(struct nl80211_sta_flag_update) },
2222                 [NL80211_STA_INFO_EXPECTED_THROUGHPUT]   = { .type = NLA_U32    },
2223                 /* mesh */
2224                 [NL80211_STA_INFO_LLID]          = { .type = NLA_U16    },
2225                 [NL80211_STA_INFO_PLID]          = { .type = NLA_U16    },
2226                 [NL80211_STA_INFO_PLINK_STATE]   = { .type = NLA_U8     },
2227                 [NL80211_STA_INFO_LOCAL_PM]      = { .type = NLA_U32    },
2228                 [NL80211_STA_INFO_PEER_PM]       = { .type = NLA_U32    },
2229                 [NL80211_STA_INFO_NONPEER_PM]    = { .type = NLA_U32    },
2230         };
2231 
2232         static struct nla_policy rate_policy[NL80211_RATE_INFO_MAX + 1] = {
2233                 [NL80211_RATE_INFO_BITRATE]      = { .type = NLA_U16    },
2234                 [NL80211_RATE_INFO_MCS]          = { .type = NLA_U8     },
2235                 [NL80211_RATE_INFO_40_MHZ_WIDTH] = { .type = NLA_FLAG   },
2236                 [NL80211_RATE_INFO_SHORT_GI]     = { .type = NLA_FLAG   },
2237         };
2238 
2239         /* advance to end of array */
2240         e += arr->count;
2241         memset(e, 0, sizeof(*e));
2242 
2243         if (attr[NL80211_ATTR_MAC])
2244                 memcpy(e->mac, nla_data(attr[NL80211_ATTR_MAC]), 6);
2245 
2246         if (attr[NL80211_ATTR_STA_INFO] &&
2247             !nla_parse_nested(sinfo, NL80211_STA_INFO_MAX,
2248                               attr[NL80211_ATTR_STA_INFO], stats_policy))
2249         {
2250                 if (sinfo[NL80211_STA_INFO_SIGNAL])
2251                         e->signal = nla_get_u8(sinfo[NL80211_STA_INFO_SIGNAL]);
2252 
2253                 if (sinfo[NL80211_STA_INFO_SIGNAL_AVG])
2254                         e->signal_avg = nla_get_u8(sinfo[NL80211_STA_INFO_SIGNAL_AVG]);
2255 
2256                 if (sinfo[NL80211_STA_INFO_INACTIVE_TIME])
2257                         e->inactive = nla_get_u32(sinfo[NL80211_STA_INFO_INACTIVE_TIME]);
2258 
2259                 if (sinfo[NL80211_STA_INFO_CONNECTED_TIME])
2260                         e->connected_time = nla_get_u32(sinfo[NL80211_STA_INFO_CONNECTED_TIME]);
2261 
2262                 if (sinfo[NL80211_STA_INFO_RX_PACKETS])
2263                         e->rx_packets = nla_get_u32(sinfo[NL80211_STA_INFO_RX_PACKETS]);
2264 
2265                 if (sinfo[NL80211_STA_INFO_TX_PACKETS])
2266                         e->tx_packets = nla_get_u32(sinfo[NL80211_STA_INFO_TX_PACKETS]);
2267 
2268                 if (sinfo[NL80211_STA_INFO_RX_BITRATE] &&
2269                     !nla_parse_nested(rinfo, NL80211_RATE_INFO_MAX,
2270                                       sinfo[NL80211_STA_INFO_RX_BITRATE], rate_policy))
2271                         nl80211_parse_rateinfo(rinfo, &e->rx_rate);
2272 
2273                 if (sinfo[NL80211_STA_INFO_TX_BITRATE] &&
2274                     !nla_parse_nested(rinfo, NL80211_RATE_INFO_MAX,
2275                                       sinfo[NL80211_STA_INFO_TX_BITRATE], rate_policy))
2276                         nl80211_parse_rateinfo(rinfo, &e->tx_rate);
2277 
2278                 if (sinfo[NL80211_STA_INFO_RX_BYTES])
2279                         e->rx_bytes = nla_get_u32(sinfo[NL80211_STA_INFO_RX_BYTES]);
2280 
2281                 if (sinfo[NL80211_STA_INFO_TX_BYTES])
2282                         e->tx_bytes = nla_get_u32(sinfo[NL80211_STA_INFO_TX_BYTES]);
2283 
2284                 if (sinfo[NL80211_STA_INFO_TX_RETRIES])
2285                         e->tx_retries = nla_get_u32(sinfo[NL80211_STA_INFO_TX_RETRIES]);
2286 
2287                 if (sinfo[NL80211_STA_INFO_TX_FAILED])
2288                         e->tx_failed = nla_get_u32(sinfo[NL80211_STA_INFO_TX_FAILED]);
2289 
2290                 if (sinfo[NL80211_STA_INFO_T_OFFSET])
2291                         e->t_offset = nla_get_u64(sinfo[NL80211_STA_INFO_T_OFFSET]);
2292 
2293                 if (sinfo[NL80211_STA_INFO_RX_DROP_MISC])
2294                         e->rx_drop_misc = nla_get_u64(sinfo[NL80211_STA_INFO_RX_DROP_MISC]);
2295 
2296                 if (sinfo[NL80211_STA_INFO_EXPECTED_THROUGHPUT])
2297                         e->thr = nla_get_u32(sinfo[NL80211_STA_INFO_EXPECTED_THROUGHPUT]);
2298 
2299                 /* mesh */
2300                 if (sinfo[NL80211_STA_INFO_LLID])
2301                         e->llid = nla_get_u16(sinfo[NL80211_STA_INFO_LLID]);
2302 
2303                 if (sinfo[NL80211_STA_INFO_PLID])
2304                         e->plid = nla_get_u16(sinfo[NL80211_STA_INFO_PLID]);
2305 
2306                 if (sinfo[NL80211_STA_INFO_PLINK_STATE])
2307                         plink_state_to_str(e->plink_state,
2308                                 nla_get_u8(sinfo[NL80211_STA_INFO_PLINK_STATE]));
2309 
2310                 if (sinfo[NL80211_STA_INFO_LOCAL_PM])
2311                         power_mode_to_str(e->local_ps, sinfo[NL80211_STA_INFO_LOCAL_PM]);
2312                 if (sinfo[NL80211_STA_INFO_PEER_PM])
2313                         power_mode_to_str(e->peer_ps, sinfo[NL80211_STA_INFO_PEER_PM]);
2314                 if (sinfo[NL80211_STA_INFO_NONPEER_PM])
2315                         power_mode_to_str(e->nonpeer_ps, sinfo[NL80211_STA_INFO_NONPEER_PM]);
2316 
2317                 /* Station flags */
2318                 if (sinfo[NL80211_STA_INFO_STA_FLAGS])
2319                 {
2320                         sta_flags = (struct nl80211_sta_flag_update *)
2321                                 nla_data(sinfo[NL80211_STA_INFO_STA_FLAGS]);
2322 
2323                         if (sta_flags->mask & BIT(NL80211_STA_FLAG_AUTHORIZED) &&
2324                             sta_flags->set & BIT(NL80211_STA_FLAG_AUTHORIZED))
2325                                 e->is_authorized = 1;
2326 
2327                         if (sta_flags->mask & BIT(NL80211_STA_FLAG_AUTHENTICATED) &&
2328                             sta_flags->set & BIT(NL80211_STA_FLAG_AUTHENTICATED))
2329                                 e->is_authenticated = 1;
2330 
2331                         if (sta_flags->mask & BIT(NL80211_STA_FLAG_SHORT_PREAMBLE) &&
2332                             sta_flags->set & BIT(NL80211_STA_FLAG_SHORT_PREAMBLE))
2333                                 e->is_preamble_short = 1;
2334 
2335                         if (sta_flags->mask & BIT(NL80211_STA_FLAG_WME) &&
2336                             sta_flags->set & BIT(NL80211_STA_FLAG_WME))
2337                                 e->is_wme = 1;
2338 
2339                         if (sta_flags->mask & BIT(NL80211_STA_FLAG_MFP) &&
2340                             sta_flags->set & BIT(NL80211_STA_FLAG_MFP))
2341                                 e->is_mfp = 1;
2342 
2343                         if (sta_flags->mask & BIT(NL80211_STA_FLAG_TDLS_PEER) &&
2344                             sta_flags->set & BIT(NL80211_STA_FLAG_TDLS_PEER))
2345                                 e->is_tdls = 1;
2346                 }
2347         }
2348 
2349         e->noise = 0; /* filled in by caller */
2350         arr->count++;
2351 
2352         return NL_SKIP;
2353 }
2354 
2355 static int nl80211_get_survey(const char *ifname, char *buf, int *len)
2356 {
2357         struct nl80211_array_buf arr = { .buf = buf, .count = 0 };
2358         int rc;
2359 
2360         rc = nl80211_request(ifname, NL80211_CMD_GET_SURVEY,
2361                         NLM_F_DUMP, nl80211_get_survey_cb, &arr);
2362         if (!rc)
2363                 *len = (arr.count * sizeof(struct iwinfo_survey_entry));
2364         else
2365                 *len = 0;
2366 
2367         return 0;
2368 }
2369 
2370 static int nl80211_get_assoclist(const char *ifname, char *buf, int *len)
2371 {
2372         DIR *d;
2373         int i, noise = 0;
2374         struct dirent *de;
2375         struct nl80211_array_buf arr = { .buf = buf, .count = 0 };
2376         struct iwinfo_assoclist_entry *e;
2377 
2378         if ((d = opendir("/sys/class/net")) != NULL)
2379         {
2380                 while ((de = readdir(d)) != NULL)
2381                 {
2382                         if (!strncmp(de->d_name, ifname, strlen(ifname)) &&
2383                             (!de->d_name[strlen(ifname)] ||
2384                              !strncmp(&de->d_name[strlen(ifname)], ".sta", 4)))
2385                         {
2386                                 nl80211_request(de->d_name, NL80211_CMD_GET_STATION,
2387                                                 NLM_F_DUMP, nl80211_get_assoclist_cb, &arr);
2388                         }
2389                 }
2390 
2391                 closedir(d);
2392 
2393                 if (!nl80211_get_noise(ifname, &noise))
2394                         for (i = 0, e = arr.buf; i < arr.count; i++, e++)
2395                                 e->noise = noise;
2396 
2397                 *len = (arr.count * sizeof(struct iwinfo_assoclist_entry));
2398                 return 0;
2399         }
2400 
2401         return -1;
2402 }
2403 
2404 static int nl80211_get_txpwrlist_cb(struct nl_msg *msg, void *arg)
2405 {
2406         int *dbm_max = arg;
2407         int ch_cur, ch_cmp, bands_remain, freqs_remain;
2408 
2409         struct nlattr **attr = nl80211_parse(msg);
2410         struct nlattr *bands[NL80211_BAND_ATTR_MAX + 1];
2411         struct nlattr *freqs[NL80211_FREQUENCY_ATTR_MAX + 1];
2412         struct nlattr *band, *freq;
2413 
2414         static struct nla_policy freq_policy[NL80211_FREQUENCY_ATTR_MAX + 1] = {
2415                 [NL80211_FREQUENCY_ATTR_FREQ]         = { .type = NLA_U32  },
2416                 [NL80211_FREQUENCY_ATTR_DISABLED]     = { .type = NLA_FLAG },
2417                 [NL80211_FREQUENCY_ATTR_PASSIVE_SCAN] = { .type = NLA_FLAG },
2418                 [NL80211_FREQUENCY_ATTR_NO_IBSS]      = { .type = NLA_FLAG },
2419                 [NL80211_FREQUENCY_ATTR_RADAR]        = { .type = NLA_FLAG },
2420                 [NL80211_FREQUENCY_ATTR_MAX_TX_POWER] = { .type = NLA_U32  },
2421         };
2422 
2423         ch_cur = *dbm_max; /* value int* is initialized with channel by caller */
2424         *dbm_max = -1;
2425 
2426         nla_for_each_nested(band, attr[NL80211_ATTR_WIPHY_BANDS], bands_remain)
2427         {
2428                 nla_parse(bands, NL80211_BAND_ATTR_MAX, nla_data(band),
2429                           nla_len(band), NULL);
2430 
2431                 nla_for_each_nested(freq, bands[NL80211_BAND_ATTR_FREQS], freqs_remain)
2432                 {
2433                         nla_parse(freqs, NL80211_FREQUENCY_ATTR_MAX,
2434                                   nla_data(freq), nla_len(freq), freq_policy);
2435 
2436                         ch_cmp = nl80211_freq2channel(nla_get_u32(
2437                                 freqs[NL80211_FREQUENCY_ATTR_FREQ]));
2438 
2439                         if ((!ch_cur || (ch_cmp == ch_cur)) &&
2440                             freqs[NL80211_FREQUENCY_ATTR_MAX_TX_POWER])
2441                         {
2442                                 *dbm_max = (int)(0.01 * nla_get_u32(
2443                                         freqs[NL80211_FREQUENCY_ATTR_MAX_TX_POWER]));
2444 
2445                                 break;
2446                         }
2447                 }
2448         }
2449 
2450         return NL_SKIP;
2451 }
2452 
2453 static int nl80211_get_txpwrlist(const char *ifname, char *buf, int *len)
2454 {
2455         int err, ch_cur;
2456         int dbm_max = -1, dbm_cur, dbm_cnt;
2457         struct iwinfo_txpwrlist_entry entry;
2458 
2459         if (nl80211_get_channel(ifname, &ch_cur))
2460                 ch_cur = 0;
2461 
2462         /* initialize the value pointer with channel for callback */
2463         dbm_max = ch_cur;
2464 
2465         err = nl80211_request(ifname, NL80211_CMD_GET_WIPHY, 0,
2466                               nl80211_get_txpwrlist_cb, &dbm_max);
2467 
2468         if (!err)
2469         {
2470                 for (dbm_cur = 0, dbm_cnt = 0;
2471                      dbm_cur < dbm_max;
2472                      dbm_cur++, dbm_cnt++)
2473                 {
2474                         entry.dbm = dbm_cur;
2475                         entry.mw  = iwinfo_dbm2mw(dbm_cur);
2476 
2477                         memcpy(&buf[dbm_cnt * sizeof(entry)], &entry, sizeof(entry));
2478                 }
2479 
2480                 entry.dbm = dbm_max;
2481                 entry.mw  = iwinfo_dbm2mw(dbm_max);
2482 
2483                 memcpy(&buf[dbm_cnt * sizeof(entry)], &entry, sizeof(entry));
2484                 dbm_cnt++;
2485 
2486                 *len = dbm_cnt * sizeof(entry);
2487                 return 0;
2488         }
2489 
2490         return -1;
2491 }
2492 
2493 static void nl80211_get_scancrypto(char *spec, struct iwinfo_crypto_entry *c)
2494 {
2495         int wpa_version = 0;
2496         char *p, *q, *proto, *suites;
2497 
2498         c->enabled = 0;
2499 
2500         for (p = strtok_r(spec, "[]", &q); p; p = strtok_r(NULL, "[]", &q)) {
2501                 if (!strcmp(p, "WEP")) {
2502                         c->enabled      = 1;
2503                         c->auth_suites  = IWINFO_KMGMT_NONE;
2504                         c->auth_algs    = IWINFO_AUTH_OPEN | IWINFO_AUTH_SHARED;
2505                         c->pair_ciphers = IWINFO_CIPHER_WEP40 | IWINFO_CIPHER_WEP104;
2506                         break;
2507                 }
2508 
2509                 proto = strtok(p, "-");
2510                 suites = strtok(NULL, "]");
2511 
2512                 if (!proto || !suites)
2513                         continue;
2514 
2515                 if (!strcmp(proto, "WPA2") || !strcmp(proto, "RSN"))
2516                         wpa_version = 2;
2517                 else if (!strcmp(proto, "WPA"))
2518                         wpa_version = 1;
2519                 else
2520                         continue;
2521 
2522                 c->enabled = 1;
2523 
2524                 parse_wpa_suites(suites, wpa_version, &c->wpa_version, &c->auth_suites);
2525                 parse_wpa_ciphers(suites, &c->pair_ciphers);
2526         }
2527 }
2528 
2529 
2530 struct nl80211_scanlist {
2531         struct iwinfo_scanlist_entry *e;
2532         int len;
2533 };
2534 
2535 
2536 static void nl80211_get_scanlist_ie(struct nlattr **bss,
2537                                     struct iwinfo_scanlist_entry *e)
2538 {
2539         int ielen = nla_len(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
2540         unsigned char *ie = nla_data(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
2541         static unsigned char ms_oui[3] = { 0x00, 0x50, 0xf2 };
2542         int len;
2543 
2544         while (ielen >= 2 && ielen >= ie[1])
2545         {
2546                 switch (ie[0])
2547                 {
2548                 case 0: /* SSID */
2549                 case 114: /* Mesh ID */
2550                         if (e->ssid[0] == 0) {
2551                                 len = min(ie[1], IWINFO_ESSID_MAX_SIZE);
2552                                 memcpy(e->ssid, ie + 2, len);
2553                                 e->ssid[len] = 0;
2554                         }
2555                         break;
2556 
2557                 case 48: /* RSN */
2558                         iwinfo_parse_rsn(&e->crypto, ie + 2, ie[1],
2559                                          IWINFO_CIPHER_CCMP, IWINFO_KMGMT_8021x);
2560                         break;
2561 
2562                 case 221: /* Vendor */
2563                         if (ie[1] >= 4 && !memcmp(ie + 2, ms_oui, 3) && ie[5] == 1)
2564                                 iwinfo_parse_rsn(&e->crypto, ie + 6, ie[1] - 4,
2565                                                  IWINFO_CIPHER_TKIP, IWINFO_KMGMT_PSK);
2566                         break;
2567                 case 61: /* HT operation */
2568                         if (ie[1] >= 3) {
2569                                 e->ht_chan_info.primary_chan = ie[2];
2570                                 e->ht_chan_info.secondary_chan_off = ie[3] & 0x3;
2571                                 e->ht_chan_info.chan_width = (ie[4] & 0x4)>>2;
2572                         }
2573                         break;
2574                 case 192: /* VHT operation */
2575                         if (ie[1] >= 3) {
2576                                 e->vht_chan_info.chan_width = ie[2];
2577                                 e->vht_chan_info.center_chan_1 = ie[3];
2578                                 e->vht_chan_info.center_chan_2 = ie[4];
2579                         }
2580                         break;
2581                 }
2582 
2583                 ielen -= ie[1] + 2;
2584                 ie += ie[1] + 2;
2585         }
2586 }
2587 
2588 static int nl80211_get_scanlist_cb(struct nl_msg *msg, void *arg)
2589 {
2590         int8_t rssi;
2591         uint16_t caps;
2592 
2593         struct nl80211_scanlist *sl = arg;
2594         struct nlattr **tb = nl80211_parse(msg);
2595         struct nlattr *bss[NL80211_BSS_MAX + 1];
2596 
2597         static struct nla_policy bss_policy[NL80211_BSS_MAX + 1] = {
2598                 [NL80211_BSS_TSF]                  = { .type = NLA_U64 },
2599                 [NL80211_BSS_FREQUENCY]            = { .type = NLA_U32 },
2600                 [NL80211_BSS_BSSID]                = { 0 },
2601                 [NL80211_BSS_BEACON_INTERVAL]      = { .type = NLA_U16 },
2602                 [NL80211_BSS_CAPABILITY]           = { .type = NLA_U16 },
2603                 [NL80211_BSS_INFORMATION_ELEMENTS] = { 0 },
2604                 [NL80211_BSS_SIGNAL_MBM]           = { .type = NLA_U32 },
2605                 [NL80211_BSS_SIGNAL_UNSPEC]        = { .type = NLA_U8  },
2606                 [NL80211_BSS_STATUS]               = { .type = NLA_U32 },
2607                 [NL80211_BSS_SEEN_MS_AGO]          = { .type = NLA_U32 },
2608                 [NL80211_BSS_BEACON_IES]           = { 0 },
2609         };
2610 
2611         if (!tb[NL80211_ATTR_BSS] ||
2612                 nla_parse_nested(bss, NL80211_BSS_MAX, tb[NL80211_ATTR_BSS],
2613                                  bss_policy) ||
2614                 !bss[NL80211_BSS_BSSID])
2615         {
2616                 return NL_SKIP;
2617         }
2618 
2619         if (bss[NL80211_BSS_CAPABILITY])
2620                 caps = nla_get_u16(bss[NL80211_BSS_CAPABILITY]);
2621         else
2622                 caps = 0;
2623 
2624         memset(sl->e, 0, sizeof(*sl->e));
2625         memcpy(sl->e->mac, nla_data(bss[NL80211_BSS_BSSID]), 6);
2626 
2627         if (caps & (1<<1))
2628                 sl->e->mode = IWINFO_OPMODE_ADHOC;
2629         else if (caps & (1<<0))
2630                 sl->e->mode = IWINFO_OPMODE_MASTER;
2631         else
2632                 sl->e->mode = IWINFO_OPMODE_MESHPOINT;
2633 
2634         if (caps & (1<<4))
2635                 sl->e->crypto.enabled = 1;
2636 
2637         if (bss[NL80211_BSS_FREQUENCY])
2638         {
2639                 sl->e->mhz = nla_get_u32(bss[NL80211_BSS_FREQUENCY]);
2640                 sl->e->band = nl80211_freq2band(sl->e->mhz);
2641                 sl->e->channel = nl80211_freq2channel(sl->e->mhz);
2642         }
2643 
2644         if (bss[NL80211_BSS_INFORMATION_ELEMENTS])
2645                 nl80211_get_scanlist_ie(bss, sl->e);
2646 
2647         if (bss[NL80211_BSS_SIGNAL_MBM])
2648         {
2649                 sl->e->signal =
2650                         (uint8_t)((int32_t)nla_get_u32(bss[NL80211_BSS_SIGNAL_MBM]) / 100);
2651 
2652                 rssi = sl->e->signal - 0x100;
2653 
2654                 if (rssi < -110)
2655                         rssi = -110;
2656                 else if (rssi > -40)
2657                         rssi = -40;
2658 
2659                 sl->e->quality = (rssi + 110);
2660                 sl->e->quality_max = 70;
2661         }
2662 
2663         if (sl->e->crypto.enabled && !sl->e->crypto.wpa_version)
2664         {
2665                 sl->e->crypto.auth_algs    = IWINFO_AUTH_OPEN | IWINFO_AUTH_SHARED;
2666                 sl->e->crypto.pair_ciphers = IWINFO_CIPHER_WEP40 | IWINFO_CIPHER_WEP104;
2667         }
2668 
2669         sl->e++;
2670         sl->len++;
2671 
2672         return NL_SKIP;
2673 }
2674 
2675 static int nl80211_get_scanlist_nl(const char *ifname, char *buf, int *len)
2676 {
2677         struct nl80211_scanlist sl = { .e = (struct iwinfo_scanlist_entry *)buf };
2678 
2679         if (nl80211_request(ifname, NL80211_CMD_TRIGGER_SCAN, 0, NULL, NULL))
2680                 goto out;
2681 
2682         if (nl80211_wait("nl80211", "scan",
2683                          NL80211_CMD_NEW_SCAN_RESULTS, NL80211_CMD_SCAN_ABORTED))
2684                 goto out;
2685 
2686         if (nl80211_request(ifname, NL80211_CMD_GET_SCAN, NLM_F_DUMP,
2687                             nl80211_get_scanlist_cb, &sl))
2688                 goto out;
2689 
2690         *len = sl.len * sizeof(struct iwinfo_scanlist_entry);
2691         return 0;
2692 
2693 out:
2694         *len = 0;
2695         return -1;
2696 }
2697 
2698 static int wpasupp_ssid_decode(const char *in, char *out, int outlen)
2699 {
2700 #define hex(x) \
2701         (((x) >= 'a') ? ((x) - 'a' + 10) : \
2702                 (((x) >= 'A') ? ((x) - 'A' + 10) : ((x) - '')))
2703 
2704         int len = 0;
2705 
2706         while (*in)
2707         {
2708                 if (len + 1 >= outlen)
2709                         break;
2710 
2711                 switch (*in)
2712                 {
2713                 case '\\':
2714                         in++;
2715                         switch (*in)
2716                         {
2717                         case 'n':
2718                                 out[len++] = '\n'; in++;
2719                                 break;
2720 
2721                         case 'r':
2722                                 out[len++] = '\r'; in++;
2723                                 break;
2724 
2725                         case 't':
2726                                 out[len++] = '\t'; in++;
2727                                 break;
2728 
2729                         case 'e':
2730                                 out[len++] = '\033'; in++;
2731                                 break;
2732 
2733                         case 'x':
2734                                 if (isxdigit(*(in+1)) && isxdigit(*(in+2)))
2735                                         out[len++] = hex(*(in+1)) * 16 + hex(*(in+2));
2736                                 in += 3;
2737                                 break;
2738 
2739                         default:
2740                                 out[len++] = *in++;
2741                                 break;
2742                         }
2743                         break;
2744 
2745                 default:
2746                         out[len++] = *in++;
2747                         break;
2748                 }
2749         }
2750 
2751         if (outlen > len)
2752                 out[len] = '\0';
2753 
2754         return len;
2755 }
2756 
2757 static int nl80211_get_scanlist_wpactl(const char *ifname, char *buf, int *len)
2758 {
2759         int sock, qmax, rssi, tries, count = -1, ready = 0;
2760         char *pos, *line, *bssid, *freq, *signal, *flags, *ssid, reply[4096];
2761         struct sockaddr_un local = { 0 };
2762         struct iwinfo_scanlist_entry *e = (struct iwinfo_scanlist_entry *)buf;
2763 
2764         sock = nl80211_wpactl_connect(ifname, &local);
2765 
2766         if (sock < 0)
2767                 return sock;
2768 
2769         send(sock, "ATTACH", 6, 0);
2770         send(sock, "SCAN", 4, 0);
2771 
2772         /*
2773          * wait for scan results:
2774          *   nl80211_wpactl_recv() will use a timeout of 256ms and we need to scan
2775          *   72 channels at most. We'll also receive two "OK" messages acknowledging
2776          *   the "ATTACH" and "SCAN" commands and the driver might need a bit extra
2777          *   time to process the results, so try 72 + 2 + 1 times.
2778          */
2779         for (tries = 0; tries < 75; tries++)
2780         {
2781                 if (nl80211_wpactl_recv(sock, reply, sizeof(reply)) <= 0)
2782                         continue;
2783 
2784                 /* got an event notification */
2785                 if (reply[0] == '<')
2786                 {
2787                         /* scan results are ready */
2788                         if (strstr(reply, "CTRL-EVENT-SCAN-RESULTS"))
2789                         {
2790                                 /* send "SCAN_RESULTS" command */
2791                                 ready = (send(sock, "SCAN_RESULTS", 12, 0) == 12);
2792                                 break;
2793                         }
2794 
2795                         /* is another unrelated event, retry */
2796                         tries--;
2797                 }
2798 
2799                 /* scanning already in progress, keep awaiting results */
2800                 else if (!strcmp(reply, "FAIL-BUSY\n"))
2801                 {
2802                         tries--;
2803                 }
2804 
2805                 /* another failure, abort */
2806                 else if (!strncmp(reply, "FAIL-", 5))
2807                 {
2808                         break;
2809                 }
2810         }
2811 
2812         /* receive and parse scan results if the wait above didn't time out */
2813         while (ready && nl80211_wpactl_recv(sock, reply, sizeof(reply)) > 0)
2814         {
2815                 /* received an event notification, receive again */
2816                 if (reply[0] == '<')
2817                         continue;
2818 
2819                 nl80211_get_quality_max(ifname, &qmax);
2820 
2821                 for (line = strtok_r(reply, "\n", &pos);
2822                      line != NULL;
2823                      line = strtok_r(NULL, "\n", &pos))
2824                 {
2825                         /* skip header line */
2826                         if (count < 0)
2827                         {
2828                                 count++;
2829                                 continue;
2830                         }
2831 
2832                         bssid  = strtok(line, "\t");
2833                         freq   = strtok(NULL, "\t");
2834                         signal = strtok(NULL, "\t");
2835                         flags  = strtok(NULL, "\t");
2836                         ssid   = strtok(NULL, "\n");
2837 
2838                         if (!bssid || !freq || !signal || !flags)
2839                                 continue;
2840 
2841                         /* BSSID */
2842                         e->mac[0] = strtol(&bssid[0],  NULL, 16);
2843                         e->mac[1] = strtol(&bssid[3],  NULL, 16);
2844                         e->mac[2] = strtol(&bssid[6],  NULL, 16);
2845                         e->mac[3] = strtol(&bssid[9],  NULL, 16);
2846                         e->mac[4] = strtol(&bssid[12], NULL, 16);
2847                         e->mac[5] = strtol(&bssid[15], NULL, 16);
2848 
2849                         /* SSID */
2850                         if (ssid)
2851                                 wpasupp_ssid_decode(ssid, e->ssid, sizeof(e->ssid));
2852                         else
2853                                 e->ssid[0] = 0;
2854 
2855                         /* Mode */
2856                         if (strstr(flags, "[MESH]"))
2857                                 e->mode = IWINFO_OPMODE_MESHPOINT;
2858                         else if (strstr(flags, "[IBSS]"))
2859                                 e->mode = IWINFO_OPMODE_ADHOC;
2860                         else
2861                                 e->mode = IWINFO_OPMODE_MASTER;
2862 
2863                         /* Channel */
2864                         e->mhz = atoi(freq);
2865                         e->band = nl80211_freq2band(e->mhz);
2866                         e->channel = nl80211_freq2channel(e->mhz);
2867 
2868                         /* Signal */
2869                         rssi = atoi(signal);
2870                         e->signal = rssi;
2871 
2872                         /* Quality */
2873                         if (rssi < 0)
2874                         {
2875                                 /* The cfg80211 wext compat layer assumes a signal range
2876                                  * of -110 dBm to -40 dBm, the quality value is derived
2877                                  * by adding 110 to the signal level */
2878                                 if (rssi < -110)
2879                                         rssi = -110;
2880                                 else if (rssi > -40)
2881                                         rssi = -40;
2882 
2883                                 e->quality = (rssi + 110);
2884                         }
2885                         else
2886                         {
2887                                 e->quality = rssi;
2888                         }
2889 
2890                         /* Max. Quality */
2891                         e->quality_max = qmax;
2892 
2893                         /* Crypto */
2894                         nl80211_get_scancrypto(flags, &e->crypto);
2895 
2896                         count++;
2897                         e++;
2898                 }
2899 
2900                 *len = count * sizeof(struct iwinfo_scanlist_entry);
2901                 break;
2902         }
2903 
2904         close(sock);
2905         unlink(local.sun_path);
2906 
2907         return (count >= 0) ? 0 : -1;
2908 }
2909 
2910 static int nl80211_get_scanlist(const char *ifname, char *buf, int *len)
2911 {
2912         char *res;
2913         int rv, mode;
2914 
2915         *len = 0;
2916 
2917         /* Got a radioX pseudo interface, find some interface on it or create one */
2918         if (!strncmp(ifname, "radio", 5))
2919         {
2920                 /* Reuse existing interface */
2921                 if ((res = nl80211_phy2ifname(ifname)) != NULL)
2922                 {
2923                         return nl80211_get_scanlist(res, buf, len);
2924                 }
2925 
2926                 /* Need to spawn a temporary iface for scanning */
2927                 else if ((res = nl80211_ifadd(ifname)) != NULL)
2928                 {
2929                         rv = nl80211_get_scanlist(res, buf, len);
2930                         nl80211_ifdel(res);
2931                         return rv;
2932                 }
2933         }
2934 
2935         /* WPA supplicant */
2936         if (!nl80211_get_scanlist_wpactl(ifname, buf, len))
2937         {
2938                 return 0;
2939         }
2940 
2941         /* station / ad-hoc / monitor scan */
2942         else if (!nl80211_get_mode(ifname, &mode) &&
2943                  (mode == IWINFO_OPMODE_ADHOC ||
2944                   mode == IWINFO_OPMODE_MASTER ||
2945                   mode == IWINFO_OPMODE_CLIENT ||
2946                   mode == IWINFO_OPMODE_MONITOR) &&
2947                  iwinfo_ifup(ifname))
2948         {
2949                 return nl80211_get_scanlist_nl(ifname, buf, len);
2950         }
2951 
2952         /* AP scan */
2953         else
2954         {
2955                 /* Got a temp interface, don't create yet another one */
2956                 if (!strncmp(ifname, "tmp.", 4))
2957                 {
2958                         if (!iwinfo_ifup(ifname))
2959                                 return -1;
2960 
2961                         rv = nl80211_get_scanlist_nl(ifname, buf, len);
2962                         iwinfo_ifdown(ifname);
2963                         return rv;
2964                 }
2965 
2966                 /* Spawn a new scan interface */
2967                 else
2968                 {
2969                         if (!(res = nl80211_ifadd(ifname)))
2970                                 return -1;
2971 
2972                         iwinfo_ifmac(res);
2973 
2974                         /* if we can take the new interface up, the driver supports an
2975                          * additional interface and there's no need to tear down the ap */
2976                         if (iwinfo_ifup(res))
2977                         {
2978                                 rv = nl80211_get_scanlist_nl(res, buf, len);
2979                                 iwinfo_ifdown(res);
2980                         }
2981 
2982                         /* driver cannot create secondary interface, take down ap
2983                          * during scan */
2984                         else if (iwinfo_ifdown(ifname) && iwinfo_ifup(res))
2985                         {
2986                                 rv = nl80211_get_scanlist_nl(res, buf, len);
2987                                 iwinfo_ifdown(res);
2988                                 iwinfo_ifup(ifname);
2989                                 nl80211_hostapd_hup(ifname);
2990                         }
2991                         else
2992                                 rv = -1;
2993 
2994                         nl80211_ifdel(res);
2995                         return rv;
2996                 }
2997         }
2998 
2999         return -1;
3000 }
3001 
3002 static int nl80211_get_freqlist_cb(struct nl_msg *msg, void *arg)
3003 {
3004         int bands_remain, freqs_remain;
3005 
3006         struct nl80211_array_buf *arr = arg;
3007         struct iwinfo_freqlist_entry *e;
3008 
3009         struct nlattr **attr = nl80211_parse(msg);
3010         struct nlattr *bands[NL80211_BAND_ATTR_MAX + 1];
3011         struct nlattr *freqs[NL80211_FREQUENCY_ATTR_MAX + 1];
3012         struct nlattr *band, *freq;
3013 
3014         e = arr->buf;
3015         e += arr->count;
3016 
3017         if (attr[NL80211_ATTR_WIPHY_BANDS]) {
3018                 nla_for_each_nested(band, attr[NL80211_ATTR_WIPHY_BANDS], bands_remain)
3019                 {
3020                         nla_parse(bands, NL80211_BAND_ATTR_MAX,
3021                                   nla_data(band), nla_len(band), NULL);
3022 
3023                         if (bands[NL80211_BAND_ATTR_FREQS]) {
3024                                 nla_for_each_nested(freq, bands[NL80211_BAND_ATTR_FREQS], freqs_remain)
3025                                 {
3026                                         nla_parse(freqs, NL80211_FREQUENCY_ATTR_MAX,
3027                                                   nla_data(freq), nla_len(freq), NULL);
3028 
3029                                         if (!freqs[NL80211_FREQUENCY_ATTR_FREQ] ||
3030                                             freqs[NL80211_FREQUENCY_ATTR_DISABLED])
3031                                                 continue;
3032 
3033                                         e->band = nl80211_get_band(band->nla_type);
3034                                         e->mhz = nla_get_u32(freqs[NL80211_FREQUENCY_ATTR_FREQ]);
3035                                         e->channel = nl80211_freq2channel(e->mhz);
3036 
3037                                         if (freqs[NL80211_FREQUENCY_ATTR_NO_HT40_MINUS])
3038                                                 e->flags |= IWINFO_FREQ_NO_HT40MINUS;
3039                                         if (freqs[NL80211_FREQUENCY_ATTR_NO_HT40_PLUS])
3040                                                 e->flags |= IWINFO_FREQ_NO_HT40PLUS;
3041                                         if (freqs[NL80211_FREQUENCY_ATTR_NO_80MHZ])
3042                                                 e->flags |= IWINFO_FREQ_NO_80MHZ;
3043                                         if (freqs[NL80211_FREQUENCY_ATTR_NO_160MHZ])
3044                                                 e->flags |= IWINFO_FREQ_NO_160MHZ;
3045                                         if (freqs[NL80211_FREQUENCY_ATTR_NO_20MHZ])
3046                                                 e->flags |= IWINFO_FREQ_NO_20MHZ;
3047                                         if (freqs[NL80211_FREQUENCY_ATTR_NO_10MHZ])
3048                                                 e->flags |= IWINFO_FREQ_NO_10MHZ;
3049                                         if (freqs[NL80211_FREQUENCY_ATTR_NO_HE])
3050                                                 e->flags |= IWINFO_FREQ_NO_HE;
3051                                         if (freqs[NL80211_FREQUENCY_ATTR_NO_IR] &&
3052                                             !freqs[NL80211_FREQUENCY_ATTR_RADAR])
3053                                                 e->flags |= IWINFO_FREQ_NO_IR;
3054                                         if (freqs[NL80211_FREQUENCY_ATTR_INDOOR_ONLY])
3055                                                 e->flags |= IWINFO_FREQ_INDOOR_ONLY;
3056 
3057                                         /* keep backwards compatibility */
3058                                         e->restricted = (e->flags & IWINFO_FREQ_NO_IR) ? 1 : 0;
3059 
3060                                         e++;
3061                                         arr->count++;
3062                                 }
3063                         }
3064                 }
3065         }
3066 
3067         return NL_SKIP;
3068 }
3069 
3070 static int nl80211_get_freqlist(const char *ifname, char *buf, int *len)
3071 {
3072         struct nl80211_msg_conveyor *cv;
3073         struct nl80211_array_buf arr = { .buf = buf, .count = 0 };
3074         uint32_t features = nl80211_get_protocol_features(ifname);
3075         int flags;
3076 
3077         flags = features & NL80211_PROTOCOL_FEATURE_SPLIT_WIPHY_DUMP ? NLM_F_DUMP : 0;
3078         cv = nl80211_msg(ifname, NL80211_CMD_GET_WIPHY, flags);
3079         if (!cv)
3080                 goto out;
3081 
3082         NLA_PUT_FLAG(cv->msg, NL80211_ATTR_SPLIT_WIPHY_DUMP);
3083         if (nl80211_send(cv, nl80211_get_freqlist_cb, &arr))
3084                 goto out;
3085 
3086         *len = arr.count * sizeof(struct iwinfo_freqlist_entry);
3087         return 0;
3088 
3089 nla_put_failure:
3090         nl80211_free(cv);
3091 out:
3092         *len = 0;
3093         return -1;
3094 }
3095 
3096 static int nl80211_get_country_cb(struct nl_msg *msg, void *arg)
3097 {
3098         char *buf = arg;
3099         struct nlattr **attr = nl80211_parse(msg);
3100 
3101         if (attr[NL80211_ATTR_REG_ALPHA2])
3102                 memcpy(buf, nla_data(attr[NL80211_ATTR_REG_ALPHA2]), 2);
3103         else
3104                 buf[0] = 0;
3105 
3106         return NL_SKIP;
3107 }
3108 
3109 static int nl80211_get_country(const char *ifname, char *buf)
3110 {
3111         if (nl80211_request(ifname, NL80211_CMD_GET_REG, 0,
3112                             nl80211_get_country_cb, buf))
3113                 return -1;
3114 
3115         return 0;
3116 }
3117 
3118 static int nl80211_get_countrylist(const char *ifname, char *buf, int *len)
3119 {
3120         int count;
3121         struct iwinfo_country_entry *e = (struct iwinfo_country_entry *)buf;
3122         const struct iwinfo_iso3166_label *l;
3123 
3124         for (l = IWINFO_ISO3166_NAMES, count = 0; l->iso3166; l++, e++, count++)
3125         {
3126                 e->iso3166 = l->iso3166;
3127                 e->ccode[0] = (l->iso3166 / 256);
3128                 e->ccode[1] = (l->iso3166 % 256);
3129                 e->ccode[2] = 0;
3130         }
3131 
3132         *len = (count * sizeof(struct iwinfo_country_entry));
3133         return 0;
3134 }
3135 
3136 
3137 struct nl80211_modes
3138 {
3139         bool ok;
3140         uint32_t hw;
3141         uint32_t ht;
3142 
3143         uint8_t bands;
3144 
3145         uint16_t nl_ht;
3146         uint32_t nl_vht;
3147         uint16_t he_phy_cap[6];
3148 };
3149 
3150 static void nl80211_eval_modelist(struct nl80211_modes *m)
3151 {
3152         /* Treat any nonzero capability as 11n */
3153         if (m->nl_ht > 0)
3154         {
3155                 m->hw |= IWINFO_80211_N;
3156                 m->ht |= IWINFO_HTMODE_HT20;
3157 
3158                 if (m->nl_ht & (1 << 1))
3159                         m->ht |= IWINFO_HTMODE_HT40;
3160         }
3161 
3162         if (m->he_phy_cap[0] != 0) {
3163                 m->hw |= IWINFO_80211_AX;
3164                 m->ht |= IWINFO_HTMODE_HE20;
3165 
3166                 if (m->he_phy_cap[0] & BIT(9))
3167                         m->ht |= IWINFO_HTMODE_HE40;
3168                 if (m->he_phy_cap[0] & BIT(10))
3169                         m->ht |= IWINFO_HTMODE_HE40 | IWINFO_HTMODE_HE80;
3170                 if (m->he_phy_cap[0] & BIT(11))
3171                         m->ht |= IWINFO_HTMODE_HE160;
3172                 if (m->he_phy_cap[0] & BIT(12))
3173                         m->ht |= IWINFO_HTMODE_HE160 | IWINFO_HTMODE_HE80_80;
3174         }
3175 
3176         if (m->bands & IWINFO_BAND_24)
3177         {
3178                 m->hw |= IWINFO_80211_B;
3179                 m->hw |= IWINFO_80211_G;
3180         }
3181 
3182         if (m->bands & IWINFO_BAND_5)
3183         {
3184                 /* Treat any nonzero capability as 11ac */
3185                 if (m->nl_vht > 0)
3186                 {
3187                         m->hw |= IWINFO_80211_AC;
3188                         m->ht |= IWINFO_HTMODE_VHT20 | IWINFO_HTMODE_VHT40 | IWINFO_HTMODE_VHT80;
3189 
3190                         switch ((m->nl_vht >> 2) & 3)
3191                         {
3192                         case 2:
3193                                 m->ht |= IWINFO_HTMODE_VHT80_80;
3194                                 /* fall through */
3195 
3196                         case 1:
3197                                 m->ht |= IWINFO_HTMODE_VHT160;
3198                         }
3199                 }
3200                 else
3201                 {
3202                         m->hw |= IWINFO_80211_A;
3203                 }
3204         }
3205 
3206         if (m->bands & IWINFO_BAND_60)
3207         {
3208                 m->hw |= IWINFO_80211_AD;
3209         }
3210 
3211 }
3212 
3213 static int nl80211_get_modelist_cb(struct nl_msg *msg, void *arg)
3214 {
3215         struct nl80211_modes *m = arg;
3216         int bands_remain;
3217         struct nlattr **attr = nl80211_parse(msg);
3218         struct nlattr *bands[NL80211_BAND_ATTR_MAX + 1];
3219         struct nlattr *band;
3220 
3221         if (attr[NL80211_ATTR_WIPHY_BANDS])
3222         {
3223                 nla_for_each_nested(band, attr[NL80211_ATTR_WIPHY_BANDS], bands_remain)
3224                 {
3225                         m->bands |= nl80211_get_band(band->nla_type);
3226 
3227                         nla_parse(bands, NL80211_BAND_ATTR_MAX,
3228                                   nla_data(band), nla_len(band), NULL);
3229 
3230                         if (bands[NL80211_BAND_ATTR_HT_CAPA])
3231                                 m->nl_ht = nla_get_u16(bands[NL80211_BAND_ATTR_HT_CAPA]);
3232 
3233                         if (bands[NL80211_BAND_ATTR_VHT_CAPA])
3234                                 m->nl_vht = nla_get_u32(bands[NL80211_BAND_ATTR_VHT_CAPA]);
3235 
3236                         if (bands[NL80211_BAND_ATTR_IFTYPE_DATA]) {
3237                                 struct nlattr *tb[NL80211_BAND_IFTYPE_ATTR_MAX + 1];
3238                                 struct nlattr *nl_iftype;
3239                                 int rem_band;
3240                                 int len;
3241 
3242                                 nla_for_each_nested(nl_iftype, bands[NL80211_BAND_ATTR_IFTYPE_DATA], rem_band) {
3243                                         nla_parse(tb, NL80211_BAND_IFTYPE_ATTR_MAX,
3244                                                   nla_data(nl_iftype), nla_len(nl_iftype), NULL);
3245                                         if (tb[NL80211_BAND_IFTYPE_ATTR_HE_CAP_PHY]) {
3246                                                 len = nla_len(tb[NL80211_BAND_IFTYPE_ATTR_HE_CAP_PHY]);
3247 
3248                                                 if (len > sizeof(m->he_phy_cap) - 1)
3249                                                         len = sizeof(m->he_phy_cap) - 1;
3250                                                 memcpy(&((__u8 *)m->he_phy_cap)[1],
3251                                                         nla_data(tb[NL80211_BAND_IFTYPE_ATTR_HE_CAP_PHY]),
3252                                                         len);
3253                                         }
3254                                 }
3255                         }
3256                 }
3257 
3258                 m->ok = 1;
3259         }
3260 
3261         return NL_SKIP;
3262 }
3263 
3264 static int nl80211_get_hwmodelist(const char *ifname, int *buf)
3265 {
3266         struct nl80211_msg_conveyor *cv;
3267         struct nl80211_modes m = {};
3268         uint32_t features = nl80211_get_protocol_features(ifname);
3269         int flags;
3270 
3271         flags = features & NL80211_PROTOCOL_FEATURE_SPLIT_WIPHY_DUMP ? NLM_F_DUMP : 0;
3272         cv = nl80211_msg(ifname, NL80211_CMD_GET_WIPHY, flags);
3273         if (!cv)
3274                 goto out;
3275 
3276         NLA_PUT_FLAG(cv->msg, NL80211_ATTR_SPLIT_WIPHY_DUMP);
3277         if (nl80211_send(cv, nl80211_get_modelist_cb, &m))
3278                 goto nla_put_failure;
3279 
3280         nl80211_eval_modelist(&m);
3281 
3282         *buf = m.hw;
3283 
3284         return 0;
3285 
3286 nla_put_failure:
3287         nl80211_free(cv);
3288 out:
3289         return -1;
3290 }
3291 
3292 struct chan_info {
3293         int width;
3294         int mode;
3295 };
3296 
3297 static int nl80211_get_htmode_cb(struct nl_msg *msg, void *arg)
3298 {
3299         struct nlattr **tb = nl80211_parse(msg);
3300         struct nlattr *cur;
3301         struct chan_info *chn = arg;
3302 
3303         if ((cur = tb[NL80211_ATTR_CHANNEL_WIDTH]))
3304                 chn->width = nla_get_u32(cur);
3305 
3306         if ((cur = tb[NL80211_ATTR_BSS_HT_OPMODE]))
3307                 chn->mode = nla_get_u32(cur);
3308 
3309         return NL_SKIP;
3310 }
3311 
3312 static int nl80211_get_htmode(const char *ifname, int *buf)
3313 {
3314         struct chan_info chn = { 0 };
3315         char *res, b[2] = { 0 };
3316         int err;
3317         bool he = false;
3318 
3319         res = nl80211_phy2ifname(ifname);
3320         *buf = 0;
3321 
3322         err =  nl80211_request(res ? res : ifname,
3323                                 NL80211_CMD_GET_INTERFACE, 0,
3324                                 nl80211_get_htmode_cb, &chn);
3325         if (err)
3326                 return -1;
3327 
3328         if (nl80211_hostapd_query(res ? res : ifname, "ieee80211ax", b, sizeof(b)))
3329                 he = b[0] == '1';
3330         else if (nl80211_wpactl_query(res ? res : ifname, "wifi_generation", b, sizeof(b)))
3331                 he = b[0] == '6';
3332 
3333         switch (chn.width) {
3334         case NL80211_CHAN_WIDTH_20:
3335                 if (he)
3336                         *buf = IWINFO_HTMODE_HE20;
3337                 else if (chn.mode == -1)
3338                         *buf = IWINFO_HTMODE_VHT20;
3339                 else
3340                         *buf = IWINFO_HTMODE_HT20;
3341                 break;
3342         case NL80211_CHAN_WIDTH_40:
3343                 if (he)
3344                         *buf = IWINFO_HTMODE_HE40;
3345                 else if (chn.mode == -1)
3346                         *buf = IWINFO_HTMODE_VHT40;
3347                 else
3348                         *buf = IWINFO_HTMODE_HT40;
3349                 break;
3350         case NL80211_CHAN_WIDTH_80:
3351                 if (he)
3352                         *buf = IWINFO_HTMODE_HE80;
3353                 else
3354                         *buf = IWINFO_HTMODE_VHT80;
3355                 break;
3356         case NL80211_CHAN_WIDTH_80P80:
3357                 if (he)
3358                         *buf = IWINFO_HTMODE_HE80_80;
3359                 else
3360                         *buf = IWINFO_HTMODE_VHT80_80;
3361                 break;
3362         case NL80211_CHAN_WIDTH_160:
3363                 if (he)
3364                         *buf = IWINFO_HTMODE_HE160;
3365                 else
3366                         *buf = IWINFO_HTMODE_VHT160;
3367                 break;
3368         case NL80211_CHAN_WIDTH_5:
3369         case NL80211_CHAN_WIDTH_10:
3370         case NL80211_CHAN_WIDTH_20_NOHT:
3371                 *buf = IWINFO_HTMODE_NOHT;
3372                 break;
3373         default:
3374                 return -1;
3375         }
3376 
3377         return 0;
3378 }
3379 
3380 static int nl80211_get_htmodelist(const char *ifname, int *buf)
3381 {
3382         struct nl80211_msg_conveyor *cv;
3383         struct nl80211_modes m = {};
3384         uint32_t features = nl80211_get_protocol_features(ifname);
3385         int flags;
3386 
3387         flags = features & NL80211_PROTOCOL_FEATURE_SPLIT_WIPHY_DUMP ? NLM_F_DUMP : 0;
3388         cv = nl80211_msg(ifname, NL80211_CMD_GET_WIPHY, flags);
3389         if (!cv)
3390                 goto out;
3391 
3392         NLA_PUT_FLAG(cv->msg, NL80211_ATTR_SPLIT_WIPHY_DUMP);
3393         if (nl80211_send(cv, nl80211_get_modelist_cb, &m))
3394                 goto nla_put_failure;
3395 
3396         nl80211_eval_modelist(&m);
3397 
3398         *buf = m.ht;
3399 
3400         return 0;
3401 
3402 nla_put_failure:
3403         nl80211_free(cv);
3404 out:
3405         return -1;
3406 }
3407 
3408 
3409 static int nl80211_get_ifcomb_cb(struct nl_msg *msg, void *arg)
3410 {
3411         struct nlattr **attr = nl80211_parse(msg);
3412         struct nlattr *comb;
3413         int *ret = arg;
3414         int comb_rem, limit_rem, mode_rem;
3415 
3416         *ret = 0;
3417         if (!attr[NL80211_ATTR_INTERFACE_COMBINATIONS])
3418                 return NL_SKIP;
3419 
3420         nla_for_each_nested(comb, attr[NL80211_ATTR_INTERFACE_COMBINATIONS], comb_rem)
3421         {
3422                 static struct nla_policy iface_combination_policy[NUM_NL80211_IFACE_COMB] = {
3423                         [NL80211_IFACE_COMB_LIMITS] = { .type = NLA_NESTED },
3424                         [NL80211_IFACE_COMB_MAXNUM] = { .type = NLA_U32 },
3425                 };
3426                 struct nlattr *tb_comb[NUM_NL80211_IFACE_COMB+1];
3427                 static struct nla_policy iface_limit_policy[NUM_NL80211_IFACE_LIMIT] = {
3428                         [NL80211_IFACE_LIMIT_TYPES] = { .type = NLA_NESTED },
3429                         [NL80211_IFACE_LIMIT_MAX] = { .type = NLA_U32 },
3430                 };
3431                 struct nlattr *tb_limit[NUM_NL80211_IFACE_LIMIT+1];
3432                 struct nlattr *limit;
3433 
3434                 nla_parse_nested(tb_comb, NUM_NL80211_IFACE_COMB, comb, iface_combination_policy);
3435 
3436                 if (!tb_comb[NL80211_IFACE_COMB_LIMITS])
3437                         continue;
3438 
3439                 nla_for_each_nested(limit, tb_comb[NL80211_IFACE_COMB_LIMITS], limit_rem)
3440                 {
3441                         struct nlattr *mode;
3442 
3443                         nla_parse_nested(tb_limit, NUM_NL80211_IFACE_LIMIT, limit, iface_limit_policy);
3444 
3445                         if (!tb_limit[NL80211_IFACE_LIMIT_TYPES] ||
3446                             !tb_limit[NL80211_IFACE_LIMIT_MAX])
3447                                 continue;
3448 
3449                         if (nla_get_u32(tb_limit[NL80211_IFACE_LIMIT_MAX]) < 2)
3450                                 continue;
3451 
3452                         nla_for_each_nested(mode, tb_limit[NL80211_IFACE_LIMIT_TYPES], mode_rem) {
3453                                 if (nla_type(mode) == NL80211_IFTYPE_AP)
3454                                         *ret = 1;
3455                         }
3456                 }
3457         }
3458 
3459         return NL_SKIP;
3460 }
3461 
3462 static int nl80211_get_mbssid_support(const char *ifname, int *buf)
3463 {
3464         if (nl80211_request(ifname, NL80211_CMD_GET_WIPHY, 0,
3465                             nl80211_get_ifcomb_cb, buf))
3466                 return -1;
3467 
3468         return 0;
3469 }
3470 
3471 static int nl80211_hardware_id_from_fdt(struct iwinfo_hardware_id *id, const char *ifname)
3472 {
3473         char *phy, path[PATH_MAX];
3474 
3475         /* Try to determine the phy name from the given interface */
3476         phy = nl80211_ifname2phy(ifname);
3477 
3478         snprintf(path, sizeof(path), "/sys/class/%s/%s/device/of_node/compatible",
3479                  phy ? "ieee80211" : "net", phy ? phy : ifname);
3480 
3481         if (nl80211_readstr(path, id->compatible, sizeof(id->compatible)) <= 0)
3482                 return -1;
3483 
3484         return 0;
3485 }
3486 
3487 
3488 static int nl80211_get_hardware_id(const char *ifname, char *buf)
3489 {
3490         struct iwinfo_hardware_id *id = (struct iwinfo_hardware_id *)buf;
3491         char *phy, num[8], path[PATH_MAX];
3492         int i;
3493 
3494         struct { const char *path; uint16_t *dest; } lookup[] = {
3495                 { "vendor", &id->vendor_id },
3496                 { "device", &id->device_id },
3497                 { "subsystem_vendor", &id->subsystem_vendor_id },
3498                 { "subsystem_device", &id->subsystem_device_id },
3499                 { "../idVendor", &id->subsystem_vendor_id },
3500                 { "../idProduct", &id->subsystem_device_id }
3501         };
3502 
3503         memset(id, 0, sizeof(*id));
3504 
3505         /* Try to determine the phy name from the given interface */
3506         phy = nl80211_ifname2phy(ifname);
3507 
3508         for (i = 0; i < ARRAY_SIZE(lookup); i++)
3509         {
3510                 snprintf(path, sizeof(path), "/sys/class/%s/%s/device/%s",
3511                          phy ? "ieee80211" : "net",
3512                          phy ? phy : ifname, lookup[i].path);
3513 
3514                 if (nl80211_readstr(path, num, sizeof(num)) > 0)
3515                         *lookup[i].dest = strtoul(num, NULL, 16);
3516         }
3517 
3518         /* Failed to obtain hardware PCI/USB IDs... */
3519         if (id->vendor_id == 0 && id->device_id == 0 &&
3520             id->subsystem_vendor_id == 0 && id->subsystem_device_id == 0)
3521                 /* ... first fallback to FDT ... */
3522                 if (nl80211_hardware_id_from_fdt(id, ifname) == -1)
3523                         /* ... then board config */
3524                         return iwinfo_hardware_id_from_mtd(id);
3525 
3526         return 0;
3527 }
3528 
3529 static const struct iwinfo_hardware_entry *
3530 nl80211_get_hardware_entry(const char *ifname)
3531 {
3532         struct iwinfo_hardware_id id;
3533 
3534         if (nl80211_get_hardware_id(ifname, (char *)&id))
3535                 return NULL;
3536 
3537         return iwinfo_hardware(&id);
3538 }
3539 
3540 static int nl80211_get_hardware_name(const char *ifname, char *buf)
3541 {
3542         const struct iwinfo_hardware_entry *hw;
3543 
3544         if (!(hw = nl80211_get_hardware_entry(ifname)))
3545                 sprintf(buf, "Generic MAC80211");
3546         else
3547                 sprintf(buf, "%s %s", hw->vendor_name, hw->device_name);
3548 
3549         return 0;
3550 }
3551 
3552 static int nl80211_get_txpower_offset(const char *ifname, int *buf)
3553 {
3554         const struct iwinfo_hardware_entry *hw;
3555 
3556         if (!(hw = nl80211_get_hardware_entry(ifname)))
3557                 return -1;
3558 
3559         *buf = hw->txpower_offset;
3560         return 0;
3561 }
3562 
3563 static int nl80211_get_frequency_offset(const char *ifname, int *buf)
3564 {
3565         const struct iwinfo_hardware_entry *hw;
3566 
3567         if (!(hw = nl80211_get_hardware_entry(ifname)))
3568                 return -1;
3569 
3570         *buf = hw->frequency_offset;
3571         return 0;
3572 }
3573 
3574 static int nl80211_lookup_phyname(const char *section, char *buf)
3575 {
3576         const char *name;
3577         int idx;
3578 
3579         if (!strncmp(section, "path=", 5))
3580                 idx = nl80211_phy_idx_from_path(section + 5);
3581         else if (!strncmp(section, "macaddr=", 8))
3582                 idx = nl80211_phy_idx_from_macaddr(section + 8);
3583         else
3584                 idx = nl80211_phy_idx_from_uci(section);
3585 
3586         if (idx < 0)
3587                 return -1;
3588 
3589         name = nl80211_phyidx2name(idx);
3590         if (!name)
3591                 return -1;
3592 
3593         strcpy(buf, name);
3594         return 0;
3595 }
3596 
3597 static int nl80211_phy_path(const char *phyname, const char **path)
3598 {
3599         if (strchr(phyname, '/'))
3600                 return -1;
3601 
3602         *path = nl80211_phy_path_str(phyname);
3603         if (!*path)
3604                 return -1;
3605 
3606         return 0;
3607 }
3608 
3609 const struct iwinfo_ops nl80211_ops = {
3610         .name             = "nl80211",
3611         .probe            = nl80211_probe,
3612         .channel          = nl80211_get_channel,
3613         .center_chan1     = nl80211_get_center_chan1,
3614         .center_chan2     = nl80211_get_center_chan2,
3615         .frequency        = nl80211_get_frequency,
3616         .frequency_offset = nl80211_get_frequency_offset,
3617         .txpower          = nl80211_get_txpower,
3618         .txpower_offset   = nl80211_get_txpower_offset,
3619         .bitrate          = nl80211_get_bitrate,
3620         .signal           = nl80211_get_signal,
3621         .noise            = nl80211_get_noise,
3622         .quality          = nl80211_get_quality,
3623         .quality_max      = nl80211_get_quality_max,
3624         .mbssid_support   = nl80211_get_mbssid_support,
3625         .hwmodelist       = nl80211_get_hwmodelist,
3626         .htmodelist       = nl80211_get_htmodelist,
3627         .htmode           = nl80211_get_htmode,
3628         .mode             = nl80211_get_mode,
3629         .ssid             = nl80211_get_ssid,
3630         .bssid            = nl80211_get_bssid,
3631         .country          = nl80211_get_country,
3632         .hardware_id      = nl80211_get_hardware_id,
3633         .hardware_name    = nl80211_get_hardware_name,
3634         .encryption       = nl80211_get_encryption,
3635         .phyname          = nl80211_get_phyname,
3636         .assoclist        = nl80211_get_assoclist,
3637         .txpwrlist        = nl80211_get_txpwrlist,
3638         .scanlist         = nl80211_get_scanlist,
3639         .freqlist         = nl80211_get_freqlist,
3640         .countrylist      = nl80211_get_countrylist,
3641         .survey           = nl80211_get_survey,
3642         .lookup_phy       = nl80211_lookup_phyname,
3643         .phy_path         = nl80211_phy_path,
3644         .close            = nl80211_close
3645 };
3646 

This page was automatically generated by LXR 0.3.1.  •  OpenWrt