nl80211: skip event notifications in wpa_supplicant scan result reply
[project/iwinfo.git] / 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
30 #include "iwinfo_nl80211.h"
31
32 #define min(x, y) ((x) < (y)) ? (x) : (y)
33
34 #define BIT(x) (1ULL<<(x))
35
36 static struct nl80211_state *nls = NULL;
37
38 static void nl80211_close(void)
39 {
40         if (nls)
41         {
42                 if (nls->nlctrl)
43                         genl_family_put(nls->nlctrl);
44
45                 if (nls->nl80211)
46                         genl_family_put(nls->nl80211);
47
48                 if (nls->nl_sock)
49                         nl_socket_free(nls->nl_sock);
50
51                 if (nls->nl_cache)
52                         nl_cache_free(nls->nl_cache);
53
54                 free(nls);
55                 nls = NULL;
56         }
57 }
58
59 static int nl80211_init(void)
60 {
61         int err, fd;
62
63         if (!nls)
64         {
65                 nls = malloc(sizeof(struct nl80211_state));
66                 if (!nls) {
67                         err = -ENOMEM;
68                         goto err;
69                 }
70
71                 memset(nls, 0, sizeof(*nls));
72
73                 nls->nl_sock = nl_socket_alloc();
74                 if (!nls->nl_sock) {
75                         err = -ENOMEM;
76                         goto err;
77                 }
78
79                 if (genl_connect(nls->nl_sock)) {
80                         err = -ENOLINK;
81                         goto err;
82                 }
83
84                 fd = nl_socket_get_fd(nls->nl_sock);
85                 if (fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC) < 0) {
86                         err = -EINVAL;
87                         goto err;
88                 }
89
90                 if (genl_ctrl_alloc_cache(nls->nl_sock, &nls->nl_cache)) {
91                         err = -ENOMEM;
92                         goto err;
93                 }
94
95                 nls->nl80211 = genl_ctrl_search_by_name(nls->nl_cache, "nl80211");
96                 if (!nls->nl80211) {
97                         err = -ENOENT;
98                         goto err;
99                 }
100
101                 nls->nlctrl = genl_ctrl_search_by_name(nls->nl_cache, "nlctrl");
102                 if (!nls->nlctrl) {
103                         err = -ENOENT;
104                         goto err;
105                 }
106         }
107
108         return 0;
109
110
111 err:
112         nl80211_close();
113         return err;
114 }
115
116 static int nl80211_readint(const char *path)
117 {
118         int fd;
119         int rv = -1;
120         char buffer[16];
121
122         if ((fd = open(path, O_RDONLY)) > -1)
123         {
124                 if (read(fd, buffer, sizeof(buffer)) > 0)
125                         rv = atoi(buffer);
126
127                 close(fd);
128         }
129
130         return rv;
131 }
132
133 static int nl80211_readstr(const char *path, char *buffer, int length)
134 {
135         int fd;
136         int rv = -1;
137
138         if ((fd = open(path, O_RDONLY)) > -1)
139         {
140                 if ((rv = read(fd, buffer, length - 1)) > 0)
141                 {
142                         if (buffer[rv - 1] == '\n')
143                                 rv--;
144
145                         buffer[rv] = 0;
146                 }
147
148                 close(fd);
149         }
150
151         return rv;
152 }
153
154
155 static int nl80211_msg_error(struct sockaddr_nl *nla,
156         struct nlmsgerr *err, void *arg)
157 {
158         int *ret = arg;
159         *ret = err->error;
160         return NL_STOP;
161 }
162
163 static int nl80211_msg_finish(struct nl_msg *msg, void *arg)
164 {
165         int *ret = arg;
166         *ret = 0;
167         return NL_SKIP;
168 }
169
170 static int nl80211_msg_ack(struct nl_msg *msg, void *arg)
171 {
172         int *ret = arg;
173         *ret = 0;
174         return NL_STOP;
175 }
176
177 static int nl80211_msg_response(struct nl_msg *msg, void *arg)
178 {
179         return NL_SKIP;
180 }
181
182 static void nl80211_free(struct nl80211_msg_conveyor *cv)
183 {
184         if (cv)
185         {
186                 if (cv->cb)
187                         nl_cb_put(cv->cb);
188
189                 if (cv->msg)
190                         nlmsg_free(cv->msg);
191
192                 cv->cb  = NULL;
193                 cv->msg = NULL;
194         }
195 }
196
197 static struct nl80211_msg_conveyor * nl80211_new(struct genl_family *family,
198                                                  int cmd, int flags)
199 {
200         static struct nl80211_msg_conveyor cv;
201
202         struct nl_msg *req = NULL;
203         struct nl_cb *cb = NULL;
204
205         req = nlmsg_alloc();
206         if (!req)
207                 goto err;
208
209         cb = nl_cb_alloc(NL_CB_DEFAULT);
210         if (!cb)
211                 goto err;
212
213         genlmsg_put(req, 0, 0, genl_family_get_id(family), 0, flags, cmd, 0);
214
215         cv.msg = req;
216         cv.cb  = cb;
217
218         return &cv;
219
220 err:
221         if (req)
222                 nlmsg_free(req);
223
224         return NULL;
225 }
226
227 static struct nl80211_msg_conveyor * nl80211_ctl(int cmd, int flags)
228 {
229         if (nl80211_init() < 0)
230                 return NULL;
231
232         return nl80211_new(nls->nlctrl, cmd, flags);
233 }
234
235 static int nl80211_phy_idx_from_uci_path(struct uci_section *s)
236 {
237         const char *opt;
238         char buf[128];
239         int idx = -1;
240         glob_t gl;
241
242         opt = uci_lookup_option_string(uci_ctx, s, "path");
243         if (!opt)
244                 return -1;
245
246         snprintf(buf, sizeof(buf), "/sys/devices/%s/ieee80211/*/index", opt);  /**/
247         if (glob(buf, 0, NULL, &gl))
248                 snprintf(buf, sizeof(buf), "/sys/devices/platform/%s/ieee80211/*/index", opt);  /**/
249
250         if (glob(buf, 0, NULL, &gl))
251                 return -1;
252
253         if (gl.gl_pathc > 0)
254                 idx = nl80211_readint(gl.gl_pathv[0]);
255
256         globfree(&gl);
257
258         return idx;
259 }
260
261 static int nl80211_phy_idx_from_uci_macaddr(struct uci_section *s)
262 {
263         const char *opt;
264         char buf[128];
265         int i, idx = -1;
266         glob_t gl;
267
268         opt = uci_lookup_option_string(uci_ctx, s, "macaddr");
269         if (!opt)
270                 return -1;
271
272         snprintf(buf, sizeof(buf), "/sys/class/ieee80211/*");   /**/
273         if (glob(buf, 0, NULL, &gl))
274                 return -1;
275
276         for (i = 0; i < gl.gl_pathc; i++)
277         {
278                 snprintf(buf, sizeof(buf), "%s/macaddress", gl.gl_pathv[i]);
279                 if (nl80211_readstr(buf, buf, sizeof(buf)) <= 0)
280                         continue;
281
282                 if (fnmatch(opt, buf, FNM_CASEFOLD))
283                         continue;
284
285                 snprintf(buf, sizeof(buf), "%s/index", gl.gl_pathv[i]);
286                 if ((idx = nl80211_readint(buf)) > -1)
287                         break;
288         }
289
290         globfree(&gl);
291
292         return idx;
293 }
294
295 static int nl80211_phy_idx_from_uci_phy(struct uci_section *s)
296 {
297         const char *opt;
298         char buf[128];
299
300         opt = uci_lookup_option_string(uci_ctx, s, "phy");
301         if (!opt)
302                 return -1;
303
304         snprintf(buf, sizeof(buf), "/sys/class/ieee80211/%s/index", opt);
305         return nl80211_readint(buf);
306 }
307
308 static int nl80211_phy_idx_from_uci(const char *name)
309 {
310         struct uci_section *s;
311         int idx = -1;
312
313         s = iwinfo_uci_get_radio(name, "mac80211");
314         if (!s)
315                 goto free;
316
317         idx = nl80211_phy_idx_from_uci_path(s);
318
319         if (idx < 0)
320                 idx = nl80211_phy_idx_from_uci_macaddr(s);
321
322         if (idx < 0)
323                 idx = nl80211_phy_idx_from_uci_phy(s);
324
325 free:
326         iwinfo_uci_free();
327         return idx;
328 }
329
330 static struct nl80211_msg_conveyor * nl80211_msg(const char *ifname,
331                                                  int cmd, int flags)
332 {
333         int ifidx = -1, phyidx = -1;
334         struct nl80211_msg_conveyor *cv;
335
336         if (ifname == NULL)
337                 return NULL;
338
339         if (nl80211_init() < 0)
340                 return NULL;
341
342         if (!strncmp(ifname, "phy", 3))
343                 phyidx = atoi(&ifname[3]);
344         else if (!strncmp(ifname, "radio", 5))
345                 phyidx = nl80211_phy_idx_from_uci(ifname);
346         else if (!strncmp(ifname, "mon.", 4))
347                 ifidx = if_nametoindex(&ifname[4]);
348         else
349                 ifidx = if_nametoindex(ifname);
350
351         /* Valid ifidx must be greater than 0 */
352         if ((ifidx <= 0) && (phyidx < 0))
353                 return NULL;
354
355         cv = nl80211_new(nls->nl80211, cmd, flags);
356         if (!cv)
357                 return NULL;
358
359         if (ifidx > -1)
360                 NLA_PUT_U32(cv->msg, NL80211_ATTR_IFINDEX, ifidx);
361
362         if (phyidx > -1)
363                 NLA_PUT_U32(cv->msg, NL80211_ATTR_WIPHY, phyidx);
364
365         return cv;
366
367 nla_put_failure:
368         nl80211_free(cv);
369         return NULL;
370 }
371
372 static int nl80211_send(struct nl80211_msg_conveyor *cv,
373                         int (*cb_func)(struct nl_msg *, void *),
374                         void *cb_arg)
375 {
376         static struct nl80211_msg_conveyor rcv;
377         int err;
378
379         if (cb_func)
380                 nl_cb_set(cv->cb, NL_CB_VALID, NL_CB_CUSTOM, cb_func, cb_arg);
381         else
382                 nl_cb_set(cv->cb, NL_CB_VALID, NL_CB_CUSTOM, nl80211_msg_response, &rcv);
383
384         err = nl_send_auto_complete(nls->nl_sock, cv->msg);
385
386         if (err < 0)
387                 goto out;
388
389         err = 1;
390
391         nl_cb_err(cv->cb,               NL_CB_CUSTOM, nl80211_msg_error,  &err);
392         nl_cb_set(cv->cb, NL_CB_FINISH, NL_CB_CUSTOM, nl80211_msg_finish, &err);
393         nl_cb_set(cv->cb, NL_CB_ACK,    NL_CB_CUSTOM, nl80211_msg_ack,    &err);
394
395         while (err > 0)
396                 nl_recvmsgs(nls->nl_sock, cv->cb);
397
398 out:
399         nl80211_free(cv);
400         return err;
401 }
402
403 static int nl80211_request(const char *ifname, int cmd, int flags,
404                            int (*cb_func)(struct nl_msg *, void *),
405                            void *cb_arg)
406 {
407         struct nl80211_msg_conveyor *cv;
408
409         cv = nl80211_msg(ifname, cmd, flags);
410
411         if (!cv)
412                 return -ENOMEM;
413
414         return nl80211_send(cv, cb_func, cb_arg);
415 }
416
417 static struct nlattr ** nl80211_parse(struct nl_msg *msg)
418 {
419         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
420         static struct nlattr *attr[NL80211_ATTR_MAX + 1];
421
422         nla_parse(attr, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
423                   genlmsg_attrlen(gnlh, 0), NULL);
424
425         return attr;
426 }
427
428 static int nl80211_get_protocol_features_cb(struct nl_msg *msg, void *arg)
429 {
430         uint32_t *features = arg;
431         struct nlattr **attr = nl80211_parse(msg);
432
433         if (attr[NL80211_ATTR_PROTOCOL_FEATURES])
434                 *features = nla_get_u32(attr[NL80211_ATTR_PROTOCOL_FEATURES]);
435
436         return NL_SKIP;
437 }
438
439 static int nl80211_get_protocol_features(const char *ifname)
440 {
441         struct nl80211_msg_conveyor *req;
442         uint32_t features = 0;
443
444         req = nl80211_msg(ifname, NL80211_CMD_GET_PROTOCOL_FEATURES, 0);
445         if (req) {
446                 nl80211_send(req, nl80211_get_protocol_features_cb, &features);
447                 nl80211_free(req);
448         }
449
450         return features;
451 }
452
453 static int nl80211_subscribe_cb(struct nl_msg *msg, void *arg)
454 {
455         struct nl80211_group_conveyor *cv = arg;
456
457         struct nlattr **attr = nl80211_parse(msg);
458         struct nlattr *mgrpinfo[CTRL_ATTR_MCAST_GRP_MAX + 1];
459         struct nlattr *mgrp;
460         int mgrpidx;
461
462         if (!attr[CTRL_ATTR_MCAST_GROUPS])
463                 return NL_SKIP;
464
465         nla_for_each_nested(mgrp, attr[CTRL_ATTR_MCAST_GROUPS], mgrpidx)
466         {
467                 nla_parse(mgrpinfo, CTRL_ATTR_MCAST_GRP_MAX,
468                           nla_data(mgrp), nla_len(mgrp), NULL);
469
470                 if (mgrpinfo[CTRL_ATTR_MCAST_GRP_ID] &&
471                     mgrpinfo[CTRL_ATTR_MCAST_GRP_NAME] &&
472                     !strncmp(nla_data(mgrpinfo[CTRL_ATTR_MCAST_GRP_NAME]),
473                              cv->name, nla_len(mgrpinfo[CTRL_ATTR_MCAST_GRP_NAME])))
474                 {
475                         cv->id = nla_get_u32(mgrpinfo[CTRL_ATTR_MCAST_GRP_ID]);
476                         break;
477                 }
478         }
479
480         return NL_SKIP;
481 }
482
483 static int nl80211_subscribe(const char *family, const char *group)
484 {
485         struct nl80211_group_conveyor cv = { .name = group, .id = -ENOENT };
486         struct nl80211_msg_conveyor *req;
487         int err;
488
489         req = nl80211_ctl(CTRL_CMD_GETFAMILY, 0);
490         if (req)
491         {
492                 NLA_PUT_STRING(req->msg, CTRL_ATTR_FAMILY_NAME, family);
493                 err = nl80211_send(req, nl80211_subscribe_cb, &cv);
494
495                 if (err)
496                         return err;
497
498                 return nl_socket_add_membership(nls->nl_sock, cv.id);
499
500 nla_put_failure:
501                 nl80211_free(req);
502         }
503
504         return -ENOMEM;
505 }
506
507
508 static int nl80211_wait_cb(struct nl_msg *msg, void *arg)
509 {
510         struct nl80211_event_conveyor *cv = arg;
511         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
512
513         if (gnlh->cmd == cv->wait)
514                 cv->recv = gnlh->cmd;
515
516         return NL_SKIP;
517 }
518
519 static int nl80211_wait_seq_check(struct nl_msg *msg, void *arg)
520 {
521         return NL_OK;
522 }
523
524 static int nl80211_wait(const char *family, const char *group, int cmd)
525 {
526         struct nl80211_event_conveyor cv = { .wait = cmd };
527         struct nl_cb *cb;
528         int err = 0;
529
530         if (nl80211_subscribe(family, group))
531                 return -ENOENT;
532
533         cb = nl_cb_alloc(NL_CB_DEFAULT);
534
535         if (!cb)
536                 return -ENOMEM;
537
538         nl_cb_err(cb,                  NL_CB_CUSTOM, nl80211_msg_error,      &err);
539         nl_cb_set(cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM, nl80211_wait_seq_check, NULL);
540         nl_cb_set(cb, NL_CB_VALID,     NL_CB_CUSTOM, nl80211_wait_cb,        &cv );
541
542         while (!cv.recv && !err)
543                 nl_recvmsgs(nls->nl_sock, cb);
544
545         nl_cb_put(cb);
546
547         return err;
548 }
549
550
551 static int nl80211_freq2channel(int freq)
552 {
553         if (freq == 2484)
554                 return 14;
555         else if (freq < 2484)
556                 return (freq - 2407) / 5;
557         else if (freq >= 4910 && freq <= 4980)
558                 return (freq - 4000) / 5;
559         else
560                 return (freq - 5000) / 5;
561 }
562
563 static int nl80211_channel2freq(int channel, const char *band)
564 {
565         if (!band || band[0] != 'a')
566         {
567                 if (channel == 14)
568                         return 2484;
569                 else if (channel < 14)
570                         return (channel * 5) + 2407;
571         }
572         else
573         {
574                 if (channel >= 182 && channel <= 196)
575                         return (channel * 5) + 4000;
576                 else
577                         return (channel * 5) + 5000;
578         }
579
580         return 0;
581 }
582
583 static int nl80211_ifname2phy_cb(struct nl_msg *msg, void *arg)
584 {
585         char *buf = arg;
586         struct nlattr **attr = nl80211_parse(msg);
587
588         if (attr[NL80211_ATTR_WIPHY_NAME])
589                 memcpy(buf, nla_data(attr[NL80211_ATTR_WIPHY_NAME]),
590                        nla_len(attr[NL80211_ATTR_WIPHY_NAME]));
591         else
592                 buf[0] = 0;
593
594         return NL_SKIP;
595 }
596
597 static char * nl80211_ifname2phy(const char *ifname)
598 {
599         static char phy[32] = { 0 };
600
601         memset(phy, 0, sizeof(phy));
602
603         nl80211_request(ifname, NL80211_CMD_GET_WIPHY, 0,
604                         nl80211_ifname2phy_cb, phy);
605
606         return phy[0] ? phy : NULL;
607 }
608
609 static char * nl80211_phy2ifname(const char *ifname)
610 {
611         int ifidx = -1, cifidx = -1, phyidx = -1;
612         char buffer[64];
613         static char nif[IFNAMSIZ] = { 0 };
614
615         DIR *d;
616         struct dirent *e;
617
618         /* Only accept phy name of the form phy%d or radio%d */
619         if (!ifname)
620                 return NULL;
621         else if (!strncmp(ifname, "phy", 3))
622                 phyidx = atoi(&ifname[3]);
623         else if (!strncmp(ifname, "radio", 5))
624                 phyidx = nl80211_phy_idx_from_uci(ifname);
625         else
626                 return NULL;
627
628         memset(nif, 0, sizeof(nif));
629
630         if (phyidx > -1)
631         {
632                 if ((d = opendir("/sys/class/net")) != NULL)
633                 {
634                         while ((e = readdir(d)) != NULL)
635                         {
636                                 snprintf(buffer, sizeof(buffer),
637                                          "/sys/class/net/%s/phy80211/index", e->d_name);
638
639                                 if (nl80211_readint(buffer) == phyidx)
640                                 {
641                                         snprintf(buffer, sizeof(buffer),
642                                                  "/sys/class/net/%s/ifindex", e->d_name);
643
644                                         if ((cifidx = nl80211_readint(buffer)) >= 0 &&
645                                             ((ifidx < 0) || (cifidx < ifidx)))
646                                         {
647                                                 ifidx = cifidx;
648                                                 strncpy(nif, e->d_name, sizeof(nif) - 1);
649                                         }
650                                 }
651                         }
652
653                         closedir(d);
654                 }
655         }
656
657         return nif[0] ? nif : NULL;
658 }
659
660 static int nl80211_get_mode_cb(struct nl_msg *msg, void *arg)
661 {
662         int *mode = arg;
663         struct nlattr **tb = nl80211_parse(msg);
664         const int ifmodes[NL80211_IFTYPE_MAX + 1] = {
665                 IWINFO_OPMODE_UNKNOWN,          /* unspecified */
666                 IWINFO_OPMODE_ADHOC,            /* IBSS */
667                 IWINFO_OPMODE_CLIENT,           /* managed */
668                 IWINFO_OPMODE_MASTER,           /* AP */
669                 IWINFO_OPMODE_AP_VLAN,          /* AP/VLAN */
670                 IWINFO_OPMODE_WDS,                      /* WDS */
671                 IWINFO_OPMODE_MONITOR,          /* monitor */
672                 IWINFO_OPMODE_MESHPOINT,        /* mesh point */
673                 IWINFO_OPMODE_P2P_CLIENT,       /* P2P-client */
674                 IWINFO_OPMODE_P2P_GO,           /* P2P-GO */
675         };
676
677         if (tb[NL80211_ATTR_IFTYPE])
678                 *mode = ifmodes[nla_get_u32(tb[NL80211_ATTR_IFTYPE])];
679
680         return NL_SKIP;
681 }
682
683
684 static int nl80211_get_mode(const char *ifname, int *buf)
685 {
686         char *res;
687
688         *buf = IWINFO_OPMODE_UNKNOWN;
689
690         res = nl80211_phy2ifname(ifname);
691
692         nl80211_request(res ? res : ifname, NL80211_CMD_GET_INTERFACE, 0,
693                         nl80211_get_mode_cb, buf);
694
695         return (*buf == IWINFO_OPMODE_UNKNOWN) ? -1 : 0;
696 }
697
698 static int __nl80211_hostapd_query(const char *ifname, ...)
699 {
700         va_list ap, ap_cur;
701         char *phy, *search, *dest, *key, *val, buf[128];
702         int len, mode, found = 0, match = 1;
703         FILE *fp;
704
705         if (nl80211_get_mode(ifname, &mode))
706                 return 0;
707
708         if (mode != IWINFO_OPMODE_MASTER && mode != IWINFO_OPMODE_AP_VLAN)
709                 return 0;
710
711         phy = nl80211_ifname2phy(ifname);
712
713         if (!phy)
714                 return 0;
715
716         snprintf(buf, sizeof(buf), "/var/run/hostapd-%s.conf", phy);
717         fp = fopen(buf, "r");
718
719         if (!fp)
720                 return 0;
721
722         va_start(ap, ifname);
723
724         /* clear all destination buffers */
725         va_copy(ap_cur, ap);
726
727         while ((search = va_arg(ap_cur, char *)) != NULL)
728         {
729                 dest = va_arg(ap_cur, char *);
730                 len  = va_arg(ap_cur, int);
731
732                 memset(dest, 0, len);
733         }
734
735         va_end(ap_cur);
736
737         /* iterate applicable lines and copy found values into dest buffers */
738         while (fgets(buf, sizeof(buf), fp))
739         {
740                 key = strtok(buf, " =\t\n");
741                 val = strtok(NULL, "\n");
742
743                 if (!key || !val || !*key || *key == '#')
744                         continue;
745
746                 if (!strcmp(key, "interface") || !strcmp(key, "bss"))
747                         match = !strcmp(ifname, val);
748
749                 if (!match)
750                         continue;
751
752                 va_copy(ap_cur, ap);
753
754                 while ((search = va_arg(ap_cur, char *)) != NULL)
755                 {
756                         dest = va_arg(ap_cur, char *);
757                         len  = va_arg(ap_cur, int);
758
759                         if (!strcmp(search, key))
760                         {
761                                 strncpy(dest, val, len - 1);
762                                 found++;
763                                 break;
764                         }
765                 }
766
767                 va_end(ap_cur);
768         }
769
770         fclose(fp);
771
772         va_end(ap);
773
774         return found;
775 }
776
777 #define nl80211_hostapd_query(ifname, ...) \
778         __nl80211_hostapd_query(ifname, ##__VA_ARGS__, NULL)
779
780
781 static inline int nl80211_wpactl_recv(int sock, char *buf, int blen)
782 {
783         fd_set rfds;
784         struct timeval tv = { 0, 256000 };
785
786         FD_ZERO(&rfds);
787         FD_SET(sock, &rfds);
788
789         memset(buf, 0, blen);
790
791         if (select(sock + 1, &rfds, NULL, NULL, &tv) < 0)
792                 return -1;
793
794         if (!FD_ISSET(sock, &rfds))
795                 return -1;
796
797         return recv(sock, buf, blen - 1, 0);
798 }
799
800 static int nl80211_wpactl_connect(const char *ifname, struct sockaddr_un *local)
801 {
802         struct sockaddr_un remote = { 0 };
803         size_t remote_length, local_length;
804
805         int sock = socket(PF_UNIX, SOCK_DGRAM, 0);
806         if (sock < 0)
807                 return sock;
808
809         remote.sun_family = AF_UNIX;
810         remote_length = sizeof(remote.sun_family) +
811                 sprintf(remote.sun_path, "/var/run/wpa_supplicant-%s/%s",
812                         ifname, ifname);
813
814         if (fcntl(sock, F_SETFD, fcntl(sock, F_GETFD) | FD_CLOEXEC) < 0)
815         {
816                 close(sock);
817                 return -1;
818         }
819
820         if (connect(sock, (struct sockaddr *)&remote, remote_length))
821         {
822                 remote_length = sizeof(remote.sun_family) +
823                         sprintf(remote.sun_path, "/var/run/wpa_supplicant/%s", ifname);
824
825                 if (connect(sock, (struct sockaddr *)&remote, remote_length))
826                 {
827                         close(sock);
828                         return -1;
829                 }
830         }
831
832         local->sun_family = AF_UNIX;
833         local_length = sizeof(local->sun_family) +
834                 sprintf(local->sun_path, "/var/run/iwinfo-%s-%d", ifname, getpid());
835
836         if (bind(sock, (struct sockaddr *)local, local_length) < 0)
837         {
838                 close(sock);
839                 return -1;
840         }
841
842         return sock;
843 }
844
845 static int __nl80211_wpactl_query(const char *ifname, ...)
846 {
847         va_list ap, ap_cur;
848         struct sockaddr_un local = { 0 };
849         int len, mode, found = 0, sock = -1;
850         char *search, *dest, *key, *val, *line, *pos, buf[512];
851
852         if (nl80211_get_mode(ifname, &mode))
853                 return 0;
854
855         if (mode != IWINFO_OPMODE_CLIENT && mode != IWINFO_OPMODE_ADHOC)
856                 return 0;
857
858         sock = nl80211_wpactl_connect(ifname, &local);
859
860         if (sock < 0)
861                 return 0;
862
863         va_start(ap, ifname);
864
865         /* clear all destination buffers */
866         va_copy(ap_cur, ap);
867
868         while ((search = va_arg(ap_cur, char *)) != NULL)
869         {
870                 dest = va_arg(ap_cur, char *);
871                 len  = va_arg(ap_cur, int);
872
873                 memset(dest, 0, len);
874         }
875
876         va_end(ap_cur);
877
878         send(sock, "STATUS", 6, 0);
879
880         while (true)
881         {
882                 if (nl80211_wpactl_recv(sock, buf, sizeof(buf)) <= 0)
883                         break;
884
885                 if (buf[0] == '<')
886                         continue;
887
888                 for (line = strtok_r(buf, "\n", &pos);
889                          line != NULL;
890                          line = strtok_r(NULL, "\n", &pos))
891                 {
892                         key = strtok(line, "=");
893                         val = strtok(NULL, "\n");
894
895                         if (!key || !val)
896                                 continue;
897
898                         va_copy(ap_cur, ap);
899
900                         while ((search = va_arg(ap_cur, char *)) != NULL)
901                         {
902                                 dest = va_arg(ap_cur, char *);
903                                 len  = va_arg(ap_cur, int);
904
905                                 if (!strcmp(search, key))
906                                 {
907                                         strncpy(dest, val, len - 1);
908                                         found++;
909                                         break;
910                                 }
911                         }
912
913                         va_end(ap_cur);
914                 }
915
916                 break;
917         }
918
919         va_end(ap);
920
921         close(sock);
922         unlink(local.sun_path);
923
924         return found;
925 }
926
927 #define nl80211_wpactl_query(ifname, ...) \
928         __nl80211_wpactl_query(ifname, ##__VA_ARGS__, NULL)
929
930
931 static char * nl80211_ifadd(const char *ifname)
932 {
933         char path[PATH_MAX];
934         static char nif[IFNAMSIZ] = { 0 };
935         struct nl80211_msg_conveyor *req;
936         FILE *sysfs;
937
938         req = nl80211_msg(ifname, NL80211_CMD_NEW_INTERFACE, 0);
939         if (req)
940         {
941                 snprintf(nif, sizeof(nif), "tmp.%s", ifname);
942
943                 NLA_PUT_STRING(req->msg, NL80211_ATTR_IFNAME, nif);
944                 NLA_PUT_U32(req->msg, NL80211_ATTR_IFTYPE, NL80211_IFTYPE_STATION);
945
946                 nl80211_send(req, NULL, NULL);
947
948                 snprintf(path, sizeof(path) - 1,
949                          "/proc/sys/net/ipv6/conf/%s/disable_ipv6", nif);
950
951                 if ((sysfs = fopen(path, "w")) != NULL)
952                 {
953                         fwrite("0\n", 1, 2, sysfs);
954                         fclose(sysfs);
955                 }
956
957                 return nif;
958
959         nla_put_failure:
960                 nl80211_free(req);
961         }
962
963         return NULL;
964 }
965
966 static void nl80211_ifdel(const char *ifname)
967 {
968         struct nl80211_msg_conveyor *req;
969         int err;
970
971         req = nl80211_msg(ifname, NL80211_CMD_DEL_INTERFACE, 0);
972         if (req)
973         {
974                 NLA_PUT_STRING(req->msg, NL80211_ATTR_IFNAME, ifname);
975
976                 nl80211_send(req, NULL, NULL);
977                 return;
978
979         nla_put_failure:
980                 nl80211_free(req);
981         }
982 }
983
984 static void nl80211_hostapd_hup(const char *ifname)
985 {
986         int fd, pid = 0;
987         char buf[32];
988         char *phy = nl80211_ifname2phy(ifname);
989
990         if (phy)
991         {
992                 snprintf(buf, sizeof(buf), "/var/run/wifi-%s.pid", phy);
993                 if ((fd = open(buf, O_RDONLY)) >= 0)
994                 {
995                         if (read(fd, buf, sizeof(buf)) > 0)
996                                 pid = atoi(buf);
997
998                         close(fd);
999                 }
1000
1001                 if (pid > 0)
1002                         kill(pid, 1);
1003         }
1004 }
1005
1006
1007 static int nl80211_probe(const char *ifname)
1008 {
1009         return !!nl80211_ifname2phy(ifname);
1010 }
1011
1012 struct nl80211_ssid_bssid {
1013         unsigned char *ssid;
1014         unsigned char bssid[7];
1015 };
1016
1017 static int nl80211_get_ssid_bssid_cb(struct nl_msg *msg, void *arg)
1018 {
1019         int ielen;
1020         unsigned char *ie;
1021         struct nl80211_ssid_bssid *sb = arg;
1022         struct nlattr **tb = nl80211_parse(msg);
1023         struct nlattr *bss[NL80211_BSS_MAX + 1];
1024
1025         static struct nla_policy bss_policy[NL80211_BSS_MAX + 1] = {
1026                 [NL80211_BSS_INFORMATION_ELEMENTS] = { 0 },
1027                 [NL80211_BSS_STATUS]               = { .type = NLA_U32 },
1028         };
1029
1030         if (!tb[NL80211_ATTR_BSS] ||
1031             nla_parse_nested(bss, NL80211_BSS_MAX, tb[NL80211_ATTR_BSS],
1032                              bss_policy) ||
1033             !bss[NL80211_BSS_BSSID] ||
1034             !bss[NL80211_BSS_STATUS] ||
1035             !bss[NL80211_BSS_INFORMATION_ELEMENTS])
1036         {
1037                 return NL_SKIP;
1038         }
1039
1040         switch (nla_get_u32(bss[NL80211_BSS_STATUS]))
1041         {
1042         case NL80211_BSS_STATUS_ASSOCIATED:
1043         case NL80211_BSS_STATUS_AUTHENTICATED:
1044         case NL80211_BSS_STATUS_IBSS_JOINED:
1045
1046                 if (sb->ssid)
1047                 {
1048                         ie = nla_data(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
1049                         ielen = nla_len(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
1050
1051                         while (ielen >= 2 && ielen >= ie[1])
1052                         {
1053                                 if (ie[0] == 0)
1054                                 {
1055                                         memcpy(sb->ssid, ie + 2, min(ie[1], IWINFO_ESSID_MAX_SIZE));
1056                                         return NL_SKIP;
1057                                 }
1058
1059                                 ielen -= ie[1] + 2;
1060                                 ie += ie[1] + 2;
1061                         }
1062                 }
1063                 else
1064                 {
1065                         sb->bssid[0] = 1;
1066                         memcpy(sb->bssid + 1, nla_data(bss[NL80211_BSS_BSSID]), 6);
1067                         return NL_SKIP;
1068                 }
1069
1070         default:
1071                 return NL_SKIP;
1072         }
1073 }
1074
1075 static int nl80211_get_ssid(const char *ifname, char *buf)
1076 {
1077         char *res;
1078         struct nl80211_ssid_bssid sb = { .ssid = (unsigned char *)buf };
1079
1080         /* try to find ssid from scan dump results */
1081         res = nl80211_phy2ifname(ifname);
1082         sb.ssid[0] = 0;
1083
1084         nl80211_request(res ? res : ifname, NL80211_CMD_GET_SCAN, NLM_F_DUMP,
1085                         nl80211_get_ssid_bssid_cb, &sb);
1086
1087         /* failed, try to find from hostapd info */
1088         if (sb.ssid[0] == 0)
1089                 nl80211_hostapd_query(ifname, "ssid", sb.ssid,
1090                                       IWINFO_ESSID_MAX_SIZE + 1);
1091
1092         return (sb.ssid[0] == 0) ? -1 : 0;
1093 }
1094
1095 static int nl80211_get_bssid(const char *ifname, char *buf)
1096 {
1097         char *res, bssid[sizeof("FF:FF:FF:FF:FF:FF\0")];
1098         struct nl80211_ssid_bssid sb = { };
1099
1100         /* try to find bssid from scan dump results */
1101         res = nl80211_phy2ifname(ifname);
1102
1103         nl80211_request(res ? res : ifname, NL80211_CMD_GET_SCAN, NLM_F_DUMP,
1104                         nl80211_get_ssid_bssid_cb, &sb);
1105
1106         /* failed, try to find mac from hostapd info */
1107         if ((sb.bssid[0] == 0) &&
1108             nl80211_hostapd_query(ifname, "bssid", bssid, sizeof(bssid)))
1109         {
1110                 sb.bssid[0] = 1;
1111                 sb.bssid[1] = strtol(&bssid[0],  NULL, 16);
1112                 sb.bssid[2] = strtol(&bssid[3],  NULL, 16);
1113                 sb.bssid[3] = strtol(&bssid[6],  NULL, 16);
1114                 sb.bssid[4] = strtol(&bssid[9],  NULL, 16);
1115                 sb.bssid[5] = strtol(&bssid[12], NULL, 16);
1116                 sb.bssid[6] = strtol(&bssid[15], NULL, 16);
1117         }
1118
1119         if (sb.bssid[0])
1120         {
1121                 sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X",
1122                         sb.bssid[1], sb.bssid[2], sb.bssid[3],
1123                         sb.bssid[4], sb.bssid[5], sb.bssid[6]);
1124
1125                 return 0;
1126         }
1127
1128         return -1;
1129 }
1130
1131
1132 static int nl80211_get_frequency_scan_cb(struct nl_msg *msg, void *arg)
1133 {
1134         int *freq = arg;
1135         struct nlattr **attr = nl80211_parse(msg);
1136         struct nlattr *binfo[NL80211_BSS_MAX + 1];
1137
1138         static struct nla_policy bss_policy[NL80211_BSS_MAX + 1] = {
1139                 [NL80211_BSS_FREQUENCY] = { .type = NLA_U32 },
1140                 [NL80211_BSS_STATUS]    = { .type = NLA_U32 },
1141         };
1142
1143         if (attr[NL80211_ATTR_BSS] &&
1144             !nla_parse_nested(binfo, NL80211_BSS_MAX,
1145                               attr[NL80211_ATTR_BSS], bss_policy))
1146         {
1147                 if (binfo[NL80211_BSS_STATUS] && binfo[NL80211_BSS_FREQUENCY])
1148                         *freq = nla_get_u32(binfo[NL80211_BSS_FREQUENCY]);
1149         }
1150
1151         return NL_SKIP;
1152 }
1153
1154 static int nl80211_get_frequency_info_cb(struct nl_msg *msg, void *arg)
1155 {
1156         int *freq = arg;
1157         struct nlattr **tb = nl80211_parse(msg);
1158
1159         if (tb[NL80211_ATTR_WIPHY_FREQ])
1160                 *freq = nla_get_u32(tb[NL80211_ATTR_WIPHY_FREQ]);
1161
1162         return NL_SKIP;
1163 }
1164
1165 static int nl80211_get_frequency(const char *ifname, int *buf)
1166 {
1167         char *res, channel[4], hwmode[2];
1168
1169         /* try to find frequency from interface info */
1170         res = nl80211_phy2ifname(ifname);
1171         *buf = 0;
1172
1173         nl80211_request(res ? res : ifname, NL80211_CMD_GET_INTERFACE, 0,
1174                         nl80211_get_frequency_info_cb, buf);
1175
1176         /* failed, try to find frequency from hostapd info */
1177         if ((*buf == 0) &&
1178             nl80211_hostapd_query(ifname, "hw_mode", hwmode, sizeof(hwmode),
1179                                           "channel", channel, sizeof(channel)) == 2)
1180         {
1181                 *buf = nl80211_channel2freq(atoi(channel), hwmode);
1182         }
1183
1184         /* failed, try to find frequency from scan results */
1185         if (*buf == 0)
1186         {
1187                 res = nl80211_phy2ifname(ifname);
1188
1189                 nl80211_request(res ? res : ifname, NL80211_CMD_GET_SCAN, NLM_F_DUMP,
1190                                 nl80211_get_frequency_scan_cb, buf);
1191         }
1192
1193         return (*buf == 0) ? -1 : 0;
1194 }
1195
1196 static int nl80211_get_channel(const char *ifname, int *buf)
1197 {
1198         if (!nl80211_get_frequency(ifname, buf))
1199         {
1200                 *buf = nl80211_freq2channel(*buf);
1201                 return 0;
1202         }
1203
1204         return -1;
1205 }
1206
1207 static int nl80211_get_txpower_cb(struct nl_msg *msg, void *arg)
1208 {
1209         int *buf = arg;
1210         struct nlattr **tb = nl80211_parse(msg);
1211
1212         if (tb[NL80211_ATTR_WIPHY_TX_POWER_LEVEL])
1213                 *buf = iwinfo_mbm2dbm(nla_get_u32(tb[NL80211_ATTR_WIPHY_TX_POWER_LEVEL]));
1214
1215         return NL_SKIP;
1216 }
1217
1218 static int nl80211_get_txpower(const char *ifname, int *buf)
1219 {
1220         char *res;
1221
1222         res = nl80211_phy2ifname(ifname);
1223         *buf = 0;
1224
1225         if (nl80211_request(res ? res : ifname, NL80211_CMD_GET_INTERFACE, 0,
1226                             nl80211_get_txpower_cb, buf))
1227                 return -1;
1228
1229         return 0;
1230 }
1231
1232
1233 static int nl80211_fill_signal_cb(struct nl_msg *msg, void *arg)
1234 {
1235         int8_t dbm;
1236         int16_t mbit;
1237         struct nl80211_rssi_rate *rr = arg;
1238         struct nlattr **attr = nl80211_parse(msg);
1239         struct nlattr *sinfo[NL80211_STA_INFO_MAX + 1];
1240         struct nlattr *rinfo[NL80211_RATE_INFO_MAX + 1];
1241
1242         static struct nla_policy stats_policy[NL80211_STA_INFO_MAX + 1] = {
1243                 [NL80211_STA_INFO_INACTIVE_TIME] = { .type = NLA_U32    },
1244                 [NL80211_STA_INFO_RX_BYTES]      = { .type = NLA_U32    },
1245                 [NL80211_STA_INFO_TX_BYTES]      = { .type = NLA_U32    },
1246                 [NL80211_STA_INFO_RX_PACKETS]    = { .type = NLA_U32    },
1247                 [NL80211_STA_INFO_TX_PACKETS]    = { .type = NLA_U32    },
1248                 [NL80211_STA_INFO_SIGNAL]        = { .type = NLA_U8     },
1249                 [NL80211_STA_INFO_TX_BITRATE]    = { .type = NLA_NESTED },
1250                 [NL80211_STA_INFO_LLID]          = { .type = NLA_U16    },
1251                 [NL80211_STA_INFO_PLID]          = { .type = NLA_U16    },
1252                 [NL80211_STA_INFO_PLINK_STATE]   = { .type = NLA_U8     },
1253         };
1254
1255         static struct nla_policy rate_policy[NL80211_RATE_INFO_MAX + 1] = {
1256                 [NL80211_RATE_INFO_BITRATE]      = { .type = NLA_U16  },
1257                 [NL80211_RATE_INFO_MCS]          = { .type = NLA_U8   },
1258                 [NL80211_RATE_INFO_40_MHZ_WIDTH] = { .type = NLA_FLAG },
1259                 [NL80211_RATE_INFO_SHORT_GI]     = { .type = NLA_FLAG },
1260         };
1261
1262         if (attr[NL80211_ATTR_STA_INFO])
1263         {
1264                 if (!nla_parse_nested(sinfo, NL80211_STA_INFO_MAX,
1265                                       attr[NL80211_ATTR_STA_INFO], stats_policy))
1266                 {
1267                         if (sinfo[NL80211_STA_INFO_SIGNAL])
1268                         {
1269                                 dbm = nla_get_u8(sinfo[NL80211_STA_INFO_SIGNAL]);
1270                                 rr->rssi = rr->rssi ? (int8_t)((rr->rssi + dbm) / 2) : dbm;
1271                         }
1272
1273                         if (sinfo[NL80211_STA_INFO_TX_BITRATE])
1274                         {
1275                                 if (!nla_parse_nested(rinfo, NL80211_RATE_INFO_MAX,
1276                                                       sinfo[NL80211_STA_INFO_TX_BITRATE],
1277                                                       rate_policy))
1278                                 {
1279                                         if (rinfo[NL80211_RATE_INFO_BITRATE])
1280                                         {
1281                                                 mbit = nla_get_u16(rinfo[NL80211_RATE_INFO_BITRATE]);
1282                                                 rr->rate = rr->rate
1283                                                         ? (int16_t)((rr->rate + mbit) / 2) : mbit;
1284                                         }
1285                                 }
1286                         }
1287                 }
1288         }
1289
1290         return NL_SKIP;
1291 }
1292
1293 static void nl80211_fill_signal(const char *ifname, struct nl80211_rssi_rate *r)
1294 {
1295         DIR *d;
1296         struct dirent *de;
1297
1298         r->rssi = 0;
1299         r->rate = 0;
1300
1301         if ((d = opendir("/sys/class/net")) != NULL)
1302         {
1303                 while ((de = readdir(d)) != NULL)
1304                 {
1305                         if (!strncmp(de->d_name, ifname, strlen(ifname)) &&
1306                             (!de->d_name[strlen(ifname)] ||
1307                              !strncmp(&de->d_name[strlen(ifname)], ".sta", 4)))
1308                         {
1309                                 nl80211_request(de->d_name, NL80211_CMD_GET_STATION,
1310                                                 NLM_F_DUMP, nl80211_fill_signal_cb, r);
1311                         }
1312                 }
1313
1314                 closedir(d);
1315         }
1316 }
1317
1318 static int nl80211_get_bitrate(const char *ifname, int *buf)
1319 {
1320         struct nl80211_rssi_rate rr;
1321
1322         nl80211_fill_signal(ifname, &rr);
1323
1324         if (rr.rate)
1325         {
1326                 *buf = (rr.rate * 100);
1327                 return 0;
1328         }
1329
1330         return -1;
1331 }
1332
1333 static int nl80211_get_signal(const char *ifname, int *buf)
1334 {
1335         struct nl80211_rssi_rate rr;
1336
1337         nl80211_fill_signal(ifname, &rr);
1338
1339         if (rr.rssi)
1340         {
1341                 *buf = rr.rssi;
1342                 return 0;
1343         }
1344
1345         return -1;
1346 }
1347
1348 static int nl80211_get_noise_cb(struct nl_msg *msg, void *arg)
1349 {
1350         int8_t *noise = arg;
1351         struct nlattr **tb = nl80211_parse(msg);
1352         struct nlattr *si[NL80211_SURVEY_INFO_MAX + 1];
1353
1354         static struct nla_policy sp[NL80211_SURVEY_INFO_MAX + 1] = {
1355                 [NL80211_SURVEY_INFO_FREQUENCY] = { .type = NLA_U32 },
1356                 [NL80211_SURVEY_INFO_NOISE]     = { .type = NLA_U8  },
1357         };
1358
1359         if (!tb[NL80211_ATTR_SURVEY_INFO])
1360                 return NL_SKIP;
1361
1362         if (nla_parse_nested(si, NL80211_SURVEY_INFO_MAX,
1363                              tb[NL80211_ATTR_SURVEY_INFO], sp))
1364                 return NL_SKIP;
1365
1366         if (!si[NL80211_SURVEY_INFO_NOISE])
1367                 return NL_SKIP;
1368
1369         if (!*noise || si[NL80211_SURVEY_INFO_IN_USE])
1370                 *noise = (int8_t)nla_get_u8(si[NL80211_SURVEY_INFO_NOISE]);
1371
1372         return NL_SKIP;
1373 }
1374
1375
1376 static int nl80211_get_noise(const char *ifname, int *buf)
1377 {
1378         int8_t noise = 0;
1379
1380         if (nl80211_request(ifname, NL80211_CMD_GET_SURVEY, NLM_F_DUMP,
1381                             nl80211_get_noise_cb, &noise))
1382                 goto out;
1383
1384         *buf = noise;
1385         return 0;
1386
1387 out:
1388         *buf = 0;
1389         return -1;
1390 }
1391
1392 static int nl80211_get_quality(const char *ifname, int *buf)
1393 {
1394         int signal;
1395
1396         if (!nl80211_get_signal(ifname, &signal))
1397         {
1398                 /* A positive signal level is usually just a quality
1399                  * value, pass through as-is */
1400                 if (signal >= 0)
1401                 {
1402                         *buf = signal;
1403                 }
1404
1405                 /* The cfg80211 wext compat layer assumes a signal range
1406                  * of -110 dBm to -40 dBm, the quality value is derived
1407                  * by adding 110 to the signal level */
1408                 else
1409                 {
1410                         if (signal < -110)
1411                                 signal = -110;
1412                         else if (signal > -40)
1413                                 signal = -40;
1414
1415                         *buf = (signal + 110);
1416                 }
1417
1418                 return 0;
1419         }
1420
1421         return -1;
1422 }
1423
1424 static int nl80211_get_quality_max(const char *ifname, int *buf)
1425 {
1426         /* The cfg80211 wext compat layer assumes a maximum
1427          * quality of 70 */
1428         *buf = 70;
1429
1430         return 0;
1431 }
1432
1433 static int nl80211_check_wepkey(const char *key)
1434 {
1435         if (key && *key)
1436         {
1437                 switch (strlen(key))
1438                 {
1439                 case 5:
1440                 case 10:
1441                         return IWINFO_CIPHER_WEP40;
1442
1443                 case 13:
1444                 case 26:
1445                         return IWINFO_CIPHER_WEP104;
1446                 }
1447         }
1448
1449         return 0;
1450 }
1451
1452 static int nl80211_get_encryption(const char *ifname, char *buf)
1453 {
1454         char wpa[2], wpa_key_mgmt[16], wpa_pairwise[16], wpa_groupwise[16];
1455         char auth_algs[2], wep_key0[27], wep_key1[27], wep_key2[27], wep_key3[27];
1456
1457         struct iwinfo_crypto_entry *c = (struct iwinfo_crypto_entry *)buf;
1458
1459         /* WPA supplicant */
1460         if (nl80211_wpactl_query(ifname,
1461                         "pairwise_cipher", wpa_pairwise,  sizeof(wpa_pairwise),
1462                         "group_cipher",    wpa_groupwise, sizeof(wpa_groupwise),
1463                         "key_mgmt",        wpa_key_mgmt,  sizeof(wpa_key_mgmt)))
1464         {
1465                 /* WEP */
1466                 if (!strcmp(wpa_key_mgmt, "NONE"))
1467                 {
1468                         if (strstr(wpa_pairwise, "WEP-40"))
1469                                 c->pair_ciphers |= IWINFO_CIPHER_WEP40;
1470                         else if (strstr(wpa_pairwise, "WEP-104"))
1471                                 c->pair_ciphers |= IWINFO_CIPHER_WEP104;
1472
1473                         if (strstr(wpa_groupwise, "WEP-40"))
1474                                 c->group_ciphers |= IWINFO_CIPHER_WEP40;
1475                         else if (strstr(wpa_groupwise, "WEP-104"))
1476                                 c->group_ciphers |= IWINFO_CIPHER_WEP104;
1477
1478                         c->enabled      = !!(c->pair_ciphers | c->group_ciphers);
1479                         c->auth_suites |= IWINFO_KMGMT_NONE;
1480                         c->auth_algs   |= IWINFO_AUTH_OPEN; /* XXX: assumption */
1481                 }
1482
1483                 /* WPA */
1484                 else if (strstr(wpa_key_mgmt, "WPA"))
1485                 {
1486                         if (strstr(wpa_pairwise, "TKIP"))
1487                                 c->pair_ciphers |= IWINFO_CIPHER_TKIP;
1488                         else if (strstr(wpa_pairwise, "CCMP"))
1489                                 c->pair_ciphers |= IWINFO_CIPHER_CCMP;
1490                         else if (strstr(wpa_pairwise, "NONE"))
1491                                 c->pair_ciphers |= IWINFO_CIPHER_NONE;
1492                         else if (strstr(wpa_pairwise, "WEP-40"))
1493                                 c->pair_ciphers |= IWINFO_CIPHER_WEP40;
1494                         else if (strstr(wpa_pairwise, "WEP-104"))
1495                                 c->pair_ciphers |= IWINFO_CIPHER_WEP104;
1496
1497                         if (strstr(wpa_groupwise, "TKIP"))
1498                                 c->group_ciphers |= IWINFO_CIPHER_TKIP;
1499                         else if (strstr(wpa_groupwise, "CCMP"))
1500                                 c->group_ciphers |= IWINFO_CIPHER_CCMP;
1501                         else if (strstr(wpa_groupwise, "NONE"))
1502                                 c->group_ciphers |= IWINFO_CIPHER_NONE;
1503                         else if (strstr(wpa_groupwise, "WEP-40"))
1504                                 c->group_ciphers |= IWINFO_CIPHER_WEP40;
1505                         else if (strstr(wpa_groupwise, "WEP-104"))
1506                                 c->group_ciphers |= IWINFO_CIPHER_WEP104;
1507
1508                         if (strstr(wpa_key_mgmt, "WPA2"))
1509                                 c->wpa_version = 2;
1510                         else if (strstr(wpa_key_mgmt, "WPA"))
1511                                 c->wpa_version = 1;
1512
1513                         if (strstr(wpa_key_mgmt, "PSK"))
1514                                 c->auth_suites |= IWINFO_KMGMT_PSK;
1515                         else if (strstr(wpa_key_mgmt, "EAP") ||
1516                                  strstr(wpa_key_mgmt, "802.1X"))
1517                                 c->auth_suites |= IWINFO_KMGMT_8021x;
1518                         else if (strstr(wpa_key_mgmt, "NONE"))
1519                                 c->auth_suites |= IWINFO_KMGMT_NONE;
1520
1521                         c->enabled = !!(c->wpa_version && c->auth_suites);
1522                 }
1523
1524                 return 0;
1525         }
1526
1527         /* Hostapd */
1528         else if (nl80211_hostapd_query(ifname,
1529                                 "wpa",          wpa,          sizeof(wpa),
1530                                 "wpa_key_mgmt", wpa_key_mgmt, sizeof(wpa_key_mgmt),
1531                                 "wpa_pairwise", wpa_pairwise, sizeof(wpa_pairwise),
1532                                 "auth_algs",    auth_algs,    sizeof(auth_algs),
1533                                 "wep_key0",     wep_key0,     sizeof(wep_key0),
1534                                 "wep_key1",     wep_key1,     sizeof(wep_key1),
1535                                 "wep_key2",     wep_key2,     sizeof(wep_key2),
1536                                 "wep_key3",     wep_key3,     sizeof(wep_key3)))
1537         {
1538                 c->wpa_version = wpa[0] ? atoi(wpa) : 0;
1539
1540                 if (wpa_key_mgmt[0])
1541                 {
1542                         if (strstr(wpa_key_mgmt, "PSK"))
1543                                 c->auth_suites |= IWINFO_KMGMT_PSK;
1544
1545                         if (strstr(wpa_key_mgmt, "EAP"))
1546                                 c->auth_suites |= IWINFO_KMGMT_8021x;
1547
1548                         if (strstr(wpa_key_mgmt, "NONE"))
1549                                 c->auth_suites |= IWINFO_KMGMT_NONE;
1550                 }
1551                 else
1552                 {
1553                         c->auth_suites |= IWINFO_KMGMT_PSK;
1554                 }
1555
1556                 if (wpa_pairwise[0])
1557                 {
1558                         if (strstr(wpa_pairwise, "TKIP"))
1559                                 c->pair_ciphers |= IWINFO_CIPHER_TKIP;
1560
1561                         if (strstr(wpa_pairwise, "CCMP"))
1562                                 c->pair_ciphers |= IWINFO_CIPHER_CCMP;
1563
1564                         if (strstr(wpa_pairwise, "NONE"))
1565                                 c->pair_ciphers |= IWINFO_CIPHER_NONE;
1566                 }
1567
1568                 if (auth_algs[0])
1569                 {
1570                         switch(atoi(auth_algs))
1571                         {
1572                         case 1:
1573                                 c->auth_algs |= IWINFO_AUTH_OPEN;
1574                                 break;
1575
1576                         case 2:
1577                                 c->auth_algs |= IWINFO_AUTH_SHARED;
1578                                 break;
1579
1580                         case 3:
1581                                 c->auth_algs |= IWINFO_AUTH_OPEN;
1582                                 c->auth_algs |= IWINFO_AUTH_SHARED;
1583                                 break;
1584                         }
1585
1586                         c->pair_ciphers |= nl80211_check_wepkey(wep_key0);
1587                         c->pair_ciphers |= nl80211_check_wepkey(wep_key1);
1588                         c->pair_ciphers |= nl80211_check_wepkey(wep_key2);
1589                         c->pair_ciphers |= nl80211_check_wepkey(wep_key3);
1590                 }
1591
1592                 c->group_ciphers = c->pair_ciphers;
1593                 c->enabled = (c->wpa_version || c->pair_ciphers) ? 1 : 0;
1594
1595                 return 0;
1596         }
1597
1598         return -1;
1599 }
1600
1601 static int nl80211_get_phyname(const char *ifname, char *buf)
1602 {
1603         const char *name;
1604
1605         name = nl80211_ifname2phy(ifname);
1606
1607         if (name)
1608         {
1609                 strcpy(buf, name);
1610                 return 0;
1611         }
1612         else if ((name = nl80211_phy2ifname(ifname)) != NULL)
1613         {
1614                 name = nl80211_ifname2phy(name);
1615
1616                 if (name)
1617                 {
1618                         strcpy(buf, ifname);
1619                         return 0;
1620                 }
1621         }
1622
1623         return -1;
1624 }
1625
1626
1627 static void nl80211_parse_rateinfo(struct nlattr **ri,
1628                                    struct iwinfo_rate_entry *re)
1629 {
1630         if (ri[NL80211_RATE_INFO_BITRATE32])
1631                 re->rate = nla_get_u32(ri[NL80211_RATE_INFO_BITRATE32]) * 100;
1632         else if (ri[NL80211_RATE_INFO_BITRATE])
1633                 re->rate = nla_get_u16(ri[NL80211_RATE_INFO_BITRATE]) * 100;
1634
1635         if (ri[NL80211_RATE_INFO_VHT_MCS])
1636         {
1637                 re->is_vht = 1;
1638                 re->mcs = nla_get_u8(ri[NL80211_RATE_INFO_VHT_MCS]);
1639
1640                 if (ri[NL80211_RATE_INFO_VHT_NSS])
1641                         re->nss = nla_get_u8(ri[NL80211_RATE_INFO_VHT_NSS]);
1642         }
1643         else if (ri[NL80211_RATE_INFO_MCS])
1644         {
1645                 re->is_ht = 1;
1646                 re->mcs = nla_get_u8(ri[NL80211_RATE_INFO_MCS]);
1647         }
1648
1649         if (ri[NL80211_RATE_INFO_5_MHZ_WIDTH])
1650                 re->mhz = 5;
1651         else if (ri[NL80211_RATE_INFO_10_MHZ_WIDTH])
1652                 re->mhz = 10;
1653         else if (ri[NL80211_RATE_INFO_40_MHZ_WIDTH])
1654                 re->mhz = 40;
1655         else if (ri[NL80211_RATE_INFO_80_MHZ_WIDTH])
1656                 re->mhz = 80;
1657         else if (ri[NL80211_RATE_INFO_80P80_MHZ_WIDTH] ||
1658                  ri[NL80211_RATE_INFO_160_MHZ_WIDTH])
1659                 re->mhz = 160;
1660         else
1661                 re->mhz = 20;
1662
1663         if (ri[NL80211_RATE_INFO_SHORT_GI])
1664                 re->is_short_gi = 1;
1665
1666         re->is_40mhz = (re->mhz == 40);
1667 }
1668
1669 static int nl80211_get_assoclist_cb(struct nl_msg *msg, void *arg)
1670 {
1671         struct nl80211_array_buf *arr = arg;
1672         struct iwinfo_assoclist_entry *e = arr->buf;
1673         struct nlattr **attr = nl80211_parse(msg);
1674         struct nlattr *sinfo[NL80211_STA_INFO_MAX + 1];
1675         struct nlattr *rinfo[NL80211_RATE_INFO_MAX + 1];
1676         struct nl80211_sta_flag_update *sta_flags;
1677
1678         static struct nla_policy stats_policy[NL80211_STA_INFO_MAX + 1] = {
1679                 [NL80211_STA_INFO_INACTIVE_TIME] = { .type = NLA_U32    },
1680                 [NL80211_STA_INFO_RX_PACKETS]    = { .type = NLA_U32    },
1681                 [NL80211_STA_INFO_TX_PACKETS]    = { .type = NLA_U32    },
1682                 [NL80211_STA_INFO_RX_BITRATE]    = { .type = NLA_NESTED },
1683                 [NL80211_STA_INFO_TX_BITRATE]    = { .type = NLA_NESTED },
1684                 [NL80211_STA_INFO_SIGNAL]        = { .type = NLA_U8     },
1685                 [NL80211_STA_INFO_RX_BYTES]      = { .type = NLA_U32    },
1686                 [NL80211_STA_INFO_TX_BYTES]      = { .type = NLA_U32    },
1687                 [NL80211_STA_INFO_TX_RETRIES]    = { .type = NLA_U32    },
1688                 [NL80211_STA_INFO_TX_FAILED]     = { .type = NLA_U32    },
1689                 [NL80211_STA_INFO_T_OFFSET]      = { .type = NLA_U64    },
1690                 [NL80211_STA_INFO_STA_FLAGS] =
1691                         { .minlen = sizeof(struct nl80211_sta_flag_update) },
1692         };
1693
1694         static struct nla_policy rate_policy[NL80211_RATE_INFO_MAX + 1] = {
1695                 [NL80211_RATE_INFO_BITRATE]      = { .type = NLA_U16    },
1696                 [NL80211_RATE_INFO_MCS]          = { .type = NLA_U8     },
1697                 [NL80211_RATE_INFO_40_MHZ_WIDTH] = { .type = NLA_FLAG   },
1698                 [NL80211_RATE_INFO_SHORT_GI]     = { .type = NLA_FLAG   },
1699         };
1700
1701         /* advance to end of array */
1702         e += arr->count;
1703         memset(e, 0, sizeof(*e));
1704
1705         if (attr[NL80211_ATTR_MAC])
1706                 memcpy(e->mac, nla_data(attr[NL80211_ATTR_MAC]), 6);
1707
1708         if (attr[NL80211_ATTR_STA_INFO] &&
1709             !nla_parse_nested(sinfo, NL80211_STA_INFO_MAX,
1710                               attr[NL80211_ATTR_STA_INFO], stats_policy))
1711         {
1712                 if (sinfo[NL80211_STA_INFO_SIGNAL])
1713                         e->signal = nla_get_u8(sinfo[NL80211_STA_INFO_SIGNAL]);
1714
1715                 if (sinfo[NL80211_STA_INFO_INACTIVE_TIME])
1716                         e->inactive = nla_get_u32(sinfo[NL80211_STA_INFO_INACTIVE_TIME]);
1717
1718                 if (sinfo[NL80211_STA_INFO_RX_PACKETS])
1719                         e->rx_packets = nla_get_u32(sinfo[NL80211_STA_INFO_RX_PACKETS]);
1720
1721                 if (sinfo[NL80211_STA_INFO_TX_PACKETS])
1722                         e->tx_packets = nla_get_u32(sinfo[NL80211_STA_INFO_TX_PACKETS]);
1723
1724                 if (sinfo[NL80211_STA_INFO_RX_BITRATE] &&
1725                     !nla_parse_nested(rinfo, NL80211_RATE_INFO_MAX,
1726                                       sinfo[NL80211_STA_INFO_RX_BITRATE], rate_policy))
1727                         nl80211_parse_rateinfo(rinfo, &e->rx_rate);
1728
1729                 if (sinfo[NL80211_STA_INFO_TX_BITRATE] &&
1730                     !nla_parse_nested(rinfo, NL80211_RATE_INFO_MAX,
1731                                       sinfo[NL80211_STA_INFO_TX_BITRATE], rate_policy))
1732                         nl80211_parse_rateinfo(rinfo, &e->tx_rate);
1733
1734                 if (sinfo[NL80211_STA_INFO_RX_BYTES])
1735                         e->rx_bytes = nla_get_u32(sinfo[NL80211_STA_INFO_RX_BYTES]);
1736
1737                 if (sinfo[NL80211_STA_INFO_TX_BYTES])
1738                         e->tx_bytes = nla_get_u32(sinfo[NL80211_STA_INFO_TX_BYTES]);
1739
1740                 if (sinfo[NL80211_STA_INFO_TX_RETRIES])
1741                         e->tx_retries = nla_get_u32(sinfo[NL80211_STA_INFO_TX_RETRIES]);
1742
1743                 if (sinfo[NL80211_STA_INFO_TX_FAILED])
1744                         e->tx_failed = nla_get_u32(sinfo[NL80211_STA_INFO_TX_FAILED]);
1745
1746                 if (sinfo[NL80211_STA_INFO_T_OFFSET])
1747                         e->t_offset = nla_get_u64(sinfo[NL80211_STA_INFO_T_OFFSET]);
1748
1749                 /* Station flags */
1750                 if (sinfo[NL80211_STA_INFO_STA_FLAGS])
1751                 {
1752                         sta_flags = (struct nl80211_sta_flag_update *)
1753                                 nla_data(sinfo[NL80211_STA_INFO_STA_FLAGS]);
1754
1755                         if (sta_flags->mask & BIT(NL80211_STA_FLAG_AUTHORIZED) &&
1756                             sta_flags->set & BIT(NL80211_STA_FLAG_AUTHORIZED))
1757                                 e->is_authorized = 1;
1758
1759                         if (sta_flags->mask & BIT(NL80211_STA_FLAG_AUTHENTICATED) &&
1760                             sta_flags->set & BIT(NL80211_STA_FLAG_AUTHENTICATED))
1761                                 e->is_authenticated = 1;
1762
1763                         if (sta_flags->mask & BIT(NL80211_STA_FLAG_SHORT_PREAMBLE) &&
1764                             sta_flags->set & BIT(NL80211_STA_FLAG_SHORT_PREAMBLE))
1765                                 e->is_preamble_short = 1;
1766
1767                         if (sta_flags->mask & BIT(NL80211_STA_FLAG_WME) &&
1768                             sta_flags->set & BIT(NL80211_STA_FLAG_WME))
1769                                 e->is_wme = 1;
1770
1771                         if (sta_flags->mask & BIT(NL80211_STA_FLAG_MFP) &&
1772                             sta_flags->set & BIT(NL80211_STA_FLAG_MFP))
1773                                 e->is_mfp = 1;
1774
1775                         if (sta_flags->mask & BIT(NL80211_STA_FLAG_TDLS_PEER) &&
1776                             sta_flags->set & BIT(NL80211_STA_FLAG_TDLS_PEER))
1777                                 e->is_tdls = 1;
1778                 }
1779         }
1780
1781         e->noise = 0; /* filled in by caller */
1782         arr->count++;
1783
1784         return NL_SKIP;
1785 }
1786
1787 static int nl80211_get_assoclist(const char *ifname, char *buf, int *len)
1788 {
1789         DIR *d;
1790         int i, noise = 0;
1791         struct dirent *de;
1792         struct nl80211_array_buf arr = { .buf = buf, .count = 0 };
1793         struct iwinfo_assoclist_entry *e;
1794
1795         if ((d = opendir("/sys/class/net")) != NULL)
1796         {
1797                 while ((de = readdir(d)) != NULL)
1798                 {
1799                         if (!strncmp(de->d_name, ifname, strlen(ifname)) &&
1800                             (!de->d_name[strlen(ifname)] ||
1801                              !strncmp(&de->d_name[strlen(ifname)], ".sta", 4)))
1802                         {
1803                                 nl80211_request(de->d_name, NL80211_CMD_GET_STATION,
1804                                                 NLM_F_DUMP, nl80211_get_assoclist_cb, &arr);
1805                         }
1806                 }
1807
1808                 closedir(d);
1809
1810                 if (!nl80211_get_noise(ifname, &noise))
1811                         for (i = 0, e = arr.buf; i < arr.count; i++, e++)
1812                                 e->noise = noise;
1813
1814                 *len = (arr.count * sizeof(struct iwinfo_assoclist_entry));
1815                 return 0;
1816         }
1817
1818         return -1;
1819 }
1820
1821 static int nl80211_get_txpwrlist_cb(struct nl_msg *msg, void *arg)
1822 {
1823         int *dbm_max = arg;
1824         int ch_cur, ch_cmp, bands_remain, freqs_remain;
1825
1826         struct nlattr **attr = nl80211_parse(msg);
1827         struct nlattr *bands[NL80211_BAND_ATTR_MAX + 1];
1828         struct nlattr *freqs[NL80211_FREQUENCY_ATTR_MAX + 1];
1829         struct nlattr *band, *freq;
1830
1831         static struct nla_policy freq_policy[NL80211_FREQUENCY_ATTR_MAX + 1] = {
1832                 [NL80211_FREQUENCY_ATTR_FREQ]         = { .type = NLA_U32  },
1833                 [NL80211_FREQUENCY_ATTR_DISABLED]     = { .type = NLA_FLAG },
1834                 [NL80211_FREQUENCY_ATTR_PASSIVE_SCAN] = { .type = NLA_FLAG },
1835                 [NL80211_FREQUENCY_ATTR_NO_IBSS]      = { .type = NLA_FLAG },
1836                 [NL80211_FREQUENCY_ATTR_RADAR]        = { .type = NLA_FLAG },
1837                 [NL80211_FREQUENCY_ATTR_MAX_TX_POWER] = { .type = NLA_U32  },
1838         };
1839
1840         ch_cur = *dbm_max; /* value int* is initialized with channel by caller */
1841         *dbm_max = -1;
1842
1843         nla_for_each_nested(band, attr[NL80211_ATTR_WIPHY_BANDS], bands_remain)
1844         {
1845                 nla_parse(bands, NL80211_BAND_ATTR_MAX, nla_data(band),
1846                           nla_len(band), NULL);
1847
1848                 nla_for_each_nested(freq, bands[NL80211_BAND_ATTR_FREQS], freqs_remain)
1849                 {
1850                         nla_parse(freqs, NL80211_FREQUENCY_ATTR_MAX,
1851                                   nla_data(freq), nla_len(freq), freq_policy);
1852
1853                         ch_cmp = nl80211_freq2channel(nla_get_u32(
1854                                 freqs[NL80211_FREQUENCY_ATTR_FREQ]));
1855
1856                         if ((!ch_cur || (ch_cmp == ch_cur)) &&
1857                             freqs[NL80211_FREQUENCY_ATTR_MAX_TX_POWER])
1858                         {
1859                                 *dbm_max = (int)(0.01 * nla_get_u32(
1860                                         freqs[NL80211_FREQUENCY_ATTR_MAX_TX_POWER]));
1861
1862                                 break;
1863                         }
1864                 }
1865         }
1866
1867         return NL_SKIP;
1868 }
1869
1870 static int nl80211_get_txpwrlist(const char *ifname, char *buf, int *len)
1871 {
1872         int err, ch_cur;
1873         int dbm_max = -1, dbm_cur, dbm_cnt;
1874         struct nl80211_msg_conveyor *req;
1875         struct iwinfo_txpwrlist_entry entry;
1876
1877         if (nl80211_get_channel(ifname, &ch_cur))
1878                 ch_cur = 0;
1879
1880         /* initialize the value pointer with channel for callback */
1881         dbm_max = ch_cur;
1882
1883         err = nl80211_request(ifname, NL80211_CMD_GET_WIPHY, 0,
1884                               nl80211_get_txpwrlist_cb, &dbm_max);
1885
1886         if (!err)
1887         {
1888                 for (dbm_cur = 0, dbm_cnt = 0;
1889                      dbm_cur < dbm_max;
1890                      dbm_cur++, dbm_cnt++)
1891                 {
1892                         entry.dbm = dbm_cur;
1893                         entry.mw  = iwinfo_dbm2mw(dbm_cur);
1894
1895                         memcpy(&buf[dbm_cnt * sizeof(entry)], &entry, sizeof(entry));
1896                 }
1897
1898                 entry.dbm = dbm_max;
1899                 entry.mw  = iwinfo_dbm2mw(dbm_max);
1900
1901                 memcpy(&buf[dbm_cnt * sizeof(entry)], &entry, sizeof(entry));
1902                 dbm_cnt++;
1903
1904                 *len = dbm_cnt * sizeof(entry);
1905                 return 0;
1906         }
1907
1908         return -1;
1909 }
1910
1911 static void nl80211_get_scancrypto(const char *spec,
1912         struct iwinfo_crypto_entry *c)
1913 {
1914         if (strstr(spec, "WPA") || strstr(spec, "WEP"))
1915         {
1916                 c->enabled = 1;
1917
1918                 if (strstr(spec, "WPA2-") && strstr(spec, "WPA-"))
1919                         c->wpa_version = 3;
1920
1921                 else if (strstr(spec, "WPA2"))
1922                         c->wpa_version = 2;
1923
1924                 else if (strstr(spec, "WPA"))
1925                         c->wpa_version = 1;
1926
1927                 else if (strstr(spec, "WEP"))
1928                         c->auth_algs = IWINFO_AUTH_OPEN | IWINFO_AUTH_SHARED;
1929
1930
1931                 if (strstr(spec, "PSK"))
1932                         c->auth_suites |= IWINFO_KMGMT_PSK;
1933
1934                 if (strstr(spec, "802.1X") || strstr(spec, "EAP"))
1935                         c->auth_suites |= IWINFO_KMGMT_8021x;
1936
1937                 if (strstr(spec, "WPA-NONE"))
1938                         c->auth_suites |= IWINFO_KMGMT_NONE;
1939
1940
1941                 if (strstr(spec, "TKIP"))
1942                         c->pair_ciphers |= IWINFO_CIPHER_TKIP;
1943
1944                 if (strstr(spec, "CCMP"))
1945                         c->pair_ciphers |= IWINFO_CIPHER_CCMP;
1946
1947                 if (strstr(spec, "WEP-40"))
1948                         c->pair_ciphers |= IWINFO_CIPHER_WEP40;
1949
1950                 if (strstr(spec, "WEP-104"))
1951                         c->pair_ciphers |= IWINFO_CIPHER_WEP104;
1952
1953                 c->group_ciphers = c->pair_ciphers;
1954         }
1955         else
1956         {
1957                 c->enabled = 0;
1958         }
1959 }
1960
1961
1962 struct nl80211_scanlist {
1963         struct iwinfo_scanlist_entry *e;
1964         int len;
1965 };
1966
1967
1968 static void nl80211_get_scanlist_ie(struct nlattr **bss,
1969                                     struct iwinfo_scanlist_entry *e)
1970 {
1971         int ielen = nla_len(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
1972         unsigned char *ie = nla_data(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
1973         static unsigned char ms_oui[3] = { 0x00, 0x50, 0xf2 };
1974         int len;
1975
1976         while (ielen >= 2 && ielen >= ie[1])
1977         {
1978                 switch (ie[0])
1979                 {
1980                 case 0: /* SSID */
1981                         len = min(ie[1], IWINFO_ESSID_MAX_SIZE);
1982                         memcpy(e->ssid, ie + 2, len);
1983                         e->ssid[len] = 0;
1984                         break;
1985
1986                 case 48: /* RSN */
1987                         iwinfo_parse_rsn(&e->crypto, ie + 2, ie[1],
1988                                          IWINFO_CIPHER_CCMP, IWINFO_KMGMT_8021x);
1989                         break;
1990
1991                 case 221: /* Vendor */
1992                         if (ie[1] >= 4 && !memcmp(ie + 2, ms_oui, 3) && ie[5] == 1)
1993                                 iwinfo_parse_rsn(&e->crypto, ie + 6, ie[1] - 4,
1994                                                  IWINFO_CIPHER_TKIP, IWINFO_KMGMT_PSK);
1995                         break;
1996                 }
1997
1998                 ielen -= ie[1] + 2;
1999                 ie += ie[1] + 2;
2000         }
2001 }
2002
2003 static int nl80211_get_scanlist_cb(struct nl_msg *msg, void *arg)
2004 {
2005         int8_t rssi;
2006         uint16_t caps;
2007
2008         struct nl80211_scanlist *sl = arg;
2009         struct nlattr **tb = nl80211_parse(msg);
2010         struct nlattr *bss[NL80211_BSS_MAX + 1];
2011
2012         static struct nla_policy bss_policy[NL80211_BSS_MAX + 1] = {
2013                 [NL80211_BSS_TSF]                  = { .type = NLA_U64 },
2014                 [NL80211_BSS_FREQUENCY]            = { .type = NLA_U32 },
2015                 [NL80211_BSS_BSSID]                = { 0 },
2016                 [NL80211_BSS_BEACON_INTERVAL]      = { .type = NLA_U16 },
2017                 [NL80211_BSS_CAPABILITY]           = { .type = NLA_U16 },
2018                 [NL80211_BSS_INFORMATION_ELEMENTS] = { 0 },
2019                 [NL80211_BSS_SIGNAL_MBM]           = { .type = NLA_U32 },
2020                 [NL80211_BSS_SIGNAL_UNSPEC]        = { .type = NLA_U8  },
2021                 [NL80211_BSS_STATUS]               = { .type = NLA_U32 },
2022                 [NL80211_BSS_SEEN_MS_AGO]          = { .type = NLA_U32 },
2023                 [NL80211_BSS_BEACON_IES]           = { 0 },
2024         };
2025
2026         if (!tb[NL80211_ATTR_BSS] ||
2027                 nla_parse_nested(bss, NL80211_BSS_MAX, tb[NL80211_ATTR_BSS],
2028                                  bss_policy) ||
2029                 !bss[NL80211_BSS_BSSID])
2030         {
2031                 return NL_SKIP;
2032         }
2033
2034         if (bss[NL80211_BSS_CAPABILITY])
2035                 caps = nla_get_u16(bss[NL80211_BSS_CAPABILITY]);
2036         else
2037                 caps = 0;
2038
2039         memset(sl->e, 0, sizeof(*sl->e));
2040         memcpy(sl->e->mac, nla_data(bss[NL80211_BSS_BSSID]), 6);
2041
2042         if (caps & (1<<1))
2043                 sl->e->mode = IWINFO_OPMODE_ADHOC;
2044         else if (caps & (1<<0))
2045                 sl->e->mode = IWINFO_OPMODE_MASTER;
2046         else
2047                 sl->e->mode = IWINFO_OPMODE_MESHPOINT;
2048
2049         if (caps & (1<<4))
2050                 sl->e->crypto.enabled = 1;
2051
2052         if (bss[NL80211_BSS_FREQUENCY])
2053                 sl->e->channel = nl80211_freq2channel(nla_get_u32(
2054                         bss[NL80211_BSS_FREQUENCY]));
2055
2056         if (bss[NL80211_BSS_INFORMATION_ELEMENTS])
2057                 nl80211_get_scanlist_ie(bss, sl->e);
2058
2059         if (bss[NL80211_BSS_SIGNAL_MBM])
2060         {
2061                 sl->e->signal =
2062                         (uint8_t)((int32_t)nla_get_u32(bss[NL80211_BSS_SIGNAL_MBM]) / 100);
2063
2064                 rssi = sl->e->signal - 0x100;
2065
2066                 if (rssi < -110)
2067                         rssi = -110;
2068                 else if (rssi > -40)
2069                         rssi = -40;
2070
2071                 sl->e->quality = (rssi + 110);
2072                 sl->e->quality_max = 70;
2073         }
2074
2075         if (sl->e->crypto.enabled && !sl->e->crypto.wpa_version)
2076         {
2077                 sl->e->crypto.auth_algs    = IWINFO_AUTH_OPEN | IWINFO_AUTH_SHARED;
2078                 sl->e->crypto.pair_ciphers = IWINFO_CIPHER_WEP40 | IWINFO_CIPHER_WEP104;
2079         }
2080
2081         sl->e++;
2082         sl->len++;
2083
2084         return NL_SKIP;
2085 }
2086
2087 static int nl80211_get_scanlist_nl(const char *ifname, char *buf, int *len)
2088 {
2089         struct nl80211_scanlist sl = { .e = (struct iwinfo_scanlist_entry *)buf };
2090
2091         if (nl80211_request(ifname, NL80211_CMD_TRIGGER_SCAN, 0, NULL, NULL))
2092                 goto out;
2093
2094         if (nl80211_wait("nl80211", "scan", NL80211_CMD_NEW_SCAN_RESULTS))
2095                 goto out;
2096
2097         if (nl80211_request(ifname, NL80211_CMD_GET_SCAN, NLM_F_DUMP,
2098                             nl80211_get_scanlist_cb, &sl))
2099                 goto out;
2100
2101         *len = sl.len * sizeof(struct iwinfo_scanlist_entry);
2102         return 0;
2103
2104 out:
2105         *len = 0;
2106         return -1;
2107 }
2108
2109 static int wpasupp_ssid_decode(const char *in, char *out, int outlen)
2110 {
2111 #define hex(x) \
2112         (((x) >= 'a') ? ((x) - 'a' + 10) : \
2113                 (((x) >= 'A') ? ((x) - 'A' + 10) : ((x) - '0')))
2114
2115         int len = 0;
2116
2117         while (*in)
2118         {
2119                 if (len + 1 >= outlen)
2120                         break;
2121
2122                 switch (*in)
2123                 {
2124                 case '\\':
2125                         in++;
2126                         switch (*in)
2127                         {
2128                         case 'n':
2129                                 out[len++] = '\n'; in++;
2130                                 break;
2131
2132                         case 'r':
2133                                 out[len++] = '\r'; in++;
2134                                 break;
2135
2136                         case 't':
2137                                 out[len++] = '\t'; in++;
2138                                 break;
2139
2140                         case 'e':
2141                                 out[len++] = '\033'; in++;
2142                                 break;
2143
2144                         case 'x':
2145                                 if (isxdigit(*(in+1)) && isxdigit(*(in+2)))
2146                                         out[len++] = hex(*(in+1)) * 16 + hex(*(in+2));
2147                                 in += 3;
2148                                 break;
2149
2150                         default:
2151                                 out[len++] = *in++;
2152                                 break;
2153                         }
2154                         break;
2155
2156                 default:
2157                         out[len++] = *in++;
2158                         break;
2159                 }
2160         }
2161
2162         if (outlen > len)
2163                 out[len] = '\0';
2164
2165         return len;
2166 }
2167
2168 static int nl80211_get_scanlist_wpactl(const char *ifname, char *buf, int *len)
2169 {
2170         int sock, qmax, rssi, tries, count = -1, ready = 0;
2171         char *pos, *line, *bssid, *freq, *signal, *flags, *ssid, reply[4096];
2172         struct sockaddr_un local = { 0 };
2173         struct iwinfo_scanlist_entry *e = (struct iwinfo_scanlist_entry *)buf;
2174
2175         sock = nl80211_wpactl_connect(ifname, &local);
2176
2177         if (sock < 0)
2178                 return sock;
2179
2180         send(sock, "ATTACH", 6, 0);
2181         send(sock, "SCAN", 4, 0);
2182
2183         /*
2184          * wait for scan results:
2185          *   nl80211_wpactl_recv() will use a timeout of 256ms and we need to scan
2186          *   72 channels at most. We'll also receive two "OK" messages acknowledging
2187          *   the "ATTACH" and "SCAN" commands and the driver might need a bit extra
2188          *   time to process the results, so try 72 + 2 + 1 times.
2189          */
2190         for (tries = 0; tries < 75; tries++)
2191         {
2192                 if (nl80211_wpactl_recv(sock, reply, sizeof(reply)) <= 0)
2193                         continue;
2194
2195                 /* got an event notification */
2196                 if (reply[0] == '<')
2197                 {
2198                         /* scan results are ready */
2199                         if (strstr(reply, "CTRL-EVENT-SCAN-RESULTS"))
2200                         {
2201                                 /* send "SCAN_RESULTS" command */
2202                                 ready = (send(sock, "SCAN_RESULTS", 12, 0) == 12);
2203                                 break;
2204                         }
2205
2206                         /* is another unrelated event, retry */
2207                         tries--;
2208                 }
2209         }
2210
2211         /* receive and parse scan results if the wait above didn't time out */
2212         while (ready && nl80211_wpactl_recv(sock, reply, sizeof(reply)) > 0)
2213         {
2214                 /* received an event notification, receive again */
2215                 if (reply[0] == '<')
2216                         continue;
2217
2218                 nl80211_get_quality_max(ifname, &qmax);
2219
2220                 for (line = strtok_r(reply, "\n", &pos);
2221                      line != NULL;
2222                      line = strtok_r(NULL, "\n", &pos))
2223                 {
2224                         /* skip header line */
2225                         if (count < 0)
2226                         {
2227                                 count++;
2228                                 continue;
2229                         }
2230
2231                         bssid  = strtok(line, "\t");
2232                         freq   = strtok(NULL, "\t");
2233                         signal = strtok(NULL, "\t");
2234                         flags  = strtok(NULL, "\t");
2235                         ssid   = strtok(NULL, "\n");
2236
2237                         if (!bssid || !freq || !signal || !flags || !ssid)
2238                                 continue;
2239
2240                         /* BSSID */
2241                         e->mac[0] = strtol(&bssid[0],  NULL, 16);
2242                         e->mac[1] = strtol(&bssid[3],  NULL, 16);
2243                         e->mac[2] = strtol(&bssid[6],  NULL, 16);
2244                         e->mac[3] = strtol(&bssid[9],  NULL, 16);
2245                         e->mac[4] = strtol(&bssid[12], NULL, 16);
2246                         e->mac[5] = strtol(&bssid[15], NULL, 16);
2247
2248                         /* SSID */
2249                         wpasupp_ssid_decode(ssid, e->ssid, sizeof(e->ssid));
2250
2251                         /* Mode */
2252                         if (strstr(flags, "[MESH]"))
2253                                 e->mode = IWINFO_OPMODE_MESHPOINT;
2254                         else if (strstr(flags, "[IBSS]"))
2255                                 e->mode = IWINFO_OPMODE_ADHOC;
2256                         else
2257                                 e->mode = IWINFO_OPMODE_MASTER;
2258
2259                         /* Channel */
2260                         e->channel = nl80211_freq2channel(atoi(freq));
2261
2262                         /* Signal */
2263                         rssi = atoi(signal);
2264                         e->signal = rssi;
2265
2266                         /* Quality */
2267                         if (rssi < 0)
2268                         {
2269                                 /* The cfg80211 wext compat layer assumes a signal range
2270                                  * of -110 dBm to -40 dBm, the quality value is derived
2271                                  * by adding 110 to the signal level */
2272                                 if (rssi < -110)
2273                                         rssi = -110;
2274                                 else if (rssi > -40)
2275                                         rssi = -40;
2276
2277                                 e->quality = (rssi + 110);
2278                         }
2279                         else
2280                         {
2281                                 e->quality = rssi;
2282                         }
2283
2284                         /* Max. Quality */
2285                         e->quality_max = qmax;
2286
2287                         /* Crypto */
2288                         nl80211_get_scancrypto(flags, &e->crypto);
2289
2290                         count++;
2291                         e++;
2292                 }
2293
2294                 *len = count * sizeof(struct iwinfo_scanlist_entry);
2295                 break;
2296         }
2297
2298         close(sock);
2299         unlink(local.sun_path);
2300
2301         return (count >= 0) ? 0 : -1;
2302 }
2303
2304 static int nl80211_get_scanlist(const char *ifname, char *buf, int *len)
2305 {
2306         char *res;
2307         int rv, mode;
2308
2309         *len = 0;
2310
2311         /* Got a radioX pseudo interface, find some interface on it or create one */
2312         if (!strncmp(ifname, "radio", 5))
2313         {
2314                 /* Reuse existing interface */
2315                 if ((res = nl80211_phy2ifname(ifname)) != NULL)
2316                 {
2317                         return nl80211_get_scanlist(res, buf, len);
2318                 }
2319
2320                 /* Need to spawn a temporary iface for scanning */
2321                 else if ((res = nl80211_ifadd(ifname)) != NULL)
2322                 {
2323                         rv = nl80211_get_scanlist(res, buf, len);
2324                         nl80211_ifdel(res);
2325                         return rv;
2326                 }
2327         }
2328
2329         /* WPA supplicant */
2330         if (!nl80211_get_scanlist_wpactl(ifname, buf, len))
2331         {
2332                 return 0;
2333         }
2334
2335         /* station / ad-hoc / monitor scan */
2336         else if (!nl80211_get_mode(ifname, &mode) &&
2337                  (mode == IWINFO_OPMODE_ADHOC ||
2338                   mode == IWINFO_OPMODE_MASTER ||
2339                   mode == IWINFO_OPMODE_CLIENT ||
2340                   mode == IWINFO_OPMODE_MONITOR) &&
2341                  iwinfo_ifup(ifname))
2342         {
2343                 return nl80211_get_scanlist_nl(ifname, buf, len);
2344         }
2345
2346         /* AP scan */
2347         else
2348         {
2349                 /* Got a temp interface, don't create yet another one */
2350                 if (!strncmp(ifname, "tmp.", 4))
2351                 {
2352                         if (!iwinfo_ifup(ifname))
2353                                 return -1;
2354
2355                         rv = nl80211_get_scanlist_nl(ifname, buf, len);
2356                         iwinfo_ifdown(ifname);
2357                         return rv;
2358                 }
2359
2360                 /* Spawn a new scan interface */
2361                 else
2362                 {
2363                         if (!(res = nl80211_ifadd(ifname)))
2364                                 return -1;
2365
2366                         iwinfo_ifmac(res);
2367
2368                         /* if we can take the new interface up, the driver supports an
2369                          * additional interface and there's no need to tear down the ap */
2370                         if (iwinfo_ifup(res))
2371                         {
2372                                 rv = nl80211_get_scanlist_nl(res, buf, len);
2373                                 iwinfo_ifdown(res);
2374                         }
2375
2376                         /* driver cannot create secondary interface, take down ap
2377                          * during scan */
2378                         else if (iwinfo_ifdown(ifname) && iwinfo_ifup(res))
2379                         {
2380                                 rv = nl80211_get_scanlist_nl(res, buf, len);
2381                                 iwinfo_ifdown(res);
2382                                 iwinfo_ifup(ifname);
2383                                 nl80211_hostapd_hup(ifname);
2384                         }
2385
2386                         nl80211_ifdel(res);
2387                         return rv;
2388                 }
2389         }
2390
2391         return -1;
2392 }
2393
2394 static int nl80211_get_freqlist_cb(struct nl_msg *msg, void *arg)
2395 {
2396         int bands_remain, freqs_remain;
2397
2398         struct nl80211_array_buf *arr = arg;
2399         struct iwinfo_freqlist_entry *e;
2400
2401         struct nlattr **attr = nl80211_parse(msg);
2402         struct nlattr *bands[NL80211_BAND_ATTR_MAX + 1];
2403         struct nlattr *freqs[NL80211_FREQUENCY_ATTR_MAX + 1];
2404         struct nlattr *band, *freq;
2405
2406         e = arr->buf;
2407         e += arr->count;
2408
2409         if (attr[NL80211_ATTR_WIPHY_BANDS]) {
2410                 nla_for_each_nested(band, attr[NL80211_ATTR_WIPHY_BANDS], bands_remain)
2411                 {
2412                         nla_parse(bands, NL80211_BAND_ATTR_MAX,
2413                                   nla_data(band), nla_len(band), NULL);
2414
2415                         if (bands[NL80211_BAND_ATTR_FREQS]) {
2416                                 nla_for_each_nested(freq, bands[NL80211_BAND_ATTR_FREQS], freqs_remain)
2417                                 {
2418                                         nla_parse(freqs, NL80211_FREQUENCY_ATTR_MAX,
2419                                                   nla_data(freq), nla_len(freq), NULL);
2420
2421                                         if (!freqs[NL80211_FREQUENCY_ATTR_FREQ] ||
2422                                             freqs[NL80211_FREQUENCY_ATTR_DISABLED])
2423                                                 continue;
2424
2425                                         e->mhz = nla_get_u32(freqs[NL80211_FREQUENCY_ATTR_FREQ]);
2426                                         e->channel = nl80211_freq2channel(e->mhz);
2427
2428                                         e->restricted = (
2429                                                 freqs[NL80211_FREQUENCY_ATTR_NO_IR] &&
2430                                                 !freqs[NL80211_FREQUENCY_ATTR_RADAR]
2431                                         ) ? 1 : 0;
2432
2433                                         if (freqs[NL80211_FREQUENCY_ATTR_NO_HT40_MINUS])
2434                                                 e->flags |= IWINFO_FREQ_NO_HT40MINUS;
2435                                         if (freqs[NL80211_FREQUENCY_ATTR_NO_HT40_PLUS])
2436                                                 e->flags |= IWINFO_FREQ_NO_HT40PLUS;
2437                                         if (freqs[NL80211_FREQUENCY_ATTR_NO_80MHZ])
2438                                                 e->flags |= IWINFO_FREQ_NO_80MHZ;
2439                                         if (freqs[NL80211_FREQUENCY_ATTR_NO_160MHZ])
2440                                                 e->flags |= IWINFO_FREQ_NO_160MHZ;
2441                                         if (freqs[NL80211_FREQUENCY_ATTR_NO_20MHZ])
2442                                                 e->flags |= IWINFO_FREQ_NO_20MHZ;
2443                                         if (freqs[NL80211_FREQUENCY_ATTR_NO_10MHZ])
2444                                                 e->flags |= IWINFO_FREQ_NO_10MHZ;
2445
2446                                         e++;
2447                                         arr->count++;
2448                                 }
2449                         }
2450                 }
2451         }
2452
2453         return NL_SKIP;
2454 }
2455
2456 static int nl80211_get_freqlist(const char *ifname, char *buf, int *len)
2457 {
2458         struct nl80211_msg_conveyor *cv;
2459         struct nl80211_array_buf arr = { .buf = buf, .count = 0 };
2460         uint32_t features = nl80211_get_protocol_features(ifname);
2461         int flags;
2462
2463         flags = features & NL80211_PROTOCOL_FEATURE_SPLIT_WIPHY_DUMP ? NLM_F_DUMP : 0;
2464         cv = nl80211_msg(ifname, NL80211_CMD_GET_WIPHY, flags);
2465         if (!cv)
2466                 goto out;
2467
2468         NLA_PUT_FLAG(cv->msg, NL80211_ATTR_SPLIT_WIPHY_DUMP);
2469         if (nl80211_send(cv, nl80211_get_freqlist_cb, &arr))
2470                 goto out;
2471
2472         *len = arr.count * sizeof(struct iwinfo_freqlist_entry);
2473         return 0;
2474
2475 nla_put_failure:
2476         nl80211_free(cv);
2477 out:
2478         *len = 0;
2479         return -1;
2480 }
2481
2482 static int nl80211_get_country_cb(struct nl_msg *msg, void *arg)
2483 {
2484         char *buf = arg;
2485         struct nlattr **attr = nl80211_parse(msg);
2486
2487         if (attr[NL80211_ATTR_REG_ALPHA2])
2488                 memcpy(buf, nla_data(attr[NL80211_ATTR_REG_ALPHA2]), 2);
2489         else
2490                 buf[0] = 0;
2491
2492         return NL_SKIP;
2493 }
2494
2495 static int nl80211_get_country(const char *ifname, char *buf)
2496 {
2497         if (nl80211_request(ifname, NL80211_CMD_GET_REG, 0,
2498                             nl80211_get_country_cb, buf))
2499                 return -1;
2500
2501         return 0;
2502 }
2503
2504 static int nl80211_get_countrylist(const char *ifname, char *buf, int *len)
2505 {
2506         int count;
2507         struct iwinfo_country_entry *e = (struct iwinfo_country_entry *)buf;
2508         const struct iwinfo_iso3166_label *l;
2509
2510         for (l = IWINFO_ISO3166_NAMES, count = 0; l->iso3166; l++, e++, count++)
2511         {
2512                 e->iso3166 = l->iso3166;
2513                 e->ccode[0] = (l->iso3166 / 256);
2514                 e->ccode[1] = (l->iso3166 % 256);
2515                 e->ccode[2] = 0;
2516         }
2517
2518         *len = (count * sizeof(struct iwinfo_country_entry));
2519         return 0;
2520 }
2521
2522
2523 struct nl80211_modes
2524 {
2525         bool ok;
2526         uint32_t hw;
2527         uint32_t ht;
2528 };
2529
2530 static int nl80211_get_modelist_cb(struct nl_msg *msg, void *arg)
2531 {
2532         struct nl80211_modes *m = arg;
2533         int bands_remain, freqs_remain;
2534         uint16_t caps = 0;
2535         uint32_t vht_caps = 0;
2536         struct nlattr **attr = nl80211_parse(msg);
2537         struct nlattr *bands[NL80211_BAND_ATTR_MAX + 1];
2538         struct nlattr *freqs[NL80211_FREQUENCY_ATTR_MAX + 1];
2539         struct nlattr *band, *freq;
2540
2541         if (attr[NL80211_ATTR_WIPHY_BANDS])
2542         {
2543                 nla_for_each_nested(band, attr[NL80211_ATTR_WIPHY_BANDS], bands_remain)
2544                 {
2545                         nla_parse(bands, NL80211_BAND_ATTR_MAX,
2546                                   nla_data(band), nla_len(band), NULL);
2547
2548                         if (bands[NL80211_BAND_ATTR_HT_CAPA])
2549                                 caps = nla_get_u16(bands[NL80211_BAND_ATTR_HT_CAPA]);
2550
2551                         /* Treat any nonzero capability as 11n */
2552                         if (caps > 0)
2553                         {
2554                                 m->hw |= IWINFO_80211_N;
2555                                 m->ht |= IWINFO_HTMODE_HT20;
2556
2557                                 if (caps & (1 << 1))
2558                                         m->ht |= IWINFO_HTMODE_HT40;
2559                         }
2560
2561                         nla_for_each_nested(freq, bands[NL80211_BAND_ATTR_FREQS],
2562                                             freqs_remain)
2563                         {
2564                                 nla_parse(freqs, NL80211_FREQUENCY_ATTR_MAX,
2565                                           nla_data(freq), nla_len(freq), NULL);
2566
2567                                 if (!freqs[NL80211_FREQUENCY_ATTR_FREQ])
2568                                         continue;
2569
2570                                 if (nla_get_u32(freqs[NL80211_FREQUENCY_ATTR_FREQ]) < 2485)
2571                                 {
2572                                         m->hw |= IWINFO_80211_B;
2573                                         m->hw |= IWINFO_80211_G;
2574                                 }
2575                                 else if (bands[NL80211_BAND_ATTR_VHT_CAPA])
2576                                 {
2577                                         vht_caps = nla_get_u32(bands[NL80211_BAND_ATTR_VHT_CAPA]);
2578
2579                                         /* Treat any nonzero capability as 11ac */
2580                                         if (vht_caps > 0)
2581                                         {
2582                                                 m->hw |= IWINFO_80211_AC;
2583                                                 m->ht |= IWINFO_HTMODE_VHT20 | IWINFO_HTMODE_VHT40 | IWINFO_HTMODE_VHT80;
2584
2585                                                 switch ((vht_caps >> 2) & 3)
2586                                                 {
2587                                                 case 2:
2588                                                         m->ht |= IWINFO_HTMODE_VHT80_80;
2589                                                         /* fall through */
2590
2591                                                 case 1:
2592                                                         m->ht |= IWINFO_HTMODE_VHT160;
2593                                                 }
2594                                         }
2595                                 }
2596                                 else if (!(m->hw & IWINFO_80211_AC))
2597                                 {
2598                                         m->hw |= IWINFO_80211_A;
2599                                 }
2600                         }
2601                 }
2602
2603                 m->ok = 1;
2604         }
2605
2606         return NL_SKIP;
2607 }
2608
2609 static int nl80211_get_hwmodelist(const char *ifname, int *buf)
2610 {
2611         struct nl80211_modes m = { 0 };
2612
2613         if (nl80211_request(ifname, NL80211_CMD_GET_WIPHY, 0,
2614                             nl80211_get_modelist_cb, &m))
2615                 goto out;
2616
2617         if (!m.ok)
2618                 goto out;
2619
2620         *buf = m.hw;
2621         return 0;
2622
2623 out:
2624         *buf = 0;
2625         return -1;
2626 }
2627
2628 static int nl80211_get_htmodelist(const char *ifname, int *buf)
2629 {
2630         struct nl80211_modes m = { 0 };
2631
2632         if (nl80211_request(ifname, NL80211_CMD_GET_WIPHY, 0,
2633                             nl80211_get_modelist_cb, &m))
2634                 goto out;
2635
2636         if (!m.ok)
2637                 goto out;
2638
2639         *buf = m.ht;
2640         return 0;
2641
2642 out:
2643         *buf = 0;
2644         return -1;
2645 }
2646
2647
2648 static int nl80211_get_ifcomb_cb(struct nl_msg *msg, void *arg)
2649 {
2650         struct nlattr **attr = nl80211_parse(msg);
2651         struct nlattr *comb;
2652         int *ret = arg;
2653         int comb_rem, limit_rem, mode_rem;
2654
2655         *ret = 0;
2656         if (!attr[NL80211_ATTR_INTERFACE_COMBINATIONS])
2657                 return NL_SKIP;
2658
2659         nla_for_each_nested(comb, attr[NL80211_ATTR_INTERFACE_COMBINATIONS], comb_rem)
2660         {
2661                 static struct nla_policy iface_combination_policy[NUM_NL80211_IFACE_COMB] = {
2662                         [NL80211_IFACE_COMB_LIMITS] = { .type = NLA_NESTED },
2663                         [NL80211_IFACE_COMB_MAXNUM] = { .type = NLA_U32 },
2664                 };
2665                 struct nlattr *tb_comb[NUM_NL80211_IFACE_COMB+1];
2666                 static struct nla_policy iface_limit_policy[NUM_NL80211_IFACE_LIMIT] = {
2667                         [NL80211_IFACE_LIMIT_TYPES] = { .type = NLA_NESTED },
2668                         [NL80211_IFACE_LIMIT_MAX] = { .type = NLA_U32 },
2669                 };
2670                 struct nlattr *tb_limit[NUM_NL80211_IFACE_LIMIT+1];
2671                 struct nlattr *limit;
2672
2673                 nla_parse_nested(tb_comb, NUM_NL80211_IFACE_COMB, comb, iface_combination_policy);
2674
2675                 if (!tb_comb[NL80211_IFACE_COMB_LIMITS])
2676                         continue;
2677
2678                 nla_for_each_nested(limit, tb_comb[NL80211_IFACE_COMB_LIMITS], limit_rem)
2679                 {
2680                         struct nlattr *mode;
2681
2682                         nla_parse_nested(tb_limit, NUM_NL80211_IFACE_LIMIT, limit, iface_limit_policy);
2683
2684                         if (!tb_limit[NL80211_IFACE_LIMIT_TYPES] ||
2685                             !tb_limit[NL80211_IFACE_LIMIT_MAX])
2686                                 continue;
2687
2688                         if (nla_get_u32(tb_limit[NL80211_IFACE_LIMIT_MAX]) < 2)
2689                                 continue;
2690
2691                         nla_for_each_nested(mode, tb_limit[NL80211_IFACE_LIMIT_TYPES], mode_rem) {
2692                                 if (nla_type(mode) == NL80211_IFTYPE_AP)
2693                                         *ret = 1;
2694                         }
2695                 }
2696         }
2697
2698         return NL_SKIP;
2699 }
2700
2701 static int nl80211_get_mbssid_support(const char *ifname, int *buf)
2702 {
2703         if (nl80211_request(ifname, NL80211_CMD_GET_WIPHY, 0,
2704                             nl80211_get_ifcomb_cb, buf))
2705                 return -1;
2706
2707         return 0;
2708 }
2709
2710 static int nl80211_get_hardware_id(const char *ifname, char *buf)
2711 {
2712         int rv = -1;
2713         char *res;
2714
2715         /* Got a radioX pseudo interface, find some interface on it or create one */
2716         if (!strncmp(ifname, "radio", 5))
2717         {
2718                 /* Reuse existing interface */
2719                 if ((res = nl80211_phy2ifname(ifname)) != NULL)
2720                 {
2721                         rv = wext_ops.hardware_id(res, buf);
2722                 }
2723
2724                 /* Need to spawn a temporary iface for finding IDs */
2725                 else if ((res = nl80211_ifadd(ifname)) != NULL)
2726                 {
2727                         rv = wext_ops.hardware_id(res, buf);
2728                         nl80211_ifdel(res);
2729                 }
2730         }
2731         else
2732         {
2733                 rv = wext_ops.hardware_id(ifname, buf);
2734         }
2735
2736         /* Failed to obtain hardware IDs, search board config */
2737         if (rv)
2738         {
2739                 rv = iwinfo_hardware_id_from_mtd((struct iwinfo_hardware_id *)buf);
2740         }
2741
2742         return rv;
2743 }
2744
2745 static const struct iwinfo_hardware_entry *
2746 nl80211_get_hardware_entry(const char *ifname)
2747 {
2748         struct iwinfo_hardware_id id;
2749
2750         if (nl80211_get_hardware_id(ifname, (char *)&id))
2751                 return NULL;
2752
2753         return iwinfo_hardware(&id);
2754 }
2755
2756 static int nl80211_get_hardware_name(const char *ifname, char *buf)
2757 {
2758         const struct iwinfo_hardware_entry *hw;
2759
2760         if (!(hw = nl80211_get_hardware_entry(ifname)))
2761                 sprintf(buf, "Generic MAC80211");
2762         else
2763                 sprintf(buf, "%s %s", hw->vendor_name, hw->device_name);
2764
2765         return 0;
2766 }
2767
2768 static int nl80211_get_txpower_offset(const char *ifname, int *buf)
2769 {
2770         const struct iwinfo_hardware_entry *hw;
2771
2772         if (!(hw = nl80211_get_hardware_entry(ifname)))
2773                 return -1;
2774
2775         *buf = hw->txpower_offset;
2776         return 0;
2777 }
2778
2779 static int nl80211_get_frequency_offset(const char *ifname, int *buf)
2780 {
2781         const struct iwinfo_hardware_entry *hw;
2782
2783         if (!(hw = nl80211_get_hardware_entry(ifname)))
2784                 return -1;
2785
2786         *buf = hw->frequency_offset;
2787         return 0;
2788 }
2789
2790 static int nl80211_lookup_phyname(const char *section, char *buf)
2791 {
2792         int idx;
2793
2794         if ((idx = nl80211_phy_idx_from_uci(section)) < 0)
2795                 return -1;
2796
2797         sprintf(buf, "phy%d", idx);
2798         return 0;
2799 }
2800
2801 const struct iwinfo_ops nl80211_ops = {
2802         .name             = "nl80211",
2803         .probe            = nl80211_probe,
2804         .channel          = nl80211_get_channel,
2805         .frequency        = nl80211_get_frequency,
2806         .frequency_offset = nl80211_get_frequency_offset,
2807         .txpower          = nl80211_get_txpower,
2808         .txpower_offset   = nl80211_get_txpower_offset,
2809         .bitrate          = nl80211_get_bitrate,
2810         .signal           = nl80211_get_signal,
2811         .noise            = nl80211_get_noise,
2812         .quality          = nl80211_get_quality,
2813         .quality_max      = nl80211_get_quality_max,
2814         .mbssid_support   = nl80211_get_mbssid_support,
2815         .hwmodelist       = nl80211_get_hwmodelist,
2816         .htmodelist       = nl80211_get_htmodelist,
2817         .mode             = nl80211_get_mode,
2818         .ssid             = nl80211_get_ssid,
2819         .bssid            = nl80211_get_bssid,
2820         .country          = nl80211_get_country,
2821         .hardware_id      = nl80211_get_hardware_id,
2822         .hardware_name    = nl80211_get_hardware_name,
2823         .encryption       = nl80211_get_encryption,
2824         .phyname          = nl80211_get_phyname,
2825         .assoclist        = nl80211_get_assoclist,
2826         .txpwrlist        = nl80211_get_txpwrlist,
2827         .scanlist         = nl80211_get_scanlist,
2828         .freqlist         = nl80211_get_freqlist,
2829         .countrylist      = nl80211_get_countrylist,
2830         .lookup_phy       = nl80211_lookup_phyname,
2831         .close            = nl80211_close
2832 };