6e438a7f7551758f4da7ed72d4302eaf05e637eb
[oweals/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 (cv->wait[gnlh->cmd / 32] & (1 << (gnlh->cmd % 32)))
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, ...)
525 {
526         struct nl80211_event_conveyor cv = { };
527         struct nl_cb *cb;
528         int err = 0;
529         int cmd;
530         va_list ap;
531
532         if (nl80211_subscribe(family, group))
533                 return -ENOENT;
534
535         cb = nl_cb_alloc(NL_CB_DEFAULT);
536
537         if (!cb)
538                 return -ENOMEM;
539
540         nl_cb_err(cb,                  NL_CB_CUSTOM, nl80211_msg_error,      &err);
541         nl_cb_set(cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM, nl80211_wait_seq_check, NULL);
542         nl_cb_set(cb, NL_CB_VALID,     NL_CB_CUSTOM, nl80211_wait_cb,        &cv );
543
544         va_start(ap, group);
545
546         for (cmd = va_arg(ap, int); cmd != 0; cmd = va_arg(ap, int))
547                 cv.wait[cmd / 32] |= (1 << (cmd % 32));
548
549         va_end(ap);
550
551         while (!cv.recv && !err)
552                 nl_recvmsgs(nls->nl_sock, cb);
553
554         nl_cb_put(cb);
555
556         return err;
557 }
558
559 #define nl80211_wait(family, group, ...) \
560         __nl80211_wait(family, group, __VA_ARGS__, 0)
561
562
563 static int nl80211_freq2channel(int freq)
564 {
565         if (freq == 2484)
566                 return 14;
567         else if (freq < 2484)
568                 return (freq - 2407) / 5;
569         else if (freq >= 4910 && freq <= 4980)
570                 return (freq - 4000) / 5;
571         else if(freq >= 56160 + 2160 * 1 && freq <= 56160 + 2160 * 6)
572                 return (freq - 56160) / 2160;
573         else
574                 return (freq - 5000) / 5;
575 }
576
577 static int nl80211_channel2freq(int channel, const char *band)
578 {
579         if (!band || band[0] != 'a')
580         {
581                 if (channel == 14)
582                         return 2484;
583                 else if (channel < 14)
584                         return (channel * 5) + 2407;
585         }
586         else if ( strcmp(band, "ad") == 0)
587         {
588                 return 56160 + 2160 * channel;
589         }
590         else
591         {
592                 if (channel >= 182 && channel <= 196)
593                         return (channel * 5) + 4000;
594                 else
595                         return (channel * 5) + 5000;
596         }
597
598         return 0;
599 }
600
601 static int nl80211_ifname2phy_cb(struct nl_msg *msg, void *arg)
602 {
603         char *buf = arg;
604         struct nlattr **attr = nl80211_parse(msg);
605
606         if (attr[NL80211_ATTR_WIPHY_NAME])
607                 memcpy(buf, nla_data(attr[NL80211_ATTR_WIPHY_NAME]),
608                        nla_len(attr[NL80211_ATTR_WIPHY_NAME]));
609         else
610                 buf[0] = 0;
611
612         return NL_SKIP;
613 }
614
615 static char * nl80211_ifname2phy(const char *ifname)
616 {
617         static char phy[32] = { 0 };
618
619         memset(phy, 0, sizeof(phy));
620
621         nl80211_request(ifname, NL80211_CMD_GET_WIPHY, 0,
622                         nl80211_ifname2phy_cb, phy);
623
624         return phy[0] ? phy : NULL;
625 }
626
627 static char * nl80211_phy2ifname(const char *ifname)
628 {
629         int ifidx = -1, cifidx = -1, phyidx = -1;
630         char buffer[64];
631         static char nif[IFNAMSIZ] = { 0 };
632
633         DIR *d;
634         struct dirent *e;
635
636         /* Only accept phy name of the form phy%d or radio%d */
637         if (!ifname)
638                 return NULL;
639         else if (!strncmp(ifname, "phy", 3))
640                 phyidx = atoi(&ifname[3]);
641         else if (!strncmp(ifname, "radio", 5))
642                 phyidx = nl80211_phy_idx_from_uci(ifname);
643         else
644                 return NULL;
645
646         memset(nif, 0, sizeof(nif));
647
648         if (phyidx > -1)
649         {
650                 if ((d = opendir("/sys/class/net")) != NULL)
651                 {
652                         while ((e = readdir(d)) != NULL)
653                         {
654                                 snprintf(buffer, sizeof(buffer),
655                                          "/sys/class/net/%s/phy80211/index", e->d_name);
656
657                                 if (nl80211_readint(buffer) == phyidx)
658                                 {
659                                         snprintf(buffer, sizeof(buffer),
660                                                  "/sys/class/net/%s/ifindex", e->d_name);
661
662                                         if ((cifidx = nl80211_readint(buffer)) >= 0 &&
663                                             ((ifidx < 0) || (cifidx < ifidx)))
664                                         {
665                                                 ifidx = cifidx;
666                                                 strncpy(nif, e->d_name, sizeof(nif) - 1);
667                                         }
668                                 }
669                         }
670
671                         closedir(d);
672                 }
673         }
674
675         return nif[0] ? nif : NULL;
676 }
677
678 static int nl80211_get_mode_cb(struct nl_msg *msg, void *arg)
679 {
680         int *mode = arg;
681         struct nlattr **tb = nl80211_parse(msg);
682         const int ifmodes[NL80211_IFTYPE_MAX + 1] = {
683                 IWINFO_OPMODE_UNKNOWN,          /* unspecified */
684                 IWINFO_OPMODE_ADHOC,            /* IBSS */
685                 IWINFO_OPMODE_CLIENT,           /* managed */
686                 IWINFO_OPMODE_MASTER,           /* AP */
687                 IWINFO_OPMODE_AP_VLAN,          /* AP/VLAN */
688                 IWINFO_OPMODE_WDS,                      /* WDS */
689                 IWINFO_OPMODE_MONITOR,          /* monitor */
690                 IWINFO_OPMODE_MESHPOINT,        /* mesh point */
691                 IWINFO_OPMODE_P2P_CLIENT,       /* P2P-client */
692                 IWINFO_OPMODE_P2P_GO,           /* P2P-GO */
693         };
694
695         if (tb[NL80211_ATTR_IFTYPE])
696                 *mode = ifmodes[nla_get_u32(tb[NL80211_ATTR_IFTYPE])];
697
698         return NL_SKIP;
699 }
700
701
702 static int nl80211_get_mode(const char *ifname, int *buf)
703 {
704         char *res;
705
706         *buf = IWINFO_OPMODE_UNKNOWN;
707
708         res = nl80211_phy2ifname(ifname);
709
710         nl80211_request(res ? res : ifname, NL80211_CMD_GET_INTERFACE, 0,
711                         nl80211_get_mode_cb, buf);
712
713         return (*buf == IWINFO_OPMODE_UNKNOWN) ? -1 : 0;
714 }
715
716 static int __nl80211_hostapd_query(const char *ifname, ...)
717 {
718         va_list ap, ap_cur;
719         char *phy, *search, *dest, *key, *val, buf[128];
720         int len, mode, found = 0, match = 1;
721         FILE *fp;
722
723         if (nl80211_get_mode(ifname, &mode))
724                 return 0;
725
726         if (mode != IWINFO_OPMODE_MASTER && mode != IWINFO_OPMODE_AP_VLAN)
727                 return 0;
728
729         phy = nl80211_ifname2phy(ifname);
730
731         if (!phy)
732                 return 0;
733
734         snprintf(buf, sizeof(buf), "/var/run/hostapd-%s.conf", phy);
735         fp = fopen(buf, "r");
736
737         if (!fp)
738                 return 0;
739
740         va_start(ap, ifname);
741
742         /* clear all destination buffers */
743         va_copy(ap_cur, ap);
744
745         while ((search = va_arg(ap_cur, char *)) != NULL)
746         {
747                 dest = va_arg(ap_cur, char *);
748                 len  = va_arg(ap_cur, int);
749
750                 memset(dest, 0, len);
751         }
752
753         va_end(ap_cur);
754
755         /* iterate applicable lines and copy found values into dest buffers */
756         while (fgets(buf, sizeof(buf), fp))
757         {
758                 key = strtok(buf, " =\t\n");
759                 val = strtok(NULL, "\n");
760
761                 if (!key || !val || !*key || *key == '#')
762                         continue;
763
764                 if (!strcmp(key, "interface") || !strcmp(key, "bss"))
765                         match = !strcmp(ifname, val);
766
767                 if (!match)
768                         continue;
769
770                 va_copy(ap_cur, ap);
771
772                 while ((search = va_arg(ap_cur, char *)) != NULL)
773                 {
774                         dest = va_arg(ap_cur, char *);
775                         len  = va_arg(ap_cur, int);
776
777                         if (!strcmp(search, key))
778                         {
779                                 strncpy(dest, val, len - 1);
780                                 found++;
781                                 break;
782                         }
783                 }
784
785                 va_end(ap_cur);
786         }
787
788         fclose(fp);
789
790         va_end(ap);
791
792         return found;
793 }
794
795 #define nl80211_hostapd_query(ifname, ...) \
796         __nl80211_hostapd_query(ifname, ##__VA_ARGS__, NULL)
797
798
799 static inline int nl80211_wpactl_recv(int sock, char *buf, int blen)
800 {
801         fd_set rfds;
802         struct timeval tv = { 0, 256000 };
803
804         FD_ZERO(&rfds);
805         FD_SET(sock, &rfds);
806
807         memset(buf, 0, blen);
808
809         if (select(sock + 1, &rfds, NULL, NULL, &tv) < 0)
810                 return -1;
811
812         if (!FD_ISSET(sock, &rfds))
813                 return -1;
814
815         return recv(sock, buf, blen - 1, 0);
816 }
817
818 static int nl80211_wpactl_connect(const char *ifname, struct sockaddr_un *local)
819 {
820         struct sockaddr_un remote = { 0 };
821         size_t remote_length, local_length;
822
823         int sock = socket(PF_UNIX, SOCK_DGRAM, 0);
824         if (sock < 0)
825                 return sock;
826
827         remote.sun_family = AF_UNIX;
828         remote_length = sizeof(remote.sun_family) +
829                 sprintf(remote.sun_path, "/var/run/wpa_supplicant-%s/%s",
830                         ifname, ifname);
831
832         if (fcntl(sock, F_SETFD, fcntl(sock, F_GETFD) | FD_CLOEXEC) < 0)
833         {
834                 close(sock);
835                 return -1;
836         }
837
838         if (connect(sock, (struct sockaddr *)&remote, remote_length))
839         {
840                 remote_length = sizeof(remote.sun_family) +
841                         sprintf(remote.sun_path, "/var/run/wpa_supplicant/%s", ifname);
842
843                 if (connect(sock, (struct sockaddr *)&remote, remote_length))
844                 {
845                         close(sock);
846                         return -1;
847                 }
848         }
849
850         local->sun_family = AF_UNIX;
851         local_length = sizeof(local->sun_family) +
852                 sprintf(local->sun_path, "/var/run/iwinfo-%s-%d", ifname, getpid());
853
854         if (bind(sock, (struct sockaddr *)local, local_length) < 0)
855         {
856                 close(sock);
857                 return -1;
858         }
859
860         return sock;
861 }
862
863 static int __nl80211_wpactl_query(const char *ifname, ...)
864 {
865         va_list ap, ap_cur;
866         struct sockaddr_un local = { 0 };
867         int len, mode, found = 0, sock = -1;
868         char *search, *dest, *key, *val, *line, *pos, buf[512];
869
870         if (nl80211_get_mode(ifname, &mode))
871                 return 0;
872
873         if (mode != IWINFO_OPMODE_CLIENT && mode != IWINFO_OPMODE_ADHOC)
874                 return 0;
875
876         sock = nl80211_wpactl_connect(ifname, &local);
877
878         if (sock < 0)
879                 return 0;
880
881         va_start(ap, ifname);
882
883         /* clear all destination buffers */
884         va_copy(ap_cur, ap);
885
886         while ((search = va_arg(ap_cur, char *)) != NULL)
887         {
888                 dest = va_arg(ap_cur, char *);
889                 len  = va_arg(ap_cur, int);
890
891                 memset(dest, 0, len);
892         }
893
894         va_end(ap_cur);
895
896         send(sock, "STATUS", 6, 0);
897
898         while (true)
899         {
900                 if (nl80211_wpactl_recv(sock, buf, sizeof(buf)) <= 0)
901                         break;
902
903                 if (buf[0] == '<')
904                         continue;
905
906                 for (line = strtok_r(buf, "\n", &pos);
907                          line != NULL;
908                          line = strtok_r(NULL, "\n", &pos))
909                 {
910                         key = strtok(line, "=");
911                         val = strtok(NULL, "\n");
912
913                         if (!key || !val)
914                                 continue;
915
916                         va_copy(ap_cur, ap);
917
918                         while ((search = va_arg(ap_cur, char *)) != NULL)
919                         {
920                                 dest = va_arg(ap_cur, char *);
921                                 len  = va_arg(ap_cur, int);
922
923                                 if (!strcmp(search, key))
924                                 {
925                                         strncpy(dest, val, len - 1);
926                                         found++;
927                                         break;
928                                 }
929                         }
930
931                         va_end(ap_cur);
932                 }
933
934                 break;
935         }
936
937         va_end(ap);
938
939         close(sock);
940         unlink(local.sun_path);
941
942         return found;
943 }
944
945 #define nl80211_wpactl_query(ifname, ...) \
946         __nl80211_wpactl_query(ifname, ##__VA_ARGS__, NULL)
947
948
949 static char * nl80211_ifadd(const char *ifname)
950 {
951         char path[PATH_MAX];
952         static char nif[IFNAMSIZ] = { 0 };
953         struct nl80211_msg_conveyor *req;
954         FILE *sysfs;
955
956         req = nl80211_msg(ifname, NL80211_CMD_NEW_INTERFACE, 0);
957         if (req)
958         {
959                 snprintf(nif, sizeof(nif), "tmp.%s", ifname);
960
961                 NLA_PUT_STRING(req->msg, NL80211_ATTR_IFNAME, nif);
962                 NLA_PUT_U32(req->msg, NL80211_ATTR_IFTYPE, NL80211_IFTYPE_STATION);
963
964                 nl80211_send(req, NULL, NULL);
965
966                 snprintf(path, sizeof(path) - 1,
967                          "/proc/sys/net/ipv6/conf/%s/disable_ipv6", nif);
968
969                 if ((sysfs = fopen(path, "w")) != NULL)
970                 {
971                         fwrite("0\n", 1, 2, sysfs);
972                         fclose(sysfs);
973                 }
974
975                 return nif;
976
977         nla_put_failure:
978                 nl80211_free(req);
979         }
980
981         return NULL;
982 }
983
984 static void nl80211_ifdel(const char *ifname)
985 {
986         struct nl80211_msg_conveyor *req;
987         int err;
988
989         req = nl80211_msg(ifname, NL80211_CMD_DEL_INTERFACE, 0);
990         if (req)
991         {
992                 NLA_PUT_STRING(req->msg, NL80211_ATTR_IFNAME, ifname);
993
994                 nl80211_send(req, NULL, NULL);
995                 return;
996
997         nla_put_failure:
998                 nl80211_free(req);
999         }
1000 }
1001
1002 static void nl80211_hostapd_hup(const char *ifname)
1003 {
1004         int fd, pid = 0;
1005         char buf[32];
1006         char *phy = nl80211_ifname2phy(ifname);
1007
1008         if (phy)
1009         {
1010                 snprintf(buf, sizeof(buf), "/var/run/wifi-%s.pid", phy);
1011                 if ((fd = open(buf, O_RDONLY)) >= 0)
1012                 {
1013                         if (read(fd, buf, sizeof(buf)) > 0)
1014                                 pid = atoi(buf);
1015
1016                         close(fd);
1017                 }
1018
1019                 if (pid > 0)
1020                         kill(pid, 1);
1021         }
1022 }
1023
1024
1025 static int nl80211_probe(const char *ifname)
1026 {
1027         return !!nl80211_ifname2phy(ifname);
1028 }
1029
1030 struct nl80211_ssid_bssid {
1031         unsigned char *ssid;
1032         unsigned char bssid[7];
1033 };
1034
1035 static int nl80211_get_macaddr_cb(struct nl_msg *msg, void *arg)
1036 {
1037         struct nl80211_ssid_bssid *sb = arg;
1038         struct nlattr **tb = nl80211_parse(msg);
1039
1040         if (tb[NL80211_ATTR_MAC]) {
1041                 sb->bssid[0] = 1;
1042                 memcpy(sb->bssid + 1, nla_data(tb[NL80211_ATTR_MAC]),
1043                        sizeof(sb->bssid) - 1);
1044         }
1045
1046         return NL_SKIP;
1047 }
1048
1049 static int nl80211_get_ssid_bssid_cb(struct nl_msg *msg, void *arg)
1050 {
1051         int ielen;
1052         unsigned char *ie;
1053         struct nl80211_ssid_bssid *sb = arg;
1054         struct nlattr **tb = nl80211_parse(msg);
1055         struct nlattr *bss[NL80211_BSS_MAX + 1];
1056
1057         static struct nla_policy bss_policy[NL80211_BSS_MAX + 1] = {
1058                 [NL80211_BSS_INFORMATION_ELEMENTS] = { 0 },
1059                 [NL80211_BSS_STATUS]               = { .type = NLA_U32 },
1060         };
1061
1062         if (!tb[NL80211_ATTR_BSS] ||
1063             nla_parse_nested(bss, NL80211_BSS_MAX, tb[NL80211_ATTR_BSS],
1064                              bss_policy) ||
1065             !bss[NL80211_BSS_BSSID] ||
1066             !bss[NL80211_BSS_STATUS] ||
1067             !bss[NL80211_BSS_INFORMATION_ELEMENTS])
1068         {
1069                 return NL_SKIP;
1070         }
1071
1072         switch (nla_get_u32(bss[NL80211_BSS_STATUS]))
1073         {
1074         case NL80211_BSS_STATUS_ASSOCIATED:
1075         case NL80211_BSS_STATUS_AUTHENTICATED:
1076         case NL80211_BSS_STATUS_IBSS_JOINED:
1077
1078                 if (sb->ssid)
1079                 {
1080                         ie = nla_data(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
1081                         ielen = nla_len(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
1082
1083                         while (ielen >= 2 && ielen >= ie[1])
1084                         {
1085                                 if (ie[0] == 0)
1086                                 {
1087                                         memcpy(sb->ssid, ie + 2, min(ie[1], IWINFO_ESSID_MAX_SIZE));
1088                                         return NL_SKIP;
1089                                 }
1090
1091                                 ielen -= ie[1] + 2;
1092                                 ie += ie[1] + 2;
1093                         }
1094                 }
1095                 else
1096                 {
1097                         sb->bssid[0] = 1;
1098                         memcpy(sb->bssid + 1, nla_data(bss[NL80211_BSS_BSSID]), 6);
1099                         return NL_SKIP;
1100                 }
1101
1102         default:
1103                 return NL_SKIP;
1104         }
1105 }
1106
1107 static int nl80211_get_ssid(const char *ifname, char *buf)
1108 {
1109         char *res;
1110         struct nl80211_ssid_bssid sb = { .ssid = (unsigned char *)buf };
1111
1112         /* try to find ssid from scan dump results */
1113         res = nl80211_phy2ifname(ifname);
1114         sb.ssid[0] = 0;
1115
1116         nl80211_request(res ? res : ifname, NL80211_CMD_GET_SCAN, NLM_F_DUMP,
1117                         nl80211_get_ssid_bssid_cb, &sb);
1118
1119         /* failed, try to find from hostapd info */
1120         if (sb.ssid[0] == 0)
1121                 nl80211_hostapd_query(ifname, "ssid", sb.ssid,
1122                                       IWINFO_ESSID_MAX_SIZE + 1);
1123
1124         /* failed, try to obtain Mesh ID */
1125         if (sb.ssid[0] == 0)
1126                 iwinfo_ubus_query(res ? res : ifname, "mesh_id",
1127                                   sb.ssid, IWINFO_ESSID_MAX_SIZE + 1);
1128
1129         return (sb.ssid[0] == 0) ? -1 : 0;
1130 }
1131
1132 static int nl80211_get_bssid(const char *ifname, char *buf)
1133 {
1134         char *res, bssid[sizeof("FF:FF:FF:FF:FF:FF\0")];
1135         struct nl80211_ssid_bssid sb = { };
1136
1137         res = nl80211_phy2ifname(ifname);
1138
1139         /* try to obtain mac address via NL80211_CMD_GET_INTERFACE */
1140         nl80211_request(res ? res : ifname, NL80211_CMD_GET_INTERFACE, 0,
1141                         nl80211_get_macaddr_cb, &sb);
1142
1143         /* failed, try to find bssid from scan dump results */
1144         if (sb.bssid[0] == 0)
1145                 nl80211_request(res ? res : ifname,
1146                                 NL80211_CMD_GET_SCAN, NLM_F_DUMP,
1147                                 nl80211_get_ssid_bssid_cb, &sb);
1148
1149         /* failed, try to find mac from hostapd info */
1150         if ((sb.bssid[0] == 0) &&
1151             nl80211_hostapd_query(ifname, "bssid", bssid, sizeof(bssid)))
1152         {
1153                 sb.bssid[0] = 1;
1154                 sb.bssid[1] = strtol(&bssid[0],  NULL, 16);
1155                 sb.bssid[2] = strtol(&bssid[3],  NULL, 16);
1156                 sb.bssid[3] = strtol(&bssid[6],  NULL, 16);
1157                 sb.bssid[4] = strtol(&bssid[9],  NULL, 16);
1158                 sb.bssid[5] = strtol(&bssid[12], NULL, 16);
1159                 sb.bssid[6] = strtol(&bssid[15], NULL, 16);
1160         }
1161
1162         if (sb.bssid[0])
1163         {
1164                 sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X",
1165                         sb.bssid[1], sb.bssid[2], sb.bssid[3],
1166                         sb.bssid[4], sb.bssid[5], sb.bssid[6]);
1167
1168                 return 0;
1169         }
1170
1171         return -1;
1172 }
1173
1174
1175 static int nl80211_get_frequency_scan_cb(struct nl_msg *msg, void *arg)
1176 {
1177         int *freq = arg;
1178         struct nlattr **attr = nl80211_parse(msg);
1179         struct nlattr *binfo[NL80211_BSS_MAX + 1];
1180
1181         static struct nla_policy bss_policy[NL80211_BSS_MAX + 1] = {
1182                 [NL80211_BSS_FREQUENCY] = { .type = NLA_U32 },
1183                 [NL80211_BSS_STATUS]    = { .type = NLA_U32 },
1184         };
1185
1186         if (attr[NL80211_ATTR_BSS] &&
1187             !nla_parse_nested(binfo, NL80211_BSS_MAX,
1188                               attr[NL80211_ATTR_BSS], bss_policy))
1189         {
1190                 if (binfo[NL80211_BSS_STATUS] && binfo[NL80211_BSS_FREQUENCY])
1191                         *freq = nla_get_u32(binfo[NL80211_BSS_FREQUENCY]);
1192         }
1193
1194         return NL_SKIP;
1195 }
1196
1197 static int nl80211_get_frequency_info_cb(struct nl_msg *msg, void *arg)
1198 {
1199         int *freq = arg;
1200         struct nlattr **tb = nl80211_parse(msg);
1201
1202         if (tb[NL80211_ATTR_WIPHY_FREQ])
1203                 *freq = nla_get_u32(tb[NL80211_ATTR_WIPHY_FREQ]);
1204
1205         return NL_SKIP;
1206 }
1207
1208 static int nl80211_get_frequency(const char *ifname, int *buf)
1209 {
1210         char *res, channel[4], hwmode[3];
1211
1212         /* try to find frequency from interface info */
1213         res = nl80211_phy2ifname(ifname);
1214         *buf = 0;
1215
1216         nl80211_request(res ? res : ifname, NL80211_CMD_GET_INTERFACE, 0,
1217                         nl80211_get_frequency_info_cb, buf);
1218
1219         /* failed, try to find frequency from hostapd info */
1220         if ((*buf == 0) &&
1221             nl80211_hostapd_query(ifname, "hw_mode", hwmode, sizeof(hwmode),
1222                                           "channel", channel, sizeof(channel)) == 2)
1223         {
1224                 *buf = nl80211_channel2freq(atoi(channel), hwmode);
1225         }
1226
1227         /* failed, try to find frequency from scan results */
1228         if (*buf == 0)
1229         {
1230                 res = nl80211_phy2ifname(ifname);
1231
1232                 nl80211_request(res ? res : ifname, NL80211_CMD_GET_SCAN, NLM_F_DUMP,
1233                                 nl80211_get_frequency_scan_cb, buf);
1234         }
1235
1236         return (*buf == 0) ? -1 : 0;
1237 }
1238
1239 static int nl80211_get_channel(const char *ifname, int *buf)
1240 {
1241         if (!nl80211_get_frequency(ifname, buf))
1242         {
1243                 *buf = nl80211_freq2channel(*buf);
1244                 return 0;
1245         }
1246
1247         return -1;
1248 }
1249
1250 static int nl80211_get_txpower_cb(struct nl_msg *msg, void *arg)
1251 {
1252         int *buf = arg;
1253         struct nlattr **tb = nl80211_parse(msg);
1254
1255         if (tb[NL80211_ATTR_WIPHY_TX_POWER_LEVEL])
1256                 *buf = iwinfo_mbm2dbm(nla_get_u32(tb[NL80211_ATTR_WIPHY_TX_POWER_LEVEL]));
1257
1258         return NL_SKIP;
1259 }
1260
1261 static int nl80211_get_txpower(const char *ifname, int *buf)
1262 {
1263         char *res;
1264
1265         res = nl80211_phy2ifname(ifname);
1266         *buf = 0;
1267
1268         if (nl80211_request(res ? res : ifname, NL80211_CMD_GET_INTERFACE, 0,
1269                             nl80211_get_txpower_cb, buf))
1270                 return -1;
1271
1272         return 0;
1273 }
1274
1275
1276 static int nl80211_fill_signal_cb(struct nl_msg *msg, void *arg)
1277 {
1278         int8_t dbm;
1279         int16_t mbit;
1280         struct nl80211_rssi_rate *rr = arg;
1281         struct nlattr **attr = nl80211_parse(msg);
1282         struct nlattr *sinfo[NL80211_STA_INFO_MAX + 1];
1283         struct nlattr *rinfo[NL80211_RATE_INFO_MAX + 1];
1284
1285         static struct nla_policy stats_policy[NL80211_STA_INFO_MAX + 1] = {
1286                 [NL80211_STA_INFO_INACTIVE_TIME] = { .type = NLA_U32    },
1287                 [NL80211_STA_INFO_RX_BYTES]      = { .type = NLA_U32    },
1288                 [NL80211_STA_INFO_TX_BYTES]      = { .type = NLA_U32    },
1289                 [NL80211_STA_INFO_RX_PACKETS]    = { .type = NLA_U32    },
1290                 [NL80211_STA_INFO_TX_PACKETS]    = { .type = NLA_U32    },
1291                 [NL80211_STA_INFO_SIGNAL]        = { .type = NLA_U8     },
1292                 [NL80211_STA_INFO_TX_BITRATE]    = { .type = NLA_NESTED },
1293                 [NL80211_STA_INFO_LLID]          = { .type = NLA_U16    },
1294                 [NL80211_STA_INFO_PLID]          = { .type = NLA_U16    },
1295                 [NL80211_STA_INFO_PLINK_STATE]   = { .type = NLA_U8     },
1296         };
1297
1298         static struct nla_policy rate_policy[NL80211_RATE_INFO_MAX + 1] = {
1299                 [NL80211_RATE_INFO_BITRATE]      = { .type = NLA_U16  },
1300                 [NL80211_RATE_INFO_MCS]          = { .type = NLA_U8   },
1301                 [NL80211_RATE_INFO_40_MHZ_WIDTH] = { .type = NLA_FLAG },
1302                 [NL80211_RATE_INFO_SHORT_GI]     = { .type = NLA_FLAG },
1303         };
1304
1305         if (attr[NL80211_ATTR_STA_INFO])
1306         {
1307                 if (!nla_parse_nested(sinfo, NL80211_STA_INFO_MAX,
1308                                       attr[NL80211_ATTR_STA_INFO], stats_policy))
1309                 {
1310                         if (sinfo[NL80211_STA_INFO_SIGNAL])
1311                         {
1312                                 dbm = nla_get_u8(sinfo[NL80211_STA_INFO_SIGNAL]);
1313                                 rr->rssi = (rr->rssi * rr->rssi_samples + dbm) / (rr->rssi_samples + 1);
1314                                 rr->rssi_samples++;
1315                         }
1316
1317                         if (sinfo[NL80211_STA_INFO_TX_BITRATE])
1318                         {
1319                                 if (!nla_parse_nested(rinfo, NL80211_RATE_INFO_MAX,
1320                                                       sinfo[NL80211_STA_INFO_TX_BITRATE],
1321                                                       rate_policy))
1322                                 {
1323                                         if (rinfo[NL80211_RATE_INFO_BITRATE])
1324                                         {
1325                                                 mbit = nla_get_u16(rinfo[NL80211_RATE_INFO_BITRATE]);
1326                                                 rr->rate = (rr->rate * rr->rate_samples + mbit) / (rr->rate_samples + 1);
1327                                                 rr->rate_samples++;
1328                                         }
1329                                 }
1330                         }
1331                 }
1332         }
1333
1334         return NL_SKIP;
1335 }
1336
1337 static void nl80211_fill_signal(const char *ifname, struct nl80211_rssi_rate *r)
1338 {
1339         DIR *d;
1340         struct dirent *de;
1341
1342         memset(r, 0, sizeof(*r));
1343
1344         if ((d = opendir("/sys/class/net")) != NULL)
1345         {
1346                 while ((de = readdir(d)) != NULL)
1347                 {
1348                         if (!strncmp(de->d_name, ifname, strlen(ifname)) &&
1349                             (!de->d_name[strlen(ifname)] ||
1350                              !strncmp(&de->d_name[strlen(ifname)], ".sta", 4)))
1351                         {
1352                                 nl80211_request(de->d_name, NL80211_CMD_GET_STATION,
1353                                                 NLM_F_DUMP, nl80211_fill_signal_cb, r);
1354                         }
1355                 }
1356
1357                 closedir(d);
1358         }
1359 }
1360
1361 static int nl80211_get_bitrate(const char *ifname, int *buf)
1362 {
1363         struct nl80211_rssi_rate rr;
1364
1365         nl80211_fill_signal(ifname, &rr);
1366
1367         if (rr.rate_samples)
1368         {
1369                 *buf = (rr.rate * 100);
1370                 return 0;
1371         }
1372
1373         return -1;
1374 }
1375
1376 static int nl80211_get_signal(const char *ifname, int *buf)
1377 {
1378         struct nl80211_rssi_rate rr;
1379
1380         nl80211_fill_signal(ifname, &rr);
1381
1382         if (rr.rssi_samples)
1383         {
1384                 *buf = rr.rssi;
1385                 return 0;
1386         }
1387
1388         return -1;
1389 }
1390
1391 static int nl80211_get_noise_cb(struct nl_msg *msg, void *arg)
1392 {
1393         int8_t *noise = arg;
1394         struct nlattr **tb = nl80211_parse(msg);
1395         struct nlattr *si[NL80211_SURVEY_INFO_MAX + 1];
1396
1397         static struct nla_policy sp[NL80211_SURVEY_INFO_MAX + 1] = {
1398                 [NL80211_SURVEY_INFO_FREQUENCY] = { .type = NLA_U32 },
1399                 [NL80211_SURVEY_INFO_NOISE]     = { .type = NLA_U8  },
1400         };
1401
1402         if (!tb[NL80211_ATTR_SURVEY_INFO])
1403                 return NL_SKIP;
1404
1405         if (nla_parse_nested(si, NL80211_SURVEY_INFO_MAX,
1406                              tb[NL80211_ATTR_SURVEY_INFO], sp))
1407                 return NL_SKIP;
1408
1409         if (!si[NL80211_SURVEY_INFO_NOISE])
1410                 return NL_SKIP;
1411
1412         if (!*noise || si[NL80211_SURVEY_INFO_IN_USE])
1413                 *noise = (int8_t)nla_get_u8(si[NL80211_SURVEY_INFO_NOISE]);
1414
1415         return NL_SKIP;
1416 }
1417
1418
1419 static int nl80211_get_noise(const char *ifname, int *buf)
1420 {
1421         int8_t noise = 0;
1422
1423         if (nl80211_request(ifname, NL80211_CMD_GET_SURVEY, NLM_F_DUMP,
1424                             nl80211_get_noise_cb, &noise))
1425                 goto out;
1426
1427         *buf = noise;
1428         return 0;
1429
1430 out:
1431         *buf = 0;
1432         return -1;
1433 }
1434
1435 static int nl80211_get_quality(const char *ifname, int *buf)
1436 {
1437         int signal;
1438
1439         if (!nl80211_get_signal(ifname, &signal))
1440         {
1441                 /* A positive signal level is usually just a quality
1442                  * value, pass through as-is */
1443                 if (signal >= 0)
1444                 {
1445                         *buf = signal;
1446                 }
1447
1448                 /* The cfg80211 wext compat layer assumes a signal range
1449                  * of -110 dBm to -40 dBm, the quality value is derived
1450                  * by adding 110 to the signal level */
1451                 else
1452                 {
1453                         if (signal < -110)
1454                                 signal = -110;
1455                         else if (signal > -40)
1456                                 signal = -40;
1457
1458                         *buf = (signal + 110);
1459                 }
1460
1461                 return 0;
1462         }
1463
1464         return -1;
1465 }
1466
1467 static int nl80211_get_quality_max(const char *ifname, int *buf)
1468 {
1469         /* The cfg80211 wext compat layer assumes a maximum
1470          * quality of 70 */
1471         *buf = 70;
1472
1473         return 0;
1474 }
1475
1476 static int nl80211_check_wepkey(const char *key)
1477 {
1478         if (key && *key)
1479         {
1480                 switch (strlen(key))
1481                 {
1482                 case 5:
1483                 case 10:
1484                         return IWINFO_CIPHER_WEP40;
1485
1486                 case 13:
1487                 case 26:
1488                         return IWINFO_CIPHER_WEP104;
1489                 }
1490         }
1491
1492         return 0;
1493 }
1494
1495 static struct {
1496         const char *match;
1497         int version;
1498         int suite;
1499 } wpa_key_mgmt_strings[] = {
1500         { "IEEE 802.1X/EAP", 0, IWINFO_KMGMT_8021x },
1501         { "EAP-SUITE-B-192", 4, IWINFO_KMGMT_8021x },
1502         { "EAP-SUITE-B",     4, IWINFO_KMGMT_8021x },
1503         { "EAP-SHA256",      0, IWINFO_KMGMT_8021x },
1504         { "PSK-SHA256",      0, IWINFO_KMGMT_PSK },
1505         { "NONE",            0, IWINFO_KMGMT_NONE },
1506         { "None",            0, IWINFO_KMGMT_NONE },
1507         { "PSK",             0, IWINFO_KMGMT_PSK },
1508         { "EAP",             0, IWINFO_KMGMT_8021x },
1509         { "SAE",             4, IWINFO_KMGMT_SAE },
1510         { "OWE",             4, IWINFO_KMGMT_OWE }
1511 };
1512
1513 static void parse_wpa_suites(const char *str, int defversion,
1514                              uint8_t *versions, uint8_t *suites)
1515 {
1516         size_t l;
1517         int i, version;
1518         const char *p, *q, *m, *sep = " \t\n,-+/";
1519
1520         for (p = str; *p; )
1521         {
1522                 q = p;
1523
1524                 for (i = 0; i < ARRAY_SIZE(wpa_key_mgmt_strings); i++)
1525                 {
1526                         m = wpa_key_mgmt_strings[i].match;
1527                         l = strlen(m);
1528
1529                         if (!strncmp(q, m, l) && (!q[l] || strchr(sep, q[l])))
1530                         {
1531                                 if (wpa_key_mgmt_strings[i].version != 0)
1532                                         version = wpa_key_mgmt_strings[i].version;
1533                                 else
1534                                         version = defversion;
1535
1536                                 *versions |= version;
1537                                 *suites |= wpa_key_mgmt_strings[i].suite;
1538
1539                                 q += l;
1540                                 break;
1541                         }
1542                 }
1543
1544                 if (q == p)
1545                         q += strcspn(q, sep);
1546
1547                 p = q + strspn(q, sep);
1548         }
1549 }
1550
1551 static struct {
1552         const char *match;
1553         int cipher;
1554 } wpa_cipher_strings[] = {
1555         { "WEP-104", IWINFO_CIPHER_WEP104 },
1556         { "WEP-40",  IWINFO_CIPHER_WEP40 },
1557         { "NONE",    IWINFO_CIPHER_NONE },
1558         { "TKIP",    IWINFO_CIPHER_TKIP },
1559         { "CCMP",    IWINFO_CIPHER_CCMP }
1560 };
1561
1562 static void parse_wpa_ciphers(const char *str, uint8_t *ciphers)
1563 {
1564         int i;
1565         size_t l;
1566         const char *m, *p, *q, *sep = " \t\n,-+/";
1567
1568         for (p = str; *p; )
1569         {
1570                 q = p;
1571
1572                 for (i = 0; i < ARRAY_SIZE(wpa_cipher_strings); i++)
1573                 {
1574                         m = wpa_cipher_strings[i].match;
1575                         l = strlen(m);
1576
1577                         if (!strncmp(q, m, l) && (!q[l] || strchr(sep, q[l])))
1578                         {
1579                                 *ciphers |= wpa_cipher_strings[i].cipher;
1580
1581                                 q += l;
1582                                 break;
1583                         }
1584                 }
1585
1586                 if (q == p)
1587                         q += strcspn(q, sep);
1588
1589                 p = q + strspn(q, sep);
1590         }
1591 }
1592
1593 static int nl80211_get_encryption(const char *ifname, char *buf)
1594 {
1595         char *p;
1596         uint8_t wpa_version = 0;
1597         char wpa[2], wpa_key_mgmt[64], wpa_pairwise[16], wpa_groupwise[16];
1598         char auth_algs[2], wep_key0[27], wep_key1[27], wep_key2[27], wep_key3[27];
1599
1600         struct iwinfo_crypto_entry *c = (struct iwinfo_crypto_entry *)buf;
1601
1602         /* WPA supplicant */
1603         if (nl80211_wpactl_query(ifname,
1604                         "pairwise_cipher", wpa_pairwise,  sizeof(wpa_pairwise),
1605                         "group_cipher",    wpa_groupwise, sizeof(wpa_groupwise),
1606                         "key_mgmt",        wpa_key_mgmt,  sizeof(wpa_key_mgmt)))
1607         {
1608                 /* WEP or Open */
1609                 if (!strcmp(wpa_key_mgmt, "NONE"))
1610                 {
1611                         parse_wpa_ciphers(wpa_pairwise, &c->pair_ciphers);
1612                         parse_wpa_ciphers(wpa_groupwise, &c->group_ciphers);
1613
1614                         if (c->pair_ciphers != 0 && c->pair_ciphers != IWINFO_CIPHER_NONE) {
1615                                 c->enabled     = 1;
1616                                 c->auth_suites = IWINFO_KMGMT_NONE;
1617                                 c->auth_algs   = IWINFO_AUTH_OPEN | IWINFO_AUTH_SHARED;
1618                         }
1619                         else {
1620                                 c->pair_ciphers = 0;
1621                                 c->group_ciphers = 0;
1622                         }
1623                 }
1624
1625                 /* WPA */
1626                 else
1627                 {
1628                         parse_wpa_ciphers(wpa_pairwise, &c->pair_ciphers);
1629                         parse_wpa_ciphers(wpa_groupwise, &c->group_ciphers);
1630
1631                         p = wpa_key_mgmt;
1632
1633                         if (!strncmp(p, "WPA2-", 5) || !strncmp(p, "WPA2/", 5))
1634                         {
1635                                 p += 5;
1636                                 wpa_version = 2;
1637                         }
1638                         else if (!strncmp(p, "WPA-", 4))
1639                         {
1640                                 p += 4;
1641                                 wpa_version = 1;
1642                         }
1643
1644                         parse_wpa_suites(p, wpa_version, &c->wpa_version, &c->auth_suites);
1645
1646                         c->enabled = !!(c->wpa_version && c->auth_suites);
1647                 }
1648
1649                 return 0;
1650         }
1651
1652         /* Hostapd */
1653         else if (nl80211_hostapd_query(ifname,
1654                                 "wpa",          wpa,          sizeof(wpa),
1655                                 "wpa_key_mgmt", wpa_key_mgmt, sizeof(wpa_key_mgmt),
1656                                 "wpa_pairwise", wpa_pairwise, sizeof(wpa_pairwise),
1657                                 "auth_algs",    auth_algs,    sizeof(auth_algs),
1658                                 "wep_key0",     wep_key0,     sizeof(wep_key0),
1659                                 "wep_key1",     wep_key1,     sizeof(wep_key1),
1660                                 "wep_key2",     wep_key2,     sizeof(wep_key2),
1661                                 "wep_key3",     wep_key3,     sizeof(wep_key3)))
1662         {
1663                 c->wpa_version = 0;
1664
1665                 if (wpa_key_mgmt[0])
1666                 {
1667                         for (p = strtok(wpa_key_mgmt, " \t"); p != NULL; p = strtok(NULL, " \t"))
1668                         {
1669                                 if (!strncmp(p, "WPA-", 4))
1670                                         p += 4;
1671
1672                                 parse_wpa_suites(p, atoi(wpa), &c->wpa_version, &c->auth_suites);
1673                         }
1674
1675                         c->enabled = c->wpa_version ? 1 : 0;
1676                 }
1677
1678                 if (wpa_pairwise[0])
1679                         parse_wpa_ciphers(wpa_pairwise, &c->pair_ciphers);
1680
1681                 if (auth_algs[0])
1682                 {
1683                         switch (atoi(auth_algs))
1684                         {
1685                         case 1:
1686                                 c->auth_algs |= IWINFO_AUTH_OPEN;
1687                                 break;
1688
1689                         case 2:
1690                                 c->auth_algs |= IWINFO_AUTH_SHARED;
1691                                 break;
1692
1693                         case 3:
1694                                 c->auth_algs |= IWINFO_AUTH_OPEN;
1695                                 c->auth_algs |= IWINFO_AUTH_SHARED;
1696                                 break;
1697                         }
1698
1699                         c->pair_ciphers |= nl80211_check_wepkey(wep_key0);
1700                         c->pair_ciphers |= nl80211_check_wepkey(wep_key1);
1701                         c->pair_ciphers |= nl80211_check_wepkey(wep_key2);
1702                         c->pair_ciphers |= nl80211_check_wepkey(wep_key3);
1703
1704                         c->enabled = (c->auth_algs && c->pair_ciphers) ? 1 : 0;
1705                 }
1706
1707                 c->group_ciphers = c->pair_ciphers;
1708
1709                 return 0;
1710         }
1711
1712         return -1;
1713 }
1714
1715 static int nl80211_get_phyname(const char *ifname, char *buf)
1716 {
1717         const char *name;
1718
1719         name = nl80211_ifname2phy(ifname);
1720
1721         if (name)
1722         {
1723                 strcpy(buf, name);
1724                 return 0;
1725         }
1726         else if ((name = nl80211_phy2ifname(ifname)) != NULL)
1727         {
1728                 name = nl80211_ifname2phy(name);
1729
1730                 if (name)
1731                 {
1732                         strcpy(buf, ifname);
1733                         return 0;
1734                 }
1735         }
1736
1737         return -1;
1738 }
1739
1740
1741 static void nl80211_parse_rateinfo(struct nlattr **ri,
1742                                    struct iwinfo_rate_entry *re)
1743 {
1744         if (ri[NL80211_RATE_INFO_BITRATE32])
1745                 re->rate = nla_get_u32(ri[NL80211_RATE_INFO_BITRATE32]) * 100;
1746         else if (ri[NL80211_RATE_INFO_BITRATE])
1747                 re->rate = nla_get_u16(ri[NL80211_RATE_INFO_BITRATE]) * 100;
1748
1749         if (ri[NL80211_RATE_INFO_VHT_MCS])
1750         {
1751                 re->is_vht = 1;
1752                 re->mcs = nla_get_u8(ri[NL80211_RATE_INFO_VHT_MCS]);
1753
1754                 if (ri[NL80211_RATE_INFO_VHT_NSS])
1755                         re->nss = nla_get_u8(ri[NL80211_RATE_INFO_VHT_NSS]);
1756         }
1757         else if (ri[NL80211_RATE_INFO_MCS])
1758         {
1759                 re->is_ht = 1;
1760                 re->mcs = nla_get_u8(ri[NL80211_RATE_INFO_MCS]);
1761         }
1762
1763         if (ri[NL80211_RATE_INFO_5_MHZ_WIDTH])
1764                 re->mhz = 5;
1765         else if (ri[NL80211_RATE_INFO_10_MHZ_WIDTH])
1766                 re->mhz = 10;
1767         else if (ri[NL80211_RATE_INFO_40_MHZ_WIDTH])
1768                 re->mhz = 40;
1769         else if (ri[NL80211_RATE_INFO_80_MHZ_WIDTH])
1770                 re->mhz = 80;
1771         else if (ri[NL80211_RATE_INFO_80P80_MHZ_WIDTH] ||
1772                  ri[NL80211_RATE_INFO_160_MHZ_WIDTH])
1773                 re->mhz = 160;
1774         else
1775                 re->mhz = 20;
1776
1777         if (ri[NL80211_RATE_INFO_SHORT_GI])
1778                 re->is_short_gi = 1;
1779
1780         re->is_40mhz = (re->mhz == 40);
1781 }
1782
1783 static int nl80211_get_survey_cb(struct nl_msg *msg, void *arg)
1784 {
1785         struct nl80211_array_buf *arr = arg;
1786         struct iwinfo_survey_entry *e = arr->buf;
1787         struct nlattr **attr = nl80211_parse(msg);
1788         struct nlattr *sinfo[NL80211_SURVEY_INFO_MAX + 1];
1789         int rc;
1790
1791         static struct nla_policy survey_policy[NL80211_SURVEY_INFO_MAX + 1] = {
1792                 [NL80211_SURVEY_INFO_FREQUENCY] = { .type = NLA_U32 },
1793                 [NL80211_SURVEY_INFO_NOISE]  = { .type = NLA_U8     },
1794                 [NL80211_SURVEY_INFO_TIME] = { .type = NLA_U64   },
1795                 [NL80211_SURVEY_INFO_TIME_BUSY] = { .type = NLA_U64   },
1796                 [NL80211_SURVEY_INFO_TIME_EXT_BUSY] = { .type = NLA_U64   },
1797                 [NL80211_SURVEY_INFO_TIME_RX] = { .type = NLA_U64   },
1798                 [NL80211_SURVEY_INFO_TIME_TX] = { .type = NLA_U64   },
1799         };
1800
1801         rc = nla_parse_nested(sinfo, NL80211_SURVEY_INFO_MAX,
1802                                 attr[NL80211_ATTR_SURVEY_INFO],
1803                                 survey_policy);
1804         if (rc)
1805                 return NL_SKIP;
1806
1807         /* advance to end of array */
1808         e += arr->count;
1809         memset(e, 0, sizeof(*e));
1810
1811         if (sinfo[NL80211_SURVEY_INFO_FREQUENCY])
1812                 e->mhz = nla_get_u32(sinfo[NL80211_SURVEY_INFO_FREQUENCY]);
1813
1814         if (sinfo[NL80211_SURVEY_INFO_NOISE])
1815                 e->noise = nla_get_u8(sinfo[NL80211_SURVEY_INFO_NOISE]);
1816
1817         if (sinfo[NL80211_SURVEY_INFO_TIME])
1818                 e->active_time = nla_get_u64(sinfo[NL80211_SURVEY_INFO_TIME]);
1819
1820         if (sinfo[NL80211_SURVEY_INFO_TIME_BUSY])
1821                 e->busy_time = nla_get_u64(sinfo[NL80211_SURVEY_INFO_TIME_BUSY]);
1822
1823         if (sinfo[NL80211_SURVEY_INFO_TIME_EXT_BUSY])
1824                 e->busy_time_ext = nla_get_u64(sinfo[NL80211_SURVEY_INFO_TIME_EXT_BUSY]);
1825
1826         if (sinfo[NL80211_SURVEY_INFO_TIME_RX])
1827                 e->rxtime = nla_get_u64(sinfo[NL80211_SURVEY_INFO_TIME_RX]);
1828
1829         if (sinfo[NL80211_SURVEY_INFO_TIME_TX])
1830                 e->txtime = nla_get_u64(sinfo[NL80211_SURVEY_INFO_TIME_TX]);
1831
1832         arr->count++;
1833         return NL_SKIP;
1834 }
1835
1836
1837 static void plink_state_to_str(char *dst, unsigned state)
1838 {
1839         switch (state) {
1840         case NL80211_PLINK_LISTEN:
1841                 strcpy(dst, "LISTEN");
1842                 break;
1843         case NL80211_PLINK_OPN_SNT:
1844                 strcpy(dst, "OPN_SNT");
1845                 break;
1846         case NL80211_PLINK_OPN_RCVD:
1847                 strcpy(dst, "OPN_RCVD");
1848                 break;
1849         case NL80211_PLINK_CNF_RCVD:
1850                 strcpy(dst, "CNF_RCVD");
1851                 break;
1852         case NL80211_PLINK_ESTAB:
1853                 strcpy(dst, "ESTAB");
1854                 break;
1855         case NL80211_PLINK_HOLDING:
1856                 strcpy(dst, "HOLDING");
1857                 break;
1858         case NL80211_PLINK_BLOCKED:
1859                 strcpy(dst, "BLOCKED");
1860                 break;
1861         default:
1862                 strcpy(dst, "UNKNOWN");
1863                 break;
1864         }
1865 }
1866
1867 static void power_mode_to_str(char *dst, struct nlattr *a)
1868 {
1869         enum nl80211_mesh_power_mode pm = nla_get_u32(a);
1870
1871         switch (pm) {
1872         case NL80211_MESH_POWER_ACTIVE:
1873                 strcpy(dst, "ACTIVE");
1874                 break;
1875         case NL80211_MESH_POWER_LIGHT_SLEEP:
1876                 strcpy(dst, "LIGHT SLEEP");
1877                 break;
1878         case NL80211_MESH_POWER_DEEP_SLEEP:
1879                 strcpy(dst, "DEEP SLEEP");
1880                 break;
1881         default:
1882                 strcpy(dst, "UNKNOWN");
1883                 break;
1884         }
1885 }
1886
1887 static int nl80211_get_assoclist_cb(struct nl_msg *msg, void *arg)
1888 {
1889         struct nl80211_array_buf *arr = arg;
1890         struct iwinfo_assoclist_entry *e = arr->buf;
1891         struct nlattr **attr = nl80211_parse(msg);
1892         struct nlattr *sinfo[NL80211_STA_INFO_MAX + 1];
1893         struct nlattr *rinfo[NL80211_RATE_INFO_MAX + 1];
1894         struct nl80211_sta_flag_update *sta_flags;
1895
1896         static struct nla_policy stats_policy[NL80211_STA_INFO_MAX + 1] = {
1897                 [NL80211_STA_INFO_INACTIVE_TIME] = { .type = NLA_U32    },
1898                 [NL80211_STA_INFO_RX_PACKETS]    = { .type = NLA_U32    },
1899                 [NL80211_STA_INFO_TX_PACKETS]    = { .type = NLA_U32    },
1900                 [NL80211_STA_INFO_RX_BITRATE]    = { .type = NLA_NESTED },
1901                 [NL80211_STA_INFO_TX_BITRATE]    = { .type = NLA_NESTED },
1902                 [NL80211_STA_INFO_SIGNAL]        = { .type = NLA_U8     },
1903                 [NL80211_STA_INFO_SIGNAL_AVG]    = { .type = NLA_U8     },
1904                 [NL80211_STA_INFO_RX_BYTES]      = { .type = NLA_U32    },
1905                 [NL80211_STA_INFO_TX_BYTES]      = { .type = NLA_U32    },
1906                 [NL80211_STA_INFO_TX_RETRIES]    = { .type = NLA_U32    },
1907                 [NL80211_STA_INFO_TX_FAILED]     = { .type = NLA_U32    },
1908                 [NL80211_STA_INFO_CONNECTED_TIME]= { .type = NLA_U32    },
1909                 [NL80211_STA_INFO_RX_DROP_MISC]  = { .type = NLA_U64    },
1910                 [NL80211_STA_INFO_T_OFFSET]      = { .type = NLA_U64    },
1911                 [NL80211_STA_INFO_STA_FLAGS] =
1912                         { .minlen = sizeof(struct nl80211_sta_flag_update) },
1913                 [NL80211_STA_INFO_EXPECTED_THROUGHPUT]   = { .type = NLA_U32    },
1914                 /* mesh */
1915                 [NL80211_STA_INFO_LLID]          = { .type = NLA_U16    },
1916                 [NL80211_STA_INFO_PLID]          = { .type = NLA_U16    },
1917                 [NL80211_STA_INFO_PLINK_STATE]   = { .type = NLA_U8     },
1918                 [NL80211_STA_INFO_LOCAL_PM]      = { .type = NLA_U32    },
1919                 [NL80211_STA_INFO_PEER_PM]       = { .type = NLA_U32    },
1920                 [NL80211_STA_INFO_NONPEER_PM]    = { .type = NLA_U32    },
1921         };
1922
1923         static struct nla_policy rate_policy[NL80211_RATE_INFO_MAX + 1] = {
1924                 [NL80211_RATE_INFO_BITRATE]      = { .type = NLA_U16    },
1925                 [NL80211_RATE_INFO_MCS]          = { .type = NLA_U8     },
1926                 [NL80211_RATE_INFO_40_MHZ_WIDTH] = { .type = NLA_FLAG   },
1927                 [NL80211_RATE_INFO_SHORT_GI]     = { .type = NLA_FLAG   },
1928         };
1929
1930         /* advance to end of array */
1931         e += arr->count;
1932         memset(e, 0, sizeof(*e));
1933
1934         if (attr[NL80211_ATTR_MAC])
1935                 memcpy(e->mac, nla_data(attr[NL80211_ATTR_MAC]), 6);
1936
1937         if (attr[NL80211_ATTR_STA_INFO] &&
1938             !nla_parse_nested(sinfo, NL80211_STA_INFO_MAX,
1939                               attr[NL80211_ATTR_STA_INFO], stats_policy))
1940         {
1941                 if (sinfo[NL80211_STA_INFO_SIGNAL])
1942                         e->signal = nla_get_u8(sinfo[NL80211_STA_INFO_SIGNAL]);
1943
1944                 if (sinfo[NL80211_STA_INFO_SIGNAL_AVG])
1945                         e->signal_avg = nla_get_u8(sinfo[NL80211_STA_INFO_SIGNAL_AVG]);
1946
1947                 if (sinfo[NL80211_STA_INFO_INACTIVE_TIME])
1948                         e->inactive = nla_get_u32(sinfo[NL80211_STA_INFO_INACTIVE_TIME]);
1949
1950                 if (sinfo[NL80211_STA_INFO_CONNECTED_TIME])
1951                         e->connected_time = nla_get_u32(sinfo[NL80211_STA_INFO_CONNECTED_TIME]);
1952
1953                 if (sinfo[NL80211_STA_INFO_RX_PACKETS])
1954                         e->rx_packets = nla_get_u32(sinfo[NL80211_STA_INFO_RX_PACKETS]);
1955
1956                 if (sinfo[NL80211_STA_INFO_TX_PACKETS])
1957                         e->tx_packets = nla_get_u32(sinfo[NL80211_STA_INFO_TX_PACKETS]);
1958
1959                 if (sinfo[NL80211_STA_INFO_RX_BITRATE] &&
1960                     !nla_parse_nested(rinfo, NL80211_RATE_INFO_MAX,
1961                                       sinfo[NL80211_STA_INFO_RX_BITRATE], rate_policy))
1962                         nl80211_parse_rateinfo(rinfo, &e->rx_rate);
1963
1964                 if (sinfo[NL80211_STA_INFO_TX_BITRATE] &&
1965                     !nla_parse_nested(rinfo, NL80211_RATE_INFO_MAX,
1966                                       sinfo[NL80211_STA_INFO_TX_BITRATE], rate_policy))
1967                         nl80211_parse_rateinfo(rinfo, &e->tx_rate);
1968
1969                 if (sinfo[NL80211_STA_INFO_RX_BYTES])
1970                         e->rx_bytes = nla_get_u32(sinfo[NL80211_STA_INFO_RX_BYTES]);
1971
1972                 if (sinfo[NL80211_STA_INFO_TX_BYTES])
1973                         e->tx_bytes = nla_get_u32(sinfo[NL80211_STA_INFO_TX_BYTES]);
1974
1975                 if (sinfo[NL80211_STA_INFO_TX_RETRIES])
1976                         e->tx_retries = nla_get_u32(sinfo[NL80211_STA_INFO_TX_RETRIES]);
1977
1978                 if (sinfo[NL80211_STA_INFO_TX_FAILED])
1979                         e->tx_failed = nla_get_u32(sinfo[NL80211_STA_INFO_TX_FAILED]);
1980
1981                 if (sinfo[NL80211_STA_INFO_T_OFFSET])
1982                         e->t_offset = nla_get_u64(sinfo[NL80211_STA_INFO_T_OFFSET]);
1983
1984                 if (sinfo[NL80211_STA_INFO_RX_DROP_MISC])
1985                         e->rx_drop_misc = nla_get_u64(sinfo[NL80211_STA_INFO_RX_DROP_MISC]);
1986
1987                 if (sinfo[NL80211_STA_INFO_EXPECTED_THROUGHPUT])
1988                         e->thr = nla_get_u32(sinfo[NL80211_STA_INFO_EXPECTED_THROUGHPUT]);
1989
1990                 /* mesh */
1991                 if (sinfo[NL80211_STA_INFO_LLID])
1992                         e->llid = nla_get_u16(sinfo[NL80211_STA_INFO_LLID]);
1993
1994                 if (sinfo[NL80211_STA_INFO_PLID])
1995                         e->plid = nla_get_u16(sinfo[NL80211_STA_INFO_PLID]);
1996
1997                 if (sinfo[NL80211_STA_INFO_PLINK_STATE])
1998                         plink_state_to_str(e->plink_state,
1999                                 nla_get_u8(sinfo[NL80211_STA_INFO_PLINK_STATE]));
2000
2001                 if (sinfo[NL80211_STA_INFO_LOCAL_PM])
2002                         power_mode_to_str(e->local_ps, sinfo[NL80211_STA_INFO_LOCAL_PM]);
2003                 if (sinfo[NL80211_STA_INFO_PEER_PM])
2004                         power_mode_to_str(e->peer_ps, sinfo[NL80211_STA_INFO_PEER_PM]);
2005                 if (sinfo[NL80211_STA_INFO_NONPEER_PM])
2006                         power_mode_to_str(e->nonpeer_ps, sinfo[NL80211_STA_INFO_NONPEER_PM]);
2007
2008                 /* Station flags */
2009                 if (sinfo[NL80211_STA_INFO_STA_FLAGS])
2010                 {
2011                         sta_flags = (struct nl80211_sta_flag_update *)
2012                                 nla_data(sinfo[NL80211_STA_INFO_STA_FLAGS]);
2013
2014                         if (sta_flags->mask & BIT(NL80211_STA_FLAG_AUTHORIZED) &&
2015                             sta_flags->set & BIT(NL80211_STA_FLAG_AUTHORIZED))
2016                                 e->is_authorized = 1;
2017
2018                         if (sta_flags->mask & BIT(NL80211_STA_FLAG_AUTHENTICATED) &&
2019                             sta_flags->set & BIT(NL80211_STA_FLAG_AUTHENTICATED))
2020                                 e->is_authenticated = 1;
2021
2022                         if (sta_flags->mask & BIT(NL80211_STA_FLAG_SHORT_PREAMBLE) &&
2023                             sta_flags->set & BIT(NL80211_STA_FLAG_SHORT_PREAMBLE))
2024                                 e->is_preamble_short = 1;
2025
2026                         if (sta_flags->mask & BIT(NL80211_STA_FLAG_WME) &&
2027                             sta_flags->set & BIT(NL80211_STA_FLAG_WME))
2028                                 e->is_wme = 1;
2029
2030                         if (sta_flags->mask & BIT(NL80211_STA_FLAG_MFP) &&
2031                             sta_flags->set & BIT(NL80211_STA_FLAG_MFP))
2032                                 e->is_mfp = 1;
2033
2034                         if (sta_flags->mask & BIT(NL80211_STA_FLAG_TDLS_PEER) &&
2035                             sta_flags->set & BIT(NL80211_STA_FLAG_TDLS_PEER))
2036                                 e->is_tdls = 1;
2037                 }
2038         }
2039
2040         e->noise = 0; /* filled in by caller */
2041         arr->count++;
2042
2043         return NL_SKIP;
2044 }
2045
2046 static int nl80211_get_survey(const char *ifname, char *buf, int *len)
2047 {
2048         struct nl80211_array_buf arr = { .buf = buf, .count = 0 };
2049         int rc;
2050
2051         rc = nl80211_request(ifname, NL80211_CMD_GET_SURVEY,
2052                         NLM_F_DUMP, nl80211_get_survey_cb, &arr);
2053         if (!rc)
2054                 *len = (arr.count * sizeof(struct iwinfo_survey_entry));
2055         else
2056                 *len = 0;
2057
2058         return 0;
2059 }
2060
2061 static int nl80211_get_assoclist(const char *ifname, char *buf, int *len)
2062 {
2063         DIR *d;
2064         int i, noise = 0;
2065         struct dirent *de;
2066         struct nl80211_array_buf arr = { .buf = buf, .count = 0 };
2067         struct iwinfo_assoclist_entry *e;
2068
2069         if ((d = opendir("/sys/class/net")) != NULL)
2070         {
2071                 while ((de = readdir(d)) != NULL)
2072                 {
2073                         if (!strncmp(de->d_name, ifname, strlen(ifname)) &&
2074                             (!de->d_name[strlen(ifname)] ||
2075                              !strncmp(&de->d_name[strlen(ifname)], ".sta", 4)))
2076                         {
2077                                 nl80211_request(de->d_name, NL80211_CMD_GET_STATION,
2078                                                 NLM_F_DUMP, nl80211_get_assoclist_cb, &arr);
2079                         }
2080                 }
2081
2082                 closedir(d);
2083
2084                 if (!nl80211_get_noise(ifname, &noise))
2085                         for (i = 0, e = arr.buf; i < arr.count; i++, e++)
2086                                 e->noise = noise;
2087
2088                 *len = (arr.count * sizeof(struct iwinfo_assoclist_entry));
2089                 return 0;
2090         }
2091
2092         return -1;
2093 }
2094
2095 static int nl80211_get_txpwrlist_cb(struct nl_msg *msg, void *arg)
2096 {
2097         int *dbm_max = arg;
2098         int ch_cur, ch_cmp, bands_remain, freqs_remain;
2099
2100         struct nlattr **attr = nl80211_parse(msg);
2101         struct nlattr *bands[NL80211_BAND_ATTR_MAX + 1];
2102         struct nlattr *freqs[NL80211_FREQUENCY_ATTR_MAX + 1];
2103         struct nlattr *band, *freq;
2104
2105         static struct nla_policy freq_policy[NL80211_FREQUENCY_ATTR_MAX + 1] = {
2106                 [NL80211_FREQUENCY_ATTR_FREQ]         = { .type = NLA_U32  },
2107                 [NL80211_FREQUENCY_ATTR_DISABLED]     = { .type = NLA_FLAG },
2108                 [NL80211_FREQUENCY_ATTR_PASSIVE_SCAN] = { .type = NLA_FLAG },
2109                 [NL80211_FREQUENCY_ATTR_NO_IBSS]      = { .type = NLA_FLAG },
2110                 [NL80211_FREQUENCY_ATTR_RADAR]        = { .type = NLA_FLAG },
2111                 [NL80211_FREQUENCY_ATTR_MAX_TX_POWER] = { .type = NLA_U32  },
2112         };
2113
2114         ch_cur = *dbm_max; /* value int* is initialized with channel by caller */
2115         *dbm_max = -1;
2116
2117         nla_for_each_nested(band, attr[NL80211_ATTR_WIPHY_BANDS], bands_remain)
2118         {
2119                 nla_parse(bands, NL80211_BAND_ATTR_MAX, nla_data(band),
2120                           nla_len(band), NULL);
2121
2122                 nla_for_each_nested(freq, bands[NL80211_BAND_ATTR_FREQS], freqs_remain)
2123                 {
2124                         nla_parse(freqs, NL80211_FREQUENCY_ATTR_MAX,
2125                                   nla_data(freq), nla_len(freq), freq_policy);
2126
2127                         ch_cmp = nl80211_freq2channel(nla_get_u32(
2128                                 freqs[NL80211_FREQUENCY_ATTR_FREQ]));
2129
2130                         if ((!ch_cur || (ch_cmp == ch_cur)) &&
2131                             freqs[NL80211_FREQUENCY_ATTR_MAX_TX_POWER])
2132                         {
2133                                 *dbm_max = (int)(0.01 * nla_get_u32(
2134                                         freqs[NL80211_FREQUENCY_ATTR_MAX_TX_POWER]));
2135
2136                                 break;
2137                         }
2138                 }
2139         }
2140
2141         return NL_SKIP;
2142 }
2143
2144 static int nl80211_get_txpwrlist(const char *ifname, char *buf, int *len)
2145 {
2146         int err, ch_cur;
2147         int dbm_max = -1, dbm_cur, dbm_cnt;
2148         struct nl80211_msg_conveyor *req;
2149         struct iwinfo_txpwrlist_entry entry;
2150
2151         if (nl80211_get_channel(ifname, &ch_cur))
2152                 ch_cur = 0;
2153
2154         /* initialize the value pointer with channel for callback */
2155         dbm_max = ch_cur;
2156
2157         err = nl80211_request(ifname, NL80211_CMD_GET_WIPHY, 0,
2158                               nl80211_get_txpwrlist_cb, &dbm_max);
2159
2160         if (!err)
2161         {
2162                 for (dbm_cur = 0, dbm_cnt = 0;
2163                      dbm_cur < dbm_max;
2164                      dbm_cur++, dbm_cnt++)
2165                 {
2166                         entry.dbm = dbm_cur;
2167                         entry.mw  = iwinfo_dbm2mw(dbm_cur);
2168
2169                         memcpy(&buf[dbm_cnt * sizeof(entry)], &entry, sizeof(entry));
2170                 }
2171
2172                 entry.dbm = dbm_max;
2173                 entry.mw  = iwinfo_dbm2mw(dbm_max);
2174
2175                 memcpy(&buf[dbm_cnt * sizeof(entry)], &entry, sizeof(entry));
2176                 dbm_cnt++;
2177
2178                 *len = dbm_cnt * sizeof(entry);
2179                 return 0;
2180         }
2181
2182         return -1;
2183 }
2184
2185 static void nl80211_get_scancrypto(char *spec, struct iwinfo_crypto_entry *c)
2186 {
2187         int wpa_version = 0;
2188         char *p, *proto, *suites;
2189
2190         c->enabled = 0;
2191
2192         for (p = strtok(spec, "[]"); p != NULL; p = strtok(NULL, "[]")) {
2193                 proto = strtok(p, "-");
2194                 suites = strtok(NULL, "]");
2195
2196                 if (!proto || !suites)
2197                         continue;
2198
2199                 if (!strcmp(proto, "WPA2") || !strcmp(proto, "RSN"))
2200                         wpa_version = 2;
2201                 else if (!strcmp(proto, "WPA"))
2202                         wpa_version = 1;
2203                 else
2204                         continue;
2205
2206                 c->enabled = 1;
2207
2208                 parse_wpa_suites(suites, wpa_version, &c->wpa_version, &c->auth_suites);
2209                 parse_wpa_ciphers(suites, &c->pair_ciphers);
2210         }
2211 }
2212
2213
2214 struct nl80211_scanlist {
2215         struct iwinfo_scanlist_entry *e;
2216         int len;
2217 };
2218
2219
2220 static void nl80211_get_scanlist_ie(struct nlattr **bss,
2221                                     struct iwinfo_scanlist_entry *e)
2222 {
2223         int ielen = nla_len(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
2224         unsigned char *ie = nla_data(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
2225         static unsigned char ms_oui[3] = { 0x00, 0x50, 0xf2 };
2226         int len;
2227
2228         while (ielen >= 2 && ielen >= ie[1])
2229         {
2230                 switch (ie[0])
2231                 {
2232                 case 0: /* SSID */
2233                 case 114: /* Mesh ID */
2234                         if (e->ssid[0] == 0) {
2235                                 len = min(ie[1], IWINFO_ESSID_MAX_SIZE);
2236                                 memcpy(e->ssid, ie + 2, len);
2237                                 e->ssid[len] = 0;
2238                         }
2239                         break;
2240
2241                 case 48: /* RSN */
2242                         iwinfo_parse_rsn(&e->crypto, ie + 2, ie[1],
2243                                          IWINFO_CIPHER_CCMP, IWINFO_KMGMT_8021x);
2244                         break;
2245
2246                 case 221: /* Vendor */
2247                         if (ie[1] >= 4 && !memcmp(ie + 2, ms_oui, 3) && ie[5] == 1)
2248                                 iwinfo_parse_rsn(&e->crypto, ie + 6, ie[1] - 4,
2249                                                  IWINFO_CIPHER_TKIP, IWINFO_KMGMT_PSK);
2250                         break;
2251                 }
2252
2253                 ielen -= ie[1] + 2;
2254                 ie += ie[1] + 2;
2255         }
2256 }
2257
2258 static int nl80211_get_scanlist_cb(struct nl_msg *msg, void *arg)
2259 {
2260         int8_t rssi;
2261         uint16_t caps;
2262
2263         struct nl80211_scanlist *sl = arg;
2264         struct nlattr **tb = nl80211_parse(msg);
2265         struct nlattr *bss[NL80211_BSS_MAX + 1];
2266
2267         static struct nla_policy bss_policy[NL80211_BSS_MAX + 1] = {
2268                 [NL80211_BSS_TSF]                  = { .type = NLA_U64 },
2269                 [NL80211_BSS_FREQUENCY]            = { .type = NLA_U32 },
2270                 [NL80211_BSS_BSSID]                = { 0 },
2271                 [NL80211_BSS_BEACON_INTERVAL]      = { .type = NLA_U16 },
2272                 [NL80211_BSS_CAPABILITY]           = { .type = NLA_U16 },
2273                 [NL80211_BSS_INFORMATION_ELEMENTS] = { 0 },
2274                 [NL80211_BSS_SIGNAL_MBM]           = { .type = NLA_U32 },
2275                 [NL80211_BSS_SIGNAL_UNSPEC]        = { .type = NLA_U8  },
2276                 [NL80211_BSS_STATUS]               = { .type = NLA_U32 },
2277                 [NL80211_BSS_SEEN_MS_AGO]          = { .type = NLA_U32 },
2278                 [NL80211_BSS_BEACON_IES]           = { 0 },
2279         };
2280
2281         if (!tb[NL80211_ATTR_BSS] ||
2282                 nla_parse_nested(bss, NL80211_BSS_MAX, tb[NL80211_ATTR_BSS],
2283                                  bss_policy) ||
2284                 !bss[NL80211_BSS_BSSID])
2285         {
2286                 return NL_SKIP;
2287         }
2288
2289         if (bss[NL80211_BSS_CAPABILITY])
2290                 caps = nla_get_u16(bss[NL80211_BSS_CAPABILITY]);
2291         else
2292                 caps = 0;
2293
2294         memset(sl->e, 0, sizeof(*sl->e));
2295         memcpy(sl->e->mac, nla_data(bss[NL80211_BSS_BSSID]), 6);
2296
2297         if (caps & (1<<1))
2298                 sl->e->mode = IWINFO_OPMODE_ADHOC;
2299         else if (caps & (1<<0))
2300                 sl->e->mode = IWINFO_OPMODE_MASTER;
2301         else
2302                 sl->e->mode = IWINFO_OPMODE_MESHPOINT;
2303
2304         if (caps & (1<<4))
2305                 sl->e->crypto.enabled = 1;
2306
2307         if (bss[NL80211_BSS_FREQUENCY])
2308                 sl->e->channel = nl80211_freq2channel(nla_get_u32(
2309                         bss[NL80211_BSS_FREQUENCY]));
2310
2311         if (bss[NL80211_BSS_INFORMATION_ELEMENTS])
2312                 nl80211_get_scanlist_ie(bss, sl->e);
2313
2314         if (bss[NL80211_BSS_SIGNAL_MBM])
2315         {
2316                 sl->e->signal =
2317                         (uint8_t)((int32_t)nla_get_u32(bss[NL80211_BSS_SIGNAL_MBM]) / 100);
2318
2319                 rssi = sl->e->signal - 0x100;
2320
2321                 if (rssi < -110)
2322                         rssi = -110;
2323                 else if (rssi > -40)
2324                         rssi = -40;
2325
2326                 sl->e->quality = (rssi + 110);
2327                 sl->e->quality_max = 70;
2328         }
2329
2330         if (sl->e->crypto.enabled && !sl->e->crypto.wpa_version)
2331         {
2332                 sl->e->crypto.auth_algs    = IWINFO_AUTH_OPEN | IWINFO_AUTH_SHARED;
2333                 sl->e->crypto.pair_ciphers = IWINFO_CIPHER_WEP40 | IWINFO_CIPHER_WEP104;
2334         }
2335
2336         sl->e++;
2337         sl->len++;
2338
2339         return NL_SKIP;
2340 }
2341
2342 static int nl80211_get_scanlist_nl(const char *ifname, char *buf, int *len)
2343 {
2344         struct nl80211_scanlist sl = { .e = (struct iwinfo_scanlist_entry *)buf };
2345
2346         if (nl80211_request(ifname, NL80211_CMD_TRIGGER_SCAN, 0, NULL, NULL))
2347                 goto out;
2348
2349         if (nl80211_wait("nl80211", "scan",
2350                          NL80211_CMD_NEW_SCAN_RESULTS, NL80211_CMD_SCAN_ABORTED))
2351                 goto out;
2352
2353         if (nl80211_request(ifname, NL80211_CMD_GET_SCAN, NLM_F_DUMP,
2354                             nl80211_get_scanlist_cb, &sl))
2355                 goto out;
2356
2357         *len = sl.len * sizeof(struct iwinfo_scanlist_entry);
2358         return 0;
2359
2360 out:
2361         *len = 0;
2362         return -1;
2363 }
2364
2365 static int wpasupp_ssid_decode(const char *in, char *out, int outlen)
2366 {
2367 #define hex(x) \
2368         (((x) >= 'a') ? ((x) - 'a' + 10) : \
2369                 (((x) >= 'A') ? ((x) - 'A' + 10) : ((x) - '0')))
2370
2371         int len = 0;
2372
2373         while (*in)
2374         {
2375                 if (len + 1 >= outlen)
2376                         break;
2377
2378                 switch (*in)
2379                 {
2380                 case '\\':
2381                         in++;
2382                         switch (*in)
2383                         {
2384                         case 'n':
2385                                 out[len++] = '\n'; in++;
2386                                 break;
2387
2388                         case 'r':
2389                                 out[len++] = '\r'; in++;
2390                                 break;
2391
2392                         case 't':
2393                                 out[len++] = '\t'; in++;
2394                                 break;
2395
2396                         case 'e':
2397                                 out[len++] = '\033'; in++;
2398                                 break;
2399
2400                         case 'x':
2401                                 if (isxdigit(*(in+1)) && isxdigit(*(in+2)))
2402                                         out[len++] = hex(*(in+1)) * 16 + hex(*(in+2));
2403                                 in += 3;
2404                                 break;
2405
2406                         default:
2407                                 out[len++] = *in++;
2408                                 break;
2409                         }
2410                         break;
2411
2412                 default:
2413                         out[len++] = *in++;
2414                         break;
2415                 }
2416         }
2417
2418         if (outlen > len)
2419                 out[len] = '\0';
2420
2421         return len;
2422 }
2423
2424 static int nl80211_get_scanlist_wpactl(const char *ifname, char *buf, int *len)
2425 {
2426         int sock, qmax, rssi, tries, count = -1, ready = 0;
2427         char *pos, *line, *bssid, *freq, *signal, *flags, *ssid, reply[4096];
2428         struct sockaddr_un local = { 0 };
2429         struct iwinfo_scanlist_entry *e = (struct iwinfo_scanlist_entry *)buf;
2430
2431         sock = nl80211_wpactl_connect(ifname, &local);
2432
2433         if (sock < 0)
2434                 return sock;
2435
2436         send(sock, "ATTACH", 6, 0);
2437         send(sock, "SCAN", 4, 0);
2438
2439         /*
2440          * wait for scan results:
2441          *   nl80211_wpactl_recv() will use a timeout of 256ms and we need to scan
2442          *   72 channels at most. We'll also receive two "OK" messages acknowledging
2443          *   the "ATTACH" and "SCAN" commands and the driver might need a bit extra
2444          *   time to process the results, so try 72 + 2 + 1 times.
2445          */
2446         for (tries = 0; tries < 75; tries++)
2447         {
2448                 if (nl80211_wpactl_recv(sock, reply, sizeof(reply)) <= 0)
2449                         continue;
2450
2451                 /* got an event notification */
2452                 if (reply[0] == '<')
2453                 {
2454                         /* scan results are ready */
2455                         if (strstr(reply, "CTRL-EVENT-SCAN-RESULTS"))
2456                         {
2457                                 /* send "SCAN_RESULTS" command */
2458                                 ready = (send(sock, "SCAN_RESULTS", 12, 0) == 12);
2459                                 break;
2460                         }
2461
2462                         /* is another unrelated event, retry */
2463                         tries--;
2464                 }
2465
2466                 /* got a failure reply */
2467                 else if (!strcmp(reply, "FAIL-BUSY\n"))
2468                 {
2469                         break;
2470                 }
2471         }
2472
2473         /* receive and parse scan results if the wait above didn't time out */
2474         while (ready && nl80211_wpactl_recv(sock, reply, sizeof(reply)) > 0)
2475         {
2476                 /* received an event notification, receive again */
2477                 if (reply[0] == '<')
2478                         continue;
2479
2480                 nl80211_get_quality_max(ifname, &qmax);
2481
2482                 for (line = strtok_r(reply, "\n", &pos);
2483                      line != NULL;
2484                      line = strtok_r(NULL, "\n", &pos))
2485                 {
2486                         /* skip header line */
2487                         if (count < 0)
2488                         {
2489                                 count++;
2490                                 continue;
2491                         }
2492
2493                         bssid  = strtok(line, "\t");
2494                         freq   = strtok(NULL, "\t");
2495                         signal = strtok(NULL, "\t");
2496                         flags  = strtok(NULL, "\t");
2497                         ssid   = strtok(NULL, "\n");
2498
2499                         if (!bssid || !freq || !signal || !flags || !ssid)
2500                                 continue;
2501
2502                         /* BSSID */
2503                         e->mac[0] = strtol(&bssid[0],  NULL, 16);
2504                         e->mac[1] = strtol(&bssid[3],  NULL, 16);
2505                         e->mac[2] = strtol(&bssid[6],  NULL, 16);
2506                         e->mac[3] = strtol(&bssid[9],  NULL, 16);
2507                         e->mac[4] = strtol(&bssid[12], NULL, 16);
2508                         e->mac[5] = strtol(&bssid[15], NULL, 16);
2509
2510                         /* SSID */
2511                         wpasupp_ssid_decode(ssid, e->ssid, sizeof(e->ssid));
2512
2513                         /* Mode */
2514                         if (strstr(flags, "[MESH]"))
2515                                 e->mode = IWINFO_OPMODE_MESHPOINT;
2516                         else if (strstr(flags, "[IBSS]"))
2517                                 e->mode = IWINFO_OPMODE_ADHOC;
2518                         else
2519                                 e->mode = IWINFO_OPMODE_MASTER;
2520
2521                         /* Channel */
2522                         e->channel = nl80211_freq2channel(atoi(freq));
2523
2524                         /* Signal */
2525                         rssi = atoi(signal);
2526                         e->signal = rssi;
2527
2528                         /* Quality */
2529                         if (rssi < 0)
2530                         {
2531                                 /* The cfg80211 wext compat layer assumes a signal range
2532                                  * of -110 dBm to -40 dBm, the quality value is derived
2533                                  * by adding 110 to the signal level */
2534                                 if (rssi < -110)
2535                                         rssi = -110;
2536                                 else if (rssi > -40)
2537                                         rssi = -40;
2538
2539                                 e->quality = (rssi + 110);
2540                         }
2541                         else
2542                         {
2543                                 e->quality = rssi;
2544                         }
2545
2546                         /* Max. Quality */
2547                         e->quality_max = qmax;
2548
2549                         /* Crypto */
2550                         nl80211_get_scancrypto(flags, &e->crypto);
2551
2552                         count++;
2553                         e++;
2554                 }
2555
2556                 *len = count * sizeof(struct iwinfo_scanlist_entry);
2557                 break;
2558         }
2559
2560         close(sock);
2561         unlink(local.sun_path);
2562
2563         return (count >= 0) ? 0 : -1;
2564 }
2565
2566 static int nl80211_get_scanlist(const char *ifname, char *buf, int *len)
2567 {
2568         char *res;
2569         int rv, mode;
2570
2571         *len = 0;
2572
2573         /* Got a radioX pseudo interface, find some interface on it or create one */
2574         if (!strncmp(ifname, "radio", 5))
2575         {
2576                 /* Reuse existing interface */
2577                 if ((res = nl80211_phy2ifname(ifname)) != NULL)
2578                 {
2579                         return nl80211_get_scanlist(res, buf, len);
2580                 }
2581
2582                 /* Need to spawn a temporary iface for scanning */
2583                 else if ((res = nl80211_ifadd(ifname)) != NULL)
2584                 {
2585                         rv = nl80211_get_scanlist(res, buf, len);
2586                         nl80211_ifdel(res);
2587                         return rv;
2588                 }
2589         }
2590
2591         /* WPA supplicant */
2592         if (!nl80211_get_scanlist_wpactl(ifname, buf, len))
2593         {
2594                 return 0;
2595         }
2596
2597         /* station / ad-hoc / monitor scan */
2598         else if (!nl80211_get_mode(ifname, &mode) &&
2599                  (mode == IWINFO_OPMODE_ADHOC ||
2600                   mode == IWINFO_OPMODE_MASTER ||
2601                   mode == IWINFO_OPMODE_CLIENT ||
2602                   mode == IWINFO_OPMODE_MONITOR) &&
2603                  iwinfo_ifup(ifname))
2604         {
2605                 return nl80211_get_scanlist_nl(ifname, buf, len);
2606         }
2607
2608         /* AP scan */
2609         else
2610         {
2611                 /* Got a temp interface, don't create yet another one */
2612                 if (!strncmp(ifname, "tmp.", 4))
2613                 {
2614                         if (!iwinfo_ifup(ifname))
2615                                 return -1;
2616
2617                         rv = nl80211_get_scanlist_nl(ifname, buf, len);
2618                         iwinfo_ifdown(ifname);
2619                         return rv;
2620                 }
2621
2622                 /* Spawn a new scan interface */
2623                 else
2624                 {
2625                         if (!(res = nl80211_ifadd(ifname)))
2626                                 return -1;
2627
2628                         iwinfo_ifmac(res);
2629
2630                         /* if we can take the new interface up, the driver supports an
2631                          * additional interface and there's no need to tear down the ap */
2632                         if (iwinfo_ifup(res))
2633                         {
2634                                 rv = nl80211_get_scanlist_nl(res, buf, len);
2635                                 iwinfo_ifdown(res);
2636                         }
2637
2638                         /* driver cannot create secondary interface, take down ap
2639                          * during scan */
2640                         else if (iwinfo_ifdown(ifname) && iwinfo_ifup(res))
2641                         {
2642                                 rv = nl80211_get_scanlist_nl(res, buf, len);
2643                                 iwinfo_ifdown(res);
2644                                 iwinfo_ifup(ifname);
2645                                 nl80211_hostapd_hup(ifname);
2646                         }
2647
2648                         nl80211_ifdel(res);
2649                         return rv;
2650                 }
2651         }
2652
2653         return -1;
2654 }
2655
2656 static int nl80211_get_freqlist_cb(struct nl_msg *msg, void *arg)
2657 {
2658         int bands_remain, freqs_remain;
2659
2660         struct nl80211_array_buf *arr = arg;
2661         struct iwinfo_freqlist_entry *e;
2662
2663         struct nlattr **attr = nl80211_parse(msg);
2664         struct nlattr *bands[NL80211_BAND_ATTR_MAX + 1];
2665         struct nlattr *freqs[NL80211_FREQUENCY_ATTR_MAX + 1];
2666         struct nlattr *band, *freq;
2667
2668         e = arr->buf;
2669         e += arr->count;
2670
2671         if (attr[NL80211_ATTR_WIPHY_BANDS]) {
2672                 nla_for_each_nested(band, attr[NL80211_ATTR_WIPHY_BANDS], bands_remain)
2673                 {
2674                         nla_parse(bands, NL80211_BAND_ATTR_MAX,
2675                                   nla_data(band), nla_len(band), NULL);
2676
2677                         if (bands[NL80211_BAND_ATTR_FREQS]) {
2678                                 nla_for_each_nested(freq, bands[NL80211_BAND_ATTR_FREQS], freqs_remain)
2679                                 {
2680                                         nla_parse(freqs, NL80211_FREQUENCY_ATTR_MAX,
2681                                                   nla_data(freq), nla_len(freq), NULL);
2682
2683                                         if (!freqs[NL80211_FREQUENCY_ATTR_FREQ] ||
2684                                             freqs[NL80211_FREQUENCY_ATTR_DISABLED])
2685                                                 continue;
2686
2687                                         e->mhz = nla_get_u32(freqs[NL80211_FREQUENCY_ATTR_FREQ]);
2688                                         e->channel = nl80211_freq2channel(e->mhz);
2689
2690                                         e->restricted = (
2691                                                 freqs[NL80211_FREQUENCY_ATTR_NO_IR] &&
2692                                                 !freqs[NL80211_FREQUENCY_ATTR_RADAR]
2693                                         ) ? 1 : 0;
2694
2695                                         if (freqs[NL80211_FREQUENCY_ATTR_NO_HT40_MINUS])
2696                                                 e->flags |= IWINFO_FREQ_NO_HT40MINUS;
2697                                         if (freqs[NL80211_FREQUENCY_ATTR_NO_HT40_PLUS])
2698                                                 e->flags |= IWINFO_FREQ_NO_HT40PLUS;
2699                                         if (freqs[NL80211_FREQUENCY_ATTR_NO_80MHZ])
2700                                                 e->flags |= IWINFO_FREQ_NO_80MHZ;
2701                                         if (freqs[NL80211_FREQUENCY_ATTR_NO_160MHZ])
2702                                                 e->flags |= IWINFO_FREQ_NO_160MHZ;
2703                                         if (freqs[NL80211_FREQUENCY_ATTR_NO_20MHZ])
2704                                                 e->flags |= IWINFO_FREQ_NO_20MHZ;
2705                                         if (freqs[NL80211_FREQUENCY_ATTR_NO_10MHZ])
2706                                                 e->flags |= IWINFO_FREQ_NO_10MHZ;
2707
2708                                         e++;
2709                                         arr->count++;
2710                                 }
2711                         }
2712                 }
2713         }
2714
2715         return NL_SKIP;
2716 }
2717
2718 static int nl80211_get_freqlist(const char *ifname, char *buf, int *len)
2719 {
2720         struct nl80211_msg_conveyor *cv;
2721         struct nl80211_array_buf arr = { .buf = buf, .count = 0 };
2722         uint32_t features = nl80211_get_protocol_features(ifname);
2723         int flags;
2724
2725         flags = features & NL80211_PROTOCOL_FEATURE_SPLIT_WIPHY_DUMP ? NLM_F_DUMP : 0;
2726         cv = nl80211_msg(ifname, NL80211_CMD_GET_WIPHY, flags);
2727         if (!cv)
2728                 goto out;
2729
2730         NLA_PUT_FLAG(cv->msg, NL80211_ATTR_SPLIT_WIPHY_DUMP);
2731         if (nl80211_send(cv, nl80211_get_freqlist_cb, &arr))
2732                 goto out;
2733
2734         *len = arr.count * sizeof(struct iwinfo_freqlist_entry);
2735         return 0;
2736
2737 nla_put_failure:
2738         nl80211_free(cv);
2739 out:
2740         *len = 0;
2741         return -1;
2742 }
2743
2744 static int nl80211_get_country_cb(struct nl_msg *msg, void *arg)
2745 {
2746         char *buf = arg;
2747         struct nlattr **attr = nl80211_parse(msg);
2748
2749         if (attr[NL80211_ATTR_REG_ALPHA2])
2750                 memcpy(buf, nla_data(attr[NL80211_ATTR_REG_ALPHA2]), 2);
2751         else
2752                 buf[0] = 0;
2753
2754         return NL_SKIP;
2755 }
2756
2757 static int nl80211_get_country(const char *ifname, char *buf)
2758 {
2759         if (nl80211_request(ifname, NL80211_CMD_GET_REG, 0,
2760                             nl80211_get_country_cb, buf))
2761                 return -1;
2762
2763         return 0;
2764 }
2765
2766 static int nl80211_get_countrylist(const char *ifname, char *buf, int *len)
2767 {
2768         int count;
2769         struct iwinfo_country_entry *e = (struct iwinfo_country_entry *)buf;
2770         const struct iwinfo_iso3166_label *l;
2771
2772         for (l = IWINFO_ISO3166_NAMES, count = 0; l->iso3166; l++, e++, count++)
2773         {
2774                 e->iso3166 = l->iso3166;
2775                 e->ccode[0] = (l->iso3166 / 256);
2776                 e->ccode[1] = (l->iso3166 % 256);
2777                 e->ccode[2] = 0;
2778         }
2779
2780         *len = (count * sizeof(struct iwinfo_country_entry));
2781         return 0;
2782 }
2783
2784
2785 struct nl80211_modes
2786 {
2787         bool ok;
2788         uint32_t hw;
2789         uint32_t ht;
2790 };
2791
2792 static int nl80211_get_modelist_cb(struct nl_msg *msg, void *arg)
2793 {
2794         struct nl80211_modes *m = arg;
2795         int bands_remain, freqs_remain;
2796         uint16_t caps = 0;
2797         uint32_t vht_caps = 0;
2798         struct nlattr **attr = nl80211_parse(msg);
2799         struct nlattr *bands[NL80211_BAND_ATTR_MAX + 1];
2800         struct nlattr *freqs[NL80211_FREQUENCY_ATTR_MAX + 1];
2801         struct nlattr *band, *freq;
2802
2803         if (attr[NL80211_ATTR_WIPHY_BANDS])
2804         {
2805                 nla_for_each_nested(band, attr[NL80211_ATTR_WIPHY_BANDS], bands_remain)
2806                 {
2807                         nla_parse(bands, NL80211_BAND_ATTR_MAX,
2808                                   nla_data(band), nla_len(band), NULL);
2809
2810                         if (bands[NL80211_BAND_ATTR_HT_CAPA])
2811                                 caps = nla_get_u16(bands[NL80211_BAND_ATTR_HT_CAPA]);
2812
2813                         /* Treat any nonzero capability as 11n */
2814                         if (caps > 0)
2815                         {
2816                                 m->hw |= IWINFO_80211_N;
2817                                 m->ht |= IWINFO_HTMODE_HT20;
2818
2819                                 if (caps & (1 << 1))
2820                                         m->ht |= IWINFO_HTMODE_HT40;
2821                         }
2822
2823                         nla_for_each_nested(freq, bands[NL80211_BAND_ATTR_FREQS],
2824                                             freqs_remain)
2825                         {
2826                                 nla_parse(freqs, NL80211_FREQUENCY_ATTR_MAX,
2827                                           nla_data(freq), nla_len(freq), NULL);
2828
2829                                 if (!freqs[NL80211_FREQUENCY_ATTR_FREQ])
2830                                         continue;
2831
2832                                 if (nla_get_u32(freqs[NL80211_FREQUENCY_ATTR_FREQ]) < 2485)
2833                                 {
2834                                         m->hw |= IWINFO_80211_B;
2835                                         m->hw |= IWINFO_80211_G;
2836                                 }
2837                                 else if (bands[NL80211_BAND_ATTR_VHT_CAPA])
2838                                 {
2839                                         vht_caps = nla_get_u32(bands[NL80211_BAND_ATTR_VHT_CAPA]);
2840
2841                                         /* Treat any nonzero capability as 11ac */
2842                                         if (vht_caps > 0)
2843                                         {
2844                                                 m->hw |= IWINFO_80211_AC;
2845                                                 m->ht |= IWINFO_HTMODE_VHT20 | IWINFO_HTMODE_VHT40 | IWINFO_HTMODE_VHT80;
2846
2847                                                 switch ((vht_caps >> 2) & 3)
2848                                                 {
2849                                                 case 2:
2850                                                         m->ht |= IWINFO_HTMODE_VHT80_80;
2851                                                         /* fall through */
2852
2853                                                 case 1:
2854                                                         m->ht |= IWINFO_HTMODE_VHT160;
2855                                                 }
2856                                         }
2857                                 }
2858                                 else if (nla_get_u32(freqs[NL80211_FREQUENCY_ATTR_FREQ]) >= 56160)
2859                                 {
2860                                         m->hw |= IWINFO_80211_AD;
2861                                 }
2862                                 else if (!(m->hw & IWINFO_80211_AC))
2863                                 {
2864                                         m->hw |= IWINFO_80211_A;
2865                                 }
2866                         }
2867                 }
2868
2869                 m->ok = 1;
2870         }
2871
2872         return NL_SKIP;
2873 }
2874
2875 static int nl80211_get_hwmodelist(const char *ifname, int *buf)
2876 {
2877         struct nl80211_modes m = { 0 };
2878
2879         if (nl80211_request(ifname, NL80211_CMD_GET_WIPHY, 0,
2880                             nl80211_get_modelist_cb, &m))
2881                 goto out;
2882
2883         if (!m.ok)
2884                 goto out;
2885
2886         *buf = m.hw;
2887         return 0;
2888
2889 out:
2890         *buf = 0;
2891         return -1;
2892 }
2893
2894 static int nl80211_get_htmodelist(const char *ifname, int *buf)
2895 {
2896         struct nl80211_modes m = { 0 };
2897
2898         if (nl80211_request(ifname, NL80211_CMD_GET_WIPHY, 0,
2899                             nl80211_get_modelist_cb, &m))
2900                 goto out;
2901
2902         if (!m.ok)
2903                 goto out;
2904
2905         *buf = m.ht;
2906         return 0;
2907
2908 out:
2909         *buf = 0;
2910         return -1;
2911 }
2912
2913
2914 static int nl80211_get_ifcomb_cb(struct nl_msg *msg, void *arg)
2915 {
2916         struct nlattr **attr = nl80211_parse(msg);
2917         struct nlattr *comb;
2918         int *ret = arg;
2919         int comb_rem, limit_rem, mode_rem;
2920
2921         *ret = 0;
2922         if (!attr[NL80211_ATTR_INTERFACE_COMBINATIONS])
2923                 return NL_SKIP;
2924
2925         nla_for_each_nested(comb, attr[NL80211_ATTR_INTERFACE_COMBINATIONS], comb_rem)
2926         {
2927                 static struct nla_policy iface_combination_policy[NUM_NL80211_IFACE_COMB] = {
2928                         [NL80211_IFACE_COMB_LIMITS] = { .type = NLA_NESTED },
2929                         [NL80211_IFACE_COMB_MAXNUM] = { .type = NLA_U32 },
2930                 };
2931                 struct nlattr *tb_comb[NUM_NL80211_IFACE_COMB+1];
2932                 static struct nla_policy iface_limit_policy[NUM_NL80211_IFACE_LIMIT] = {
2933                         [NL80211_IFACE_LIMIT_TYPES] = { .type = NLA_NESTED },
2934                         [NL80211_IFACE_LIMIT_MAX] = { .type = NLA_U32 },
2935                 };
2936                 struct nlattr *tb_limit[NUM_NL80211_IFACE_LIMIT+1];
2937                 struct nlattr *limit;
2938
2939                 nla_parse_nested(tb_comb, NUM_NL80211_IFACE_COMB, comb, iface_combination_policy);
2940
2941                 if (!tb_comb[NL80211_IFACE_COMB_LIMITS])
2942                         continue;
2943
2944                 nla_for_each_nested(limit, tb_comb[NL80211_IFACE_COMB_LIMITS], limit_rem)
2945                 {
2946                         struct nlattr *mode;
2947
2948                         nla_parse_nested(tb_limit, NUM_NL80211_IFACE_LIMIT, limit, iface_limit_policy);
2949
2950                         if (!tb_limit[NL80211_IFACE_LIMIT_TYPES] ||
2951                             !tb_limit[NL80211_IFACE_LIMIT_MAX])
2952                                 continue;
2953
2954                         if (nla_get_u32(tb_limit[NL80211_IFACE_LIMIT_MAX]) < 2)
2955                                 continue;
2956
2957                         nla_for_each_nested(mode, tb_limit[NL80211_IFACE_LIMIT_TYPES], mode_rem) {
2958                                 if (nla_type(mode) == NL80211_IFTYPE_AP)
2959                                         *ret = 1;
2960                         }
2961                 }
2962         }
2963
2964         return NL_SKIP;
2965 }
2966
2967 static int nl80211_get_mbssid_support(const char *ifname, int *buf)
2968 {
2969         if (nl80211_request(ifname, NL80211_CMD_GET_WIPHY, 0,
2970                             nl80211_get_ifcomb_cb, buf))
2971                 return -1;
2972
2973         return 0;
2974 }
2975
2976 static int nl80211_get_hardware_id(const char *ifname, char *buf)
2977 {
2978         struct iwinfo_hardware_id *id = (struct iwinfo_hardware_id *)buf;
2979         char *phy, num[8], path[PATH_MAX];
2980         int i;
2981
2982         struct { const char *path; uint16_t *dest; } lookup[] = {
2983                 { "vendor", &id->vendor_id },
2984                 { "device", &id->device_id },
2985                 { "subsystem_vendor", &id->subsystem_vendor_id },
2986                 { "subsystem_device", &id->subsystem_device_id }
2987         };
2988
2989         memset(id, 0, sizeof(*id));
2990
2991         /* Try to determine the phy name from the given interface */
2992         phy = nl80211_ifname2phy(ifname);
2993
2994         for (i = 0; i < ARRAY_SIZE(lookup); i++)
2995         {
2996                 snprintf(path, sizeof(path), "/sys/class/%s/%s/device/%s",
2997                          phy ? "ieee80211" : "net",
2998                          phy ? phy : ifname, lookup[i].path);
2999
3000                 if (nl80211_readstr(path, num, sizeof(num)) > 0)
3001                         *lookup[i].dest = strtoul(num, NULL, 16);
3002         }
3003
3004         /* Failed to obtain hardware IDs, search board config */
3005         if (id->vendor_id == 0 || id->device_id == 0)
3006                 return iwinfo_hardware_id_from_mtd(id);
3007
3008         return 0;
3009 }
3010
3011 static const struct iwinfo_hardware_entry *
3012 nl80211_get_hardware_entry(const char *ifname)
3013 {
3014         struct iwinfo_hardware_id id;
3015
3016         if (nl80211_get_hardware_id(ifname, (char *)&id))
3017                 return NULL;
3018
3019         return iwinfo_hardware(&id);
3020 }
3021
3022 static int nl80211_get_hardware_name(const char *ifname, char *buf)
3023 {
3024         const struct iwinfo_hardware_entry *hw;
3025
3026         if (!(hw = nl80211_get_hardware_entry(ifname)))
3027                 sprintf(buf, "Generic MAC80211");
3028         else
3029                 sprintf(buf, "%s %s", hw->vendor_name, hw->device_name);
3030
3031         return 0;
3032 }
3033
3034 static int nl80211_get_txpower_offset(const char *ifname, int *buf)
3035 {
3036         const struct iwinfo_hardware_entry *hw;
3037
3038         if (!(hw = nl80211_get_hardware_entry(ifname)))
3039                 return -1;
3040
3041         *buf = hw->txpower_offset;
3042         return 0;
3043 }
3044
3045 static int nl80211_get_frequency_offset(const char *ifname, int *buf)
3046 {
3047         const struct iwinfo_hardware_entry *hw;
3048
3049         if (!(hw = nl80211_get_hardware_entry(ifname)))
3050                 return -1;
3051
3052         *buf = hw->frequency_offset;
3053         return 0;
3054 }
3055
3056 static int nl80211_lookup_phyname(const char *section, char *buf)
3057 {
3058         int idx;
3059
3060         if ((idx = nl80211_phy_idx_from_uci(section)) < 0)
3061                 return -1;
3062
3063         sprintf(buf, "phy%d", idx);
3064         return 0;
3065 }
3066
3067 const struct iwinfo_ops nl80211_ops = {
3068         .name             = "nl80211",
3069         .probe            = nl80211_probe,
3070         .channel          = nl80211_get_channel,
3071         .frequency        = nl80211_get_frequency,
3072         .frequency_offset = nl80211_get_frequency_offset,
3073         .txpower          = nl80211_get_txpower,
3074         .txpower_offset   = nl80211_get_txpower_offset,
3075         .bitrate          = nl80211_get_bitrate,
3076         .signal           = nl80211_get_signal,
3077         .noise            = nl80211_get_noise,
3078         .quality          = nl80211_get_quality,
3079         .quality_max      = nl80211_get_quality_max,
3080         .mbssid_support   = nl80211_get_mbssid_support,
3081         .hwmodelist       = nl80211_get_hwmodelist,
3082         .htmodelist       = nl80211_get_htmodelist,
3083         .mode             = nl80211_get_mode,
3084         .ssid             = nl80211_get_ssid,
3085         .bssid            = nl80211_get_bssid,
3086         .country          = nl80211_get_country,
3087         .hardware_id      = nl80211_get_hardware_id,
3088         .hardware_name    = nl80211_get_hardware_name,
3089         .encryption       = nl80211_get_encryption,
3090         .phyname          = nl80211_get_phyname,
3091         .assoclist        = nl80211_get_assoclist,
3092         .txpwrlist        = nl80211_get_txpwrlist,
3093         .scanlist         = nl80211_get_scanlist,
3094         .freqlist         = nl80211_get_freqlist,
3095         .countrylist      = nl80211_get_countrylist,
3096         .survey           = nl80211_get_survey,
3097         .lookup_phy       = nl80211_lookup_phyname,
3098         .close            = nl80211_close
3099 };