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