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