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