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