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