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