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

This page was automatically generated by LXR 0.3.1.  •  OpenWrt