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