]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sbin/ifconfig/ifieee80211.c
MFV 312436
[FreeBSD/FreeBSD.git] / sbin / ifconfig / ifieee80211.c
1 /*
2  * Copyright 2001 The Aerospace Corporation.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  * 3. The name of The Aerospace Corporation may not be used to endorse or
13  *    promote products derived from this software.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AEROSPACE CORPORATION ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AEROSPACE CORPORATION BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  *
27  * $FreeBSD$
28  */
29
30 /*-
31  * Copyright (c) 1997, 1998, 2000 The NetBSD Foundation, Inc.
32  * All rights reserved.
33  *
34  * This code is derived from software contributed to The NetBSD Foundation
35  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
36  * NASA Ames Research Center.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions
40  * are met:
41  * 1. Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  * 2. Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in the
45  *    documentation and/or other materials provided with the distribution.
46  *
47  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
48  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
49  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
50  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
51  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
52  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
53  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
54  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
55  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
56  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
57  * POSSIBILITY OF SUCH DAMAGE.
58  */
59
60 #include <sys/param.h>
61 #include <sys/ioctl.h>
62 #include <sys/socket.h>
63 #include <sys/sysctl.h>
64 #include <sys/time.h>
65
66 #include <net/ethernet.h>
67 #include <net/if.h>
68 #include <net/if_dl.h>
69 #include <net/if_types.h>
70 #include <net/if_media.h>
71 #include <net/route.h>
72
73 #include <net80211/ieee80211_ioctl.h>
74 #include <net80211/ieee80211_freebsd.h>
75 #include <net80211/ieee80211_superg.h>
76 #include <net80211/ieee80211_tdma.h>
77 #include <net80211/ieee80211_mesh.h>
78
79 #include <assert.h>
80 #include <ctype.h>
81 #include <err.h>
82 #include <errno.h>
83 #include <fcntl.h>
84 #include <inttypes.h>
85 #include <stdio.h>
86 #include <stdlib.h>
87 #include <string.h>
88 #include <unistd.h>
89 #include <stdarg.h>
90 #include <stddef.h>             /* NB: for offsetof */
91
92 #include "ifconfig.h"
93
94 #include <lib80211/lib80211_regdomain.h>
95 #include <lib80211/lib80211_ioctl.h>
96
97 #ifndef IEEE80211_FIXED_RATE_NONE
98 #define IEEE80211_FIXED_RATE_NONE       0xff
99 #endif
100
101 /* XXX need these publicly defined or similar */
102 #ifndef IEEE80211_NODE_AUTH
103 #define IEEE80211_NODE_AUTH     0x000001        /* authorized for data */
104 #define IEEE80211_NODE_QOS      0x000002        /* QoS enabled */
105 #define IEEE80211_NODE_ERP      0x000004        /* ERP enabled */
106 #define IEEE80211_NODE_PWR_MGT  0x000010        /* power save mode enabled */
107 #define IEEE80211_NODE_AREF     0x000020        /* authentication ref held */
108 #define IEEE80211_NODE_HT       0x000040        /* HT enabled */
109 #define IEEE80211_NODE_HTCOMPAT 0x000080        /* HT setup w/ vendor OUI's */
110 #define IEEE80211_NODE_WPS      0x000100        /* WPS association */
111 #define IEEE80211_NODE_TSN      0x000200        /* TSN association */
112 #define IEEE80211_NODE_AMPDU_RX 0x000400        /* AMPDU rx enabled */
113 #define IEEE80211_NODE_AMPDU_TX 0x000800        /* AMPDU tx enabled */
114 #define IEEE80211_NODE_MIMO_PS  0x001000        /* MIMO power save enabled */
115 #define IEEE80211_NODE_MIMO_RTS 0x002000        /* send RTS in MIMO PS */
116 #define IEEE80211_NODE_RIFS     0x004000        /* RIFS enabled */
117 #define IEEE80211_NODE_SGI20    0x008000        /* Short GI in HT20 enabled */
118 #define IEEE80211_NODE_SGI40    0x010000        /* Short GI in HT40 enabled */
119 #define IEEE80211_NODE_ASSOCID  0x020000        /* xmit requires associd */
120 #define IEEE80211_NODE_AMSDU_RX 0x040000        /* AMSDU rx enabled */
121 #define IEEE80211_NODE_AMSDU_TX 0x080000        /* AMSDU tx enabled */
122 #define IEEE80211_NODE_VHT      0x100000        /* VHT enabled */
123 #endif
124
125 #define MAXCHAN 1536            /* max 1.5K channels */
126
127 #define MAXCOL  78
128 static  int col;
129 static  char spacer;
130
131 static void LINE_INIT(char c);
132 static void LINE_BREAK(void);
133 static void LINE_CHECK(const char *fmt, ...);
134
135 static const char *modename[IEEE80211_MODE_MAX] = {
136         [IEEE80211_MODE_AUTO]     = "auto",
137         [IEEE80211_MODE_11A]      = "11a",
138         [IEEE80211_MODE_11B]      = "11b",
139         [IEEE80211_MODE_11G]      = "11g",
140         [IEEE80211_MODE_FH]       = "fh",
141         [IEEE80211_MODE_TURBO_A]  = "turboA",
142         [IEEE80211_MODE_TURBO_G]  = "turboG",
143         [IEEE80211_MODE_STURBO_A] = "sturbo",
144         [IEEE80211_MODE_11NA]     = "11na",
145         [IEEE80211_MODE_11NG]     = "11ng",
146         [IEEE80211_MODE_HALF]     = "half",
147         [IEEE80211_MODE_QUARTER]  = "quarter",
148         [IEEE80211_MODE_VHT_2GHZ] = "11acg",
149         [IEEE80211_MODE_VHT_5GHZ] = "11ac",
150 };
151
152 static void set80211(int s, int type, int val, int len, void *data);
153 static int get80211(int s, int type, void *data, int len);
154 static int get80211len(int s, int type, void *data, int len, int *plen);
155 static int get80211val(int s, int type, int *val);
156 static const char *get_string(const char *val, const char *sep,
157     u_int8_t *buf, int *lenp);
158 static void print_string(const u_int8_t *buf, int len);
159 static void print_regdomain(const struct ieee80211_regdomain *, int);
160 static void print_channels(int, const struct ieee80211req_chaninfo *,
161     int allchans, int verbose);
162 static void regdomain_makechannels(struct ieee80211_regdomain_req *,
163     const struct ieee80211_devcaps_req *);
164 static const char *mesh_linkstate_string(uint8_t state);
165
166 static struct ieee80211req_chaninfo *chaninfo;
167 static struct ieee80211_regdomain regdomain;
168 static int gotregdomain = 0;
169 static struct ieee80211_roamparams_req roamparams;
170 static int gotroam = 0;
171 static struct ieee80211_txparams_req txparams;
172 static int gottxparams = 0;
173 static struct ieee80211_channel curchan;
174 static int gotcurchan = 0;
175 static struct ifmediareq *ifmr;
176 static int htconf = 0;
177 static  int gothtconf = 0;
178
179 static void
180 gethtconf(int s)
181 {
182         if (gothtconf)
183                 return;
184         if (get80211val(s, IEEE80211_IOC_HTCONF, &htconf) < 0)
185                 warn("unable to get HT configuration information");
186         gothtconf = 1;
187 }
188
189 /* VHT */
190 static int vhtconf = 0;
191 static  int gotvhtconf = 0;
192
193 static void
194 getvhtconf(int s)
195 {
196         if (gotvhtconf)
197                 return;
198         if (get80211val(s, IEEE80211_IOC_VHTCONF, &vhtconf) < 0)
199                 warn("unable to get VHT configuration information");
200         gotvhtconf = 1;
201 }
202
203 /*
204  * Collect channel info from the kernel.  We use this (mostly)
205  * to handle mapping between frequency and IEEE channel number.
206  */
207 static void
208 getchaninfo(int s)
209 {
210         if (chaninfo != NULL)
211                 return;
212         chaninfo = malloc(IEEE80211_CHANINFO_SIZE(MAXCHAN));
213         if (chaninfo == NULL)
214                 errx(1, "no space for channel list");
215         if (get80211(s, IEEE80211_IOC_CHANINFO, chaninfo,
216             IEEE80211_CHANINFO_SIZE(MAXCHAN)) < 0)
217                 err(1, "unable to get channel information");
218         ifmr = ifmedia_getstate(s);
219         gethtconf(s);
220         getvhtconf(s);
221 }
222
223 static struct regdata *
224 getregdata(void)
225 {
226         static struct regdata *rdp = NULL;
227         if (rdp == NULL) {
228                 rdp = lib80211_alloc_regdata();
229                 if (rdp == NULL)
230                         errx(-1, "missing or corrupted regdomain database");
231         }
232         return rdp;
233 }
234
235 /*
236  * Given the channel at index i with attributes from,
237  * check if there is a channel with attributes to in
238  * the channel table.  With suitable attributes this
239  * allows the caller to look for promotion; e.g. from
240  * 11b > 11g.
241  */
242 static int
243 canpromote(int i, int from, int to)
244 {
245         const struct ieee80211_channel *fc = &chaninfo->ic_chans[i];
246         u_int j;
247
248         if ((fc->ic_flags & from) != from)
249                 return i;
250         /* NB: quick check exploiting ordering of chans w/ same frequency */
251         if (i+1 < chaninfo->ic_nchans &&
252             chaninfo->ic_chans[i+1].ic_freq == fc->ic_freq &&
253             (chaninfo->ic_chans[i+1].ic_flags & to) == to)
254                 return i+1;
255         /* brute force search in case channel list is not ordered */
256         for (j = 0; j < chaninfo->ic_nchans; j++) {
257                 const struct ieee80211_channel *tc = &chaninfo->ic_chans[j];
258                 if (j != i &&
259                     tc->ic_freq == fc->ic_freq && (tc->ic_flags & to) == to)
260                 return j;
261         }
262         return i;
263 }
264
265 /*
266  * Handle channel promotion.  When a channel is specified with
267  * only a frequency we want to promote it to the ``best'' channel
268  * available.  The channel list has separate entries for 11b, 11g,
269  * 11a, and 11n[ga] channels so specifying a frequency w/o any
270  * attributes requires we upgrade, e.g. from 11b -> 11g.  This
271  * gets complicated when the channel is specified on the same
272  * command line with a media request that constrains the available
273  * channe list (e.g. mode 11a); we want to honor that to avoid
274  * confusing behaviour.
275  */
276 /*
277  * XXX VHT
278  */
279 static int
280 promote(int i)
281 {
282         /*
283          * Query the current mode of the interface in case it's
284          * constrained (e.g. to 11a).  We must do this carefully
285          * as there may be a pending ifmedia request in which case
286          * asking the kernel will give us the wrong answer.  This
287          * is an unfortunate side-effect of the way ifconfig is
288          * structure for modularity (yech).
289          *
290          * NB: ifmr is actually setup in getchaninfo (above); we
291          *     assume it's called coincident with to this call so
292          *     we have a ``current setting''; otherwise we must pass
293          *     the socket descriptor down to here so we can make
294          *     the ifmedia_getstate call ourselves.
295          */
296         int chanmode = ifmr != NULL ? IFM_MODE(ifmr->ifm_current) : IFM_AUTO;
297
298         /* when ambiguous promote to ``best'' */
299         /* NB: we abitrarily pick HT40+ over HT40- */
300         if (chanmode != IFM_IEEE80211_11B)
301                 i = canpromote(i, IEEE80211_CHAN_B, IEEE80211_CHAN_G);
302         if (chanmode != IFM_IEEE80211_11G && (htconf & 1)) {
303                 i = canpromote(i, IEEE80211_CHAN_G,
304                         IEEE80211_CHAN_G | IEEE80211_CHAN_HT20);
305                 if (htconf & 2) {
306                         i = canpromote(i, IEEE80211_CHAN_G,
307                                 IEEE80211_CHAN_G | IEEE80211_CHAN_HT40D);
308                         i = canpromote(i, IEEE80211_CHAN_G,
309                                 IEEE80211_CHAN_G | IEEE80211_CHAN_HT40U);
310                 }
311         }
312         if (chanmode != IFM_IEEE80211_11A && (htconf & 1)) {
313                 i = canpromote(i, IEEE80211_CHAN_A,
314                         IEEE80211_CHAN_A | IEEE80211_CHAN_HT20);
315                 if (htconf & 2) {
316                         i = canpromote(i, IEEE80211_CHAN_A,
317                                 IEEE80211_CHAN_A | IEEE80211_CHAN_HT40D);
318                         i = canpromote(i, IEEE80211_CHAN_A,
319                                 IEEE80211_CHAN_A | IEEE80211_CHAN_HT40U);
320                 }
321         }
322         return i;
323 }
324
325 static void
326 mapfreq(struct ieee80211_channel *chan, int freq, int flags)
327 {
328         u_int i;
329
330         for (i = 0; i < chaninfo->ic_nchans; i++) {
331                 const struct ieee80211_channel *c = &chaninfo->ic_chans[i];
332
333                 if (c->ic_freq == freq && (c->ic_flags & flags) == flags) {
334                         if (flags == 0) {
335                                 /* when ambiguous promote to ``best'' */
336                                 c = &chaninfo->ic_chans[promote(i)];
337                         }
338                         *chan = *c;
339                         return;
340                 }
341         }
342         errx(1, "unknown/undefined frequency %u/0x%x", freq, flags);
343 }
344
345 static void
346 mapchan(struct ieee80211_channel *chan, int ieee, int flags)
347 {
348         u_int i;
349
350         for (i = 0; i < chaninfo->ic_nchans; i++) {
351                 const struct ieee80211_channel *c = &chaninfo->ic_chans[i];
352
353                 if (c->ic_ieee == ieee && (c->ic_flags & flags) == flags) {
354                         if (flags == 0) {
355                                 /* when ambiguous promote to ``best'' */
356                                 c = &chaninfo->ic_chans[promote(i)];
357                         }
358                         *chan = *c;
359                         return;
360                 }
361         }
362         errx(1, "unknown/undefined channel number %d flags 0x%x", ieee, flags);
363 }
364
365 static const struct ieee80211_channel *
366 getcurchan(int s)
367 {
368         if (gotcurchan)
369                 return &curchan;
370         if (get80211(s, IEEE80211_IOC_CURCHAN, &curchan, sizeof(curchan)) < 0) {
371                 int val;
372                 /* fall back to legacy ioctl */
373                 if (get80211val(s, IEEE80211_IOC_CHANNEL, &val) < 0)
374                         err(-1, "cannot figure out current channel");
375                 getchaninfo(s);
376                 mapchan(&curchan, val, 0);
377         }
378         gotcurchan = 1;
379         return &curchan;
380 }
381
382 static enum ieee80211_phymode
383 chan2mode(const struct ieee80211_channel *c)
384 {
385         if (IEEE80211_IS_CHAN_VHTA(c))
386                 return IEEE80211_MODE_VHT_5GHZ;
387         if (IEEE80211_IS_CHAN_VHTG(c))
388                 return IEEE80211_MODE_VHT_2GHZ;
389         if (IEEE80211_IS_CHAN_HTA(c))
390                 return IEEE80211_MODE_11NA;
391         if (IEEE80211_IS_CHAN_HTG(c))
392                 return IEEE80211_MODE_11NG;
393         if (IEEE80211_IS_CHAN_108A(c))
394                 return IEEE80211_MODE_TURBO_A;
395         if (IEEE80211_IS_CHAN_108G(c))
396                 return IEEE80211_MODE_TURBO_G;
397         if (IEEE80211_IS_CHAN_ST(c))
398                 return IEEE80211_MODE_STURBO_A;
399         if (IEEE80211_IS_CHAN_FHSS(c))
400                 return IEEE80211_MODE_FH;
401         if (IEEE80211_IS_CHAN_HALF(c))
402                 return IEEE80211_MODE_HALF;
403         if (IEEE80211_IS_CHAN_QUARTER(c))
404                 return IEEE80211_MODE_QUARTER;
405         if (IEEE80211_IS_CHAN_A(c))
406                 return IEEE80211_MODE_11A;
407         if (IEEE80211_IS_CHAN_ANYG(c))
408                 return IEEE80211_MODE_11G;
409         if (IEEE80211_IS_CHAN_B(c))
410                 return IEEE80211_MODE_11B;
411         return IEEE80211_MODE_AUTO;
412 }
413
414 static void
415 getroam(int s)
416 {
417         if (gotroam)
418                 return;
419         if (get80211(s, IEEE80211_IOC_ROAM,
420             &roamparams, sizeof(roamparams)) < 0)
421                 err(1, "unable to get roaming parameters");
422         gotroam = 1;
423 }
424
425 static void
426 setroam_cb(int s, void *arg)
427 {
428         struct ieee80211_roamparams_req *roam = arg;
429         set80211(s, IEEE80211_IOC_ROAM, 0, sizeof(*roam), roam);
430 }
431
432 static void
433 gettxparams(int s)
434 {
435         if (gottxparams)
436                 return;
437         if (get80211(s, IEEE80211_IOC_TXPARAMS,
438             &txparams, sizeof(txparams)) < 0)
439                 err(1, "unable to get transmit parameters");
440         gottxparams = 1;
441 }
442
443 static void
444 settxparams_cb(int s, void *arg)
445 {
446         struct ieee80211_txparams_req *txp = arg;
447         set80211(s, IEEE80211_IOC_TXPARAMS, 0, sizeof(*txp), txp);
448 }
449
450 static void
451 getregdomain(int s)
452 {
453         if (gotregdomain)
454                 return;
455         if (get80211(s, IEEE80211_IOC_REGDOMAIN,
456             &regdomain, sizeof(regdomain)) < 0)
457                 err(1, "unable to get regulatory domain info");
458         gotregdomain = 1;
459 }
460
461 static void
462 getdevcaps(int s, struct ieee80211_devcaps_req *dc)
463 {
464         if (get80211(s, IEEE80211_IOC_DEVCAPS, dc,
465             IEEE80211_DEVCAPS_SPACE(dc)) < 0)
466                 err(1, "unable to get device capabilities");
467 }
468
469 static void
470 setregdomain_cb(int s, void *arg)
471 {
472         struct ieee80211_regdomain_req *req;
473         struct ieee80211_regdomain *rd = arg;
474         struct ieee80211_devcaps_req *dc;
475         struct regdata *rdp = getregdata();
476
477         if (rd->country != NO_COUNTRY) {
478                 const struct country *cc;
479                 /*
480                  * Check current country seting to make sure it's
481                  * compatible with the new regdomain.  If not, then
482                  * override it with any default country for this
483                  * SKU.  If we cannot arrange a match, then abort.
484                  */
485                 cc = lib80211_country_findbycc(rdp, rd->country);
486                 if (cc == NULL)
487                         errx(1, "unknown ISO country code %d", rd->country);
488                 if (cc->rd->sku != rd->regdomain) {
489                         const struct regdomain *rp;
490                         /*
491                          * Check if country is incompatible with regdomain.
492                          * To enable multiple regdomains for a country code
493                          * we permit a mismatch between the regdomain and
494                          * the country's associated regdomain when the
495                          * regdomain is setup w/o a default country.  For
496                          * example, US is bound to the FCC regdomain but
497                          * we allow US to be combined with FCC3 because FCC3
498                          * has not default country.  This allows bogus
499                          * combinations like FCC3+DK which are resolved when
500                          * constructing the channel list by deferring to the
501                          * regdomain to construct the channel list.
502                          */
503                         rp = lib80211_regdomain_findbysku(rdp, rd->regdomain);
504                         if (rp == NULL)
505                                 errx(1, "country %s (%s) is not usable with "
506                                     "regdomain %d", cc->isoname, cc->name,
507                                     rd->regdomain);
508                         else if (rp->cc != NULL && rp->cc != cc)
509                                 errx(1, "country %s (%s) is not usable with "
510                                    "regdomain %s", cc->isoname, cc->name,
511                                    rp->name);
512                 }
513         }
514         /*
515          * Fetch the device capabilities and calculate the
516          * full set of netbands for which we request a new
517          * channel list be constructed.  Once that's done we
518          * push the regdomain info + channel list to the kernel.
519          */
520         dc = malloc(IEEE80211_DEVCAPS_SIZE(MAXCHAN));
521         if (dc == NULL)
522                 errx(1, "no space for device capabilities");
523         dc->dc_chaninfo.ic_nchans = MAXCHAN;
524         getdevcaps(s, dc);
525 #if 0
526         if (verbose) {
527                 printf("drivercaps: 0x%x\n", dc->dc_drivercaps);
528                 printf("cryptocaps: 0x%x\n", dc->dc_cryptocaps);
529                 printf("htcaps    : 0x%x\n", dc->dc_htcaps);
530                 printf("vhtcaps   : 0x%x\n", dc->dc_vhtcaps);
531 #if 0
532                 memcpy(chaninfo, &dc->dc_chaninfo,
533                     IEEE80211_CHANINFO_SPACE(&dc->dc_chaninfo));
534                 print_channels(s, &dc->dc_chaninfo, 1/*allchans*/, 1/*verbose*/);
535 #endif
536         }
537 #endif
538         req = malloc(IEEE80211_REGDOMAIN_SIZE(dc->dc_chaninfo.ic_nchans));
539         if (req == NULL)
540                 errx(1, "no space for regdomain request");
541         req->rd = *rd;
542         regdomain_makechannels(req, dc);
543         if (verbose) {
544                 LINE_INIT(':');
545                 print_regdomain(rd, 1/*verbose*/);
546                 LINE_BREAK();
547                 /* blech, reallocate channel list for new data */
548                 if (chaninfo != NULL)
549                         free(chaninfo);
550                 chaninfo = malloc(IEEE80211_CHANINFO_SPACE(&req->chaninfo));
551                 if (chaninfo == NULL)
552                         errx(1, "no space for channel list");
553                 memcpy(chaninfo, &req->chaninfo,
554                     IEEE80211_CHANINFO_SPACE(&req->chaninfo));
555                 print_channels(s, &req->chaninfo, 1/*allchans*/, 1/*verbose*/);
556         }
557         if (req->chaninfo.ic_nchans == 0)
558                 errx(1, "no channels calculated");
559         set80211(s, IEEE80211_IOC_REGDOMAIN, 0,
560             IEEE80211_REGDOMAIN_SPACE(req), req);
561         free(req);
562         free(dc);
563 }
564
565 static int
566 ieee80211_mhz2ieee(int freq, int flags)
567 {
568         struct ieee80211_channel chan;
569         mapfreq(&chan, freq, flags);
570         return chan.ic_ieee;
571 }
572
573 static int
574 isanyarg(const char *arg)
575 {
576         return (strncmp(arg, "-", 1) == 0 ||
577             strncasecmp(arg, "any", 3) == 0 || strncasecmp(arg, "off", 3) == 0);
578 }
579
580 static void
581 set80211ssid(const char *val, int d, int s, const struct afswtch *rafp)
582 {
583         int             ssid;
584         int             len;
585         u_int8_t        data[IEEE80211_NWID_LEN];
586
587         ssid = 0;
588         len = strlen(val);
589         if (len > 2 && isdigit((int)val[0]) && val[1] == ':') {
590                 ssid = atoi(val)-1;
591                 val += 2;
592         }
593
594         bzero(data, sizeof(data));
595         len = sizeof(data);
596         if (get_string(val, NULL, data, &len) == NULL)
597                 exit(1);
598
599         set80211(s, IEEE80211_IOC_SSID, ssid, len, data);
600 }
601
602 static void
603 set80211meshid(const char *val, int d, int s, const struct afswtch *rafp)
604 {
605         int             len;
606         u_int8_t        data[IEEE80211_NWID_LEN];
607
608         memset(data, 0, sizeof(data));
609         len = sizeof(data);
610         if (get_string(val, NULL, data, &len) == NULL)
611                 exit(1);
612
613         set80211(s, IEEE80211_IOC_MESH_ID, 0, len, data);
614 }       
615
616 static void
617 set80211stationname(const char *val, int d, int s, const struct afswtch *rafp)
618 {
619         int                     len;
620         u_int8_t                data[33];
621
622         bzero(data, sizeof(data));
623         len = sizeof(data);
624         get_string(val, NULL, data, &len);
625
626         set80211(s, IEEE80211_IOC_STATIONNAME, 0, len, data);
627 }
628
629 /*
630  * Parse a channel specification for attributes/flags.
631  * The syntax is:
632  *      freq/xx         channel width (5,10,20,40,40+,40-)
633  *      freq:mode       channel mode (a,b,g,h,n,t,s,d)
634  *
635  * These can be combined in either order; e.g. 2437:ng/40.
636  * Modes are case insensitive.
637  *
638  * The result is not validated here; it's assumed to be
639  * checked against the channel table fetched from the kernel.
640  */ 
641 static int
642 getchannelflags(const char *val, int freq)
643 {
644 #define _CHAN_HT        0x80000000
645         const char *cp;
646         int flags;
647         int is_vht = 0;
648
649         flags = 0;
650
651         cp = strchr(val, ':');
652         if (cp != NULL) {
653                 for (cp++; isalpha((int) *cp); cp++) {
654                         /* accept mixed case */
655                         int c = *cp;
656                         if (isupper(c))
657                                 c = tolower(c);
658                         switch (c) {
659                         case 'a':               /* 802.11a */
660                                 flags |= IEEE80211_CHAN_A;
661                                 break;
662                         case 'b':               /* 802.11b */
663                                 flags |= IEEE80211_CHAN_B;
664                                 break;
665                         case 'g':               /* 802.11g */
666                                 flags |= IEEE80211_CHAN_G;
667                                 break;
668                         case 'v':               /* vht: 802.11ac */
669                                 is_vht = 1;
670                                 /* Fallthrough */
671                         case 'h':               /* ht = 802.11n */
672                         case 'n':               /* 802.11n */
673                                 flags |= _CHAN_HT;      /* NB: private */
674                                 break;
675                         case 'd':               /* dt = Atheros Dynamic Turbo */
676                                 flags |= IEEE80211_CHAN_TURBO;
677                                 break;
678                         case 't':               /* ht, dt, st, t */
679                                 /* dt and unadorned t specify Dynamic Turbo */
680                                 if ((flags & (IEEE80211_CHAN_STURBO|_CHAN_HT)) == 0)
681                                         flags |= IEEE80211_CHAN_TURBO;
682                                 break;
683                         case 's':               /* st = Atheros Static Turbo */
684                                 flags |= IEEE80211_CHAN_STURBO;
685                                 break;
686                         default:
687                                 errx(-1, "%s: Invalid channel attribute %c\n",
688                                     val, *cp);
689                         }
690                 }
691         }
692         cp = strchr(val, '/');
693         if (cp != NULL) {
694                 char *ep;
695                 u_long cw = strtoul(cp+1, &ep, 10);
696
697                 switch (cw) {
698                 case 5:
699                         flags |= IEEE80211_CHAN_QUARTER;
700                         break;
701                 case 10:
702                         flags |= IEEE80211_CHAN_HALF;
703                         break;
704                 case 20:
705                         /* NB: this may be removed below */
706                         flags |= IEEE80211_CHAN_HT20;
707                         break;
708                 case 40:
709                 case 80:
710                 case 160:
711                         /* Handle the 80/160 VHT flag */
712                         if (cw == 80)
713                                 flags |= IEEE80211_CHAN_VHT80;
714                         else if (cw == 160)
715                                 flags |= IEEE80211_CHAN_VHT160;
716
717                         /* Fallthrough */
718                         if (ep != NULL && *ep == '+')
719                                 flags |= IEEE80211_CHAN_HT40U;
720                         else if (ep != NULL && *ep == '-')
721                                 flags |= IEEE80211_CHAN_HT40D;
722                         break;
723                 default:
724                         errx(-1, "%s: Invalid channel width\n", val);
725                 }
726         }
727
728         /*
729          * Cleanup specifications.
730          */ 
731         if ((flags & _CHAN_HT) == 0) {
732                 /*
733                  * If user specified freq/20 or freq/40 quietly remove
734                  * HT cw attributes depending on channel use.  To give
735                  * an explicit 20/40 width for an HT channel you must
736                  * indicate it is an HT channel since all HT channels
737                  * are also usable for legacy operation; e.g. freq:n/40.
738                  */
739                 flags &= ~IEEE80211_CHAN_HT;
740                 flags &= ~IEEE80211_CHAN_VHT;
741         } else {
742                 /*
743                  * Remove private indicator that this is an HT channel
744                  * and if no explicit channel width has been given
745                  * provide the default settings.
746                  */
747                 flags &= ~_CHAN_HT;
748                 if ((flags & IEEE80211_CHAN_HT) == 0) {
749                         struct ieee80211_channel chan;
750                         /*
751                          * Consult the channel list to see if we can use
752                          * HT40+ or HT40- (if both the map routines choose).
753                          */
754                         if (freq > 255)
755                                 mapfreq(&chan, freq, 0);
756                         else
757                                 mapchan(&chan, freq, 0);
758                         flags |= (chan.ic_flags & IEEE80211_CHAN_HT);
759                 }
760
761                 /*
762                  * If VHT is enabled, then also set the VHT flag and the
763                  * relevant channel up/down.
764                  */
765                 if (is_vht && (flags & IEEE80211_CHAN_HT)) {
766                         /*
767                          * XXX yes, maybe we should just have VHT, and reuse
768                          * HT20/HT40U/HT40D
769                          */
770                         if (flags & IEEE80211_CHAN_VHT80)
771                                 ;
772                         else if (flags & IEEE80211_CHAN_HT20)
773                                 flags |= IEEE80211_CHAN_VHT20;
774                         else if (flags & IEEE80211_CHAN_HT40U)
775                                 flags |= IEEE80211_CHAN_VHT40U;
776                         else if (flags & IEEE80211_CHAN_HT40D)
777                                 flags |= IEEE80211_CHAN_VHT40D;
778                 }
779         }
780         return flags;
781 #undef _CHAN_HT
782 }
783
784 static void
785 getchannel(int s, struct ieee80211_channel *chan, const char *val)
786 {
787         int v, flags;
788         char *eptr;
789
790         memset(chan, 0, sizeof(*chan));
791         if (isanyarg(val)) {
792                 chan->ic_freq = IEEE80211_CHAN_ANY;
793                 return;
794         }
795         getchaninfo(s);
796         errno = 0;
797         v = strtol(val, &eptr, 10);
798         if (val[0] == '\0' || val == eptr || errno == ERANGE ||
799             /* channel may be suffixed with nothing, :flag, or /width */
800             (eptr[0] != '\0' && eptr[0] != ':' && eptr[0] != '/'))
801                 errx(1, "invalid channel specification%s",
802                     errno == ERANGE ? " (out of range)" : "");
803         flags = getchannelflags(val, v);
804         if (v > 255) {          /* treat as frequency */
805                 mapfreq(chan, v, flags);
806         } else {
807                 mapchan(chan, v, flags);
808         }
809 }
810
811 static void
812 set80211channel(const char *val, int d, int s, const struct afswtch *rafp)
813 {
814         struct ieee80211_channel chan;
815
816         getchannel(s, &chan, val);
817         set80211(s, IEEE80211_IOC_CURCHAN, 0, sizeof(chan), &chan);
818 }
819
820 static void
821 set80211chanswitch(const char *val, int d, int s, const struct afswtch *rafp)
822 {
823         struct ieee80211_chanswitch_req csr;
824
825         getchannel(s, &csr.csa_chan, val);
826         csr.csa_mode = 1;
827         csr.csa_count = 5;
828         set80211(s, IEEE80211_IOC_CHANSWITCH, 0, sizeof(csr), &csr);
829 }
830
831 static void
832 set80211authmode(const char *val, int d, int s, const struct afswtch *rafp)
833 {
834         int     mode;
835
836         if (strcasecmp(val, "none") == 0) {
837                 mode = IEEE80211_AUTH_NONE;
838         } else if (strcasecmp(val, "open") == 0) {
839                 mode = IEEE80211_AUTH_OPEN;
840         } else if (strcasecmp(val, "shared") == 0) {
841                 mode = IEEE80211_AUTH_SHARED;
842         } else if (strcasecmp(val, "8021x") == 0) {
843                 mode = IEEE80211_AUTH_8021X;
844         } else if (strcasecmp(val, "wpa") == 0) {
845                 mode = IEEE80211_AUTH_WPA;
846         } else {
847                 errx(1, "unknown authmode");
848         }
849
850         set80211(s, IEEE80211_IOC_AUTHMODE, mode, 0, NULL);
851 }
852
853 static void
854 set80211powersavemode(const char *val, int d, int s, const struct afswtch *rafp)
855 {
856         int     mode;
857
858         if (strcasecmp(val, "off") == 0) {
859                 mode = IEEE80211_POWERSAVE_OFF;
860         } else if (strcasecmp(val, "on") == 0) {
861                 mode = IEEE80211_POWERSAVE_ON;
862         } else if (strcasecmp(val, "cam") == 0) {
863                 mode = IEEE80211_POWERSAVE_CAM;
864         } else if (strcasecmp(val, "psp") == 0) {
865                 mode = IEEE80211_POWERSAVE_PSP;
866         } else if (strcasecmp(val, "psp-cam") == 0) {
867                 mode = IEEE80211_POWERSAVE_PSP_CAM;
868         } else {
869                 errx(1, "unknown powersavemode");
870         }
871
872         set80211(s, IEEE80211_IOC_POWERSAVE, mode, 0, NULL);
873 }
874
875 static void
876 set80211powersave(const char *val, int d, int s, const struct afswtch *rafp)
877 {
878         if (d == 0)
879                 set80211(s, IEEE80211_IOC_POWERSAVE, IEEE80211_POWERSAVE_OFF,
880                     0, NULL);
881         else
882                 set80211(s, IEEE80211_IOC_POWERSAVE, IEEE80211_POWERSAVE_ON,
883                     0, NULL);
884 }
885
886 static void
887 set80211powersavesleep(const char *val, int d, int s, const struct afswtch *rafp)
888 {
889         set80211(s, IEEE80211_IOC_POWERSAVESLEEP, atoi(val), 0, NULL);
890 }
891
892 static void
893 set80211wepmode(const char *val, int d, int s, const struct afswtch *rafp)
894 {
895         int     mode;
896
897         if (strcasecmp(val, "off") == 0) {
898                 mode = IEEE80211_WEP_OFF;
899         } else if (strcasecmp(val, "on") == 0) {
900                 mode = IEEE80211_WEP_ON;
901         } else if (strcasecmp(val, "mixed") == 0) {
902                 mode = IEEE80211_WEP_MIXED;
903         } else {
904                 errx(1, "unknown wep mode");
905         }
906
907         set80211(s, IEEE80211_IOC_WEP, mode, 0, NULL);
908 }
909
910 static void
911 set80211wep(const char *val, int d, int s, const struct afswtch *rafp)
912 {
913         set80211(s, IEEE80211_IOC_WEP, d, 0, NULL);
914 }
915
916 static int
917 isundefarg(const char *arg)
918 {
919         return (strcmp(arg, "-") == 0 || strncasecmp(arg, "undef", 5) == 0);
920 }
921
922 static void
923 set80211weptxkey(const char *val, int d, int s, const struct afswtch *rafp)
924 {
925         if (isundefarg(val))
926                 set80211(s, IEEE80211_IOC_WEPTXKEY, IEEE80211_KEYIX_NONE, 0, NULL);
927         else
928                 set80211(s, IEEE80211_IOC_WEPTXKEY, atoi(val)-1, 0, NULL);
929 }
930
931 static void
932 set80211wepkey(const char *val, int d, int s, const struct afswtch *rafp)
933 {
934         int             key = 0;
935         int             len;
936         u_int8_t        data[IEEE80211_KEYBUF_SIZE];
937
938         if (isdigit((int)val[0]) && val[1] == ':') {
939                 key = atoi(val)-1;
940                 val += 2;
941         }
942
943         bzero(data, sizeof(data));
944         len = sizeof(data);
945         get_string(val, NULL, data, &len);
946
947         set80211(s, IEEE80211_IOC_WEPKEY, key, len, data);
948 }
949
950 /*
951  * This function is purely a NetBSD compatibility interface.  The NetBSD
952  * interface is too inflexible, but it's there so we'll support it since
953  * it's not all that hard.
954  */
955 static void
956 set80211nwkey(const char *val, int d, int s, const struct afswtch *rafp)
957 {
958         int             txkey;
959         int             i, len;
960         u_int8_t        data[IEEE80211_KEYBUF_SIZE];
961
962         set80211(s, IEEE80211_IOC_WEP, IEEE80211_WEP_ON, 0, NULL);
963
964         if (isdigit((int)val[0]) && val[1] == ':') {
965                 txkey = val[0]-'0'-1;
966                 val += 2;
967
968                 for (i = 0; i < 4; i++) {
969                         bzero(data, sizeof(data));
970                         len = sizeof(data);
971                         val = get_string(val, ",", data, &len);
972                         if (val == NULL)
973                                 exit(1);
974
975                         set80211(s, IEEE80211_IOC_WEPKEY, i, len, data);
976                 }
977         } else {
978                 bzero(data, sizeof(data));
979                 len = sizeof(data);
980                 get_string(val, NULL, data, &len);
981                 txkey = 0;
982
983                 set80211(s, IEEE80211_IOC_WEPKEY, 0, len, data);
984
985                 bzero(data, sizeof(data));
986                 for (i = 1; i < 4; i++)
987                         set80211(s, IEEE80211_IOC_WEPKEY, i, 0, data);
988         }
989
990         set80211(s, IEEE80211_IOC_WEPTXKEY, txkey, 0, NULL);
991 }
992
993 static void
994 set80211rtsthreshold(const char *val, int d, int s, const struct afswtch *rafp)
995 {
996         set80211(s, IEEE80211_IOC_RTSTHRESHOLD,
997                 isundefarg(val) ? IEEE80211_RTS_MAX : atoi(val), 0, NULL);
998 }
999
1000 static void
1001 set80211protmode(const char *val, int d, int s, const struct afswtch *rafp)
1002 {
1003         int     mode;
1004
1005         if (strcasecmp(val, "off") == 0) {
1006                 mode = IEEE80211_PROTMODE_OFF;
1007         } else if (strcasecmp(val, "cts") == 0) {
1008                 mode = IEEE80211_PROTMODE_CTS;
1009         } else if (strncasecmp(val, "rtscts", 3) == 0) {
1010                 mode = IEEE80211_PROTMODE_RTSCTS;
1011         } else {
1012                 errx(1, "unknown protection mode");
1013         }
1014
1015         set80211(s, IEEE80211_IOC_PROTMODE, mode, 0, NULL);
1016 }
1017
1018 static void
1019 set80211htprotmode(const char *val, int d, int s, const struct afswtch *rafp)
1020 {
1021         int     mode;
1022
1023         if (strcasecmp(val, "off") == 0) {
1024                 mode = IEEE80211_PROTMODE_OFF;
1025         } else if (strncasecmp(val, "rts", 3) == 0) {
1026                 mode = IEEE80211_PROTMODE_RTSCTS;
1027         } else {
1028                 errx(1, "unknown protection mode");
1029         }
1030
1031         set80211(s, IEEE80211_IOC_HTPROTMODE, mode, 0, NULL);
1032 }
1033
1034 static void
1035 set80211txpower(const char *val, int d, int s, const struct afswtch *rafp)
1036 {
1037         double v = atof(val);
1038         int txpow;
1039
1040         txpow = (int) (2*v);
1041         if (txpow != 2*v)
1042                 errx(-1, "invalid tx power (must be .5 dBm units)");
1043         set80211(s, IEEE80211_IOC_TXPOWER, txpow, 0, NULL);
1044 }
1045
1046 #define IEEE80211_ROAMING_DEVICE        0
1047 #define IEEE80211_ROAMING_AUTO          1
1048 #define IEEE80211_ROAMING_MANUAL        2
1049
1050 static void
1051 set80211roaming(const char *val, int d, int s, const struct afswtch *rafp)
1052 {
1053         int mode;
1054
1055         if (strcasecmp(val, "device") == 0) {
1056                 mode = IEEE80211_ROAMING_DEVICE;
1057         } else if (strcasecmp(val, "auto") == 0) {
1058                 mode = IEEE80211_ROAMING_AUTO;
1059         } else if (strcasecmp(val, "manual") == 0) {
1060                 mode = IEEE80211_ROAMING_MANUAL;
1061         } else {
1062                 errx(1, "unknown roaming mode");
1063         }
1064         set80211(s, IEEE80211_IOC_ROAMING, mode, 0, NULL);
1065 }
1066
1067 static void
1068 set80211wme(const char *val, int d, int s, const struct afswtch *rafp)
1069 {
1070         set80211(s, IEEE80211_IOC_WME, d, 0, NULL);
1071 }
1072
1073 static void
1074 set80211hidessid(const char *val, int d, int s, const struct afswtch *rafp)
1075 {
1076         set80211(s, IEEE80211_IOC_HIDESSID, d, 0, NULL);
1077 }
1078
1079 static void
1080 set80211apbridge(const char *val, int d, int s, const struct afswtch *rafp)
1081 {
1082         set80211(s, IEEE80211_IOC_APBRIDGE, d, 0, NULL);
1083 }
1084
1085 static void
1086 set80211fastframes(const char *val, int d, int s, const struct afswtch *rafp)
1087 {
1088         set80211(s, IEEE80211_IOC_FF, d, 0, NULL);
1089 }
1090
1091 static void
1092 set80211dturbo(const char *val, int d, int s, const struct afswtch *rafp)
1093 {
1094         set80211(s, IEEE80211_IOC_TURBOP, d, 0, NULL);
1095 }
1096
1097 static void
1098 set80211chanlist(const char *val, int d, int s, const struct afswtch *rafp)
1099 {
1100         struct ieee80211req_chanlist chanlist;
1101         char *temp, *cp, *tp;
1102
1103         temp = malloc(strlen(val) + 1);
1104         if (temp == NULL)
1105                 errx(1, "malloc failed");
1106         strcpy(temp, val);
1107         memset(&chanlist, 0, sizeof(chanlist));
1108         cp = temp;
1109         for (;;) {
1110                 int first, last, f, c;
1111
1112                 tp = strchr(cp, ',');
1113                 if (tp != NULL)
1114                         *tp++ = '\0';
1115                 switch (sscanf(cp, "%u-%u", &first, &last)) {
1116                 case 1:
1117                         if (first > IEEE80211_CHAN_MAX)
1118                                 errx(-1, "channel %u out of range, max %u",
1119                                         first, IEEE80211_CHAN_MAX);
1120                         setbit(chanlist.ic_channels, first);
1121                         break;
1122                 case 2:
1123                         if (first > IEEE80211_CHAN_MAX)
1124                                 errx(-1, "channel %u out of range, max %u",
1125                                         first, IEEE80211_CHAN_MAX);
1126                         if (last > IEEE80211_CHAN_MAX)
1127                                 errx(-1, "channel %u out of range, max %u",
1128                                         last, IEEE80211_CHAN_MAX);
1129                         if (first > last)
1130                                 errx(-1, "void channel range, %u > %u",
1131                                         first, last);
1132                         for (f = first; f <= last; f++)
1133                                 setbit(chanlist.ic_channels, f);
1134                         break;
1135                 }
1136                 if (tp == NULL)
1137                         break;
1138                 c = *tp;
1139                 while (isspace(c))
1140                         tp++;
1141                 if (!isdigit(c))
1142                         break;
1143                 cp = tp;
1144         }
1145         set80211(s, IEEE80211_IOC_CHANLIST, 0, sizeof(chanlist), &chanlist);
1146 }
1147
1148 static void
1149 set80211bssid(const char *val, int d, int s, const struct afswtch *rafp)
1150 {
1151
1152         if (!isanyarg(val)) {
1153                 char *temp;
1154                 struct sockaddr_dl sdl;
1155
1156                 temp = malloc(strlen(val) + 2); /* ':' and '\0' */
1157                 if (temp == NULL)
1158                         errx(1, "malloc failed");
1159                 temp[0] = ':';
1160                 strcpy(temp + 1, val);
1161                 sdl.sdl_len = sizeof(sdl);
1162                 link_addr(temp, &sdl);
1163                 free(temp);
1164                 if (sdl.sdl_alen != IEEE80211_ADDR_LEN)
1165                         errx(1, "malformed link-level address");
1166                 set80211(s, IEEE80211_IOC_BSSID, 0,
1167                         IEEE80211_ADDR_LEN, LLADDR(&sdl));
1168         } else {
1169                 uint8_t zerobssid[IEEE80211_ADDR_LEN];
1170                 memset(zerobssid, 0, sizeof(zerobssid));
1171                 set80211(s, IEEE80211_IOC_BSSID, 0,
1172                         IEEE80211_ADDR_LEN, zerobssid);
1173         }
1174 }
1175
1176 static int
1177 getac(const char *ac)
1178 {
1179         if (strcasecmp(ac, "ac_be") == 0 || strcasecmp(ac, "be") == 0)
1180                 return WME_AC_BE;
1181         if (strcasecmp(ac, "ac_bk") == 0 || strcasecmp(ac, "bk") == 0)
1182                 return WME_AC_BK;
1183         if (strcasecmp(ac, "ac_vi") == 0 || strcasecmp(ac, "vi") == 0)
1184                 return WME_AC_VI;
1185         if (strcasecmp(ac, "ac_vo") == 0 || strcasecmp(ac, "vo") == 0)
1186                 return WME_AC_VO;
1187         errx(1, "unknown wme access class %s", ac);
1188 }
1189
1190 static
1191 DECL_CMD_FUNC2(set80211cwmin, ac, val)
1192 {
1193         set80211(s, IEEE80211_IOC_WME_CWMIN, atoi(val), getac(ac), NULL);
1194 }
1195
1196 static
1197 DECL_CMD_FUNC2(set80211cwmax, ac, val)
1198 {
1199         set80211(s, IEEE80211_IOC_WME_CWMAX, atoi(val), getac(ac), NULL);
1200 }
1201
1202 static
1203 DECL_CMD_FUNC2(set80211aifs, ac, val)
1204 {
1205         set80211(s, IEEE80211_IOC_WME_AIFS, atoi(val), getac(ac), NULL);
1206 }
1207
1208 static
1209 DECL_CMD_FUNC2(set80211txoplimit, ac, val)
1210 {
1211         set80211(s, IEEE80211_IOC_WME_TXOPLIMIT, atoi(val), getac(ac), NULL);
1212 }
1213
1214 static
1215 DECL_CMD_FUNC(set80211acm, ac, d)
1216 {
1217         set80211(s, IEEE80211_IOC_WME_ACM, 1, getac(ac), NULL);
1218 }
1219 static
1220 DECL_CMD_FUNC(set80211noacm, ac, d)
1221 {
1222         set80211(s, IEEE80211_IOC_WME_ACM, 0, getac(ac), NULL);
1223 }
1224
1225 static
1226 DECL_CMD_FUNC(set80211ackpolicy, ac, d)
1227 {
1228         set80211(s, IEEE80211_IOC_WME_ACKPOLICY, 1, getac(ac), NULL);
1229 }
1230 static
1231 DECL_CMD_FUNC(set80211noackpolicy, ac, d)
1232 {
1233         set80211(s, IEEE80211_IOC_WME_ACKPOLICY, 0, getac(ac), NULL);
1234 }
1235
1236 static
1237 DECL_CMD_FUNC2(set80211bsscwmin, ac, val)
1238 {
1239         set80211(s, IEEE80211_IOC_WME_CWMIN, atoi(val),
1240                 getac(ac)|IEEE80211_WMEPARAM_BSS, NULL);
1241 }
1242
1243 static
1244 DECL_CMD_FUNC2(set80211bsscwmax, ac, val)
1245 {
1246         set80211(s, IEEE80211_IOC_WME_CWMAX, atoi(val),
1247                 getac(ac)|IEEE80211_WMEPARAM_BSS, NULL);
1248 }
1249
1250 static
1251 DECL_CMD_FUNC2(set80211bssaifs, ac, val)
1252 {
1253         set80211(s, IEEE80211_IOC_WME_AIFS, atoi(val),
1254                 getac(ac)|IEEE80211_WMEPARAM_BSS, NULL);
1255 }
1256
1257 static
1258 DECL_CMD_FUNC2(set80211bsstxoplimit, ac, val)
1259 {
1260         set80211(s, IEEE80211_IOC_WME_TXOPLIMIT, atoi(val),
1261                 getac(ac)|IEEE80211_WMEPARAM_BSS, NULL);
1262 }
1263
1264 static
1265 DECL_CMD_FUNC(set80211dtimperiod, val, d)
1266 {
1267         set80211(s, IEEE80211_IOC_DTIM_PERIOD, atoi(val), 0, NULL);
1268 }
1269
1270 static
1271 DECL_CMD_FUNC(set80211bintval, val, d)
1272 {
1273         set80211(s, IEEE80211_IOC_BEACON_INTERVAL, atoi(val), 0, NULL);
1274 }
1275
1276 static void
1277 set80211macmac(int s, int op, const char *val)
1278 {
1279         char *temp;
1280         struct sockaddr_dl sdl;
1281
1282         temp = malloc(strlen(val) + 2); /* ':' and '\0' */
1283         if (temp == NULL)
1284                 errx(1, "malloc failed");
1285         temp[0] = ':';
1286         strcpy(temp + 1, val);
1287         sdl.sdl_len = sizeof(sdl);
1288         link_addr(temp, &sdl);
1289         free(temp);
1290         if (sdl.sdl_alen != IEEE80211_ADDR_LEN)
1291                 errx(1, "malformed link-level address");
1292         set80211(s, op, 0, IEEE80211_ADDR_LEN, LLADDR(&sdl));
1293 }
1294
1295 static
1296 DECL_CMD_FUNC(set80211addmac, val, d)
1297 {
1298         set80211macmac(s, IEEE80211_IOC_ADDMAC, val);
1299 }
1300
1301 static
1302 DECL_CMD_FUNC(set80211delmac, val, d)
1303 {
1304         set80211macmac(s, IEEE80211_IOC_DELMAC, val);
1305 }
1306
1307 static
1308 DECL_CMD_FUNC(set80211kickmac, val, d)
1309 {
1310         char *temp;
1311         struct sockaddr_dl sdl;
1312         struct ieee80211req_mlme mlme;
1313
1314         temp = malloc(strlen(val) + 2); /* ':' and '\0' */
1315         if (temp == NULL)
1316                 errx(1, "malloc failed");
1317         temp[0] = ':';
1318         strcpy(temp + 1, val);
1319         sdl.sdl_len = sizeof(sdl);
1320         link_addr(temp, &sdl);
1321         free(temp);
1322         if (sdl.sdl_alen != IEEE80211_ADDR_LEN)
1323                 errx(1, "malformed link-level address");
1324         memset(&mlme, 0, sizeof(mlme));
1325         mlme.im_op = IEEE80211_MLME_DEAUTH;
1326         mlme.im_reason = IEEE80211_REASON_AUTH_EXPIRE;
1327         memcpy(mlme.im_macaddr, LLADDR(&sdl), IEEE80211_ADDR_LEN);
1328         set80211(s, IEEE80211_IOC_MLME, 0, sizeof(mlme), &mlme);
1329 }
1330
1331 static
1332 DECL_CMD_FUNC(set80211maccmd, val, d)
1333 {
1334         set80211(s, IEEE80211_IOC_MACCMD, d, 0, NULL);
1335 }
1336
1337 static void
1338 set80211meshrtmac(int s, int req, const char *val)
1339 {
1340         char *temp;
1341         struct sockaddr_dl sdl;
1342
1343         temp = malloc(strlen(val) + 2); /* ':' and '\0' */
1344         if (temp == NULL)
1345                 errx(1, "malloc failed");
1346         temp[0] = ':';
1347         strcpy(temp + 1, val);
1348         sdl.sdl_len = sizeof(sdl);
1349         link_addr(temp, &sdl);
1350         free(temp);
1351         if (sdl.sdl_alen != IEEE80211_ADDR_LEN)
1352                 errx(1, "malformed link-level address");
1353         set80211(s, IEEE80211_IOC_MESH_RTCMD, req,
1354             IEEE80211_ADDR_LEN, LLADDR(&sdl));
1355 }
1356
1357 static
1358 DECL_CMD_FUNC(set80211addmeshrt, val, d)
1359 {
1360         set80211meshrtmac(s, IEEE80211_MESH_RTCMD_ADD, val);
1361 }
1362
1363 static
1364 DECL_CMD_FUNC(set80211delmeshrt, val, d)
1365 {
1366         set80211meshrtmac(s, IEEE80211_MESH_RTCMD_DELETE, val);
1367 }
1368
1369 static
1370 DECL_CMD_FUNC(set80211meshrtcmd, val, d)
1371 {
1372         set80211(s, IEEE80211_IOC_MESH_RTCMD, d, 0, NULL);
1373 }
1374
1375 static
1376 DECL_CMD_FUNC(set80211hwmprootmode, val, d)
1377 {
1378         int mode;
1379
1380         if (strcasecmp(val, "normal") == 0)
1381                 mode = IEEE80211_HWMP_ROOTMODE_NORMAL;
1382         else if (strcasecmp(val, "proactive") == 0)
1383                 mode = IEEE80211_HWMP_ROOTMODE_PROACTIVE;
1384         else if (strcasecmp(val, "rann") == 0)
1385                 mode = IEEE80211_HWMP_ROOTMODE_RANN;
1386         else
1387                 mode = IEEE80211_HWMP_ROOTMODE_DISABLED;
1388         set80211(s, IEEE80211_IOC_HWMP_ROOTMODE, mode, 0, NULL);
1389 }
1390
1391 static
1392 DECL_CMD_FUNC(set80211hwmpmaxhops, val, d)
1393 {
1394         set80211(s, IEEE80211_IOC_HWMP_MAXHOPS, atoi(val), 0, NULL);
1395 }
1396
1397 static void
1398 set80211pureg(const char *val, int d, int s, const struct afswtch *rafp)
1399 {
1400         set80211(s, IEEE80211_IOC_PUREG, d, 0, NULL);
1401 }
1402
1403 static void
1404 set80211quiet(const char *val, int d, int s, const struct afswtch *rafp)
1405 {
1406         set80211(s, IEEE80211_IOC_QUIET, d, 0, NULL);
1407 }
1408
1409 static
1410 DECL_CMD_FUNC(set80211quietperiod, val, d)
1411 {
1412         set80211(s, IEEE80211_IOC_QUIET_PERIOD, atoi(val), 0, NULL);
1413 }
1414
1415 static
1416 DECL_CMD_FUNC(set80211quietcount, val, d)
1417 {
1418         set80211(s, IEEE80211_IOC_QUIET_COUNT, atoi(val), 0, NULL);
1419 }
1420
1421 static
1422 DECL_CMD_FUNC(set80211quietduration, val, d)
1423 {
1424         set80211(s, IEEE80211_IOC_QUIET_DUR, atoi(val), 0, NULL);
1425 }
1426
1427 static
1428 DECL_CMD_FUNC(set80211quietoffset, val, d)
1429 {
1430         set80211(s, IEEE80211_IOC_QUIET_OFFSET, atoi(val), 0, NULL);
1431 }
1432
1433 static void
1434 set80211bgscan(const char *val, int d, int s, const struct afswtch *rafp)
1435 {
1436         set80211(s, IEEE80211_IOC_BGSCAN, d, 0, NULL);
1437 }
1438
1439 static
1440 DECL_CMD_FUNC(set80211bgscanidle, val, d)
1441 {
1442         set80211(s, IEEE80211_IOC_BGSCAN_IDLE, atoi(val), 0, NULL);
1443 }
1444
1445 static
1446 DECL_CMD_FUNC(set80211bgscanintvl, val, d)
1447 {
1448         set80211(s, IEEE80211_IOC_BGSCAN_INTERVAL, atoi(val), 0, NULL);
1449 }
1450
1451 static
1452 DECL_CMD_FUNC(set80211scanvalid, val, d)
1453 {
1454         set80211(s, IEEE80211_IOC_SCANVALID, atoi(val), 0, NULL);
1455 }
1456
1457 /*
1458  * Parse an optional trailing specification of which netbands
1459  * to apply a parameter to.  This is basically the same syntax
1460  * as used for channels but you can concatenate to specify
1461  * multiple.  For example:
1462  *      14:abg          apply to 11a, 11b, and 11g
1463  *      6:ht            apply to 11na and 11ng
1464  * We don't make a big effort to catch silly things; this is
1465  * really a convenience mechanism.
1466  */
1467 static int
1468 getmodeflags(const char *val)
1469 {
1470         const char *cp;
1471         int flags;
1472
1473         flags = 0;
1474
1475         cp = strchr(val, ':');
1476         if (cp != NULL) {
1477                 for (cp++; isalpha((int) *cp); cp++) {
1478                         /* accept mixed case */
1479                         int c = *cp;
1480                         if (isupper(c))
1481                                 c = tolower(c);
1482                         switch (c) {
1483                         case 'a':               /* 802.11a */
1484                                 flags |= IEEE80211_CHAN_A;
1485                                 break;
1486                         case 'b':               /* 802.11b */
1487                                 flags |= IEEE80211_CHAN_B;
1488                                 break;
1489                         case 'g':               /* 802.11g */
1490                                 flags |= IEEE80211_CHAN_G;
1491                                 break;
1492                         case 'n':               /* 802.11n */
1493                                 flags |= IEEE80211_CHAN_HT;
1494                                 break;
1495                         case 'd':               /* dt = Atheros Dynamic Turbo */
1496                                 flags |= IEEE80211_CHAN_TURBO;
1497                                 break;
1498                         case 't':               /* ht, dt, st, t */
1499                                 /* dt and unadorned t specify Dynamic Turbo */
1500                                 if ((flags & (IEEE80211_CHAN_STURBO|IEEE80211_CHAN_HT)) == 0)
1501                                         flags |= IEEE80211_CHAN_TURBO;
1502                                 break;
1503                         case 's':               /* st = Atheros Static Turbo */
1504                                 flags |= IEEE80211_CHAN_STURBO;
1505                                 break;
1506                         case 'h':               /* 1/2-width channels */
1507                                 flags |= IEEE80211_CHAN_HALF;
1508                                 break;
1509                         case 'q':               /* 1/4-width channels */
1510                                 flags |= IEEE80211_CHAN_QUARTER;
1511                                 break;
1512                         case 'v':
1513                                 /* XXX set HT too? */
1514                                 flags |= IEEE80211_CHAN_VHT;
1515                                 break;
1516                         default:
1517                                 errx(-1, "%s: Invalid mode attribute %c\n",
1518                                     val, *cp);
1519                         }
1520                 }
1521         }
1522         return flags;
1523 }
1524
1525 #define IEEE80211_CHAN_HTA      (IEEE80211_CHAN_HT|IEEE80211_CHAN_5GHZ)
1526 #define IEEE80211_CHAN_HTG      (IEEE80211_CHAN_HT|IEEE80211_CHAN_2GHZ)
1527
1528 #define _APPLY(_flags, _base, _param, _v) do {                          \
1529     if (_flags & IEEE80211_CHAN_HT) {                                   \
1530             if ((_flags & (IEEE80211_CHAN_5GHZ|IEEE80211_CHAN_2GHZ)) == 0) {\
1531                     _base.params[IEEE80211_MODE_11NA]._param = _v;      \
1532                     _base.params[IEEE80211_MODE_11NG]._param = _v;      \
1533             } else if (_flags & IEEE80211_CHAN_5GHZ)                    \
1534                     _base.params[IEEE80211_MODE_11NA]._param = _v;      \
1535             else                                                        \
1536                     _base.params[IEEE80211_MODE_11NG]._param = _v;      \
1537     }                                                                   \
1538     if (_flags & IEEE80211_CHAN_TURBO) {                                \
1539             if ((_flags & (IEEE80211_CHAN_5GHZ|IEEE80211_CHAN_2GHZ)) == 0) {\
1540                     _base.params[IEEE80211_MODE_TURBO_A]._param = _v;   \
1541                     _base.params[IEEE80211_MODE_TURBO_G]._param = _v;   \
1542             } else if (_flags & IEEE80211_CHAN_5GHZ)                    \
1543                     _base.params[IEEE80211_MODE_TURBO_A]._param = _v;   \
1544             else                                                        \
1545                     _base.params[IEEE80211_MODE_TURBO_G]._param = _v;   \
1546     }                                                                   \
1547     if (_flags & IEEE80211_CHAN_STURBO)                                 \
1548             _base.params[IEEE80211_MODE_STURBO_A]._param = _v;          \
1549     if ((_flags & IEEE80211_CHAN_A) == IEEE80211_CHAN_A)                \
1550             _base.params[IEEE80211_MODE_11A]._param = _v;               \
1551     if ((_flags & IEEE80211_CHAN_G) == IEEE80211_CHAN_G)                \
1552             _base.params[IEEE80211_MODE_11G]._param = _v;               \
1553     if ((_flags & IEEE80211_CHAN_B) == IEEE80211_CHAN_B)                \
1554             _base.params[IEEE80211_MODE_11B]._param = _v;               \
1555     if (_flags & IEEE80211_CHAN_HALF)                                   \
1556             _base.params[IEEE80211_MODE_HALF]._param = _v;              \
1557     if (_flags & IEEE80211_CHAN_QUARTER)                                \
1558             _base.params[IEEE80211_MODE_QUARTER]._param = _v;           \
1559 } while (0)
1560 #define _APPLY1(_flags, _base, _param, _v) do {                         \
1561     if (_flags & IEEE80211_CHAN_HT) {                                   \
1562             if (_flags & IEEE80211_CHAN_5GHZ)                           \
1563                     _base.params[IEEE80211_MODE_11NA]._param = _v;      \
1564             else                                                        \
1565                     _base.params[IEEE80211_MODE_11NG]._param = _v;      \
1566     } else if ((_flags & IEEE80211_CHAN_108A) == IEEE80211_CHAN_108A)   \
1567             _base.params[IEEE80211_MODE_TURBO_A]._param = _v;           \
1568     else if ((_flags & IEEE80211_CHAN_108G) == IEEE80211_CHAN_108G)     \
1569             _base.params[IEEE80211_MODE_TURBO_G]._param = _v;           \
1570     else if ((_flags & IEEE80211_CHAN_ST) == IEEE80211_CHAN_ST)         \
1571             _base.params[IEEE80211_MODE_STURBO_A]._param = _v;          \
1572     else if (_flags & IEEE80211_CHAN_HALF)                              \
1573             _base.params[IEEE80211_MODE_HALF]._param = _v;              \
1574     else if (_flags & IEEE80211_CHAN_QUARTER)                           \
1575             _base.params[IEEE80211_MODE_QUARTER]._param = _v;           \
1576     else if ((_flags & IEEE80211_CHAN_A) == IEEE80211_CHAN_A)           \
1577             _base.params[IEEE80211_MODE_11A]._param = _v;               \
1578     else if ((_flags & IEEE80211_CHAN_G) == IEEE80211_CHAN_G)           \
1579             _base.params[IEEE80211_MODE_11G]._param = _v;               \
1580     else if ((_flags & IEEE80211_CHAN_B) == IEEE80211_CHAN_B)           \
1581             _base.params[IEEE80211_MODE_11B]._param = _v;               \
1582 } while (0)
1583 #define _APPLY_RATE(_flags, _base, _param, _v) do {                     \
1584     if (_flags & IEEE80211_CHAN_HT) {                                   \
1585         (_v) = (_v / 2) | IEEE80211_RATE_MCS;                           \
1586     }                                                                   \
1587     _APPLY(_flags, _base, _param, _v);                                  \
1588 } while (0)
1589 #define _APPLY_RATE1(_flags, _base, _param, _v) do {                    \
1590     if (_flags & IEEE80211_CHAN_HT) {                                   \
1591         (_v) = (_v / 2) | IEEE80211_RATE_MCS;                           \
1592     }                                                                   \
1593     _APPLY1(_flags, _base, _param, _v);                                 \
1594 } while (0)
1595
1596 static
1597 DECL_CMD_FUNC(set80211roamrssi, val, d)
1598 {
1599         double v = atof(val);
1600         int rssi, flags;
1601
1602         rssi = (int) (2*v);
1603         if (rssi != 2*v)
1604                 errx(-1, "invalid rssi (must be .5 dBm units)");
1605         flags = getmodeflags(val);
1606         getroam(s);
1607         if (flags == 0) {               /* NB: no flags => current channel */
1608                 flags = getcurchan(s)->ic_flags;
1609                 _APPLY1(flags, roamparams, rssi, rssi);
1610         } else
1611                 _APPLY(flags, roamparams, rssi, rssi);
1612         callback_register(setroam_cb, &roamparams);
1613 }
1614
1615 static int
1616 getrate(const char *val, const char *tag)
1617 {
1618         double v = atof(val);
1619         int rate;
1620
1621         rate = (int) (2*v);
1622         if (rate != 2*v)
1623                 errx(-1, "invalid %s rate (must be .5 Mb/s units)", tag);
1624         return rate;            /* NB: returns 2x the specified value */
1625 }
1626
1627 static
1628 DECL_CMD_FUNC(set80211roamrate, val, d)
1629 {
1630         int rate, flags;
1631
1632         rate = getrate(val, "roam");
1633         flags = getmodeflags(val);
1634         getroam(s);
1635         if (flags == 0) {               /* NB: no flags => current channel */
1636                 flags = getcurchan(s)->ic_flags;
1637                 _APPLY_RATE1(flags, roamparams, rate, rate);
1638         } else
1639                 _APPLY_RATE(flags, roamparams, rate, rate);
1640         callback_register(setroam_cb, &roamparams);
1641 }
1642
1643 static
1644 DECL_CMD_FUNC(set80211mcastrate, val, d)
1645 {
1646         int rate, flags;
1647
1648         rate = getrate(val, "mcast");
1649         flags = getmodeflags(val);
1650         gettxparams(s);
1651         if (flags == 0) {               /* NB: no flags => current channel */
1652                 flags = getcurchan(s)->ic_flags;
1653                 _APPLY_RATE1(flags, txparams, mcastrate, rate);
1654         } else
1655                 _APPLY_RATE(flags, txparams, mcastrate, rate);
1656         callback_register(settxparams_cb, &txparams);
1657 }
1658
1659 static
1660 DECL_CMD_FUNC(set80211mgtrate, val, d)
1661 {
1662         int rate, flags;
1663
1664         rate = getrate(val, "mgmt");
1665         flags = getmodeflags(val);
1666         gettxparams(s);
1667         if (flags == 0) {               /* NB: no flags => current channel */
1668                 flags = getcurchan(s)->ic_flags;
1669                 _APPLY_RATE1(flags, txparams, mgmtrate, rate);
1670         } else
1671                 _APPLY_RATE(flags, txparams, mgmtrate, rate);
1672         callback_register(settxparams_cb, &txparams);
1673 }
1674
1675 static
1676 DECL_CMD_FUNC(set80211ucastrate, val, d)
1677 {
1678         int flags;
1679
1680         gettxparams(s);
1681         flags = getmodeflags(val);
1682         if (isanyarg(val)) {
1683                 if (flags == 0) {       /* NB: no flags => current channel */
1684                         flags = getcurchan(s)->ic_flags;
1685                         _APPLY1(flags, txparams, ucastrate,
1686                             IEEE80211_FIXED_RATE_NONE);
1687                 } else
1688                         _APPLY(flags, txparams, ucastrate,
1689                             IEEE80211_FIXED_RATE_NONE);
1690         } else {
1691                 int rate = getrate(val, "ucast");
1692                 if (flags == 0) {       /* NB: no flags => current channel */
1693                         flags = getcurchan(s)->ic_flags;
1694                         _APPLY_RATE1(flags, txparams, ucastrate, rate);
1695                 } else
1696                         _APPLY_RATE(flags, txparams, ucastrate, rate);
1697         }
1698         callback_register(settxparams_cb, &txparams);
1699 }
1700
1701 static
1702 DECL_CMD_FUNC(set80211maxretry, val, d)
1703 {
1704         int v = atoi(val), flags;
1705
1706         flags = getmodeflags(val);
1707         gettxparams(s);
1708         if (flags == 0) {               /* NB: no flags => current channel */
1709                 flags = getcurchan(s)->ic_flags;
1710                 _APPLY1(flags, txparams, maxretry, v);
1711         } else
1712                 _APPLY(flags, txparams, maxretry, v);
1713         callback_register(settxparams_cb, &txparams);
1714 }
1715 #undef _APPLY_RATE
1716 #undef _APPLY
1717 #undef IEEE80211_CHAN_HTA
1718 #undef IEEE80211_CHAN_HTG
1719
1720 static
1721 DECL_CMD_FUNC(set80211fragthreshold, val, d)
1722 {
1723         set80211(s, IEEE80211_IOC_FRAGTHRESHOLD,
1724                 isundefarg(val) ? IEEE80211_FRAG_MAX : atoi(val), 0, NULL);
1725 }
1726
1727 static
1728 DECL_CMD_FUNC(set80211bmissthreshold, val, d)
1729 {
1730         set80211(s, IEEE80211_IOC_BMISSTHRESHOLD,
1731                 isundefarg(val) ? IEEE80211_HWBMISS_MAX : atoi(val), 0, NULL);
1732 }
1733
1734 static void
1735 set80211burst(const char *val, int d, int s, const struct afswtch *rafp)
1736 {
1737         set80211(s, IEEE80211_IOC_BURST, d, 0, NULL);
1738 }
1739
1740 static void
1741 set80211doth(const char *val, int d, int s, const struct afswtch *rafp)
1742 {
1743         set80211(s, IEEE80211_IOC_DOTH, d, 0, NULL);
1744 }
1745
1746 static void
1747 set80211dfs(const char *val, int d, int s, const struct afswtch *rafp)
1748 {
1749         set80211(s, IEEE80211_IOC_DFS, d, 0, NULL);
1750 }
1751
1752 static void
1753 set80211shortgi(const char *val, int d, int s, const struct afswtch *rafp)
1754 {
1755         set80211(s, IEEE80211_IOC_SHORTGI,
1756                 d ? (IEEE80211_HTCAP_SHORTGI20 | IEEE80211_HTCAP_SHORTGI40) : 0,
1757                 0, NULL);
1758 }
1759
1760 static void
1761 set80211ampdu(const char *val, int d, int s, const struct afswtch *rafp)
1762 {
1763         int ampdu;
1764
1765         if (get80211val(s, IEEE80211_IOC_AMPDU, &ampdu) < 0)
1766                 errx(-1, "cannot set AMPDU setting");
1767         if (d < 0) {
1768                 d = -d;
1769                 ampdu &= ~d;
1770         } else
1771                 ampdu |= d;
1772         set80211(s, IEEE80211_IOC_AMPDU, ampdu, 0, NULL);
1773 }
1774
1775 static void
1776 set80211stbc(const char *val, int d, int s, const struct afswtch *rafp)
1777 {
1778         int stbc;
1779
1780         if (get80211val(s, IEEE80211_IOC_STBC, &stbc) < 0)
1781                 errx(-1, "cannot set STBC setting");
1782         if (d < 0) {
1783                 d = -d;
1784                 stbc &= ~d;
1785         } else
1786                 stbc |= d;
1787         set80211(s, IEEE80211_IOC_STBC, stbc, 0, NULL);
1788 }
1789
1790 static
1791 DECL_CMD_FUNC(set80211ampdulimit, val, d)
1792 {
1793         int v;
1794
1795         switch (atoi(val)) {
1796         case 8:
1797         case 8*1024:
1798                 v = IEEE80211_HTCAP_MAXRXAMPDU_8K;
1799                 break;
1800         case 16:
1801         case 16*1024:
1802                 v = IEEE80211_HTCAP_MAXRXAMPDU_16K;
1803                 break;
1804         case 32:
1805         case 32*1024:
1806                 v = IEEE80211_HTCAP_MAXRXAMPDU_32K;
1807                 break;
1808         case 64:
1809         case 64*1024:
1810                 v = IEEE80211_HTCAP_MAXRXAMPDU_64K;
1811                 break;
1812         default:
1813                 errx(-1, "invalid A-MPDU limit %s", val);
1814         }
1815         set80211(s, IEEE80211_IOC_AMPDU_LIMIT, v, 0, NULL);
1816 }
1817
1818 static
1819 DECL_CMD_FUNC(set80211ampdudensity, val, d)
1820 {
1821         int v;
1822
1823         if (isanyarg(val) || strcasecmp(val, "na") == 0)
1824                 v = IEEE80211_HTCAP_MPDUDENSITY_NA;
1825         else switch ((int)(atof(val)*4)) {
1826         case 0:
1827                 v = IEEE80211_HTCAP_MPDUDENSITY_NA;
1828                 break;
1829         case 1:
1830                 v = IEEE80211_HTCAP_MPDUDENSITY_025;
1831                 break;
1832         case 2:
1833                 v = IEEE80211_HTCAP_MPDUDENSITY_05;
1834                 break;
1835         case 4:
1836                 v = IEEE80211_HTCAP_MPDUDENSITY_1;
1837                 break;
1838         case 8:
1839                 v = IEEE80211_HTCAP_MPDUDENSITY_2;
1840                 break;
1841         case 16:
1842                 v = IEEE80211_HTCAP_MPDUDENSITY_4;
1843                 break;
1844         case 32:
1845                 v = IEEE80211_HTCAP_MPDUDENSITY_8;
1846                 break;
1847         case 64:
1848                 v = IEEE80211_HTCAP_MPDUDENSITY_16;
1849                 break;
1850         default:
1851                 errx(-1, "invalid A-MPDU density %s", val);
1852         }
1853         set80211(s, IEEE80211_IOC_AMPDU_DENSITY, v, 0, NULL);
1854 }
1855
1856 static void
1857 set80211amsdu(const char *val, int d, int s, const struct afswtch *rafp)
1858 {
1859         int amsdu;
1860
1861         if (get80211val(s, IEEE80211_IOC_AMSDU, &amsdu) < 0)
1862                 err(-1, "cannot get AMSDU setting");
1863         if (d < 0) {
1864                 d = -d;
1865                 amsdu &= ~d;
1866         } else
1867                 amsdu |= d;
1868         set80211(s, IEEE80211_IOC_AMSDU, amsdu, 0, NULL);
1869 }
1870
1871 static
1872 DECL_CMD_FUNC(set80211amsdulimit, val, d)
1873 {
1874         set80211(s, IEEE80211_IOC_AMSDU_LIMIT, atoi(val), 0, NULL);
1875 }
1876
1877 static void
1878 set80211puren(const char *val, int d, int s, const struct afswtch *rafp)
1879 {
1880         set80211(s, IEEE80211_IOC_PUREN, d, 0, NULL);
1881 }
1882
1883 static void
1884 set80211htcompat(const char *val, int d, int s, const struct afswtch *rafp)
1885 {
1886         set80211(s, IEEE80211_IOC_HTCOMPAT, d, 0, NULL);
1887 }
1888
1889 static void
1890 set80211htconf(const char *val, int d, int s, const struct afswtch *rafp)
1891 {
1892         set80211(s, IEEE80211_IOC_HTCONF, d, 0, NULL);
1893         htconf = d;
1894 }
1895
1896 static void
1897 set80211dwds(const char *val, int d, int s, const struct afswtch *rafp)
1898 {
1899         set80211(s, IEEE80211_IOC_DWDS, d, 0, NULL);
1900 }
1901
1902 static void
1903 set80211inact(const char *val, int d, int s, const struct afswtch *rafp)
1904 {
1905         set80211(s, IEEE80211_IOC_INACTIVITY, d, 0, NULL);
1906 }
1907
1908 static void
1909 set80211tsn(const char *val, int d, int s, const struct afswtch *rafp)
1910 {
1911         set80211(s, IEEE80211_IOC_TSN, d, 0, NULL);
1912 }
1913
1914 static void
1915 set80211dotd(const char *val, int d, int s, const struct afswtch *rafp)
1916 {
1917         set80211(s, IEEE80211_IOC_DOTD, d, 0, NULL);
1918 }
1919
1920 static void
1921 set80211smps(const char *val, int d, int s, const struct afswtch *rafp)
1922 {
1923         set80211(s, IEEE80211_IOC_SMPS, d, 0, NULL);
1924 }
1925
1926 static void
1927 set80211rifs(const char *val, int d, int s, const struct afswtch *rafp)
1928 {
1929         set80211(s, IEEE80211_IOC_RIFS, d, 0, NULL);
1930 }
1931
1932 static void
1933 set80211vhtconf(const char *val, int d, int s, const struct afswtch *rafp)
1934 {
1935         if (get80211val(s, IEEE80211_IOC_VHTCONF, &vhtconf) < 0)
1936                 errx(-1, "cannot set VHT setting");
1937         printf("%s: vhtconf=0x%08x, d=%d\n", __func__, vhtconf, d);
1938         if (d < 0) {
1939                 d = -d;
1940                 vhtconf &= ~d;
1941         } else
1942                 vhtconf |= d;
1943         printf("%s: vhtconf is now 0x%08x\n", __func__, vhtconf);
1944         set80211(s, IEEE80211_IOC_VHTCONF, vhtconf, 0, NULL);
1945 }
1946
1947 static
1948 DECL_CMD_FUNC(set80211tdmaslot, val, d)
1949 {
1950         set80211(s, IEEE80211_IOC_TDMA_SLOT, atoi(val), 0, NULL);
1951 }
1952
1953 static
1954 DECL_CMD_FUNC(set80211tdmaslotcnt, val, d)
1955 {
1956         set80211(s, IEEE80211_IOC_TDMA_SLOTCNT, atoi(val), 0, NULL);
1957 }
1958
1959 static
1960 DECL_CMD_FUNC(set80211tdmaslotlen, val, d)
1961 {
1962         set80211(s, IEEE80211_IOC_TDMA_SLOTLEN, atoi(val), 0, NULL);
1963 }
1964
1965 static
1966 DECL_CMD_FUNC(set80211tdmabintval, val, d)
1967 {
1968         set80211(s, IEEE80211_IOC_TDMA_BINTERVAL, atoi(val), 0, NULL);
1969 }
1970
1971 static
1972 DECL_CMD_FUNC(set80211meshttl, val, d)
1973 {
1974         set80211(s, IEEE80211_IOC_MESH_TTL, atoi(val), 0, NULL);
1975 }
1976
1977 static
1978 DECL_CMD_FUNC(set80211meshforward, val, d)
1979 {
1980         set80211(s, IEEE80211_IOC_MESH_FWRD, d, 0, NULL);
1981 }
1982
1983 static
1984 DECL_CMD_FUNC(set80211meshgate, val, d)
1985 {
1986         set80211(s, IEEE80211_IOC_MESH_GATE, d, 0, NULL);
1987 }
1988
1989 static
1990 DECL_CMD_FUNC(set80211meshpeering, val, d)
1991 {
1992         set80211(s, IEEE80211_IOC_MESH_AP, d, 0, NULL);
1993 }
1994
1995 static
1996 DECL_CMD_FUNC(set80211meshmetric, val, d)
1997 {
1998         char v[12];
1999         
2000         memcpy(v, val, sizeof(v));
2001         set80211(s, IEEE80211_IOC_MESH_PR_METRIC, 0, 0, v);
2002 }
2003
2004 static
2005 DECL_CMD_FUNC(set80211meshpath, val, d)
2006 {
2007         char v[12];
2008         
2009         memcpy(v, val, sizeof(v));
2010         set80211(s, IEEE80211_IOC_MESH_PR_PATH, 0, 0, v);
2011 }
2012
2013 static int
2014 regdomain_sort(const void *a, const void *b)
2015 {
2016 #define CHAN_ALL \
2017         (IEEE80211_CHAN_ALLTURBO|IEEE80211_CHAN_HALF|IEEE80211_CHAN_QUARTER)
2018         const struct ieee80211_channel *ca = a;
2019         const struct ieee80211_channel *cb = b;
2020
2021         return ca->ic_freq == cb->ic_freq ?
2022             (ca->ic_flags & CHAN_ALL) - (cb->ic_flags & CHAN_ALL) :
2023             ca->ic_freq - cb->ic_freq;
2024 #undef CHAN_ALL
2025 }
2026
2027 static const struct ieee80211_channel *
2028 chanlookup(const struct ieee80211_channel chans[], int nchans,
2029         int freq, int flags)
2030 {
2031         int i;
2032
2033         flags &= IEEE80211_CHAN_ALLTURBO;
2034         for (i = 0; i < nchans; i++) {
2035                 const struct ieee80211_channel *c = &chans[i];
2036                 if (c->ic_freq == freq &&
2037                     (c->ic_flags & IEEE80211_CHAN_ALLTURBO) == flags)
2038                         return c;
2039         }
2040         return NULL;
2041 }
2042
2043 static int
2044 chanfind(const struct ieee80211_channel chans[], int nchans, int flags)
2045 {
2046         int i;
2047
2048         for (i = 0; i < nchans; i++) {
2049                 const struct ieee80211_channel *c = &chans[i];
2050                 if ((c->ic_flags & flags) == flags)
2051                         return 1;
2052         }
2053         return 0;
2054 }
2055
2056 /*
2057  * Check channel compatibility.
2058  */
2059 static int
2060 checkchan(const struct ieee80211req_chaninfo *avail, int freq, int flags)
2061 {
2062         flags &= ~REQ_FLAGS;
2063         /*
2064          * Check if exact channel is in the calibration table;
2065          * everything below is to deal with channels that we
2066          * want to include but that are not explicitly listed.
2067          */
2068         if (chanlookup(avail->ic_chans, avail->ic_nchans, freq, flags) != NULL)
2069                 return 1;
2070         if (flags & IEEE80211_CHAN_GSM) {
2071                 /*
2072                  * XXX GSM frequency mapping is handled in the kernel
2073                  * so we cannot find them in the calibration table;
2074                  * just accept the channel and the kernel will reject
2075                  * the channel list if it's wrong.
2076                  */
2077                 return 1;
2078         }
2079         /*
2080          * If this is a 1/2 or 1/4 width channel allow it if a full
2081          * width channel is present for this frequency, and the device
2082          * supports fractional channels on this band.  This is a hack
2083          * that avoids bloating the calibration table; it may be better
2084          * by per-band attributes though (we are effectively calculating
2085          * this attribute by scanning the channel list ourself).
2086          */
2087         if ((flags & (IEEE80211_CHAN_HALF | IEEE80211_CHAN_QUARTER)) == 0)
2088                 return 0;
2089         if (chanlookup(avail->ic_chans, avail->ic_nchans, freq,
2090             flags &~ (IEEE80211_CHAN_HALF | IEEE80211_CHAN_QUARTER)) == NULL)
2091                 return 0;
2092         if (flags & IEEE80211_CHAN_HALF) {
2093                 return chanfind(avail->ic_chans, avail->ic_nchans,
2094                     IEEE80211_CHAN_HALF |
2095                        (flags & (IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_5GHZ)));
2096         } else {
2097                 return chanfind(avail->ic_chans, avail->ic_nchans,
2098                     IEEE80211_CHAN_QUARTER |
2099                         (flags & (IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_5GHZ)));
2100         }
2101 }
2102
2103 static void
2104 regdomain_addchans(struct ieee80211req_chaninfo *ci,
2105         const netband_head *bands,
2106         const struct ieee80211_regdomain *reg,
2107         uint32_t chanFlags,
2108         const struct ieee80211req_chaninfo *avail)
2109 {
2110         const struct netband *nb;
2111         const struct freqband *b;
2112         struct ieee80211_channel *c, *prev;
2113         int freq, hi_adj, lo_adj, channelSep;
2114         uint32_t flags;
2115
2116         hi_adj = (chanFlags & IEEE80211_CHAN_HT40U) ? -20 : 0;
2117         lo_adj = (chanFlags & IEEE80211_CHAN_HT40D) ? 20 : 0;
2118         channelSep = (chanFlags & IEEE80211_CHAN_2GHZ) ? 0 : 40;
2119
2120         LIST_FOREACH(nb, bands, next) {
2121                 b = nb->band;
2122                 if (verbose) {
2123                         printf("%s:", __func__);
2124                         printb(" chanFlags", chanFlags, IEEE80211_CHAN_BITS);
2125                         printb(" bandFlags", nb->flags | b->flags,
2126                             IEEE80211_CHAN_BITS);
2127                         putchar('\n');
2128                 }
2129                 prev = NULL;
2130
2131                 for (freq = b->freqStart + lo_adj;
2132                      freq <= b->freqEnd + hi_adj; freq += b->chanSep) {
2133                         /*
2134                          * Construct flags for the new channel.  We take
2135                          * the attributes from the band descriptions except
2136                          * for HT40 which is enabled generically (i.e. +/-
2137                          * extension channel) in the band description and
2138                          * then constrained according by channel separation.
2139                          */
2140                         flags = nb->flags | b->flags;
2141
2142                         /*
2143                          * VHT first - HT is a subset.
2144                          *
2145                          * XXX TODO: VHT80p80, VHT160 is not yet done.
2146                          */
2147                         if (flags & IEEE80211_CHAN_VHT) {
2148                                 if ((chanFlags & IEEE80211_CHAN_VHT20) &&
2149                                     (flags & IEEE80211_CHAN_VHT20) == 0) {
2150                                         if (verbose)
2151                                                 printf("%u: skip, not a "
2152                                                     "VHT20 channel\n", freq);
2153                                         continue;
2154                                 }
2155                                 if ((chanFlags & IEEE80211_CHAN_VHT40) &&
2156                                     (flags & IEEE80211_CHAN_VHT40) == 0) {
2157                                         if (verbose)
2158                                                 printf("%u: skip, not a "
2159                                                     "VHT40 channel\n", freq);
2160                                         continue;
2161                                 }
2162                                 if ((chanFlags & IEEE80211_CHAN_VHT80) &&
2163                                     (flags & IEEE80211_CHAN_VHT80) == 0) {
2164                                         if (verbose)
2165                                                 printf("%u: skip, not a "
2166                                                     "VHT80 channel\n", freq);
2167                                         continue;
2168                                 }
2169
2170                                 flags &= ~IEEE80211_CHAN_VHT;
2171                                 flags |= chanFlags & IEEE80211_CHAN_VHT;
2172                         }
2173
2174                         /* Now, constrain HT */
2175                         if (flags & IEEE80211_CHAN_HT) {
2176                                 /*
2177                                  * HT channels are generated specially; we're
2178                                  * called to add HT20, HT40+, and HT40- chan's
2179                                  * so we need to expand only band specs for
2180                                  * the HT channel type being added.
2181                                  */
2182                                 if ((chanFlags & IEEE80211_CHAN_HT20) &&
2183                                     (flags & IEEE80211_CHAN_HT20) == 0) {
2184                                         if (verbose)
2185                                                 printf("%u: skip, not an "
2186                                                     "HT20 channel\n", freq);
2187                                         continue;
2188                                 }
2189                                 if ((chanFlags & IEEE80211_CHAN_HT40) &&
2190                                     (flags & IEEE80211_CHAN_HT40) == 0) {
2191                                         if (verbose)
2192                                                 printf("%u: skip, not an "
2193                                                     "HT40 channel\n", freq);
2194                                         continue;
2195                                 }
2196                                 /* NB: HT attribute comes from caller */
2197                                 flags &= ~IEEE80211_CHAN_HT;
2198                                 flags |= chanFlags & IEEE80211_CHAN_HT;
2199                         }
2200                         /*
2201                          * Check if device can operate on this frequency.
2202                          */
2203                         if (!checkchan(avail, freq, flags)) {
2204                                 if (verbose) {
2205                                         printf("%u: skip, ", freq);
2206                                         printb("flags", flags,
2207                                             IEEE80211_CHAN_BITS);
2208                                         printf(" not available\n");
2209                                 }
2210                                 continue;
2211                         }
2212                         if ((flags & REQ_ECM) && !reg->ecm) {
2213                                 if (verbose)
2214                                         printf("%u: skip, ECM channel\n", freq);
2215                                 continue;
2216                         }
2217                         if ((flags & REQ_INDOOR) && reg->location == 'O') {
2218                                 if (verbose)
2219                                         printf("%u: skip, indoor channel\n",
2220                                             freq);
2221                                 continue;
2222                         }
2223                         if ((flags & REQ_OUTDOOR) && reg->location == 'I') {
2224                                 if (verbose)
2225                                         printf("%u: skip, outdoor channel\n",
2226                                             freq);
2227                                 continue;
2228                         }
2229                         if ((flags & IEEE80211_CHAN_HT40) &&
2230                             prev != NULL && (freq - prev->ic_freq) < channelSep) {
2231                                 if (verbose)
2232                                         printf("%u: skip, only %u channel "
2233                                             "separation, need %d\n", freq, 
2234                                             freq - prev->ic_freq, channelSep);
2235                                 continue;
2236                         }
2237                         if (ci->ic_nchans == IEEE80211_CHAN_MAX) {
2238                                 if (verbose)
2239                                         printf("%u: skip, channel table full\n",
2240                                             freq);
2241                                 break;
2242                         }
2243                         c = &ci->ic_chans[ci->ic_nchans++];
2244                         memset(c, 0, sizeof(*c));
2245                         c->ic_freq = freq;
2246                         c->ic_flags = flags;
2247                 if (c->ic_flags & IEEE80211_CHAN_DFS)
2248                                 c->ic_maxregpower = nb->maxPowerDFS;
2249                         else
2250                                 c->ic_maxregpower = nb->maxPower;
2251                         if (verbose) {
2252                                 printf("[%3d] add freq %u ",
2253                                     ci->ic_nchans-1, c->ic_freq);
2254                                 printb("flags", c->ic_flags, IEEE80211_CHAN_BITS);
2255                                 printf(" power %u\n", c->ic_maxregpower);
2256                         }
2257                         /* NB: kernel fills in other fields */
2258                         prev = c;
2259                 }
2260         }
2261 }
2262
2263 static void
2264 regdomain_makechannels(
2265         struct ieee80211_regdomain_req *req,
2266         const struct ieee80211_devcaps_req *dc)
2267 {
2268         struct regdata *rdp = getregdata();
2269         const struct country *cc;
2270         const struct ieee80211_regdomain *reg = &req->rd;
2271         struct ieee80211req_chaninfo *ci = &req->chaninfo;
2272         const struct regdomain *rd;
2273
2274         /*
2275          * Locate construction table for new channel list.  We treat
2276          * the regdomain/SKU as definitive so a country can be in
2277          * multiple with different properties (e.g. US in FCC+FCC3).
2278          * If no regdomain is specified then we fallback on the country
2279          * code to find the associated regdomain since countries always
2280          * belong to at least one regdomain.
2281          */
2282         if (reg->regdomain == 0) {
2283                 cc = lib80211_country_findbycc(rdp, reg->country);
2284                 if (cc == NULL)
2285                         errx(1, "internal error, country %d not found",
2286                             reg->country);
2287                 rd = cc->rd;
2288         } else
2289                 rd = lib80211_regdomain_findbysku(rdp, reg->regdomain);
2290         if (rd == NULL)
2291                 errx(1, "internal error, regdomain %d not found",
2292                             reg->regdomain);
2293         if (rd->sku != SKU_DEBUG) {
2294                 /*
2295                  * regdomain_addchans incrememnts the channel count for
2296                  * each channel it adds so initialize ic_nchans to zero.
2297                  * Note that we know we have enough space to hold all possible
2298                  * channels because the devcaps list size was used to
2299                  * allocate our request.
2300                  */
2301                 ci->ic_nchans = 0;
2302                 if (!LIST_EMPTY(&rd->bands_11b))
2303                         regdomain_addchans(ci, &rd->bands_11b, reg,
2304                             IEEE80211_CHAN_B, &dc->dc_chaninfo);
2305                 if (!LIST_EMPTY(&rd->bands_11g))
2306                         regdomain_addchans(ci, &rd->bands_11g, reg,
2307                             IEEE80211_CHAN_G, &dc->dc_chaninfo);
2308                 if (!LIST_EMPTY(&rd->bands_11a))
2309                         regdomain_addchans(ci, &rd->bands_11a, reg,
2310                             IEEE80211_CHAN_A, &dc->dc_chaninfo);
2311                 if (!LIST_EMPTY(&rd->bands_11na) && dc->dc_htcaps != 0) {
2312                         regdomain_addchans(ci, &rd->bands_11na, reg,
2313                             IEEE80211_CHAN_A | IEEE80211_CHAN_HT20,
2314                             &dc->dc_chaninfo);
2315                         if (dc->dc_htcaps & IEEE80211_HTCAP_CHWIDTH40) {
2316                                 regdomain_addchans(ci, &rd->bands_11na, reg,
2317                                     IEEE80211_CHAN_A | IEEE80211_CHAN_HT40U,
2318                                     &dc->dc_chaninfo);
2319                                 regdomain_addchans(ci, &rd->bands_11na, reg,
2320                                     IEEE80211_CHAN_A | IEEE80211_CHAN_HT40D,
2321                                     &dc->dc_chaninfo);
2322                         }
2323                 }
2324                 if (!LIST_EMPTY(&rd->bands_11ac) && dc->dc_vhtcaps != 0) {
2325                         regdomain_addchans(ci, &rd->bands_11ac, reg,
2326                             IEEE80211_CHAN_A | IEEE80211_CHAN_HT20 |
2327                             IEEE80211_CHAN_VHT20,
2328                             &dc->dc_chaninfo);
2329
2330                         /* VHT40 is a function of HT40.. */
2331                         if (dc->dc_htcaps & IEEE80211_HTCAP_CHWIDTH40) {
2332                                 regdomain_addchans(ci, &rd->bands_11ac, reg,
2333                                     IEEE80211_CHAN_A | IEEE80211_CHAN_HT40U |
2334                                     IEEE80211_CHAN_VHT40U,
2335                                     &dc->dc_chaninfo);
2336                                 regdomain_addchans(ci, &rd->bands_11ac, reg,
2337                                     IEEE80211_CHAN_A | IEEE80211_CHAN_HT40D |
2338                                     IEEE80211_CHAN_VHT40D,
2339                                     &dc->dc_chaninfo);
2340                         }
2341
2342                         /* VHT80 */
2343                         /* XXX dc_vhtcap? */
2344                         if (1) {
2345                                 regdomain_addchans(ci, &rd->bands_11ac, reg,
2346                                     IEEE80211_CHAN_A | IEEE80211_CHAN_HT40U |
2347                                     IEEE80211_CHAN_VHT80,
2348                                     &dc->dc_chaninfo);
2349                                 regdomain_addchans(ci, &rd->bands_11ac, reg,
2350                                     IEEE80211_CHAN_A | IEEE80211_CHAN_HT40D |
2351                                     IEEE80211_CHAN_VHT80,
2352                                     &dc->dc_chaninfo);
2353                         }
2354
2355                         /* XXX TODO: VHT80_80, VHT160 */
2356                 }
2357
2358                 if (!LIST_EMPTY(&rd->bands_11ng) && dc->dc_htcaps != 0) {
2359                         regdomain_addchans(ci, &rd->bands_11ng, reg,
2360                             IEEE80211_CHAN_G | IEEE80211_CHAN_HT20,
2361                             &dc->dc_chaninfo);
2362                         if (dc->dc_htcaps & IEEE80211_HTCAP_CHWIDTH40) {
2363                                 regdomain_addchans(ci, &rd->bands_11ng, reg,
2364                                     IEEE80211_CHAN_G | IEEE80211_CHAN_HT40U,
2365                                     &dc->dc_chaninfo);
2366                                 regdomain_addchans(ci, &rd->bands_11ng, reg,
2367                                     IEEE80211_CHAN_G | IEEE80211_CHAN_HT40D,
2368                                     &dc->dc_chaninfo);
2369                         }
2370                 }
2371                 qsort(ci->ic_chans, ci->ic_nchans, sizeof(ci->ic_chans[0]),
2372                     regdomain_sort);
2373         } else
2374                 memcpy(ci, &dc->dc_chaninfo,
2375                     IEEE80211_CHANINFO_SPACE(&dc->dc_chaninfo));
2376 }
2377
2378 static void
2379 list_countries(void)
2380 {
2381         struct regdata *rdp = getregdata();
2382         const struct country *cp;
2383         const struct regdomain *dp;
2384         int i;
2385
2386         i = 0;
2387         printf("\nCountry codes:\n");
2388         LIST_FOREACH(cp, &rdp->countries, next) {
2389                 printf("%2s %-15.15s%s", cp->isoname,
2390                     cp->name, ((i+1)%4) == 0 ? "\n" : " ");
2391                 i++;
2392         }
2393         i = 0;
2394         printf("\nRegulatory domains:\n");
2395         LIST_FOREACH(dp, &rdp->domains, next) {
2396                 printf("%-15.15s%s", dp->name, ((i+1)%4) == 0 ? "\n" : " ");
2397                 i++;
2398         }
2399         printf("\n");
2400 }
2401
2402 static void
2403 defaultcountry(const struct regdomain *rd)
2404 {
2405         struct regdata *rdp = getregdata();
2406         const struct country *cc;
2407
2408         cc = lib80211_country_findbycc(rdp, rd->cc->code);
2409         if (cc == NULL)
2410                 errx(1, "internal error, ISO country code %d not "
2411                     "defined for regdomain %s", rd->cc->code, rd->name);
2412         regdomain.country = cc->code;
2413         regdomain.isocc[0] = cc->isoname[0];
2414         regdomain.isocc[1] = cc->isoname[1];
2415 }
2416
2417 static
2418 DECL_CMD_FUNC(set80211regdomain, val, d)
2419 {
2420         struct regdata *rdp = getregdata();
2421         const struct regdomain *rd;
2422
2423         rd = lib80211_regdomain_findbyname(rdp, val);
2424         if (rd == NULL) {
2425                 char *eptr;
2426                 long sku = strtol(val, &eptr, 0);
2427
2428                 if (eptr != val)
2429                         rd = lib80211_regdomain_findbysku(rdp, sku);
2430                 if (eptr == val || rd == NULL)
2431                         errx(1, "unknown regdomain %s", val);
2432         }
2433         getregdomain(s);
2434         regdomain.regdomain = rd->sku;
2435         if (regdomain.country == 0 && rd->cc != NULL) {
2436                 /*
2437                  * No country code setup and there's a default
2438                  * one for this regdomain fill it in.
2439                  */
2440                 defaultcountry(rd);
2441         }
2442         callback_register(setregdomain_cb, &regdomain);
2443 }
2444
2445 static
2446 DECL_CMD_FUNC(set80211country, val, d)
2447 {
2448         struct regdata *rdp = getregdata();
2449         const struct country *cc;
2450
2451         cc = lib80211_country_findbyname(rdp, val);
2452         if (cc == NULL) {
2453                 char *eptr;
2454                 long code = strtol(val, &eptr, 0);
2455
2456                 if (eptr != val)
2457                         cc = lib80211_country_findbycc(rdp, code);
2458                 if (eptr == val || cc == NULL)
2459                         errx(1, "unknown ISO country code %s", val);
2460         }
2461         getregdomain(s);
2462         regdomain.regdomain = cc->rd->sku;
2463         regdomain.country = cc->code;
2464         regdomain.isocc[0] = cc->isoname[0];
2465         regdomain.isocc[1] = cc->isoname[1];
2466         callback_register(setregdomain_cb, &regdomain);
2467 }
2468
2469 static void
2470 set80211location(const char *val, int d, int s, const struct afswtch *rafp)
2471 {
2472         getregdomain(s);
2473         regdomain.location = d;
2474         callback_register(setregdomain_cb, &regdomain);
2475 }
2476
2477 static void
2478 set80211ecm(const char *val, int d, int s, const struct afswtch *rafp)
2479 {
2480         getregdomain(s);
2481         regdomain.ecm = d;
2482         callback_register(setregdomain_cb, &regdomain);
2483 }
2484
2485 static void
2486 LINE_INIT(char c)
2487 {
2488         spacer = c;
2489         if (c == '\t')
2490                 col = 8;
2491         else
2492                 col = 1;
2493 }
2494
2495 static void
2496 LINE_BREAK(void)
2497 {
2498         if (spacer != '\t') {
2499                 printf("\n");
2500                 spacer = '\t';
2501         }
2502         col = 8;                /* 8-col tab */
2503 }
2504
2505 static void
2506 LINE_CHECK(const char *fmt, ...)
2507 {
2508         char buf[80];
2509         va_list ap;
2510         int n;
2511
2512         va_start(ap, fmt);
2513         n = vsnprintf(buf+1, sizeof(buf)-1, fmt, ap);
2514         va_end(ap);
2515         col += 1+n;
2516         if (col > MAXCOL) {
2517                 LINE_BREAK();
2518                 col += n;
2519         }
2520         buf[0] = spacer;
2521         printf("%s", buf);
2522         spacer = ' ';
2523 }
2524
2525 static int
2526 getmaxrate(const uint8_t rates[15], uint8_t nrates)
2527 {
2528         int i, maxrate = -1;
2529
2530         for (i = 0; i < nrates; i++) {
2531                 int rate = rates[i] & IEEE80211_RATE_VAL;
2532                 if (rate > maxrate)
2533                         maxrate = rate;
2534         }
2535         return maxrate / 2;
2536 }
2537
2538 static const char *
2539 getcaps(int capinfo)
2540 {
2541         static char capstring[32];
2542         char *cp = capstring;
2543
2544         if (capinfo & IEEE80211_CAPINFO_ESS)
2545                 *cp++ = 'E';
2546         if (capinfo & IEEE80211_CAPINFO_IBSS)
2547                 *cp++ = 'I';
2548         if (capinfo & IEEE80211_CAPINFO_CF_POLLABLE)
2549                 *cp++ = 'c';
2550         if (capinfo & IEEE80211_CAPINFO_CF_POLLREQ)
2551                 *cp++ = 'C';
2552         if (capinfo & IEEE80211_CAPINFO_PRIVACY)
2553                 *cp++ = 'P';
2554         if (capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE)
2555                 *cp++ = 'S';
2556         if (capinfo & IEEE80211_CAPINFO_PBCC)
2557                 *cp++ = 'B';
2558         if (capinfo & IEEE80211_CAPINFO_CHNL_AGILITY)
2559                 *cp++ = 'A';
2560         if (capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME)
2561                 *cp++ = 's';
2562         if (capinfo & IEEE80211_CAPINFO_RSN)
2563                 *cp++ = 'R';
2564         if (capinfo & IEEE80211_CAPINFO_DSSSOFDM)
2565                 *cp++ = 'D';
2566         *cp = '\0';
2567         return capstring;
2568 }
2569
2570 static const char *
2571 getflags(int flags)
2572 {
2573         static char flagstring[32];
2574         char *cp = flagstring;
2575
2576         if (flags & IEEE80211_NODE_AUTH)
2577                 *cp++ = 'A';
2578         if (flags & IEEE80211_NODE_QOS)
2579                 *cp++ = 'Q';
2580         if (flags & IEEE80211_NODE_ERP)
2581                 *cp++ = 'E';
2582         if (flags & IEEE80211_NODE_PWR_MGT)
2583                 *cp++ = 'P';
2584         if (flags & IEEE80211_NODE_HT) {
2585                 *cp++ = 'H';
2586                 if (flags & IEEE80211_NODE_HTCOMPAT)
2587                         *cp++ = '+';
2588         }
2589         if (flags & IEEE80211_NODE_VHT)
2590                 *cp++ = 'V';
2591         if (flags & IEEE80211_NODE_WPS)
2592                 *cp++ = 'W';
2593         if (flags & IEEE80211_NODE_TSN)
2594                 *cp++ = 'N';
2595         if (flags & IEEE80211_NODE_AMPDU_TX)
2596                 *cp++ = 'T';
2597         if (flags & IEEE80211_NODE_AMPDU_RX)
2598                 *cp++ = 'R';
2599         if (flags & IEEE80211_NODE_MIMO_PS) {
2600                 *cp++ = 'M';
2601                 if (flags & IEEE80211_NODE_MIMO_RTS)
2602                         *cp++ = '+';
2603         }
2604         if (flags & IEEE80211_NODE_RIFS)
2605                 *cp++ = 'I';
2606         if (flags & IEEE80211_NODE_SGI40) {
2607                 *cp++ = 'S';
2608                 if (flags & IEEE80211_NODE_SGI20)
2609                         *cp++ = '+';
2610         } else if (flags & IEEE80211_NODE_SGI20)
2611                 *cp++ = 's';
2612         if (flags & IEEE80211_NODE_AMSDU_TX)
2613                 *cp++ = 't';
2614         if (flags & IEEE80211_NODE_AMSDU_RX)
2615                 *cp++ = 'r';
2616         *cp = '\0';
2617         return flagstring;
2618 }
2619
2620 static void
2621 printie(const char* tag, const uint8_t *ie, size_t ielen, int maxlen)
2622 {
2623         printf("%s", tag);
2624         if (verbose) {
2625                 maxlen -= strlen(tag)+2;
2626                 if (2*ielen > maxlen)
2627                         maxlen--;
2628                 printf("<");
2629                 for (; ielen > 0; ie++, ielen--) {
2630                         if (maxlen-- <= 0)
2631                                 break;
2632                         printf("%02x", *ie);
2633                 }
2634                 if (ielen != 0)
2635                         printf("-");
2636                 printf(">");
2637         }
2638 }
2639
2640 #define LE_READ_2(p)                                    \
2641         ((u_int16_t)                                    \
2642          ((((const u_int8_t *)(p))[0]      ) |          \
2643           (((const u_int8_t *)(p))[1] <<  8)))
2644 #define LE_READ_4(p)                                    \
2645         ((u_int32_t)                                    \
2646          ((((const u_int8_t *)(p))[0]      ) |          \
2647           (((const u_int8_t *)(p))[1] <<  8) |          \
2648           (((const u_int8_t *)(p))[2] << 16) |          \
2649           (((const u_int8_t *)(p))[3] << 24)))
2650
2651 /*
2652  * NB: The decoding routines assume a properly formatted ie
2653  *     which should be safe as the kernel only retains them
2654  *     if they parse ok.
2655  */
2656
2657 static void
2658 printwmeparam(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2659 {
2660 #define MS(_v, _f)      (((_v) & _f) >> _f##_S)
2661         static const char *acnames[] = { "BE", "BK", "VO", "VI" };
2662         const struct ieee80211_wme_param *wme =
2663             (const struct ieee80211_wme_param *) ie;
2664         int i;
2665
2666         printf("%s", tag);
2667         if (!verbose)
2668                 return;
2669         printf("<qosinfo 0x%x", wme->param_qosInfo);
2670         ie += offsetof(struct ieee80211_wme_param, params_acParams);
2671         for (i = 0; i < WME_NUM_AC; i++) {
2672                 const struct ieee80211_wme_acparams *ac =
2673                     &wme->params_acParams[i];
2674
2675                 printf(" %s[%saifsn %u cwmin %u cwmax %u txop %u]"
2676                         , acnames[i]
2677                         , MS(ac->acp_aci_aifsn, WME_PARAM_ACM) ? "acm " : ""
2678                         , MS(ac->acp_aci_aifsn, WME_PARAM_AIFSN)
2679                         , MS(ac->acp_logcwminmax, WME_PARAM_LOGCWMIN)
2680                         , MS(ac->acp_logcwminmax, WME_PARAM_LOGCWMAX)
2681                         , LE_READ_2(&ac->acp_txop)
2682                 );
2683         }
2684         printf(">");
2685 #undef MS
2686 }
2687
2688 static void
2689 printwmeinfo(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2690 {
2691         printf("%s", tag);
2692         if (verbose) {
2693                 const struct ieee80211_wme_info *wme =
2694                     (const struct ieee80211_wme_info *) ie;
2695                 printf("<version 0x%x info 0x%x>",
2696                     wme->wme_version, wme->wme_info);
2697         }
2698 }
2699
2700 static void
2701 printvhtcap(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2702 {
2703         printf("%s", tag);
2704         if (verbose) {
2705                 const struct ieee80211_ie_vhtcap *vhtcap =
2706                     (const struct ieee80211_ie_vhtcap *) ie;
2707                 uint32_t vhtcap_info = LE_READ_4(&vhtcap->vht_cap_info);
2708
2709                 printf("<cap 0x%08x", vhtcap_info);
2710                 printf(" rx_mcs_map 0x%x",
2711                     LE_READ_2(&vhtcap->supp_mcs.rx_mcs_map));
2712                 printf(" rx_highest %d",
2713                     LE_READ_2(&vhtcap->supp_mcs.rx_highest) & 0x1fff);
2714                 printf(" tx_mcs_map 0x%x",
2715                     LE_READ_2(&vhtcap->supp_mcs.tx_mcs_map));
2716                 printf(" tx_highest %d",
2717                     LE_READ_2(&vhtcap->supp_mcs.tx_highest) & 0x1fff);
2718
2719                 printf(">");
2720         }
2721 }
2722
2723 static void
2724 printvhtinfo(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2725 {
2726         printf("%s", tag);
2727         if (verbose) {
2728                 const struct ieee80211_ie_vht_operation *vhtinfo =
2729                     (const struct ieee80211_ie_vht_operation *) ie;
2730
2731                 printf("<chw %d freq1_idx %d freq2_idx %d basic_mcs_set 0x%04x>",
2732                     vhtinfo->chan_width,
2733                     vhtinfo->center_freq_seg1_idx,
2734                     vhtinfo->center_freq_seg2_idx,
2735                     LE_READ_2(&vhtinfo->basic_mcs_set));
2736         }
2737 }
2738
2739 static void
2740 printvhtpwrenv(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2741 {
2742         printf("%s", tag);
2743         static const char *txpwrmap[] = {
2744                 "20",
2745                 "40",
2746                 "80",
2747                 "160",
2748         };
2749         if (verbose) {
2750                 const struct ieee80211_ie_vht_txpwrenv *vhtpwr =
2751                     (const struct ieee80211_ie_vht_txpwrenv *) ie;
2752                 int i, n;
2753                 const char *sep = "";
2754
2755                 /* Get count; trim at ielen */
2756                 n = (vhtpwr->tx_info &
2757                     IEEE80211_VHT_TXPWRENV_INFO_COUNT_MASK) + 1;
2758                 /* Trim at ielen */
2759                 if (n > ielen - 3)
2760                         n = ielen - 3;
2761                 printf("<tx_info 0x%02x pwr:[", vhtpwr->tx_info);
2762                 for (i = 0; i < n; i++) {
2763                         printf("%s%s:%.2f", sep, txpwrmap[i],
2764                             ((float) ((int8_t) ie[i+3])) / 2.0);
2765                         sep = " ";
2766                 }
2767
2768                 printf("]>");
2769         }
2770 }
2771
2772 static void
2773 printhtcap(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2774 {
2775         printf("%s", tag);
2776         if (verbose) {
2777                 const struct ieee80211_ie_htcap *htcap =
2778                     (const struct ieee80211_ie_htcap *) ie;
2779                 const char *sep;
2780                 int i, j;
2781
2782                 printf("<cap 0x%x param 0x%x",
2783                     LE_READ_2(&htcap->hc_cap), htcap->hc_param);
2784                 printf(" mcsset[");
2785                 sep = "";
2786                 for (i = 0; i < IEEE80211_HTRATE_MAXSIZE; i++)
2787                         if (isset(htcap->hc_mcsset, i)) {
2788                                 for (j = i+1; j < IEEE80211_HTRATE_MAXSIZE; j++)
2789                                         if (isclr(htcap->hc_mcsset, j))
2790                                                 break;
2791                                 j--;
2792                                 if (i == j)
2793                                         printf("%s%u", sep, i);
2794                                 else
2795                                         printf("%s%u-%u", sep, i, j);
2796                                 i += j-i;
2797                                 sep = ",";
2798                         }
2799                 printf("] extcap 0x%x txbf 0x%x antenna 0x%x>",
2800                     LE_READ_2(&htcap->hc_extcap),
2801                     LE_READ_4(&htcap->hc_txbf),
2802                     htcap->hc_antenna);
2803         }
2804 }
2805
2806 static void
2807 printhtinfo(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2808 {
2809         printf("%s", tag);
2810         if (verbose) {
2811                 const struct ieee80211_ie_htinfo *htinfo =
2812                     (const struct ieee80211_ie_htinfo *) ie;
2813                 const char *sep;
2814                 int i, j;
2815
2816                 printf("<ctl %u, %x,%x,%x,%x", htinfo->hi_ctrlchannel,
2817                     htinfo->hi_byte1, htinfo->hi_byte2, htinfo->hi_byte3,
2818                     LE_READ_2(&htinfo->hi_byte45));
2819                 printf(" basicmcs[");
2820                 sep = "";
2821                 for (i = 0; i < IEEE80211_HTRATE_MAXSIZE; i++)
2822                         if (isset(htinfo->hi_basicmcsset, i)) {
2823                                 for (j = i+1; j < IEEE80211_HTRATE_MAXSIZE; j++)
2824                                         if (isclr(htinfo->hi_basicmcsset, j))
2825                                                 break;
2826                                 j--;
2827                                 if (i == j)
2828                                         printf("%s%u", sep, i);
2829                                 else
2830                                         printf("%s%u-%u", sep, i, j);
2831                                 i += j-i;
2832                                 sep = ",";
2833                         }
2834                 printf("]>");
2835         }
2836 }
2837
2838 static void
2839 printathie(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2840 {
2841
2842         printf("%s", tag);
2843         if (verbose) {
2844                 const struct ieee80211_ath_ie *ath =
2845                         (const struct ieee80211_ath_ie *)ie;
2846
2847                 printf("<");
2848                 if (ath->ath_capability & ATHEROS_CAP_TURBO_PRIME)
2849                         printf("DTURBO,");
2850                 if (ath->ath_capability & ATHEROS_CAP_COMPRESSION)
2851                         printf("COMP,");
2852                 if (ath->ath_capability & ATHEROS_CAP_FAST_FRAME)
2853                         printf("FF,");
2854                 if (ath->ath_capability & ATHEROS_CAP_XR)
2855                         printf("XR,");
2856                 if (ath->ath_capability & ATHEROS_CAP_AR)
2857                         printf("AR,");
2858                 if (ath->ath_capability & ATHEROS_CAP_BURST)
2859                         printf("BURST,");
2860                 if (ath->ath_capability & ATHEROS_CAP_WME)
2861                         printf("WME,");
2862                 if (ath->ath_capability & ATHEROS_CAP_BOOST)
2863                         printf("BOOST,");
2864                 printf("0x%x>", LE_READ_2(ath->ath_defkeyix));
2865         }
2866 }
2867
2868
2869 static void
2870 printmeshconf(const char *tag, const uint8_t *ie, size_t ielen, int maxlen)
2871 {
2872
2873         printf("%s", tag);
2874         if (verbose) {
2875                 const struct ieee80211_meshconf_ie *mconf =
2876                         (const struct ieee80211_meshconf_ie *)ie;
2877                 printf("<PATH:");
2878                 if (mconf->conf_pselid == IEEE80211_MESHCONF_PATH_HWMP)
2879                         printf("HWMP");
2880                 else
2881                         printf("UNKNOWN");
2882                 printf(" LINK:");
2883                 if (mconf->conf_pmetid == IEEE80211_MESHCONF_METRIC_AIRTIME)
2884                         printf("AIRTIME");
2885                 else
2886                         printf("UNKNOWN");
2887                 printf(" CONGESTION:");
2888                 if (mconf->conf_ccid == IEEE80211_MESHCONF_CC_DISABLED)
2889                         printf("DISABLED");
2890                 else
2891                         printf("UNKNOWN");
2892                 printf(" SYNC:");
2893                 if (mconf->conf_syncid == IEEE80211_MESHCONF_SYNC_NEIGHOFF)
2894                         printf("NEIGHOFF");
2895                 else
2896                         printf("UNKNOWN");
2897                 printf(" AUTH:");
2898                 if (mconf->conf_authid == IEEE80211_MESHCONF_AUTH_DISABLED)
2899                         printf("DISABLED");
2900                 else
2901                         printf("UNKNOWN");
2902                 printf(" FORM:0x%x CAPS:0x%x>", mconf->conf_form,
2903                     mconf->conf_cap);
2904         }
2905 }
2906
2907 static void
2908 printbssload(const char *tag, const uint8_t *ie, size_t ielen, int maxlen)
2909 {
2910         printf("%s", tag);
2911         if (verbose) {
2912                 const struct ieee80211_bss_load_ie *bssload =
2913                     (const struct ieee80211_bss_load_ie *) ie;
2914                 printf("<sta count %d, chan load %d, aac %d>",
2915                     LE_READ_2(&bssload->sta_count),
2916                     bssload->chan_load,
2917                     bssload->aac);
2918         }
2919 }
2920
2921 static void
2922 printapchanrep(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2923 {
2924         printf("%s", tag);
2925         if (verbose) {
2926                 const struct ieee80211_ap_chan_report_ie *ap =
2927                     (const struct ieee80211_ap_chan_report_ie *) ie;
2928                 const char *sep = "";
2929                 int i;
2930
2931                 printf("<class %u, chan:[", ap->i_class);
2932
2933                 for (i = 3; i < ielen; i++) {
2934                         printf("%s%u", sep, ie[i]);
2935                         sep = ",";
2936                 }
2937                 printf("]>");
2938         }
2939 }
2940
2941 static const char *
2942 wpa_cipher(const u_int8_t *sel)
2943 {
2944 #define WPA_SEL(x)      (((x)<<24)|WPA_OUI)
2945         u_int32_t w = LE_READ_4(sel);
2946
2947         switch (w) {
2948         case WPA_SEL(WPA_CSE_NULL):
2949                 return "NONE";
2950         case WPA_SEL(WPA_CSE_WEP40):
2951                 return "WEP40";
2952         case WPA_SEL(WPA_CSE_WEP104):
2953                 return "WEP104";
2954         case WPA_SEL(WPA_CSE_TKIP):
2955                 return "TKIP";
2956         case WPA_SEL(WPA_CSE_CCMP):
2957                 return "AES-CCMP";
2958         }
2959         return "?";             /* NB: so 1<< is discarded */
2960 #undef WPA_SEL
2961 }
2962
2963 static const char *
2964 wpa_keymgmt(const u_int8_t *sel)
2965 {
2966 #define WPA_SEL(x)      (((x)<<24)|WPA_OUI)
2967         u_int32_t w = LE_READ_4(sel);
2968
2969         switch (w) {
2970         case WPA_SEL(WPA_ASE_8021X_UNSPEC):
2971                 return "8021X-UNSPEC";
2972         case WPA_SEL(WPA_ASE_8021X_PSK):
2973                 return "8021X-PSK";
2974         case WPA_SEL(WPA_ASE_NONE):
2975                 return "NONE";
2976         }
2977         return "?";
2978 #undef WPA_SEL
2979 }
2980
2981 static void
2982 printwpaie(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
2983 {
2984         u_int8_t len = ie[1];
2985
2986         printf("%s", tag);
2987         if (verbose) {
2988                 const char *sep;
2989                 int n;
2990
2991                 ie += 6, len -= 4;              /* NB: len is payload only */
2992
2993                 printf("<v%u", LE_READ_2(ie));
2994                 ie += 2, len -= 2;
2995
2996                 printf(" mc:%s", wpa_cipher(ie));
2997                 ie += 4, len -= 4;
2998
2999                 /* unicast ciphers */
3000                 n = LE_READ_2(ie);
3001                 ie += 2, len -= 2;
3002                 sep = " uc:";
3003                 for (; n > 0; n--) {
3004                         printf("%s%s", sep, wpa_cipher(ie));
3005                         ie += 4, len -= 4;
3006                         sep = "+";
3007                 }
3008
3009                 /* key management algorithms */
3010                 n = LE_READ_2(ie);
3011                 ie += 2, len -= 2;
3012                 sep = " km:";
3013                 for (; n > 0; n--) {
3014                         printf("%s%s", sep, wpa_keymgmt(ie));
3015                         ie += 4, len -= 4;
3016                         sep = "+";
3017                 }
3018
3019                 if (len > 2)            /* optional capabilities */
3020                         printf(", caps 0x%x", LE_READ_2(ie));
3021                 printf(">");
3022         }
3023 }
3024
3025 static const char *
3026 rsn_cipher(const u_int8_t *sel)
3027 {
3028 #define RSN_SEL(x)      (((x)<<24)|RSN_OUI)
3029         u_int32_t w = LE_READ_4(sel);
3030
3031         switch (w) {
3032         case RSN_SEL(RSN_CSE_NULL):
3033                 return "NONE";
3034         case RSN_SEL(RSN_CSE_WEP40):
3035                 return "WEP40";
3036         case RSN_SEL(RSN_CSE_WEP104):
3037                 return "WEP104";
3038         case RSN_SEL(RSN_CSE_TKIP):
3039                 return "TKIP";
3040         case RSN_SEL(RSN_CSE_CCMP):
3041                 return "AES-CCMP";
3042         case RSN_SEL(RSN_CSE_WRAP):
3043                 return "AES-OCB";
3044         }
3045         return "?";
3046 #undef WPA_SEL
3047 }
3048
3049 static const char *
3050 rsn_keymgmt(const u_int8_t *sel)
3051 {
3052 #define RSN_SEL(x)      (((x)<<24)|RSN_OUI)
3053         u_int32_t w = LE_READ_4(sel);
3054
3055         switch (w) {
3056         case RSN_SEL(RSN_ASE_8021X_UNSPEC):
3057                 return "8021X-UNSPEC";
3058         case RSN_SEL(RSN_ASE_8021X_PSK):
3059                 return "8021X-PSK";
3060         case RSN_SEL(RSN_ASE_NONE):
3061                 return "NONE";
3062         }
3063         return "?";
3064 #undef RSN_SEL
3065 }
3066
3067 static void
3068 printrsnie(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
3069 {
3070         printf("%s", tag);
3071         if (verbose) {
3072                 const char *sep;
3073                 int n;
3074
3075                 ie += 2, ielen -= 2;
3076
3077                 printf("<v%u", LE_READ_2(ie));
3078                 ie += 2, ielen -= 2;
3079
3080                 printf(" mc:%s", rsn_cipher(ie));
3081                 ie += 4, ielen -= 4;
3082
3083                 /* unicast ciphers */
3084                 n = LE_READ_2(ie);
3085                 ie += 2, ielen -= 2;
3086                 sep = " uc:";
3087                 for (; n > 0; n--) {
3088                         printf("%s%s", sep, rsn_cipher(ie));
3089                         ie += 4, ielen -= 4;
3090                         sep = "+";
3091                 }
3092
3093                 /* key management algorithms */
3094                 n = LE_READ_2(ie);
3095                 ie += 2, ielen -= 2;
3096                 sep = " km:";
3097                 for (; n > 0; n--) {
3098                         printf("%s%s", sep, rsn_keymgmt(ie));
3099                         ie += 4, ielen -= 4;
3100                         sep = "+";
3101                 }
3102
3103                 if (ielen > 2)          /* optional capabilities */
3104                         printf(", caps 0x%x", LE_READ_2(ie));
3105                 /* XXXPMKID */
3106                 printf(">");
3107         }
3108 }
3109
3110 /* XXX move to a public include file */
3111 #define IEEE80211_WPS_DEV_PASS_ID       0x1012
3112 #define IEEE80211_WPS_SELECTED_REG      0x1041
3113 #define IEEE80211_WPS_SETUP_STATE       0x1044
3114 #define IEEE80211_WPS_UUID_E            0x1047
3115 #define IEEE80211_WPS_VERSION           0x104a
3116
3117 #define BE_READ_2(p)                                    \
3118         ((u_int16_t)                                    \
3119          ((((const u_int8_t *)(p))[1]      ) |          \
3120           (((const u_int8_t *)(p))[0] <<  8)))
3121
3122 static void
3123 printwpsie(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
3124 {
3125         u_int8_t len = ie[1];
3126
3127         printf("%s", tag);
3128         if (verbose) {
3129                 static const char *dev_pass_id[] = {
3130                         "D",    /* Default (PIN) */
3131                         "U",    /* User-specified */
3132                         "M",    /* Machine-specified */
3133                         "K",    /* Rekey */
3134                         "P",    /* PushButton */
3135                         "R"     /* Registrar-specified */
3136                 };
3137                 int n;
3138
3139                 ie +=6, len -= 4;               /* NB: len is payload only */
3140
3141                 /* WPS IE in Beacon and Probe Resp frames have different fields */
3142                 printf("<");
3143                 while (len) {
3144                         uint16_t tlv_type = BE_READ_2(ie);
3145                         uint16_t tlv_len  = BE_READ_2(ie + 2);
3146
3147                         ie += 4, len -= 4;
3148
3149                         switch (tlv_type) {
3150                         case IEEE80211_WPS_VERSION:
3151                                 printf("v:%d.%d", *ie >> 4, *ie & 0xf);
3152                                 break;
3153                         case IEEE80211_WPS_SETUP_STATE:
3154                                 /* Only 1 and 2 are valid */
3155                                 if (*ie == 0 || *ie >= 3)
3156                                         printf(" state:B");
3157                                 else
3158                                         printf(" st:%s", *ie == 1 ? "N" : "C");
3159                                 break;
3160                         case IEEE80211_WPS_SELECTED_REG:
3161                                 printf(" sel:%s", *ie ? "T" : "F");
3162                                 break;
3163                         case IEEE80211_WPS_DEV_PASS_ID:
3164                                 n = LE_READ_2(ie);
3165                                 if (n < nitems(dev_pass_id))
3166                                         printf(" dpi:%s", dev_pass_id[n]);
3167                                 break;
3168                         case IEEE80211_WPS_UUID_E:
3169                                 printf(" uuid-e:");
3170                                 for (n = 0; n < (tlv_len - 1); n++)
3171                                         printf("%02x-", ie[n]);
3172                                 printf("%02x", ie[n]);
3173                                 break;
3174                         }
3175                         ie += tlv_len, len -= tlv_len;
3176                 }
3177                 printf(">");
3178         }
3179 }
3180
3181 static void
3182 printtdmaie(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
3183 {
3184         printf("%s", tag);
3185         if (verbose && ielen >= sizeof(struct ieee80211_tdma_param)) {
3186                 const struct ieee80211_tdma_param *tdma =
3187                    (const struct ieee80211_tdma_param *) ie;
3188
3189                 /* XXX tstamp */
3190                 printf("<v%u slot:%u slotcnt:%u slotlen:%u bintval:%u inuse:0x%x>",
3191                     tdma->tdma_version, tdma->tdma_slot, tdma->tdma_slotcnt,
3192                     LE_READ_2(&tdma->tdma_slotlen), tdma->tdma_bintval,
3193                     tdma->tdma_inuse[0]);
3194         }
3195 }
3196
3197 /*
3198  * Copy the ssid string contents into buf, truncating to fit.  If the
3199  * ssid is entirely printable then just copy intact.  Otherwise convert
3200  * to hexadecimal.  If the result is truncated then replace the last
3201  * three characters with "...".
3202  */
3203 static int
3204 copy_essid(char buf[], size_t bufsize, const u_int8_t *essid, size_t essid_len)
3205 {
3206         const u_int8_t *p; 
3207         size_t maxlen;
3208         u_int i;
3209
3210         if (essid_len > bufsize)
3211                 maxlen = bufsize;
3212         else
3213                 maxlen = essid_len;
3214         /* determine printable or not */
3215         for (i = 0, p = essid; i < maxlen; i++, p++) {
3216                 if (*p < ' ' || *p > 0x7e)
3217                         break;
3218         }
3219         if (i != maxlen) {              /* not printable, print as hex */
3220                 if (bufsize < 3)
3221                         return 0;
3222                 strlcpy(buf, "0x", bufsize);
3223                 bufsize -= 2;
3224                 p = essid;
3225                 for (i = 0; i < maxlen && bufsize >= 2; i++) {
3226                         sprintf(&buf[2+2*i], "%02x", p[i]);
3227                         bufsize -= 2;
3228                 }
3229                 if (i != essid_len)
3230                         memcpy(&buf[2+2*i-3], "...", 3);
3231         } else {                        /* printable, truncate as needed */
3232                 memcpy(buf, essid, maxlen);
3233                 if (maxlen != essid_len)
3234                         memcpy(&buf[maxlen-3], "...", 3);
3235         }
3236         return maxlen;
3237 }
3238
3239 static void
3240 printssid(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
3241 {
3242         char ssid[2*IEEE80211_NWID_LEN+1];
3243
3244         printf("%s<%.*s>", tag, copy_essid(ssid, maxlen, ie+2, ie[1]), ssid);
3245 }
3246
3247 static void
3248 printrates(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
3249 {
3250         const char *sep;
3251         int i;
3252
3253         printf("%s", tag);
3254         sep = "<";
3255         for (i = 2; i < ielen; i++) {
3256                 printf("%s%s%d", sep,
3257                     ie[i] & IEEE80211_RATE_BASIC ? "B" : "",
3258                     ie[i] & IEEE80211_RATE_VAL);
3259                 sep = ",";
3260         }
3261         printf(">");
3262 }
3263
3264 static void
3265 printcountry(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
3266 {
3267         const struct ieee80211_country_ie *cie =
3268            (const struct ieee80211_country_ie *) ie;
3269         int i, nbands, schan, nchan;
3270
3271         printf("%s<%c%c%c", tag, cie->cc[0], cie->cc[1], cie->cc[2]);
3272         nbands = (cie->len - 3) / sizeof(cie->band[0]);
3273         for (i = 0; i < nbands; i++) {
3274                 schan = cie->band[i].schan;
3275                 nchan = cie->band[i].nchan;
3276                 if (nchan != 1)
3277                         printf(" %u-%u,%u", schan, schan + nchan-1,
3278                             cie->band[i].maxtxpwr);
3279                 else
3280                         printf(" %u,%u", schan, cie->band[i].maxtxpwr);
3281         }
3282         printf(">");
3283 }
3284
3285 static __inline int
3286 iswpaoui(const u_int8_t *frm)
3287 {
3288         return frm[1] > 3 && LE_READ_4(frm+2) == ((WPA_OUI_TYPE<<24)|WPA_OUI);
3289 }
3290
3291 static __inline int
3292 iswmeinfo(const u_int8_t *frm)
3293 {
3294         return frm[1] > 5 && LE_READ_4(frm+2) == ((WME_OUI_TYPE<<24)|WME_OUI) &&
3295                 frm[6] == WME_INFO_OUI_SUBTYPE;
3296 }
3297
3298 static __inline int
3299 iswmeparam(const u_int8_t *frm)
3300 {
3301         return frm[1] > 5 && LE_READ_4(frm+2) == ((WME_OUI_TYPE<<24)|WME_OUI) &&
3302                 frm[6] == WME_PARAM_OUI_SUBTYPE;
3303 }
3304
3305 static __inline int
3306 isatherosoui(const u_int8_t *frm)
3307 {
3308         return frm[1] > 3 && LE_READ_4(frm+2) == ((ATH_OUI_TYPE<<24)|ATH_OUI);
3309 }
3310
3311 static __inline int
3312 istdmaoui(const uint8_t *frm)
3313 {
3314         return frm[1] > 3 && LE_READ_4(frm+2) == ((TDMA_OUI_TYPE<<24)|TDMA_OUI);
3315 }
3316
3317 static __inline int
3318 iswpsoui(const uint8_t *frm)
3319 {
3320         return frm[1] > 3 && LE_READ_4(frm+2) == ((WPS_OUI_TYPE<<24)|WPA_OUI);
3321 }
3322
3323 static const char *
3324 iename(int elemid)
3325 {
3326         switch (elemid) {
3327         case IEEE80211_ELEMID_FHPARMS:  return " FHPARMS";
3328         case IEEE80211_ELEMID_CFPARMS:  return " CFPARMS";
3329         case IEEE80211_ELEMID_TIM:      return " TIM";
3330         case IEEE80211_ELEMID_IBSSPARMS:return " IBSSPARMS";
3331         case IEEE80211_ELEMID_BSSLOAD:  return " BSSLOAD";
3332         case IEEE80211_ELEMID_CHALLENGE:return " CHALLENGE";
3333         case IEEE80211_ELEMID_PWRCNSTR: return " PWRCNSTR";
3334         case IEEE80211_ELEMID_PWRCAP:   return " PWRCAP";
3335         case IEEE80211_ELEMID_TPCREQ:   return " TPCREQ";
3336         case IEEE80211_ELEMID_TPCREP:   return " TPCREP";
3337         case IEEE80211_ELEMID_SUPPCHAN: return " SUPPCHAN";
3338         case IEEE80211_ELEMID_CSA:      return " CSA";
3339         case IEEE80211_ELEMID_MEASREQ:  return " MEASREQ";
3340         case IEEE80211_ELEMID_MEASREP:  return " MEASREP";
3341         case IEEE80211_ELEMID_QUIET:    return " QUIET";
3342         case IEEE80211_ELEMID_IBSSDFS:  return " IBSSDFS";
3343         case IEEE80211_ELEMID_TPC:      return " TPC";
3344         case IEEE80211_ELEMID_CCKM:     return " CCKM";
3345         }
3346         return " ???";
3347 }
3348
3349 static void
3350 printies(const u_int8_t *vp, int ielen, int maxcols)
3351 {
3352         while (ielen > 0) {
3353                 switch (vp[0]) {
3354                 case IEEE80211_ELEMID_SSID:
3355                         if (verbose)
3356                                 printssid(" SSID", vp, 2+vp[1], maxcols);
3357                         break;
3358                 case IEEE80211_ELEMID_RATES:
3359                 case IEEE80211_ELEMID_XRATES:
3360                         if (verbose)
3361                                 printrates(vp[0] == IEEE80211_ELEMID_RATES ?
3362                                     " RATES" : " XRATES", vp, 2+vp[1], maxcols);
3363                         break;
3364                 case IEEE80211_ELEMID_DSPARMS:
3365                         if (verbose)
3366                                 printf(" DSPARMS<%u>", vp[2]);
3367                         break;
3368                 case IEEE80211_ELEMID_COUNTRY:
3369                         if (verbose)
3370                                 printcountry(" COUNTRY", vp, 2+vp[1], maxcols);
3371                         break;
3372                 case IEEE80211_ELEMID_ERP:
3373                         if (verbose)
3374                                 printf(" ERP<0x%x>", vp[2]);
3375                         break;
3376                 case IEEE80211_ELEMID_VENDOR:
3377                         if (iswpaoui(vp))
3378                                 printwpaie(" WPA", vp, 2+vp[1], maxcols);
3379                         else if (iswmeinfo(vp))
3380                                 printwmeinfo(" WME", vp, 2+vp[1], maxcols);
3381                         else if (iswmeparam(vp))
3382                                 printwmeparam(" WME", vp, 2+vp[1], maxcols);
3383                         else if (isatherosoui(vp))
3384                                 printathie(" ATH", vp, 2+vp[1], maxcols);
3385                         else if (iswpsoui(vp))
3386                                 printwpsie(" WPS", vp, 2+vp[1], maxcols);
3387                         else if (istdmaoui(vp))
3388                                 printtdmaie(" TDMA", vp, 2+vp[1], maxcols);
3389                         else if (verbose)
3390                                 printie(" VEN", vp, 2+vp[1], maxcols);
3391                         break;
3392                 case IEEE80211_ELEMID_RSN:
3393                         printrsnie(" RSN", vp, 2+vp[1], maxcols);
3394                         break;
3395                 case IEEE80211_ELEMID_HTCAP:
3396                         printhtcap(" HTCAP", vp, 2+vp[1], maxcols);
3397                         break;
3398                 case IEEE80211_ELEMID_HTINFO:
3399                         if (verbose)
3400                                 printhtinfo(" HTINFO", vp, 2+vp[1], maxcols);
3401                         break;
3402                 case IEEE80211_ELEMID_MESHID:
3403                         if (verbose)
3404                                 printssid(" MESHID", vp, 2+vp[1], maxcols);
3405                         break;
3406                 case IEEE80211_ELEMID_MESHCONF:
3407                         printmeshconf(" MESHCONF", vp, 2+vp[1], maxcols);
3408                         break;
3409                 case IEEE80211_ELEMID_VHT_CAP:
3410                         printvhtcap(" VHTCAP", vp, 2+vp[1], maxcols);
3411                         break;
3412                 case IEEE80211_ELEMID_VHT_OPMODE:
3413                         printvhtinfo(" VHTOPMODE", vp, 2+vp[1], maxcols);
3414                         break;
3415                 case IEEE80211_ELEMID_VHT_PWR_ENV:
3416                         printvhtpwrenv(" VHTPWRENV", vp, 2+vp[1], maxcols);
3417                         break;
3418                 case IEEE80211_ELEMID_BSSLOAD:
3419                         printbssload(" BSSLOAD", vp, 2+vp[1], maxcols);
3420                         break;
3421                 case IEEE80211_ELEMID_APCHANREP:
3422                         printapchanrep(" APCHANREP", vp, 2+vp[1], maxcols);
3423                         break;
3424                 default:
3425                         if (verbose)
3426                                 printie(iename(vp[0]), vp, 2+vp[1], maxcols);
3427                         break;
3428                 }
3429                 ielen -= 2+vp[1];
3430                 vp += 2+vp[1];
3431         }
3432 }
3433
3434 static void
3435 printmimo(const struct ieee80211_mimo_info *mi)
3436 {
3437         /* NB: don't muddy display unless there's something to show */
3438         if (mi->rssi[0] != 0 || mi->rssi[1] != 0 || mi->rssi[2] != 0) {
3439                 /* XXX ignore EVM for now */
3440                 printf(" (rssi %.1f:%.1f:%.1f nf %d:%d:%d)",
3441                     mi->rssi[0] / 2.0, mi->rssi[1] / 2.0, mi->rssi[2] / 2.0,
3442                     mi->noise[0], mi->noise[1], mi->noise[2]);
3443         }
3444 }
3445
3446 static void
3447 list_scan(int s)
3448 {
3449         uint8_t buf[24*1024];
3450         char ssid[IEEE80211_NWID_LEN+1];
3451         const uint8_t *cp;
3452         int len, ssidmax, idlen;
3453
3454         if (get80211len(s, IEEE80211_IOC_SCAN_RESULTS, buf, sizeof(buf), &len) < 0)
3455                 errx(1, "unable to get scan results");
3456         if (len < sizeof(struct ieee80211req_scan_result))
3457                 return;
3458
3459         getchaninfo(s);
3460
3461         ssidmax = verbose ? IEEE80211_NWID_LEN : 14;
3462         printf("%-*.*s  %-17.17s  %4s %4s   %-7s  %3s %4s\n"
3463                 , ssidmax, ssidmax, "SSID/MESH ID"
3464                 , "BSSID"
3465                 , "CHAN"
3466                 , "RATE"
3467                 , " S:N"
3468                 , "INT"
3469                 , "CAPS"
3470         );
3471         cp = buf;
3472         do {
3473                 const struct ieee80211req_scan_result *sr;
3474                 const uint8_t *vp, *idp;
3475
3476                 sr = (const struct ieee80211req_scan_result *) cp;
3477                 vp = cp + sr->isr_ie_off;
3478                 if (sr->isr_meshid_len) {
3479                         idp = vp + sr->isr_ssid_len;
3480                         idlen = sr->isr_meshid_len;
3481                 } else {
3482                         idp = vp;
3483                         idlen = sr->isr_ssid_len;
3484                 }
3485                 printf("%-*.*s  %s  %3d  %3dM %4d:%-4d %4d %-4.4s"
3486                         , ssidmax
3487                           , copy_essid(ssid, ssidmax, idp, idlen)
3488                           , ssid
3489                         , ether_ntoa((const struct ether_addr *) sr->isr_bssid)
3490                         , ieee80211_mhz2ieee(sr->isr_freq, sr->isr_flags)
3491                         , getmaxrate(sr->isr_rates, sr->isr_nrates)
3492                         , (sr->isr_rssi/2)+sr->isr_noise, sr->isr_noise
3493                         , sr->isr_intval
3494                         , getcaps(sr->isr_capinfo)
3495                 );
3496                 printies(vp + sr->isr_ssid_len + sr->isr_meshid_len,
3497                     sr->isr_ie_len, 24);
3498                 printf("\n");
3499                 cp += sr->isr_len, len -= sr->isr_len;
3500         } while (len >= sizeof(struct ieee80211req_scan_result));
3501 }
3502
3503 static void
3504 scan_and_wait(int s)
3505 {
3506         struct ieee80211_scan_req sr;
3507         struct ieee80211req ireq;
3508         int sroute;
3509
3510         sroute = socket(PF_ROUTE, SOCK_RAW, 0);
3511         if (sroute < 0) {
3512                 perror("socket(PF_ROUTE,SOCK_RAW)");
3513                 return;
3514         }
3515         (void) memset(&ireq, 0, sizeof(ireq));
3516         (void) strlcpy(ireq.i_name, name, sizeof(ireq.i_name));
3517         ireq.i_type = IEEE80211_IOC_SCAN_REQ;
3518
3519         memset(&sr, 0, sizeof(sr));
3520         sr.sr_flags = IEEE80211_IOC_SCAN_ACTIVE
3521                     | IEEE80211_IOC_SCAN_BGSCAN
3522                     | IEEE80211_IOC_SCAN_NOPICK
3523                     | IEEE80211_IOC_SCAN_ONCE;
3524         sr.sr_duration = IEEE80211_IOC_SCAN_FOREVER;
3525         sr.sr_nssid = 0;
3526
3527         ireq.i_data = &sr;
3528         ireq.i_len = sizeof(sr);
3529         /*
3530          * NB: only root can trigger a scan so ignore errors. Also ignore
3531          * possible errors from net80211, even if no new scan could be
3532          * started there might still be a valid scan cache.
3533          */
3534         if (ioctl(s, SIOCS80211, &ireq) == 0) {
3535                 char buf[2048];
3536                 struct if_announcemsghdr *ifan;
3537                 struct rt_msghdr *rtm;
3538
3539                 do {
3540                         if (read(sroute, buf, sizeof(buf)) < 0) {
3541                                 perror("read(PF_ROUTE)");
3542                                 break;
3543                         }
3544                         rtm = (struct rt_msghdr *) buf;
3545                         if (rtm->rtm_version != RTM_VERSION)
3546                                 break;
3547                         ifan = (struct if_announcemsghdr *) rtm;
3548                 } while (rtm->rtm_type != RTM_IEEE80211 ||
3549                     ifan->ifan_what != RTM_IEEE80211_SCAN);
3550         }
3551         close(sroute);
3552 }
3553
3554 static
3555 DECL_CMD_FUNC(set80211scan, val, d)
3556 {
3557         scan_and_wait(s);
3558         list_scan(s);
3559 }
3560
3561 static enum ieee80211_opmode get80211opmode(int s);
3562
3563 static int
3564 gettxseq(const struct ieee80211req_sta_info *si)
3565 {
3566         int i, txseq;
3567
3568         if ((si->isi_state & IEEE80211_NODE_QOS) == 0)
3569                 return si->isi_txseqs[0];
3570         /* XXX not right but usually what folks want */
3571         txseq = 0;
3572         for (i = 0; i < IEEE80211_TID_SIZE; i++)
3573                 if (si->isi_txseqs[i] > txseq)
3574                         txseq = si->isi_txseqs[i];
3575         return txseq;
3576 }
3577
3578 static int
3579 getrxseq(const struct ieee80211req_sta_info *si)
3580 {
3581         int i, rxseq;
3582
3583         if ((si->isi_state & IEEE80211_NODE_QOS) == 0)
3584                 return si->isi_rxseqs[0];
3585         /* XXX not right but usually what folks want */
3586         rxseq = 0;
3587         for (i = 0; i < IEEE80211_TID_SIZE; i++)
3588                 if (si->isi_rxseqs[i] > rxseq)
3589                         rxseq = si->isi_rxseqs[i];
3590         return rxseq;
3591 }
3592
3593 static void
3594 list_stations(int s)
3595 {
3596         union {
3597                 struct ieee80211req_sta_req req;
3598                 uint8_t buf[24*1024];
3599         } u;
3600         enum ieee80211_opmode opmode = get80211opmode(s);
3601         const uint8_t *cp;
3602         int len;
3603
3604         /* broadcast address =>'s get all stations */
3605         (void) memset(u.req.is_u.macaddr, 0xff, IEEE80211_ADDR_LEN);
3606         if (opmode == IEEE80211_M_STA) {
3607                 /*
3608                  * Get information about the associated AP.
3609                  */
3610                 (void) get80211(s, IEEE80211_IOC_BSSID,
3611                     u.req.is_u.macaddr, IEEE80211_ADDR_LEN);
3612         }
3613         if (get80211len(s, IEEE80211_IOC_STA_INFO, &u, sizeof(u), &len) < 0)
3614                 errx(1, "unable to get station information");
3615         if (len < sizeof(struct ieee80211req_sta_info))
3616                 return;
3617
3618         getchaninfo(s);
3619
3620         if (opmode == IEEE80211_M_MBSS)
3621                 printf("%-17.17s %4s %5s %5s %7s %4s %4s %4s %6s %6s\n"
3622                         , "ADDR"
3623                         , "CHAN"
3624                         , "LOCAL"
3625                         , "PEER"
3626                         , "STATE"
3627                         , "RATE"
3628                         , "RSSI"
3629                         , "IDLE"
3630                         , "TXSEQ"
3631                         , "RXSEQ"
3632                 );
3633         else 
3634                 printf("%-17.17s %4s %4s %4s %4s %4s %6s %6s %4s %-7s\n"
3635                         , "ADDR"
3636                         , "AID"
3637                         , "CHAN"
3638                         , "RATE"
3639                         , "RSSI"
3640                         , "IDLE"
3641                         , "TXSEQ"
3642                         , "RXSEQ"
3643                         , "CAPS"
3644                         , "FLAG"
3645                 );
3646         cp = (const uint8_t *) u.req.info;
3647         do {
3648                 const struct ieee80211req_sta_info *si;
3649
3650                 si = (const struct ieee80211req_sta_info *) cp;
3651                 if (si->isi_len < sizeof(*si))
3652                         break;
3653                 if (opmode == IEEE80211_M_MBSS)
3654                         printf("%s %4d %5x %5x %7.7s %3dM %4.1f %4d %6d %6d"
3655                                 , ether_ntoa((const struct ether_addr*)
3656                                     si->isi_macaddr)
3657                                 , ieee80211_mhz2ieee(si->isi_freq,
3658                                     si->isi_flags)
3659                                 , si->isi_localid
3660                                 , si->isi_peerid
3661                                 , mesh_linkstate_string(si->isi_peerstate)
3662                                 , si->isi_txmbps/2
3663                                 , si->isi_rssi/2.
3664                                 , si->isi_inact
3665                                 , gettxseq(si)
3666                                 , getrxseq(si)
3667                         );
3668                 else 
3669                         printf("%s %4u %4d %3dM %4.1f %4d %6d %6d %-4.4s %-7.7s"
3670                                 , ether_ntoa((const struct ether_addr*)
3671                                     si->isi_macaddr)
3672                                 , IEEE80211_AID(si->isi_associd)
3673                                 , ieee80211_mhz2ieee(si->isi_freq,
3674                                     si->isi_flags)
3675                                 , si->isi_txmbps/2
3676                                 , si->isi_rssi/2.
3677                                 , si->isi_inact
3678                                 , gettxseq(si)
3679                                 , getrxseq(si)
3680                                 , getcaps(si->isi_capinfo)
3681                                 , getflags(si->isi_state)
3682                         );
3683                 printies(cp + si->isi_ie_off, si->isi_ie_len, 24);
3684                 printmimo(&si->isi_mimo);
3685                 printf("\n");
3686                 cp += si->isi_len, len -= si->isi_len;
3687         } while (len >= sizeof(struct ieee80211req_sta_info));
3688 }
3689
3690 static const char *
3691 mesh_linkstate_string(uint8_t state)
3692 {
3693         static const char *state_names[] = {
3694             [0] = "IDLE",
3695             [1] = "OPEN-TX",
3696             [2] = "OPEN-RX",
3697             [3] = "CONF-RX",
3698             [4] = "ESTAB",
3699             [5] = "HOLDING",
3700         };
3701
3702         if (state >= nitems(state_names)) {
3703                 static char buf[10];
3704                 snprintf(buf, sizeof(buf), "#%u", state);
3705                 return buf;
3706         } else
3707                 return state_names[state];
3708 }
3709
3710 static const char *
3711 get_chaninfo(const struct ieee80211_channel *c, int precise,
3712         char buf[], size_t bsize)
3713 {
3714         buf[0] = '\0';
3715         if (IEEE80211_IS_CHAN_FHSS(c))
3716                 strlcat(buf, " FHSS", bsize);
3717         if (IEEE80211_IS_CHAN_A(c))
3718                 strlcat(buf, " 11a", bsize);
3719         else if (IEEE80211_IS_CHAN_ANYG(c))
3720                 strlcat(buf, " 11g", bsize);
3721         else if (IEEE80211_IS_CHAN_B(c))
3722                 strlcat(buf, " 11b", bsize);
3723         if (IEEE80211_IS_CHAN_HALF(c))
3724                 strlcat(buf, "/10MHz", bsize);
3725         if (IEEE80211_IS_CHAN_QUARTER(c))
3726                 strlcat(buf, "/5MHz", bsize);
3727         if (IEEE80211_IS_CHAN_TURBO(c))
3728                 strlcat(buf, " Turbo", bsize);
3729         if (precise) {
3730                 /* XXX should make VHT80U, VHT80D */
3731                 if (IEEE80211_IS_CHAN_VHT80(c) &&
3732                     IEEE80211_IS_CHAN_HT40D(c))
3733                         strlcat(buf, " vht/80-", bsize);
3734                 else if (IEEE80211_IS_CHAN_VHT80(c) &&
3735                     IEEE80211_IS_CHAN_HT40U(c))
3736                         strlcat(buf, " vht/80+", bsize);
3737                 else if (IEEE80211_IS_CHAN_VHT80(c))
3738                         strlcat(buf, " vht/80", bsize);
3739                 else if (IEEE80211_IS_CHAN_VHT40D(c))
3740                         strlcat(buf, " vht/40-", bsize);
3741                 else if (IEEE80211_IS_CHAN_VHT40U(c))
3742                         strlcat(buf, " vht/40+", bsize);
3743                 else if (IEEE80211_IS_CHAN_VHT20(c))
3744                         strlcat(buf, " vht/20", bsize);
3745                 else if (IEEE80211_IS_CHAN_HT20(c))
3746                         strlcat(buf, " ht/20", bsize);
3747                 else if (IEEE80211_IS_CHAN_HT40D(c))
3748                         strlcat(buf, " ht/40-", bsize);
3749                 else if (IEEE80211_IS_CHAN_HT40U(c))
3750                         strlcat(buf, " ht/40+", bsize);
3751         } else {
3752                 if (IEEE80211_IS_CHAN_VHT(c))
3753                         strlcat(buf, " vht", bsize);
3754                 else if (IEEE80211_IS_CHAN_HT(c))
3755                         strlcat(buf, " ht", bsize);
3756         }
3757         return buf;
3758 }
3759
3760 static void
3761 print_chaninfo(const struct ieee80211_channel *c, int verb)
3762 {
3763         char buf[14];
3764
3765         if (verb)
3766                 printf("Channel %3u : %u%c%c%c%c%c MHz%-14.14s",
3767                     ieee80211_mhz2ieee(c->ic_freq, c->ic_flags), c->ic_freq,
3768                     IEEE80211_IS_CHAN_PASSIVE(c) ? '*' : ' ',
3769                     IEEE80211_IS_CHAN_DFS(c) ? 'D' : ' ',
3770                     IEEE80211_IS_CHAN_RADAR(c) ? 'R' : ' ',
3771                     IEEE80211_IS_CHAN_CWINT(c) ? 'I' : ' ',
3772                     IEEE80211_IS_CHAN_CACDONE(c) ? 'C' : ' ',
3773                     get_chaninfo(c, verb, buf, sizeof(buf)));
3774         else
3775         printf("Channel %3u : %u%c MHz%-14.14s",
3776             ieee80211_mhz2ieee(c->ic_freq, c->ic_flags), c->ic_freq,
3777             IEEE80211_IS_CHAN_PASSIVE(c) ? '*' : ' ',
3778             get_chaninfo(c, verb, buf, sizeof(buf)));
3779
3780 }
3781
3782 static int
3783 chanpref(const struct ieee80211_channel *c)
3784 {
3785         if (IEEE80211_IS_CHAN_VHT160(c))
3786                 return 80;
3787         if (IEEE80211_IS_CHAN_VHT80_80(c))
3788                 return 75;
3789         if (IEEE80211_IS_CHAN_VHT80(c))
3790                 return 70;
3791         if (IEEE80211_IS_CHAN_VHT40(c))
3792                 return 60;
3793         if (IEEE80211_IS_CHAN_VHT20(c))
3794                 return 50;
3795         if (IEEE80211_IS_CHAN_HT40(c))
3796                 return 40;
3797         if (IEEE80211_IS_CHAN_HT20(c))
3798                 return 30;
3799         if (IEEE80211_IS_CHAN_HALF(c))
3800                 return 10;
3801         if (IEEE80211_IS_CHAN_QUARTER(c))
3802                 return 5;
3803         if (IEEE80211_IS_CHAN_TURBO(c))
3804                 return 25;
3805         if (IEEE80211_IS_CHAN_A(c))
3806                 return 20;
3807         if (IEEE80211_IS_CHAN_G(c))
3808                 return 20;
3809         if (IEEE80211_IS_CHAN_B(c))
3810                 return 15;
3811         if (IEEE80211_IS_CHAN_PUREG(c))
3812                 return 15;
3813         return 0;
3814 }
3815
3816 static void
3817 print_channels(int s, const struct ieee80211req_chaninfo *chans,
3818         int allchans, int verb)
3819 {
3820         struct ieee80211req_chaninfo *achans;
3821         uint8_t reported[IEEE80211_CHAN_BYTES];
3822         const struct ieee80211_channel *c;
3823         int i, half;
3824
3825         achans = malloc(IEEE80211_CHANINFO_SPACE(chans));
3826         if (achans == NULL)
3827                 errx(1, "no space for active channel list");
3828         achans->ic_nchans = 0;
3829         memset(reported, 0, sizeof(reported));
3830         if (!allchans) {
3831                 struct ieee80211req_chanlist active;
3832
3833                 if (get80211(s, IEEE80211_IOC_CHANLIST, &active, sizeof(active)) < 0)
3834                         errx(1, "unable to get active channel list");
3835                 for (i = 0; i < chans->ic_nchans; i++) {
3836                         c = &chans->ic_chans[i];
3837                         if (!isset(active.ic_channels, c->ic_ieee))
3838                                 continue;
3839                         /*
3840                          * Suppress compatible duplicates unless
3841                          * verbose.  The kernel gives us it's
3842                          * complete channel list which has separate
3843                          * entries for 11g/11b and 11a/turbo.
3844                          */
3845                         if (isset(reported, c->ic_ieee) && !verb) {
3846                                 /* XXX we assume duplicates are adjacent */
3847                                 achans->ic_chans[achans->ic_nchans-1] = *c;
3848                         } else {
3849                                 achans->ic_chans[achans->ic_nchans++] = *c;
3850                                 setbit(reported, c->ic_ieee);
3851                         }
3852                 }
3853         } else {
3854                 for (i = 0; i < chans->ic_nchans; i++) {
3855                         c = &chans->ic_chans[i];
3856                         /* suppress duplicates as above */
3857                         if (isset(reported, c->ic_ieee) && !verb) {
3858                                 /* XXX we assume duplicates are adjacent */
3859                                 struct ieee80211_channel *a =
3860                                     &achans->ic_chans[achans->ic_nchans-1];
3861                                 if (chanpref(c) > chanpref(a))
3862                                         *a = *c;
3863                         } else {
3864                                 achans->ic_chans[achans->ic_nchans++] = *c;
3865                                 setbit(reported, c->ic_ieee);
3866                         }
3867                 }
3868         }
3869         half = achans->ic_nchans / 2;
3870         if (achans->ic_nchans % 2)
3871                 half++;
3872
3873         for (i = 0; i < achans->ic_nchans / 2; i++) {
3874                 print_chaninfo(&achans->ic_chans[i], verb);
3875                 print_chaninfo(&achans->ic_chans[half+i], verb);
3876                 printf("\n");
3877         }
3878         if (achans->ic_nchans % 2) {
3879                 print_chaninfo(&achans->ic_chans[i], verb);
3880                 printf("\n");
3881         }
3882         free(achans);
3883 }
3884
3885 static void
3886 list_channels(int s, int allchans)
3887 {
3888         getchaninfo(s);
3889         print_channels(s, chaninfo, allchans, verbose);
3890 }
3891
3892 static void
3893 print_txpow(const struct ieee80211_channel *c)
3894 {
3895         printf("Channel %3u : %u MHz %3.1f reg %2d  ",
3896             c->ic_ieee, c->ic_freq,
3897             c->ic_maxpower/2., c->ic_maxregpower);
3898 }
3899
3900 static void
3901 print_txpow_verbose(const struct ieee80211_channel *c)
3902 {
3903         print_chaninfo(c, 1);
3904         printf("min %4.1f dBm  max %3.1f dBm  reg %2d dBm",
3905             c->ic_minpower/2., c->ic_maxpower/2., c->ic_maxregpower);
3906         /* indicate where regulatory cap limits power use */
3907         if (c->ic_maxpower > 2*c->ic_maxregpower)
3908                 printf(" <");
3909 }
3910
3911 static void
3912 list_txpow(int s)
3913 {
3914         struct ieee80211req_chaninfo *achans;
3915         uint8_t reported[IEEE80211_CHAN_BYTES];
3916         struct ieee80211_channel *c, *prev;
3917         int i, half;
3918
3919         getchaninfo(s);
3920         achans = malloc(IEEE80211_CHANINFO_SPACE(chaninfo));
3921         if (achans == NULL)
3922                 errx(1, "no space for active channel list");
3923         achans->ic_nchans = 0;
3924         memset(reported, 0, sizeof(reported));
3925         for (i = 0; i < chaninfo->ic_nchans; i++) {
3926                 c = &chaninfo->ic_chans[i];
3927                 /* suppress duplicates as above */
3928                 if (isset(reported, c->ic_ieee) && !verbose) {
3929                         /* XXX we assume duplicates are adjacent */
3930                         assert(achans->ic_nchans > 0);
3931                         prev = &achans->ic_chans[achans->ic_nchans-1];
3932                         /* display highest power on channel */
3933                         if (c->ic_maxpower > prev->ic_maxpower)
3934                                 *prev = *c;
3935                 } else {
3936                         achans->ic_chans[achans->ic_nchans++] = *c;
3937                         setbit(reported, c->ic_ieee);
3938                 }
3939         }
3940         if (!verbose) {
3941                 half = achans->ic_nchans / 2;
3942                 if (achans->ic_nchans % 2)
3943                         half++;
3944
3945                 for (i = 0; i < achans->ic_nchans / 2; i++) {
3946                         print_txpow(&achans->ic_chans[i]);
3947                         print_txpow(&achans->ic_chans[half+i]);
3948                         printf("\n");
3949                 }
3950                 if (achans->ic_nchans % 2) {
3951                         print_txpow(&achans->ic_chans[i]);
3952                         printf("\n");
3953                 }
3954         } else {
3955                 for (i = 0; i < achans->ic_nchans; i++) {
3956                         print_txpow_verbose(&achans->ic_chans[i]);
3957                         printf("\n");
3958                 }
3959         }
3960         free(achans);
3961 }
3962
3963 static void
3964 list_keys(int s)
3965 {
3966 }
3967
3968 static void
3969 list_capabilities(int s)
3970 {
3971         struct ieee80211_devcaps_req *dc;
3972
3973         if (verbose)
3974                 dc = malloc(IEEE80211_DEVCAPS_SIZE(MAXCHAN));
3975         else
3976                 dc = malloc(IEEE80211_DEVCAPS_SIZE(1));
3977         if (dc == NULL)
3978                 errx(1, "no space for device capabilities");
3979         dc->dc_chaninfo.ic_nchans = verbose ? MAXCHAN : 1;
3980         getdevcaps(s, dc);
3981         printb("drivercaps", dc->dc_drivercaps, IEEE80211_C_BITS);
3982         if (dc->dc_cryptocaps != 0 || verbose) {
3983                 putchar('\n');
3984                 printb("cryptocaps", dc->dc_cryptocaps, IEEE80211_CRYPTO_BITS);
3985         }
3986         if (dc->dc_htcaps != 0 || verbose) {
3987                 putchar('\n');
3988                 printb("htcaps", dc->dc_htcaps, IEEE80211_HTCAP_BITS);
3989         }
3990         if (dc->dc_vhtcaps != 0 || verbose) {
3991                 putchar('\n');
3992                 printb("vhtcaps", dc->dc_vhtcaps, IEEE80211_VHTCAP_BITS);
3993         }
3994
3995         putchar('\n');
3996         if (verbose) {
3997                 chaninfo = &dc->dc_chaninfo;    /* XXX */
3998                 print_channels(s, &dc->dc_chaninfo, 1/*allchans*/, verbose);
3999         }
4000         free(dc);
4001 }
4002
4003 static int
4004 get80211wme(int s, int param, int ac, int *val)
4005 {
4006         struct ieee80211req ireq;
4007
4008         (void) memset(&ireq, 0, sizeof(ireq));
4009         (void) strlcpy(ireq.i_name, name, sizeof(ireq.i_name));
4010         ireq.i_type = param;
4011         ireq.i_len = ac;
4012         if (ioctl(s, SIOCG80211, &ireq) < 0) {
4013                 warn("cannot get WME parameter %d, ac %d%s",
4014                     param, ac & IEEE80211_WMEPARAM_VAL,
4015                     ac & IEEE80211_WMEPARAM_BSS ? " (BSS)" : "");
4016                 return -1;
4017         }
4018         *val = ireq.i_val;
4019         return 0;
4020 }
4021
4022 static void
4023 list_wme_aci(int s, const char *tag, int ac)
4024 {
4025         int val;
4026
4027         printf("\t%s", tag);
4028
4029         /* show WME BSS parameters */
4030         if (get80211wme(s, IEEE80211_IOC_WME_CWMIN, ac, &val) != -1)
4031                 printf(" cwmin %2u", val);
4032         if (get80211wme(s, IEEE80211_IOC_WME_CWMAX, ac, &val) != -1)
4033                 printf(" cwmax %2u", val);
4034         if (get80211wme(s, IEEE80211_IOC_WME_AIFS, ac, &val) != -1)
4035                 printf(" aifs %2u", val);
4036         if (get80211wme(s, IEEE80211_IOC_WME_TXOPLIMIT, ac, &val) != -1)
4037                 printf(" txopLimit %3u", val);
4038         if (get80211wme(s, IEEE80211_IOC_WME_ACM, ac, &val) != -1) {
4039                 if (val)
4040                         printf(" acm");
4041                 else if (verbose)
4042                         printf(" -acm");
4043         }
4044         /* !BSS only */
4045         if ((ac & IEEE80211_WMEPARAM_BSS) == 0) {
4046                 if (get80211wme(s, IEEE80211_IOC_WME_ACKPOLICY, ac, &val) != -1) {
4047                         if (!val)
4048                                 printf(" -ack");
4049                         else if (verbose)
4050                                 printf(" ack");
4051                 }
4052         }
4053         printf("\n");
4054 }
4055
4056 static void
4057 list_wme(int s)
4058 {
4059         static const char *acnames[] = { "AC_BE", "AC_BK", "AC_VI", "AC_VO" };
4060         int ac;
4061
4062         if (verbose) {
4063                 /* display both BSS and local settings */
4064                 for (ac = WME_AC_BE; ac <= WME_AC_VO; ac++) {
4065         again:
4066                         if (ac & IEEE80211_WMEPARAM_BSS)
4067                                 list_wme_aci(s, "     ", ac);
4068                         else
4069                                 list_wme_aci(s, acnames[ac], ac);
4070                         if ((ac & IEEE80211_WMEPARAM_BSS) == 0) {
4071                                 ac |= IEEE80211_WMEPARAM_BSS;
4072                                 goto again;
4073                         } else
4074                                 ac &= ~IEEE80211_WMEPARAM_BSS;
4075                 }
4076         } else {
4077                 /* display only channel settings */
4078                 for (ac = WME_AC_BE; ac <= WME_AC_VO; ac++)
4079                         list_wme_aci(s, acnames[ac], ac);
4080         }
4081 }
4082
4083 static void
4084 list_roam(int s)
4085 {
4086         const struct ieee80211_roamparam *rp;
4087         int mode;
4088
4089         getroam(s);
4090         for (mode = IEEE80211_MODE_11A; mode < IEEE80211_MODE_MAX; mode++) {
4091                 rp = &roamparams.params[mode];
4092                 if (rp->rssi == 0 && rp->rate == 0)
4093                         continue;
4094                 if (mode == IEEE80211_MODE_11NA || mode == IEEE80211_MODE_11NG) {
4095                         if (rp->rssi & 1)
4096                                 LINE_CHECK("roam:%-7.7s rssi %2u.5dBm  MCS %2u    ",
4097                                     modename[mode], rp->rssi/2,
4098                                     rp->rate &~ IEEE80211_RATE_MCS);
4099                         else
4100                                 LINE_CHECK("roam:%-7.7s rssi %4udBm  MCS %2u    ",
4101                                     modename[mode], rp->rssi/2,
4102                                     rp->rate &~ IEEE80211_RATE_MCS);
4103                 } else {
4104                         if (rp->rssi & 1)
4105                                 LINE_CHECK("roam:%-7.7s rssi %2u.5dBm rate %2u Mb/s",
4106                                     modename[mode], rp->rssi/2, rp->rate/2);
4107                         else
4108                                 LINE_CHECK("roam:%-7.7s rssi %4udBm rate %2u Mb/s",
4109                                     modename[mode], rp->rssi/2, rp->rate/2);
4110                 }
4111         }
4112 }
4113
4114 static void
4115 list_txparams(int s)
4116 {
4117         const struct ieee80211_txparam *tp;
4118         int mode;
4119
4120         gettxparams(s);
4121         for (mode = IEEE80211_MODE_11A; mode < IEEE80211_MODE_MAX; mode++) {
4122                 tp = &txparams.params[mode];
4123                 if (tp->mgmtrate == 0 && tp->mcastrate == 0)
4124                         continue;
4125                 if (mode == IEEE80211_MODE_11NA || mode == IEEE80211_MODE_11NG) {
4126                         if (tp->ucastrate == IEEE80211_FIXED_RATE_NONE)
4127                                 LINE_CHECK("%-7.7s ucast NONE    mgmt %2u MCS  "
4128                                     "mcast %2u MCS  maxretry %u",
4129                                     modename[mode],
4130                                     tp->mgmtrate &~ IEEE80211_RATE_MCS,
4131                                     tp->mcastrate &~ IEEE80211_RATE_MCS,
4132                                     tp->maxretry);
4133                         else
4134                                 LINE_CHECK("%-7.7s ucast %2u MCS  mgmt %2u MCS  "
4135                                     "mcast %2u MCS  maxretry %u",
4136                                     modename[mode],
4137                                     tp->ucastrate &~ IEEE80211_RATE_MCS,
4138                                     tp->mgmtrate &~ IEEE80211_RATE_MCS,
4139                                     tp->mcastrate &~ IEEE80211_RATE_MCS,
4140                                     tp->maxretry);
4141                 } else {
4142                         if (tp->ucastrate == IEEE80211_FIXED_RATE_NONE)
4143                                 LINE_CHECK("%-7.7s ucast NONE    mgmt %2u Mb/s "
4144                                     "mcast %2u Mb/s maxretry %u",
4145                                     modename[mode],
4146                                     tp->mgmtrate/2,
4147                                     tp->mcastrate/2, tp->maxretry);
4148                         else
4149                                 LINE_CHECK("%-7.7s ucast %2u Mb/s mgmt %2u Mb/s "
4150                                     "mcast %2u Mb/s maxretry %u",
4151                                     modename[mode],
4152                                     tp->ucastrate/2, tp->mgmtrate/2,
4153                                     tp->mcastrate/2, tp->maxretry);
4154                 }
4155         }
4156 }
4157
4158 static void
4159 printpolicy(int policy)
4160 {
4161         switch (policy) {
4162         case IEEE80211_MACCMD_POLICY_OPEN:
4163                 printf("policy: open\n");
4164                 break;
4165         case IEEE80211_MACCMD_POLICY_ALLOW:
4166                 printf("policy: allow\n");
4167                 break;
4168         case IEEE80211_MACCMD_POLICY_DENY:
4169                 printf("policy: deny\n");
4170                 break;
4171         case IEEE80211_MACCMD_POLICY_RADIUS:
4172                 printf("policy: radius\n");
4173                 break;
4174         default:
4175                 printf("policy: unknown (%u)\n", policy);
4176                 break;
4177         }
4178 }
4179
4180 static void
4181 list_mac(int s)
4182 {
4183         struct ieee80211req ireq;
4184         struct ieee80211req_maclist *acllist;
4185         int i, nacls, policy, len;
4186         uint8_t *data;
4187         char c;
4188
4189         (void) memset(&ireq, 0, sizeof(ireq));
4190         (void) strlcpy(ireq.i_name, name, sizeof(ireq.i_name)); /* XXX ?? */
4191         ireq.i_type = IEEE80211_IOC_MACCMD;
4192         ireq.i_val = IEEE80211_MACCMD_POLICY;
4193         if (ioctl(s, SIOCG80211, &ireq) < 0) {
4194                 if (errno == EINVAL) {
4195                         printf("No acl policy loaded\n");
4196                         return;
4197                 }
4198                 err(1, "unable to get mac policy");
4199         }
4200         policy = ireq.i_val;
4201         if (policy == IEEE80211_MACCMD_POLICY_OPEN) {
4202                 c = '*';
4203         } else if (policy == IEEE80211_MACCMD_POLICY_ALLOW) {
4204                 c = '+';
4205         } else if (policy == IEEE80211_MACCMD_POLICY_DENY) {
4206                 c = '-';
4207         } else if (policy == IEEE80211_MACCMD_POLICY_RADIUS) {
4208                 c = 'r';                /* NB: should never have entries */
4209         } else {
4210                 printf("policy: unknown (%u)\n", policy);
4211                 c = '?';
4212         }
4213         if (verbose || c == '?')
4214                 printpolicy(policy);
4215
4216         ireq.i_val = IEEE80211_MACCMD_LIST;
4217         ireq.i_len = 0;
4218         if (ioctl(s, SIOCG80211, &ireq) < 0)
4219                 err(1, "unable to get mac acl list size");
4220         if (ireq.i_len == 0) {          /* NB: no acls */
4221                 if (!(verbose || c == '?'))
4222                         printpolicy(policy);
4223                 return;
4224         }
4225         len = ireq.i_len;
4226
4227         data = malloc(len);
4228         if (data == NULL)
4229                 err(1, "out of memory for acl list");
4230
4231         ireq.i_data = data;
4232         if (ioctl(s, SIOCG80211, &ireq) < 0)
4233                 err(1, "unable to get mac acl list");
4234         nacls = len / sizeof(*acllist);
4235         acllist = (struct ieee80211req_maclist *) data;
4236         for (i = 0; i < nacls; i++)
4237                 printf("%c%s\n", c, ether_ntoa(
4238                         (const struct ether_addr *) acllist[i].ml_macaddr));
4239         free(data);
4240 }
4241
4242 static void
4243 print_regdomain(const struct ieee80211_regdomain *reg, int verb)
4244 {
4245         if ((reg->regdomain != 0 &&
4246             reg->regdomain != reg->country) || verb) {
4247                 const struct regdomain *rd =
4248                     lib80211_regdomain_findbysku(getregdata(), reg->regdomain);
4249                 if (rd == NULL)
4250                         LINE_CHECK("regdomain %d", reg->regdomain);
4251                 else
4252                         LINE_CHECK("regdomain %s", rd->name);
4253         }
4254         if (reg->country != 0 || verb) {
4255                 const struct country *cc =
4256                     lib80211_country_findbycc(getregdata(), reg->country);
4257                 if (cc == NULL)
4258                         LINE_CHECK("country %d", reg->country);
4259                 else
4260                         LINE_CHECK("country %s", cc->isoname);
4261         }
4262         if (reg->location == 'I')
4263                 LINE_CHECK("indoor");
4264         else if (reg->location == 'O')
4265                 LINE_CHECK("outdoor");
4266         else if (verb)
4267                 LINE_CHECK("anywhere");
4268         if (reg->ecm)
4269                 LINE_CHECK("ecm");
4270         else if (verb)
4271                 LINE_CHECK("-ecm");
4272 }
4273
4274 static void
4275 list_regdomain(int s, int channelsalso)
4276 {
4277         getregdomain(s);
4278         if (channelsalso) {
4279                 getchaninfo(s);
4280                 spacer = ':';
4281                 print_regdomain(&regdomain, 1);
4282                 LINE_BREAK();
4283                 print_channels(s, chaninfo, 1/*allchans*/, 1/*verbose*/);
4284         } else
4285                 print_regdomain(&regdomain, verbose);
4286 }
4287
4288 static void
4289 list_mesh(int s)
4290 {
4291         struct ieee80211req ireq;
4292         struct ieee80211req_mesh_route routes[128];
4293         struct ieee80211req_mesh_route *rt;
4294
4295         (void) memset(&ireq, 0, sizeof(ireq));
4296         (void) strlcpy(ireq.i_name, name, sizeof(ireq.i_name));
4297         ireq.i_type = IEEE80211_IOC_MESH_RTCMD;
4298         ireq.i_val = IEEE80211_MESH_RTCMD_LIST;
4299         ireq.i_data = &routes;
4300         ireq.i_len = sizeof(routes);
4301         if (ioctl(s, SIOCG80211, &ireq) < 0)
4302                 err(1, "unable to get the Mesh routing table");
4303
4304         printf("%-17.17s %-17.17s %4s %4s %4s %6s %s\n"
4305                 , "DEST"
4306                 , "NEXT HOP"
4307                 , "HOPS"
4308                 , "METRIC"
4309                 , "LIFETIME"
4310                 , "MSEQ"
4311                 , "FLAGS");
4312
4313         for (rt = &routes[0]; rt - &routes[0] < ireq.i_len / sizeof(*rt); rt++){
4314                 printf("%s ",
4315                     ether_ntoa((const struct ether_addr *)rt->imr_dest));
4316                 printf("%s %4u   %4u   %6u %6u    %c%c\n",
4317                         ether_ntoa((const struct ether_addr *)rt->imr_nexthop),
4318                         rt->imr_nhops, rt->imr_metric, rt->imr_lifetime,
4319                         rt->imr_lastmseq,
4320                         (rt->imr_flags & IEEE80211_MESHRT_FLAGS_DISCOVER) ?
4321                             'D' :
4322                         (rt->imr_flags & IEEE80211_MESHRT_FLAGS_VALID) ?
4323                             'V' : '!',
4324                         (rt->imr_flags & IEEE80211_MESHRT_FLAGS_PROXY) ?
4325                             'P' :
4326                         (rt->imr_flags & IEEE80211_MESHRT_FLAGS_GATE) ?
4327                             'G' :' ');
4328         }
4329 }
4330
4331 static
4332 DECL_CMD_FUNC(set80211list, arg, d)
4333 {
4334 #define iseq(a,b)       (strncasecmp(a,b,sizeof(b)-1) == 0)
4335
4336         LINE_INIT('\t');
4337
4338         if (iseq(arg, "sta"))
4339                 list_stations(s);
4340         else if (iseq(arg, "scan") || iseq(arg, "ap"))
4341                 list_scan(s);
4342         else if (iseq(arg, "chan") || iseq(arg, "freq"))
4343                 list_channels(s, 1);
4344         else if (iseq(arg, "active"))
4345                 list_channels(s, 0);
4346         else if (iseq(arg, "keys"))
4347                 list_keys(s);
4348         else if (iseq(arg, "caps"))
4349                 list_capabilities(s);
4350         else if (iseq(arg, "wme") || iseq(arg, "wmm"))
4351                 list_wme(s);
4352         else if (iseq(arg, "mac"))
4353                 list_mac(s);
4354         else if (iseq(arg, "txpow"))
4355                 list_txpow(s);
4356         else if (iseq(arg, "roam"))
4357                 list_roam(s);
4358         else if (iseq(arg, "txparam") || iseq(arg, "txparm"))
4359                 list_txparams(s);
4360         else if (iseq(arg, "regdomain"))
4361                 list_regdomain(s, 1);
4362         else if (iseq(arg, "countries"))
4363                 list_countries();
4364         else if (iseq(arg, "mesh"))
4365                 list_mesh(s);
4366         else
4367                 errx(1, "Don't know how to list %s for %s", arg, name);
4368         LINE_BREAK();
4369 #undef iseq
4370 }
4371
4372 static enum ieee80211_opmode
4373 get80211opmode(int s)
4374 {
4375         struct ifmediareq ifmr;
4376
4377         (void) memset(&ifmr, 0, sizeof(ifmr));
4378         (void) strlcpy(ifmr.ifm_name, name, sizeof(ifmr.ifm_name));
4379
4380         if (ioctl(s, SIOCGIFMEDIA, (caddr_t)&ifmr) >= 0) {
4381                 if (ifmr.ifm_current & IFM_IEEE80211_ADHOC) {
4382                         if (ifmr.ifm_current & IFM_FLAG0)
4383                                 return IEEE80211_M_AHDEMO;
4384                         else
4385                                 return IEEE80211_M_IBSS;
4386                 }
4387                 if (ifmr.ifm_current & IFM_IEEE80211_HOSTAP)
4388                         return IEEE80211_M_HOSTAP;
4389                 if (ifmr.ifm_current & IFM_IEEE80211_IBSS)
4390                         return IEEE80211_M_IBSS;
4391                 if (ifmr.ifm_current & IFM_IEEE80211_MONITOR)
4392                         return IEEE80211_M_MONITOR;
4393                 if (ifmr.ifm_current & IFM_IEEE80211_MBSS)
4394                         return IEEE80211_M_MBSS;
4395         }
4396         return IEEE80211_M_STA;
4397 }
4398
4399 #if 0
4400 static void
4401 printcipher(int s, struct ieee80211req *ireq, int keylenop)
4402 {
4403         switch (ireq->i_val) {
4404         case IEEE80211_CIPHER_WEP:
4405                 ireq->i_type = keylenop;
4406                 if (ioctl(s, SIOCG80211, ireq) != -1)
4407                         printf("WEP-%s", 
4408                             ireq->i_len <= 5 ? "40" :
4409                             ireq->i_len <= 13 ? "104" : "128");
4410                 else
4411                         printf("WEP");
4412                 break;
4413         case IEEE80211_CIPHER_TKIP:
4414                 printf("TKIP");
4415                 break;
4416         case IEEE80211_CIPHER_AES_OCB:
4417                 printf("AES-OCB");
4418                 break;
4419         case IEEE80211_CIPHER_AES_CCM:
4420                 printf("AES-CCM");
4421                 break;
4422         case IEEE80211_CIPHER_CKIP:
4423                 printf("CKIP");
4424                 break;
4425         case IEEE80211_CIPHER_NONE:
4426                 printf("NONE");
4427                 break;
4428         default:
4429                 printf("UNKNOWN (0x%x)", ireq->i_val);
4430                 break;
4431         }
4432 }
4433 #endif
4434
4435 static void
4436 printkey(const struct ieee80211req_key *ik)
4437 {
4438         static const uint8_t zerodata[IEEE80211_KEYBUF_SIZE];
4439         u_int keylen = ik->ik_keylen;
4440         int printcontents;
4441
4442         printcontents = printkeys &&
4443                 (memcmp(ik->ik_keydata, zerodata, keylen) != 0 || verbose);
4444         if (printcontents)
4445                 LINE_BREAK();
4446         switch (ik->ik_type) {
4447         case IEEE80211_CIPHER_WEP:
4448                 /* compatibility */
4449                 LINE_CHECK("wepkey %u:%s", ik->ik_keyix+1,
4450                     keylen <= 5 ? "40-bit" :
4451                     keylen <= 13 ? "104-bit" : "128-bit");
4452                 break;
4453         case IEEE80211_CIPHER_TKIP:
4454                 if (keylen > 128/8)
4455                         keylen -= 128/8;        /* ignore MIC for now */
4456                 LINE_CHECK("TKIP %u:%u-bit", ik->ik_keyix+1, 8*keylen);
4457                 break;
4458         case IEEE80211_CIPHER_AES_OCB:
4459                 LINE_CHECK("AES-OCB %u:%u-bit", ik->ik_keyix+1, 8*keylen);
4460                 break;
4461         case IEEE80211_CIPHER_AES_CCM:
4462                 LINE_CHECK("AES-CCM %u:%u-bit", ik->ik_keyix+1, 8*keylen);
4463                 break;
4464         case IEEE80211_CIPHER_CKIP:
4465                 LINE_CHECK("CKIP %u:%u-bit", ik->ik_keyix+1, 8*keylen);
4466                 break;
4467         case IEEE80211_CIPHER_NONE:
4468                 LINE_CHECK("NULL %u:%u-bit", ik->ik_keyix+1, 8*keylen);
4469                 break;
4470         default:
4471                 LINE_CHECK("UNKNOWN (0x%x) %u:%u-bit",
4472                         ik->ik_type, ik->ik_keyix+1, 8*keylen);
4473                 break;
4474         }
4475         if (printcontents) {
4476                 u_int i;
4477
4478                 printf(" <");
4479                 for (i = 0; i < keylen; i++)
4480                         printf("%02x", ik->ik_keydata[i]);
4481                 printf(">");
4482                 if (ik->ik_type != IEEE80211_CIPHER_WEP &&
4483                     (ik->ik_keyrsc != 0 || verbose))
4484                         printf(" rsc %ju", (uintmax_t)ik->ik_keyrsc);
4485                 if (ik->ik_type != IEEE80211_CIPHER_WEP &&
4486                     (ik->ik_keytsc != 0 || verbose))
4487                         printf(" tsc %ju", (uintmax_t)ik->ik_keytsc);
4488                 if (ik->ik_flags != 0 && verbose) {
4489                         const char *sep = " ";
4490
4491                         if (ik->ik_flags & IEEE80211_KEY_XMIT)
4492                                 printf("%stx", sep), sep = "+";
4493                         if (ik->ik_flags & IEEE80211_KEY_RECV)
4494                                 printf("%srx", sep), sep = "+";
4495                         if (ik->ik_flags & IEEE80211_KEY_DEFAULT)
4496                                 printf("%sdef", sep), sep = "+";
4497                 }
4498                 LINE_BREAK();
4499         }
4500 }
4501
4502 static void
4503 printrate(const char *tag, int v, int defrate, int defmcs)
4504 {
4505         if ((v & IEEE80211_RATE_MCS) == 0) {
4506                 if (v != defrate) {
4507                         if (v & 1)
4508                                 LINE_CHECK("%s %d.5", tag, v/2);
4509                         else
4510                                 LINE_CHECK("%s %d", tag, v/2);
4511                 }
4512         } else {
4513                 if (v != defmcs)
4514                         LINE_CHECK("%s %d", tag, v &~ 0x80);
4515         }
4516 }
4517
4518 static int
4519 getid(int s, int ix, void *data, size_t len, int *plen, int mesh)
4520 {
4521         struct ieee80211req ireq;
4522
4523         (void) memset(&ireq, 0, sizeof(ireq));
4524         (void) strlcpy(ireq.i_name, name, sizeof(ireq.i_name));
4525         ireq.i_type = (!mesh) ? IEEE80211_IOC_SSID : IEEE80211_IOC_MESH_ID;
4526         ireq.i_val = ix;
4527         ireq.i_data = data;
4528         ireq.i_len = len;
4529         if (ioctl(s, SIOCG80211, &ireq) < 0)
4530                 return -1;
4531         *plen = ireq.i_len;
4532         return 0;
4533 }
4534
4535 static void
4536 ieee80211_status(int s)
4537 {
4538         static const uint8_t zerobssid[IEEE80211_ADDR_LEN];
4539         enum ieee80211_opmode opmode = get80211opmode(s);
4540         int i, num, wpa, wme, bgscan, bgscaninterval, val, len, wepmode;
4541         uint8_t data[32];
4542         const struct ieee80211_channel *c;
4543         const struct ieee80211_roamparam *rp;
4544         const struct ieee80211_txparam *tp;
4545
4546         if (getid(s, -1, data, sizeof(data), &len, 0) < 0) {
4547                 /* If we can't get the SSID, this isn't an 802.11 device. */
4548                 return;
4549         }
4550
4551         /*
4552          * Invalidate cached state so printing status for multiple
4553          * if's doesn't reuse the first interfaces' cached state.
4554          */
4555         gotcurchan = 0;
4556         gotroam = 0;
4557         gottxparams = 0;
4558         gothtconf = 0;
4559         gotregdomain = 0;
4560
4561         printf("\t");
4562         if (opmode == IEEE80211_M_MBSS) {
4563                 printf("meshid ");
4564                 getid(s, 0, data, sizeof(data), &len, 1);
4565                 print_string(data, len);
4566         } else {
4567                 if (get80211val(s, IEEE80211_IOC_NUMSSIDS, &num) < 0)
4568                         num = 0;
4569                 printf("ssid ");
4570                 if (num > 1) {
4571                         for (i = 0; i < num; i++) {
4572                                 if (getid(s, i, data, sizeof(data), &len, 0) >= 0 && len > 0) {
4573                                         printf(" %d:", i + 1);
4574                                         print_string(data, len);
4575                                 }
4576                         }
4577                 } else
4578                         print_string(data, len);
4579         }
4580         c = getcurchan(s);
4581         if (c->ic_freq != IEEE80211_CHAN_ANY) {
4582                 char buf[14];
4583                 printf(" channel %d (%u MHz%s)", c->ic_ieee, c->ic_freq,
4584                         get_chaninfo(c, 1, buf, sizeof(buf)));
4585         } else if (verbose)
4586                 printf(" channel UNDEF");
4587
4588         if (get80211(s, IEEE80211_IOC_BSSID, data, IEEE80211_ADDR_LEN) >= 0 &&
4589             (memcmp(data, zerobssid, sizeof(zerobssid)) != 0 || verbose))
4590                 printf(" bssid %s", ether_ntoa((struct ether_addr *)data));
4591
4592         if (get80211len(s, IEEE80211_IOC_STATIONNAME, data, sizeof(data), &len) != -1) {
4593                 printf("\n\tstationname ");
4594                 print_string(data, len);
4595         }
4596
4597         spacer = ' ';           /* force first break */
4598         LINE_BREAK();
4599
4600         list_regdomain(s, 0);
4601
4602         wpa = 0;
4603         if (get80211val(s, IEEE80211_IOC_AUTHMODE, &val) != -1) {
4604                 switch (val) {
4605                 case IEEE80211_AUTH_NONE:
4606                         LINE_CHECK("authmode NONE");
4607                         break;
4608                 case IEEE80211_AUTH_OPEN:
4609                         LINE_CHECK("authmode OPEN");
4610                         break;
4611                 case IEEE80211_AUTH_SHARED:
4612                         LINE_CHECK("authmode SHARED");
4613                         break;
4614                 case IEEE80211_AUTH_8021X:
4615                         LINE_CHECK("authmode 802.1x");
4616                         break;
4617                 case IEEE80211_AUTH_WPA:
4618                         if (get80211val(s, IEEE80211_IOC_WPA, &wpa) < 0)
4619                                 wpa = 1;        /* default to WPA1 */
4620                         switch (wpa) {
4621                         case 2:
4622                                 LINE_CHECK("authmode WPA2/802.11i");
4623                                 break;
4624                         case 3:
4625                                 LINE_CHECK("authmode WPA1+WPA2/802.11i");
4626                                 break;
4627                         default:
4628                                 LINE_CHECK("authmode WPA");
4629                                 break;
4630                         }
4631                         break;
4632                 case IEEE80211_AUTH_AUTO:
4633                         LINE_CHECK("authmode AUTO");
4634                         break;
4635                 default:
4636                         LINE_CHECK("authmode UNKNOWN (0x%x)", val);
4637                         break;
4638                 }
4639         }
4640
4641         if (wpa || verbose) {
4642                 if (get80211val(s, IEEE80211_IOC_WPS, &val) != -1) {
4643                         if (val)
4644                                 LINE_CHECK("wps");
4645                         else if (verbose)
4646                                 LINE_CHECK("-wps");
4647                 }
4648                 if (get80211val(s, IEEE80211_IOC_TSN, &val) != -1) {
4649                         if (val)
4650                                 LINE_CHECK("tsn");
4651                         else if (verbose)
4652                                 LINE_CHECK("-tsn");
4653                 }
4654                 if (ioctl(s, IEEE80211_IOC_COUNTERMEASURES, &val) != -1) {
4655                         if (val)
4656                                 LINE_CHECK("countermeasures");
4657                         else if (verbose)
4658                                 LINE_CHECK("-countermeasures");
4659                 }
4660 #if 0
4661                 /* XXX not interesting with WPA done in user space */
4662                 ireq.i_type = IEEE80211_IOC_KEYMGTALGS;
4663                 if (ioctl(s, SIOCG80211, &ireq) != -1) {
4664                 }
4665
4666                 ireq.i_type = IEEE80211_IOC_MCASTCIPHER;
4667                 if (ioctl(s, SIOCG80211, &ireq) != -1) {
4668                         LINE_CHECK("mcastcipher ");
4669                         printcipher(s, &ireq, IEEE80211_IOC_MCASTKEYLEN);
4670                         spacer = ' ';
4671                 }
4672
4673                 ireq.i_type = IEEE80211_IOC_UCASTCIPHER;
4674                 if (ioctl(s, SIOCG80211, &ireq) != -1) {
4675                         LINE_CHECK("ucastcipher ");
4676                         printcipher(s, &ireq, IEEE80211_IOC_UCASTKEYLEN);
4677                 }
4678
4679                 if (wpa & 2) {
4680                         ireq.i_type = IEEE80211_IOC_RSNCAPS;
4681                         if (ioctl(s, SIOCG80211, &ireq) != -1) {
4682                                 LINE_CHECK("RSN caps 0x%x", ireq.i_val);
4683                                 spacer = ' ';
4684                         }
4685                 }
4686
4687                 ireq.i_type = IEEE80211_IOC_UCASTCIPHERS;
4688                 if (ioctl(s, SIOCG80211, &ireq) != -1) {
4689                 }
4690 #endif
4691         }
4692
4693         if (get80211val(s, IEEE80211_IOC_WEP, &wepmode) != -1 &&
4694             wepmode != IEEE80211_WEP_NOSUP) {
4695
4696                 switch (wepmode) {
4697                 case IEEE80211_WEP_OFF:
4698                         LINE_CHECK("privacy OFF");
4699                         break;
4700                 case IEEE80211_WEP_ON:
4701                         LINE_CHECK("privacy ON");
4702                         break;
4703                 case IEEE80211_WEP_MIXED:
4704                         LINE_CHECK("privacy MIXED");
4705                         break;
4706                 default:
4707                         LINE_CHECK("privacy UNKNOWN (0x%x)", wepmode);
4708                         break;
4709                 }
4710
4711                 /*
4712                  * If we get here then we've got WEP support so we need
4713                  * to print WEP status.
4714                  */
4715
4716                 if (get80211val(s, IEEE80211_IOC_WEPTXKEY, &val) < 0) {
4717                         warn("WEP support, but no tx key!");
4718                         goto end;
4719                 }
4720                 if (val != -1)
4721                         LINE_CHECK("deftxkey %d", val+1);
4722                 else if (wepmode != IEEE80211_WEP_OFF || verbose)
4723                         LINE_CHECK("deftxkey UNDEF");
4724
4725                 if (get80211val(s, IEEE80211_IOC_NUMWEPKEYS, &num) < 0) {
4726                         warn("WEP support, but no NUMWEPKEYS support!");
4727                         goto end;
4728                 }
4729
4730                 for (i = 0; i < num; i++) {
4731                         struct ieee80211req_key ik;
4732
4733                         memset(&ik, 0, sizeof(ik));
4734                         ik.ik_keyix = i;
4735                         if (get80211(s, IEEE80211_IOC_WPAKEY, &ik, sizeof(ik)) < 0) {
4736                                 warn("WEP support, but can get keys!");
4737                                 goto end;
4738                         }
4739                         if (ik.ik_keylen != 0) {
4740                                 if (verbose)
4741                                         LINE_BREAK();
4742                                 printkey(&ik);
4743                         }
4744                 }
4745 end:
4746                 ;
4747         }
4748
4749         if (get80211val(s, IEEE80211_IOC_POWERSAVE, &val) != -1 &&
4750             val != IEEE80211_POWERSAVE_NOSUP ) {
4751                 if (val != IEEE80211_POWERSAVE_OFF || verbose) {
4752                         switch (val) {
4753                         case IEEE80211_POWERSAVE_OFF:
4754                                 LINE_CHECK("powersavemode OFF");
4755                                 break;
4756                         case IEEE80211_POWERSAVE_CAM:
4757                                 LINE_CHECK("powersavemode CAM");
4758                                 break;
4759                         case IEEE80211_POWERSAVE_PSP:
4760                                 LINE_CHECK("powersavemode PSP");
4761                                 break;
4762                         case IEEE80211_POWERSAVE_PSP_CAM:
4763                                 LINE_CHECK("powersavemode PSP-CAM");
4764                                 break;
4765                         }
4766                         if (get80211val(s, IEEE80211_IOC_POWERSAVESLEEP, &val) != -1)
4767                                 LINE_CHECK("powersavesleep %d", val);
4768                 }
4769         }
4770
4771         if (get80211val(s, IEEE80211_IOC_TXPOWER, &val) != -1) {
4772                 if (val & 1)
4773                         LINE_CHECK("txpower %d.5", val/2);
4774                 else
4775                         LINE_CHECK("txpower %d", val/2);
4776         }
4777         if (verbose) {
4778                 if (get80211val(s, IEEE80211_IOC_TXPOWMAX, &val) != -1)
4779                         LINE_CHECK("txpowmax %.1f", val/2.);
4780         }
4781
4782         if (get80211val(s, IEEE80211_IOC_DOTD, &val) != -1) {
4783                 if (val)
4784                         LINE_CHECK("dotd");
4785                 else if (verbose)
4786                         LINE_CHECK("-dotd");
4787         }
4788
4789         if (get80211val(s, IEEE80211_IOC_RTSTHRESHOLD, &val) != -1) {
4790                 if (val != IEEE80211_RTS_MAX || verbose)
4791                         LINE_CHECK("rtsthreshold %d", val);
4792         }
4793
4794         if (get80211val(s, IEEE80211_IOC_FRAGTHRESHOLD, &val) != -1) {
4795                 if (val != IEEE80211_FRAG_MAX || verbose)
4796                         LINE_CHECK("fragthreshold %d", val);
4797         }
4798         if (opmode == IEEE80211_M_STA || verbose) {
4799                 if (get80211val(s, IEEE80211_IOC_BMISSTHRESHOLD, &val) != -1) {
4800                         if (val != IEEE80211_HWBMISS_MAX || verbose)
4801                                 LINE_CHECK("bmiss %d", val);
4802                 }
4803         }
4804
4805         if (!verbose) {
4806                 gettxparams(s);
4807                 tp = &txparams.params[chan2mode(c)];
4808                 printrate("ucastrate", tp->ucastrate,
4809                     IEEE80211_FIXED_RATE_NONE, IEEE80211_FIXED_RATE_NONE);
4810                 printrate("mcastrate", tp->mcastrate, 2*1,
4811                     IEEE80211_RATE_MCS|0);
4812                 printrate("mgmtrate", tp->mgmtrate, 2*1,
4813                     IEEE80211_RATE_MCS|0);
4814                 if (tp->maxretry != 6)          /* XXX */
4815                         LINE_CHECK("maxretry %d", tp->maxretry);
4816         } else {
4817                 LINE_BREAK();
4818                 list_txparams(s);
4819         }
4820
4821         bgscaninterval = -1;
4822         (void) get80211val(s, IEEE80211_IOC_BGSCAN_INTERVAL, &bgscaninterval);
4823
4824         if (get80211val(s, IEEE80211_IOC_SCANVALID, &val) != -1) {
4825                 if (val != bgscaninterval || verbose)
4826                         LINE_CHECK("scanvalid %u", val);
4827         }
4828
4829         bgscan = 0;
4830         if (get80211val(s, IEEE80211_IOC_BGSCAN, &bgscan) != -1) {
4831                 if (bgscan)
4832                         LINE_CHECK("bgscan");
4833                 else if (verbose)
4834                         LINE_CHECK("-bgscan");
4835         }
4836         if (bgscan || verbose) {
4837                 if (bgscaninterval != -1)
4838                         LINE_CHECK("bgscanintvl %u", bgscaninterval);
4839                 if (get80211val(s, IEEE80211_IOC_BGSCAN_IDLE, &val) != -1)
4840                         LINE_CHECK("bgscanidle %u", val);
4841                 if (!verbose) {
4842                         getroam(s);
4843                         rp = &roamparams.params[chan2mode(c)];
4844                         if (rp->rssi & 1)
4845                                 LINE_CHECK("roam:rssi %u.5", rp->rssi/2);
4846                         else
4847                                 LINE_CHECK("roam:rssi %u", rp->rssi/2);
4848                         LINE_CHECK("roam:rate %u", rp->rate/2);
4849                 } else {
4850                         LINE_BREAK();
4851                         list_roam(s);
4852                         LINE_BREAK();
4853                 }
4854         }
4855
4856         if (IEEE80211_IS_CHAN_ANYG(c) || verbose) {
4857                 if (get80211val(s, IEEE80211_IOC_PUREG, &val) != -1) {
4858                         if (val)
4859                                 LINE_CHECK("pureg");
4860                         else if (verbose)
4861                                 LINE_CHECK("-pureg");
4862                 }
4863                 if (get80211val(s, IEEE80211_IOC_PROTMODE, &val) != -1) {
4864                         switch (val) {
4865                         case IEEE80211_PROTMODE_OFF:
4866                                 LINE_CHECK("protmode OFF");
4867                                 break;
4868                         case IEEE80211_PROTMODE_CTS:
4869                                 LINE_CHECK("protmode CTS");
4870                                 break;
4871                         case IEEE80211_PROTMODE_RTSCTS:
4872                                 LINE_CHECK("protmode RTSCTS");
4873                                 break;
4874                         default:
4875                                 LINE_CHECK("protmode UNKNOWN (0x%x)", val);
4876                                 break;
4877                         }
4878                 }
4879         }
4880
4881         if (IEEE80211_IS_CHAN_HT(c) || verbose) {
4882                 gethtconf(s);
4883                 switch (htconf & 3) {
4884                 case 0:
4885                 case 2:
4886                         LINE_CHECK("-ht");
4887                         break;
4888                 case 1:
4889                         LINE_CHECK("ht20");
4890                         break;
4891                 case 3:
4892                         if (verbose)
4893                                 LINE_CHECK("ht");
4894                         break;
4895                 }
4896                 if (get80211val(s, IEEE80211_IOC_HTCOMPAT, &val) != -1) {
4897                         if (!val)
4898                                 LINE_CHECK("-htcompat");
4899                         else if (verbose)
4900                                 LINE_CHECK("htcompat");
4901                 }
4902                 if (get80211val(s, IEEE80211_IOC_AMPDU, &val) != -1) {
4903                         switch (val) {
4904                         case 0:
4905                                 LINE_CHECK("-ampdu");
4906                                 break;
4907                         case 1:
4908                                 LINE_CHECK("ampdutx -ampdurx");
4909                                 break;
4910                         case 2:
4911                                 LINE_CHECK("-ampdutx ampdurx");
4912                                 break;
4913                         case 3:
4914                                 if (verbose)
4915                                         LINE_CHECK("ampdu");
4916                                 break;
4917                         }
4918                 }
4919                 if (get80211val(s, IEEE80211_IOC_AMPDU_LIMIT, &val) != -1) {
4920                         switch (val) {
4921                         case IEEE80211_HTCAP_MAXRXAMPDU_8K:
4922                                 LINE_CHECK("ampdulimit 8k");
4923                                 break;
4924                         case IEEE80211_HTCAP_MAXRXAMPDU_16K:
4925                                 LINE_CHECK("ampdulimit 16k");
4926                                 break;
4927                         case IEEE80211_HTCAP_MAXRXAMPDU_32K:
4928                                 LINE_CHECK("ampdulimit 32k");
4929                                 break;
4930                         case IEEE80211_HTCAP_MAXRXAMPDU_64K:
4931                                 LINE_CHECK("ampdulimit 64k");
4932                                 break;
4933                         }
4934                 }
4935                 if (get80211val(s, IEEE80211_IOC_AMPDU_DENSITY, &val) != -1) {
4936                         switch (val) {
4937                         case IEEE80211_HTCAP_MPDUDENSITY_NA:
4938                                 if (verbose)
4939                                         LINE_CHECK("ampdudensity NA");
4940                                 break;
4941                         case IEEE80211_HTCAP_MPDUDENSITY_025:
4942                                 LINE_CHECK("ampdudensity .25");
4943                                 break;
4944                         case IEEE80211_HTCAP_MPDUDENSITY_05:
4945                                 LINE_CHECK("ampdudensity .5");
4946                                 break;
4947                         case IEEE80211_HTCAP_MPDUDENSITY_1:
4948                                 LINE_CHECK("ampdudensity 1");
4949                                 break;
4950                         case IEEE80211_HTCAP_MPDUDENSITY_2:
4951                                 LINE_CHECK("ampdudensity 2");
4952                                 break;
4953                         case IEEE80211_HTCAP_MPDUDENSITY_4:
4954                                 LINE_CHECK("ampdudensity 4");
4955                                 break;
4956                         case IEEE80211_HTCAP_MPDUDENSITY_8:
4957                                 LINE_CHECK("ampdudensity 8");
4958                                 break;
4959                         case IEEE80211_HTCAP_MPDUDENSITY_16:
4960                                 LINE_CHECK("ampdudensity 16");
4961                                 break;
4962                         }
4963                 }
4964                 if (get80211val(s, IEEE80211_IOC_AMSDU, &val) != -1) {
4965                         switch (val) {
4966                         case 0:
4967                                 LINE_CHECK("-amsdu");
4968                                 break;
4969                         case 1:
4970                                 LINE_CHECK("amsdutx -amsdurx");
4971                                 break;
4972                         case 2:
4973                                 LINE_CHECK("-amsdutx amsdurx");
4974                                 break;
4975                         case 3:
4976                                 if (verbose)
4977                                         LINE_CHECK("amsdu");
4978                                 break;
4979                         }
4980                 }
4981                 /* XXX amsdu limit */
4982                 if (get80211val(s, IEEE80211_IOC_SHORTGI, &val) != -1) {
4983                         if (val)
4984                                 LINE_CHECK("shortgi");
4985                         else if (verbose)
4986                                 LINE_CHECK("-shortgi");
4987                 }
4988                 if (get80211val(s, IEEE80211_IOC_HTPROTMODE, &val) != -1) {
4989                         if (val == IEEE80211_PROTMODE_OFF)
4990                                 LINE_CHECK("htprotmode OFF");
4991                         else if (val != IEEE80211_PROTMODE_RTSCTS)
4992                                 LINE_CHECK("htprotmode UNKNOWN (0x%x)", val);
4993                         else if (verbose)
4994                                 LINE_CHECK("htprotmode RTSCTS");
4995                 }
4996                 if (get80211val(s, IEEE80211_IOC_PUREN, &val) != -1) {
4997                         if (val)
4998                                 LINE_CHECK("puren");
4999                         else if (verbose)
5000                                 LINE_CHECK("-puren");
5001                 }
5002                 if (get80211val(s, IEEE80211_IOC_SMPS, &val) != -1) {
5003                         if (val == IEEE80211_HTCAP_SMPS_DYNAMIC)
5004                                 LINE_CHECK("smpsdyn");
5005                         else if (val == IEEE80211_HTCAP_SMPS_ENA)
5006                                 LINE_CHECK("smps");
5007                         else if (verbose)
5008                                 LINE_CHECK("-smps");
5009                 }
5010                 if (get80211val(s, IEEE80211_IOC_RIFS, &val) != -1) {
5011                         if (val)
5012                                 LINE_CHECK("rifs");
5013                         else if (verbose)
5014                                 LINE_CHECK("-rifs");
5015                 }
5016                 if (get80211val(s, IEEE80211_IOC_STBC, &val) != -1) {
5017                         switch (val) {
5018                         case 0:
5019                                 LINE_CHECK("-stbc");
5020                                 break;
5021                         case 1:
5022                                 LINE_CHECK("stbctx -stbcrx");
5023                                 break;
5024                         case 2:
5025                                 LINE_CHECK("-stbctx stbcrx");
5026                                 break;
5027                         case 3:
5028                                 if (verbose)
5029                                         LINE_CHECK("stbc");
5030                                 break;
5031                         }
5032                 }
5033         }
5034
5035         if (IEEE80211_IS_CHAN_VHT(c) || verbose) {
5036                 getvhtconf(s);
5037                 if (vhtconf & 0x1)
5038                         LINE_CHECK("vht");
5039                 else
5040                         LINE_CHECK("-vht");
5041                 if (vhtconf & 0x2)
5042                         LINE_CHECK("vht40");
5043                 else
5044                         LINE_CHECK("-vht40");
5045                 if (vhtconf & 0x4)
5046                         LINE_CHECK("vht80");
5047                 else
5048                         LINE_CHECK("-vht80");
5049                 if (vhtconf & 0x8)
5050                         LINE_CHECK("vht80p80");
5051                 else
5052                         LINE_CHECK("-vht80p80");
5053                 if (vhtconf & 0x10)
5054                         LINE_CHECK("vht160");
5055                 else
5056                         LINE_CHECK("-vht160");
5057         }
5058
5059         if (get80211val(s, IEEE80211_IOC_WME, &wme) != -1) {
5060                 if (wme)
5061                         LINE_CHECK("wme");
5062                 else if (verbose)
5063                         LINE_CHECK("-wme");
5064         } else
5065                 wme = 0;
5066
5067         if (get80211val(s, IEEE80211_IOC_BURST, &val) != -1) {
5068                 if (val)
5069                         LINE_CHECK("burst");
5070                 else if (verbose)
5071                         LINE_CHECK("-burst");
5072         }
5073
5074         if (get80211val(s, IEEE80211_IOC_FF, &val) != -1) {
5075                 if (val)
5076                         LINE_CHECK("ff");
5077                 else if (verbose)
5078                         LINE_CHECK("-ff");
5079         }
5080         if (get80211val(s, IEEE80211_IOC_TURBOP, &val) != -1) {
5081                 if (val)
5082                         LINE_CHECK("dturbo");
5083                 else if (verbose)
5084                         LINE_CHECK("-dturbo");
5085         }
5086         if (get80211val(s, IEEE80211_IOC_DWDS, &val) != -1) {
5087                 if (val)
5088                         LINE_CHECK("dwds");
5089                 else if (verbose)
5090                         LINE_CHECK("-dwds");
5091         }
5092
5093         if (opmode == IEEE80211_M_HOSTAP) {
5094                 if (get80211val(s, IEEE80211_IOC_HIDESSID, &val) != -1) {
5095                         if (val)
5096                                 LINE_CHECK("hidessid");
5097                         else if (verbose)
5098                                 LINE_CHECK("-hidessid");
5099                 }
5100                 if (get80211val(s, IEEE80211_IOC_APBRIDGE, &val) != -1) {
5101                         if (!val)
5102                                 LINE_CHECK("-apbridge");
5103                         else if (verbose)
5104                                 LINE_CHECK("apbridge");
5105                 }
5106                 if (get80211val(s, IEEE80211_IOC_DTIM_PERIOD, &val) != -1)
5107                         LINE_CHECK("dtimperiod %u", val);
5108
5109                 if (get80211val(s, IEEE80211_IOC_DOTH, &val) != -1) {
5110                         if (!val)
5111                                 LINE_CHECK("-doth");
5112                         else if (verbose)
5113                                 LINE_CHECK("doth");
5114                 }
5115                 if (get80211val(s, IEEE80211_IOC_DFS, &val) != -1) {
5116                         if (!val)
5117                                 LINE_CHECK("-dfs");
5118                         else if (verbose)
5119                                 LINE_CHECK("dfs");
5120                 }
5121                 if (get80211val(s, IEEE80211_IOC_INACTIVITY, &val) != -1) {
5122                         if (!val)
5123                                 LINE_CHECK("-inact");
5124                         else if (verbose)
5125                                 LINE_CHECK("inact");
5126                 }
5127         } else {
5128                 if (get80211val(s, IEEE80211_IOC_ROAMING, &val) != -1) {
5129                         if (val != IEEE80211_ROAMING_AUTO || verbose) {
5130                                 switch (val) {
5131                                 case IEEE80211_ROAMING_DEVICE:
5132                                         LINE_CHECK("roaming DEVICE");
5133                                         break;
5134                                 case IEEE80211_ROAMING_AUTO:
5135                                         LINE_CHECK("roaming AUTO");
5136                                         break;
5137                                 case IEEE80211_ROAMING_MANUAL:
5138                                         LINE_CHECK("roaming MANUAL");
5139                                         break;
5140                                 default:
5141                                         LINE_CHECK("roaming UNKNOWN (0x%x)",
5142                                                 val);
5143                                         break;
5144                                 }
5145                         }
5146                 }
5147         }
5148
5149         if (opmode == IEEE80211_M_AHDEMO) {
5150                 if (get80211val(s, IEEE80211_IOC_TDMA_SLOT, &val) != -1)
5151                         LINE_CHECK("tdmaslot %u", val);
5152                 if (get80211val(s, IEEE80211_IOC_TDMA_SLOTCNT, &val) != -1)
5153                         LINE_CHECK("tdmaslotcnt %u", val);
5154                 if (get80211val(s, IEEE80211_IOC_TDMA_SLOTLEN, &val) != -1)
5155                         LINE_CHECK("tdmaslotlen %u", val);
5156                 if (get80211val(s, IEEE80211_IOC_TDMA_BINTERVAL, &val) != -1)
5157                         LINE_CHECK("tdmabintval %u", val);
5158         } else if (get80211val(s, IEEE80211_IOC_BEACON_INTERVAL, &val) != -1) {
5159                 /* XXX default define not visible */
5160                 if (val != 100 || verbose)
5161                         LINE_CHECK("bintval %u", val);
5162         }
5163
5164         if (wme && verbose) {
5165                 LINE_BREAK();
5166                 list_wme(s);
5167         }
5168
5169         if (opmode == IEEE80211_M_MBSS) {
5170                 if (get80211val(s, IEEE80211_IOC_MESH_TTL, &val) != -1) {
5171                         LINE_CHECK("meshttl %u", val);
5172                 }
5173                 if (get80211val(s, IEEE80211_IOC_MESH_AP, &val) != -1) {
5174                         if (val)
5175                                 LINE_CHECK("meshpeering");
5176                         else
5177                                 LINE_CHECK("-meshpeering");
5178                 }
5179                 if (get80211val(s, IEEE80211_IOC_MESH_FWRD, &val) != -1) {
5180                         if (val)
5181                                 LINE_CHECK("meshforward");
5182                         else
5183                                 LINE_CHECK("-meshforward");
5184                 }
5185                 if (get80211val(s, IEEE80211_IOC_MESH_GATE, &val) != -1) {
5186                         if (val)
5187                                 LINE_CHECK("meshgate");
5188                         else
5189                                 LINE_CHECK("-meshgate");
5190                 }
5191                 if (get80211len(s, IEEE80211_IOC_MESH_PR_METRIC, data, 12,
5192                     &len) != -1) {
5193                         data[len] = '\0';
5194                         LINE_CHECK("meshmetric %s", data);
5195                 }
5196                 if (get80211len(s, IEEE80211_IOC_MESH_PR_PATH, data, 12,
5197                     &len) != -1) {
5198                         data[len] = '\0';
5199                         LINE_CHECK("meshpath %s", data);
5200                 }
5201                 if (get80211val(s, IEEE80211_IOC_HWMP_ROOTMODE, &val) != -1) {
5202                         switch (val) {
5203                         case IEEE80211_HWMP_ROOTMODE_DISABLED:
5204                                 LINE_CHECK("hwmprootmode DISABLED");
5205                                 break;
5206                         case IEEE80211_HWMP_ROOTMODE_NORMAL:
5207                                 LINE_CHECK("hwmprootmode NORMAL");
5208                                 break;
5209                         case IEEE80211_HWMP_ROOTMODE_PROACTIVE:
5210                                 LINE_CHECK("hwmprootmode PROACTIVE");
5211                                 break;
5212                         case IEEE80211_HWMP_ROOTMODE_RANN:
5213                                 LINE_CHECK("hwmprootmode RANN");
5214                                 break;
5215                         default:
5216                                 LINE_CHECK("hwmprootmode UNKNOWN(%d)", val);
5217                                 break;
5218                         }
5219                 }
5220                 if (get80211val(s, IEEE80211_IOC_HWMP_MAXHOPS, &val) != -1) {
5221                         LINE_CHECK("hwmpmaxhops %u", val);
5222                 }
5223         }
5224
5225         LINE_BREAK();
5226 }
5227
5228 static int
5229 get80211(int s, int type, void *data, int len)
5230 {
5231
5232         return (lib80211_get80211(s, name, type, data, len));
5233 }
5234
5235 static int
5236 get80211len(int s, int type, void *data, int len, int *plen)
5237 {
5238
5239         return (lib80211_get80211len(s, name, type, data, len, plen));
5240 }
5241
5242 static int
5243 get80211val(int s, int type, int *val)
5244 {
5245
5246         return (lib80211_get80211val(s, name, type, val));
5247 }
5248
5249 static void
5250 set80211(int s, int type, int val, int len, void *data)
5251 {
5252         int ret;
5253
5254         ret = lib80211_set80211(s, name, type, val, len, data);
5255         if (ret < 0)
5256                 err(1, "SIOCS80211");
5257 }
5258
5259 static const char *
5260 get_string(const char *val, const char *sep, u_int8_t *buf, int *lenp)
5261 {
5262         int len;
5263         int hexstr;
5264         u_int8_t *p;
5265
5266         len = *lenp;
5267         p = buf;
5268         hexstr = (val[0] == '0' && tolower((u_char)val[1]) == 'x');
5269         if (hexstr)
5270                 val += 2;
5271         for (;;) {
5272                 if (*val == '\0')
5273                         break;
5274                 if (sep != NULL && strchr(sep, *val) != NULL) {
5275                         val++;
5276                         break;
5277                 }
5278                 if (hexstr) {
5279                         if (!isxdigit((u_char)val[0])) {
5280                                 warnx("bad hexadecimal digits");
5281                                 return NULL;
5282                         }
5283                         if (!isxdigit((u_char)val[1])) {
5284                                 warnx("odd count hexadecimal digits");
5285                                 return NULL;
5286                         }
5287                 }
5288                 if (p >= buf + len) {
5289                         if (hexstr)
5290                                 warnx("hexadecimal digits too long");
5291                         else
5292                                 warnx("string too long");
5293                         return NULL;
5294                 }
5295                 if (hexstr) {
5296 #define tohex(x)        (isdigit(x) ? (x) - '0' : tolower(x) - 'a' + 10)
5297                         *p++ = (tohex((u_char)val[0]) << 4) |
5298                             tohex((u_char)val[1]);
5299 #undef tohex
5300                         val += 2;
5301                 } else
5302                         *p++ = *val++;
5303         }
5304         len = p - buf;
5305         /* The string "-" is treated as the empty string. */
5306         if (!hexstr && len == 1 && buf[0] == '-') {
5307                 len = 0;
5308                 memset(buf, 0, *lenp);
5309         } else if (len < *lenp)
5310                 memset(p, 0, *lenp - len);
5311         *lenp = len;
5312         return val;
5313 }
5314
5315 static void
5316 print_string(const u_int8_t *buf, int len)
5317 {
5318         int i;
5319         int hasspc;
5320
5321         i = 0;
5322         hasspc = 0;
5323         for (; i < len; i++) {
5324                 if (!isprint(buf[i]) && buf[i] != '\0')
5325                         break;
5326                 if (isspace(buf[i]))
5327                         hasspc++;
5328         }
5329         if (i == len) {
5330                 if (hasspc || len == 0 || buf[0] == '\0')
5331                         printf("\"%.*s\"", len, buf);
5332                 else
5333                         printf("%.*s", len, buf);
5334         } else {
5335                 printf("0x");
5336                 for (i = 0; i < len; i++)
5337                         printf("%02x", buf[i]);
5338         }
5339 }
5340
5341 static void
5342 setdefregdomain(int s)
5343 {
5344         struct regdata *rdp = getregdata();
5345         const struct regdomain *rd;
5346
5347         /* Check if regdomain/country was already set by a previous call. */
5348         /* XXX is it possible? */
5349         if (regdomain.regdomain != 0 ||
5350             regdomain.country != CTRY_DEFAULT)
5351                 return;
5352
5353         getregdomain(s);
5354
5355         /* Check if it was already set by the driver. */
5356         if (regdomain.regdomain != 0 ||
5357             regdomain.country != CTRY_DEFAULT)
5358                 return;
5359
5360         /* Set FCC/US as default. */
5361         rd = lib80211_regdomain_findbysku(rdp, SKU_FCC);
5362         if (rd == NULL)
5363                 errx(1, "FCC regdomain was not found");
5364
5365         regdomain.regdomain = rd->sku;
5366         if (rd->cc != NULL)
5367                 defaultcountry(rd);
5368
5369         /* Send changes to net80211. */
5370         setregdomain_cb(s, &regdomain);
5371
5372         /* Cleanup (so it can be overriden by subsequent parameters). */
5373         regdomain.regdomain = 0;
5374         regdomain.country = CTRY_DEFAULT;
5375         regdomain.isocc[0] = 0;
5376         regdomain.isocc[1] = 0;
5377 }
5378
5379 /*
5380  * Virtual AP cloning support.
5381  */
5382 static struct ieee80211_clone_params params = {
5383         .icp_opmode     = IEEE80211_M_STA,      /* default to station mode */
5384 };
5385
5386 static void
5387 wlan_create(int s, struct ifreq *ifr)
5388 {
5389         static const uint8_t zerobssid[IEEE80211_ADDR_LEN];
5390         char orig_name[IFNAMSIZ];
5391
5392         if (params.icp_parent[0] == '\0')
5393                 errx(1, "must specify a parent device (wlandev) when creating "
5394                     "a wlan device");
5395         if (params.icp_opmode == IEEE80211_M_WDS &&
5396             memcmp(params.icp_bssid, zerobssid, sizeof(zerobssid)) == 0)
5397                 errx(1, "no bssid specified for WDS (use wlanbssid)");
5398         ifr->ifr_data = (caddr_t) &params;
5399         if (ioctl(s, SIOCIFCREATE2, ifr) < 0)
5400                 err(1, "SIOCIFCREATE2");
5401
5402         /* XXX preserve original name for ifclonecreate(). */
5403         strlcpy(orig_name, name, sizeof(orig_name));
5404         strlcpy(name, ifr->ifr_name, sizeof(name));
5405
5406         setdefregdomain(s);
5407
5408         strlcpy(name, orig_name, sizeof(name));
5409 }
5410
5411 static
5412 DECL_CMD_FUNC(set80211clone_wlandev, arg, d)
5413 {
5414         strlcpy(params.icp_parent, arg, IFNAMSIZ);
5415 }
5416
5417 static
5418 DECL_CMD_FUNC(set80211clone_wlanbssid, arg, d)
5419 {
5420         const struct ether_addr *ea;
5421
5422         ea = ether_aton(arg);
5423         if (ea == NULL)
5424                 errx(1, "%s: cannot parse bssid", arg);
5425         memcpy(params.icp_bssid, ea->octet, IEEE80211_ADDR_LEN);
5426 }
5427
5428 static
5429 DECL_CMD_FUNC(set80211clone_wlanaddr, arg, d)
5430 {
5431         const struct ether_addr *ea;
5432
5433         ea = ether_aton(arg);
5434         if (ea == NULL)
5435                 errx(1, "%s: cannot parse address", arg);
5436         memcpy(params.icp_macaddr, ea->octet, IEEE80211_ADDR_LEN);
5437         params.icp_flags |= IEEE80211_CLONE_MACADDR;
5438 }
5439
5440 static
5441 DECL_CMD_FUNC(set80211clone_wlanmode, arg, d)
5442 {
5443 #define iseq(a,b)       (strncasecmp(a,b,sizeof(b)-1) == 0)
5444         if (iseq(arg, "sta"))
5445                 params.icp_opmode = IEEE80211_M_STA;
5446         else if (iseq(arg, "ahdemo") || iseq(arg, "adhoc-demo"))
5447                 params.icp_opmode = IEEE80211_M_AHDEMO;
5448         else if (iseq(arg, "ibss") || iseq(arg, "adhoc"))
5449                 params.icp_opmode = IEEE80211_M_IBSS;
5450         else if (iseq(arg, "ap") || iseq(arg, "host"))
5451                 params.icp_opmode = IEEE80211_M_HOSTAP;
5452         else if (iseq(arg, "wds"))
5453                 params.icp_opmode = IEEE80211_M_WDS;
5454         else if (iseq(arg, "monitor"))
5455                 params.icp_opmode = IEEE80211_M_MONITOR;
5456         else if (iseq(arg, "tdma")) {
5457                 params.icp_opmode = IEEE80211_M_AHDEMO;
5458                 params.icp_flags |= IEEE80211_CLONE_TDMA;
5459         } else if (iseq(arg, "mesh") || iseq(arg, "mp")) /* mesh point */
5460                 params.icp_opmode = IEEE80211_M_MBSS;
5461         else
5462                 errx(1, "Don't know to create %s for %s", arg, name);
5463 #undef iseq
5464 }
5465
5466 static void
5467 set80211clone_beacons(const char *val, int d, int s, const struct afswtch *rafp)
5468 {
5469         /* NB: inverted sense */
5470         if (d)
5471                 params.icp_flags &= ~IEEE80211_CLONE_NOBEACONS;
5472         else
5473                 params.icp_flags |= IEEE80211_CLONE_NOBEACONS;
5474 }
5475
5476 static void
5477 set80211clone_bssid(const char *val, int d, int s, const struct afswtch *rafp)
5478 {
5479         if (d)
5480                 params.icp_flags |= IEEE80211_CLONE_BSSID;
5481         else
5482                 params.icp_flags &= ~IEEE80211_CLONE_BSSID;
5483 }
5484
5485 static void
5486 set80211clone_wdslegacy(const char *val, int d, int s, const struct afswtch *rafp)
5487 {
5488         if (d)
5489                 params.icp_flags |= IEEE80211_CLONE_WDSLEGACY;
5490         else
5491                 params.icp_flags &= ~IEEE80211_CLONE_WDSLEGACY;
5492 }
5493
5494 static struct cmd ieee80211_cmds[] = {
5495         DEF_CMD_ARG("ssid",             set80211ssid),
5496         DEF_CMD_ARG("nwid",             set80211ssid),
5497         DEF_CMD_ARG("meshid",           set80211meshid),
5498         DEF_CMD_ARG("stationname",      set80211stationname),
5499         DEF_CMD_ARG("station",          set80211stationname),   /* BSD/OS */
5500         DEF_CMD_ARG("channel",          set80211channel),
5501         DEF_CMD_ARG("authmode",         set80211authmode),
5502         DEF_CMD_ARG("powersavemode",    set80211powersavemode),
5503         DEF_CMD("powersave",    1,      set80211powersave),
5504         DEF_CMD("-powersave",   0,      set80211powersave),
5505         DEF_CMD_ARG("powersavesleep",   set80211powersavesleep),
5506         DEF_CMD_ARG("wepmode",          set80211wepmode),
5507         DEF_CMD("wep",          1,      set80211wep),
5508         DEF_CMD("-wep",         0,      set80211wep),
5509         DEF_CMD_ARG("deftxkey",         set80211weptxkey),
5510         DEF_CMD_ARG("weptxkey",         set80211weptxkey),
5511         DEF_CMD_ARG("wepkey",           set80211wepkey),
5512         DEF_CMD_ARG("nwkey",            set80211nwkey),         /* NetBSD */
5513         DEF_CMD("-nwkey",       0,      set80211wep),           /* NetBSD */
5514         DEF_CMD_ARG("rtsthreshold",     set80211rtsthreshold),
5515         DEF_CMD_ARG("protmode",         set80211protmode),
5516         DEF_CMD_ARG("txpower",          set80211txpower),
5517         DEF_CMD_ARG("roaming",          set80211roaming),
5518         DEF_CMD("wme",          1,      set80211wme),
5519         DEF_CMD("-wme",         0,      set80211wme),
5520         DEF_CMD("wmm",          1,      set80211wme),
5521         DEF_CMD("-wmm",         0,      set80211wme),
5522         DEF_CMD("hidessid",     1,      set80211hidessid),
5523         DEF_CMD("-hidessid",    0,      set80211hidessid),
5524         DEF_CMD("apbridge",     1,      set80211apbridge),
5525         DEF_CMD("-apbridge",    0,      set80211apbridge),
5526         DEF_CMD_ARG("chanlist",         set80211chanlist),
5527         DEF_CMD_ARG("bssid",            set80211bssid),
5528         DEF_CMD_ARG("ap",               set80211bssid),
5529         DEF_CMD("scan", 0,              set80211scan),
5530         DEF_CMD_ARG("list",             set80211list),
5531         DEF_CMD_ARG2("cwmin",           set80211cwmin),
5532         DEF_CMD_ARG2("cwmax",           set80211cwmax),
5533         DEF_CMD_ARG2("aifs",            set80211aifs),
5534         DEF_CMD_ARG2("txoplimit",       set80211txoplimit),
5535         DEF_CMD_ARG("acm",              set80211acm),
5536         DEF_CMD_ARG("-acm",             set80211noacm),
5537         DEF_CMD_ARG("ack",              set80211ackpolicy),
5538         DEF_CMD_ARG("-ack",             set80211noackpolicy),
5539         DEF_CMD_ARG2("bss:cwmin",       set80211bsscwmin),
5540         DEF_CMD_ARG2("bss:cwmax",       set80211bsscwmax),
5541         DEF_CMD_ARG2("bss:aifs",        set80211bssaifs),
5542         DEF_CMD_ARG2("bss:txoplimit",   set80211bsstxoplimit),
5543         DEF_CMD_ARG("dtimperiod",       set80211dtimperiod),
5544         DEF_CMD_ARG("bintval",          set80211bintval),
5545         DEF_CMD("mac:open",     IEEE80211_MACCMD_POLICY_OPEN,   set80211maccmd),
5546         DEF_CMD("mac:allow",    IEEE80211_MACCMD_POLICY_ALLOW,  set80211maccmd),
5547         DEF_CMD("mac:deny",     IEEE80211_MACCMD_POLICY_DENY,   set80211maccmd),
5548         DEF_CMD("mac:radius",   IEEE80211_MACCMD_POLICY_RADIUS, set80211maccmd),
5549         DEF_CMD("mac:flush",    IEEE80211_MACCMD_FLUSH,         set80211maccmd),
5550         DEF_CMD("mac:detach",   IEEE80211_MACCMD_DETACH,        set80211maccmd),
5551         DEF_CMD_ARG("mac:add",          set80211addmac),
5552         DEF_CMD_ARG("mac:del",          set80211delmac),
5553         DEF_CMD_ARG("mac:kick",         set80211kickmac),
5554         DEF_CMD("pureg",        1,      set80211pureg),
5555         DEF_CMD("-pureg",       0,      set80211pureg),
5556         DEF_CMD("ff",           1,      set80211fastframes),
5557         DEF_CMD("-ff",          0,      set80211fastframes),
5558         DEF_CMD("dturbo",       1,      set80211dturbo),
5559         DEF_CMD("-dturbo",      0,      set80211dturbo),
5560         DEF_CMD("bgscan",       1,      set80211bgscan),
5561         DEF_CMD("-bgscan",      0,      set80211bgscan),
5562         DEF_CMD_ARG("bgscanidle",       set80211bgscanidle),
5563         DEF_CMD_ARG("bgscanintvl",      set80211bgscanintvl),
5564         DEF_CMD_ARG("scanvalid",        set80211scanvalid),
5565         DEF_CMD("quiet",        1,      set80211quiet),
5566         DEF_CMD("-quiet",       0,      set80211quiet),
5567         DEF_CMD_ARG("quiet_count",      set80211quietcount),
5568         DEF_CMD_ARG("quiet_period",     set80211quietperiod),
5569         DEF_CMD_ARG("quiet_dur",        set80211quietduration),
5570         DEF_CMD_ARG("quiet_offset",     set80211quietoffset),
5571         DEF_CMD_ARG("roam:rssi",        set80211roamrssi),
5572         DEF_CMD_ARG("roam:rate",        set80211roamrate),
5573         DEF_CMD_ARG("mcastrate",        set80211mcastrate),
5574         DEF_CMD_ARG("ucastrate",        set80211ucastrate),
5575         DEF_CMD_ARG("mgtrate",          set80211mgtrate),
5576         DEF_CMD_ARG("mgmtrate",         set80211mgtrate),
5577         DEF_CMD_ARG("maxretry",         set80211maxretry),
5578         DEF_CMD_ARG("fragthreshold",    set80211fragthreshold),
5579         DEF_CMD("burst",        1,      set80211burst),
5580         DEF_CMD("-burst",       0,      set80211burst),
5581         DEF_CMD_ARG("bmiss",            set80211bmissthreshold),
5582         DEF_CMD_ARG("bmissthreshold",   set80211bmissthreshold),
5583         DEF_CMD("shortgi",      1,      set80211shortgi),
5584         DEF_CMD("-shortgi",     0,      set80211shortgi),
5585         DEF_CMD("ampdurx",      2,      set80211ampdu),
5586         DEF_CMD("-ampdurx",     -2,     set80211ampdu),
5587         DEF_CMD("ampdutx",      1,      set80211ampdu),
5588         DEF_CMD("-ampdutx",     -1,     set80211ampdu),
5589         DEF_CMD("ampdu",        3,      set80211ampdu),         /* NB: tx+rx */
5590         DEF_CMD("-ampdu",       -3,     set80211ampdu),
5591         DEF_CMD_ARG("ampdulimit",       set80211ampdulimit),
5592         DEF_CMD_ARG("ampdudensity",     set80211ampdudensity),
5593         DEF_CMD("amsdurx",      2,      set80211amsdu),
5594         DEF_CMD("-amsdurx",     -2,     set80211amsdu),
5595         DEF_CMD("amsdutx",      1,      set80211amsdu),
5596         DEF_CMD("-amsdutx",     -1,     set80211amsdu),
5597         DEF_CMD("amsdu",        3,      set80211amsdu),         /* NB: tx+rx */
5598         DEF_CMD("-amsdu",       -3,     set80211amsdu),
5599         DEF_CMD_ARG("amsdulimit",       set80211amsdulimit),
5600         DEF_CMD("stbcrx",       2,      set80211stbc),
5601         DEF_CMD("-stbcrx",      -2,     set80211stbc),
5602         DEF_CMD("stbctx",       1,      set80211stbc),
5603         DEF_CMD("-stbctx",      -1,     set80211stbc),
5604         DEF_CMD("stbc",         3,      set80211stbc),          /* NB: tx+rx */
5605         DEF_CMD("-ampdu",       -3,     set80211stbc),
5606         DEF_CMD("puren",        1,      set80211puren),
5607         DEF_CMD("-puren",       0,      set80211puren),
5608         DEF_CMD("doth",         1,      set80211doth),
5609         DEF_CMD("-doth",        0,      set80211doth),
5610         DEF_CMD("dfs",          1,      set80211dfs),
5611         DEF_CMD("-dfs",         0,      set80211dfs),
5612         DEF_CMD("htcompat",     1,      set80211htcompat),
5613         DEF_CMD("-htcompat",    0,      set80211htcompat),
5614         DEF_CMD("dwds",         1,      set80211dwds),
5615         DEF_CMD("-dwds",        0,      set80211dwds),
5616         DEF_CMD("inact",        1,      set80211inact),
5617         DEF_CMD("-inact",       0,      set80211inact),
5618         DEF_CMD("tsn",          1,      set80211tsn),
5619         DEF_CMD("-tsn",         0,      set80211tsn),
5620         DEF_CMD_ARG("regdomain",        set80211regdomain),
5621         DEF_CMD_ARG("country",          set80211country),
5622         DEF_CMD("indoor",       'I',    set80211location),
5623         DEF_CMD("-indoor",      'O',    set80211location),
5624         DEF_CMD("outdoor",      'O',    set80211location),
5625         DEF_CMD("-outdoor",     'I',    set80211location),
5626         DEF_CMD("anywhere",     ' ',    set80211location),
5627         DEF_CMD("ecm",          1,      set80211ecm),
5628         DEF_CMD("-ecm",         0,      set80211ecm),
5629         DEF_CMD("dotd",         1,      set80211dotd),
5630         DEF_CMD("-dotd",        0,      set80211dotd),
5631         DEF_CMD_ARG("htprotmode",       set80211htprotmode),
5632         DEF_CMD("ht20",         1,      set80211htconf),
5633         DEF_CMD("-ht20",        0,      set80211htconf),
5634         DEF_CMD("ht40",         3,      set80211htconf),        /* NB: 20+40 */
5635         DEF_CMD("-ht40",        0,      set80211htconf),
5636         DEF_CMD("ht",           3,      set80211htconf),        /* NB: 20+40 */
5637         DEF_CMD("-ht",          0,      set80211htconf),
5638         DEF_CMD("vht",          1,      set80211vhtconf),
5639         DEF_CMD("-vht",         0,      set80211vhtconf),
5640         DEF_CMD("vht40",                2,      set80211vhtconf),
5641         DEF_CMD("-vht40",               -2,     set80211vhtconf),
5642         DEF_CMD("vht80",                4,      set80211vhtconf),
5643         DEF_CMD("-vht80",               -4,     set80211vhtconf),
5644         DEF_CMD("vht80p80",             8,      set80211vhtconf),
5645         DEF_CMD("-vht80p80",            -8,     set80211vhtconf),
5646         DEF_CMD("vht160",               16,     set80211vhtconf),
5647         DEF_CMD("-vht160",              -16,    set80211vhtconf),
5648         DEF_CMD("rifs",         1,      set80211rifs),
5649         DEF_CMD("-rifs",        0,      set80211rifs),
5650         DEF_CMD("smps",         IEEE80211_HTCAP_SMPS_ENA,       set80211smps),
5651         DEF_CMD("smpsdyn",      IEEE80211_HTCAP_SMPS_DYNAMIC,   set80211smps),
5652         DEF_CMD("-smps",        IEEE80211_HTCAP_SMPS_OFF,       set80211smps),
5653         /* XXX for testing */
5654         DEF_CMD_ARG("chanswitch",       set80211chanswitch),
5655
5656         DEF_CMD_ARG("tdmaslot",         set80211tdmaslot),
5657         DEF_CMD_ARG("tdmaslotcnt",      set80211tdmaslotcnt),
5658         DEF_CMD_ARG("tdmaslotlen",      set80211tdmaslotlen),
5659         DEF_CMD_ARG("tdmabintval",      set80211tdmabintval),
5660
5661         DEF_CMD_ARG("meshttl",          set80211meshttl),
5662         DEF_CMD("meshforward",  1,      set80211meshforward),
5663         DEF_CMD("-meshforward", 0,      set80211meshforward),
5664         DEF_CMD("meshgate",     1,      set80211meshgate),
5665         DEF_CMD("-meshgate",    0,      set80211meshgate),
5666         DEF_CMD("meshpeering",  1,      set80211meshpeering),
5667         DEF_CMD("-meshpeering", 0,      set80211meshpeering),
5668         DEF_CMD_ARG("meshmetric",       set80211meshmetric),
5669         DEF_CMD_ARG("meshpath",         set80211meshpath),
5670         DEF_CMD("meshrt:flush", IEEE80211_MESH_RTCMD_FLUSH,     set80211meshrtcmd),
5671         DEF_CMD_ARG("meshrt:add",       set80211addmeshrt),
5672         DEF_CMD_ARG("meshrt:del",       set80211delmeshrt),
5673         DEF_CMD_ARG("hwmprootmode",     set80211hwmprootmode),
5674         DEF_CMD_ARG("hwmpmaxhops",      set80211hwmpmaxhops),
5675
5676         /* vap cloning support */
5677         DEF_CLONE_CMD_ARG("wlanaddr",   set80211clone_wlanaddr),
5678         DEF_CLONE_CMD_ARG("wlanbssid",  set80211clone_wlanbssid),
5679         DEF_CLONE_CMD_ARG("wlandev",    set80211clone_wlandev),
5680         DEF_CLONE_CMD_ARG("wlanmode",   set80211clone_wlanmode),
5681         DEF_CLONE_CMD("beacons", 1,     set80211clone_beacons),
5682         DEF_CLONE_CMD("-beacons", 0,    set80211clone_beacons),
5683         DEF_CLONE_CMD("bssid",  1,      set80211clone_bssid),
5684         DEF_CLONE_CMD("-bssid", 0,      set80211clone_bssid),
5685         DEF_CLONE_CMD("wdslegacy", 1,   set80211clone_wdslegacy),
5686         DEF_CLONE_CMD("-wdslegacy", 0,  set80211clone_wdslegacy),
5687 };
5688 static struct afswtch af_ieee80211 = {
5689         .af_name        = "af_ieee80211",
5690         .af_af          = AF_UNSPEC,
5691         .af_other_status = ieee80211_status,
5692 };
5693
5694 static __constructor void
5695 ieee80211_ctor(void)
5696 {
5697         int i;
5698
5699         for (i = 0; i < nitems(ieee80211_cmds);  i++)
5700                 cmd_register(&ieee80211_cmds[i]);
5701         af_register(&af_ieee80211);
5702         clone_setdefcallback("wlan", wlan_create);
5703 }