]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sbin/ifconfig/ifieee80211.c
Update to ELF Tool Chain r3668
[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, 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         printf("%-*.*s  %-17.17s  %4s %4s   %-7s  %3s %4s\n"
3509                 , IEEE80211_NWID_LEN, IEEE80211_NWID_LEN, "SSID/MESH ID"
3510                 , "BSSID"
3511                 , "CHAN"
3512                 , "RATE"
3513                 , " S:N"
3514                 , "INT"
3515                 , "CAPS"
3516         );
3517         cp = buf;
3518         do {
3519                 const struct ieee80211req_scan_result *sr;
3520                 const uint8_t *vp, *idp;
3521
3522                 sr = (const struct ieee80211req_scan_result *) cp;
3523                 vp = cp + sr->isr_ie_off;
3524                 if (sr->isr_meshid_len) {
3525                         idp = vp + sr->isr_ssid_len;
3526                         idlen = sr->isr_meshid_len;
3527                 } else {
3528                         idp = vp;
3529                         idlen = sr->isr_ssid_len;
3530                 }
3531                 printf("%-*.*s  %s  %3d  %3dM %4d:%-4d %4d %-4.4s"
3532                         , IEEE80211_NWID_LEN
3533                           , copy_essid(ssid, IEEE80211_NWID_LEN, idp, idlen)
3534                           , ssid
3535                         , ether_ntoa((const struct ether_addr *) sr->isr_bssid)
3536                         , ieee80211_mhz2ieee(sr->isr_freq, sr->isr_flags)
3537                         , getmaxrate(sr->isr_rates, sr->isr_nrates)
3538                         , (sr->isr_rssi/2)+sr->isr_noise, sr->isr_noise
3539                         , sr->isr_intval
3540                         , getcaps(sr->isr_capinfo)
3541                 );
3542                 printies(vp + sr->isr_ssid_len + sr->isr_meshid_len,
3543                     sr->isr_ie_len, 24);
3544                 printf("\n");
3545                 cp += sr->isr_len, len -= sr->isr_len;
3546         } while (len >= sizeof(struct ieee80211req_scan_result));
3547 }
3548
3549 static void
3550 scan_and_wait(int s)
3551 {
3552         struct ieee80211_scan_req sr;
3553         struct ieee80211req ireq;
3554         int sroute;
3555
3556         sroute = socket(PF_ROUTE, SOCK_RAW, 0);
3557         if (sroute < 0) {
3558                 perror("socket(PF_ROUTE,SOCK_RAW)");
3559                 return;
3560         }
3561         (void) memset(&ireq, 0, sizeof(ireq));
3562         (void) strlcpy(ireq.i_name, name, sizeof(ireq.i_name));
3563         ireq.i_type = IEEE80211_IOC_SCAN_REQ;
3564
3565         memset(&sr, 0, sizeof(sr));
3566         sr.sr_flags = IEEE80211_IOC_SCAN_ACTIVE
3567                     | IEEE80211_IOC_SCAN_BGSCAN
3568                     | IEEE80211_IOC_SCAN_NOPICK
3569                     | IEEE80211_IOC_SCAN_ONCE;
3570         sr.sr_duration = IEEE80211_IOC_SCAN_FOREVER;
3571         sr.sr_nssid = 0;
3572
3573         ireq.i_data = &sr;
3574         ireq.i_len = sizeof(sr);
3575         /*
3576          * NB: only root can trigger a scan so ignore errors. Also ignore
3577          * possible errors from net80211, even if no new scan could be
3578          * started there might still be a valid scan cache.
3579          */
3580         if (ioctl(s, SIOCS80211, &ireq) == 0) {
3581                 char buf[2048];
3582                 struct if_announcemsghdr *ifan;
3583                 struct rt_msghdr *rtm;
3584
3585                 do {
3586                         if (read(sroute, buf, sizeof(buf)) < 0) {
3587                                 perror("read(PF_ROUTE)");
3588                                 break;
3589                         }
3590                         rtm = (struct rt_msghdr *) buf;
3591                         if (rtm->rtm_version != RTM_VERSION)
3592                                 break;
3593                         ifan = (struct if_announcemsghdr *) rtm;
3594                 } while (rtm->rtm_type != RTM_IEEE80211 ||
3595                     ifan->ifan_what != RTM_IEEE80211_SCAN);
3596         }
3597         close(sroute);
3598 }
3599
3600 static
3601 DECL_CMD_FUNC(set80211scan, val, d)
3602 {
3603         scan_and_wait(s);
3604         list_scan(s);
3605 }
3606
3607 static enum ieee80211_opmode get80211opmode(int s);
3608
3609 static int
3610 gettxseq(const struct ieee80211req_sta_info *si)
3611 {
3612         int i, txseq;
3613
3614         if ((si->isi_state & IEEE80211_NODE_QOS) == 0)
3615                 return si->isi_txseqs[0];
3616         /* XXX not right but usually what folks want */
3617         txseq = 0;
3618         for (i = 0; i < IEEE80211_TID_SIZE; i++)
3619                 if (si->isi_txseqs[i] > txseq)
3620                         txseq = si->isi_txseqs[i];
3621         return txseq;
3622 }
3623
3624 static int
3625 getrxseq(const struct ieee80211req_sta_info *si)
3626 {
3627         int i, rxseq;
3628
3629         if ((si->isi_state & IEEE80211_NODE_QOS) == 0)
3630                 return si->isi_rxseqs[0];
3631         /* XXX not right but usually what folks want */
3632         rxseq = 0;
3633         for (i = 0; i < IEEE80211_TID_SIZE; i++)
3634                 if (si->isi_rxseqs[i] > rxseq)
3635                         rxseq = si->isi_rxseqs[i];
3636         return rxseq;
3637 }
3638
3639 static void
3640 list_stations(int s)
3641 {
3642         union {
3643                 struct ieee80211req_sta_req req;
3644                 uint8_t buf[24*1024];
3645         } u;
3646         enum ieee80211_opmode opmode = get80211opmode(s);
3647         const uint8_t *cp;
3648         int len;
3649
3650         /* broadcast address =>'s get all stations */
3651         (void) memset(u.req.is_u.macaddr, 0xff, IEEE80211_ADDR_LEN);
3652         if (opmode == IEEE80211_M_STA) {
3653                 /*
3654                  * Get information about the associated AP.
3655                  */
3656                 (void) get80211(s, IEEE80211_IOC_BSSID,
3657                     u.req.is_u.macaddr, IEEE80211_ADDR_LEN);
3658         }
3659         if (get80211len(s, IEEE80211_IOC_STA_INFO, &u, sizeof(u), &len) < 0)
3660                 errx(1, "unable to get station information");
3661         if (len < sizeof(struct ieee80211req_sta_info))
3662                 return;
3663
3664         getchaninfo(s);
3665
3666         if (opmode == IEEE80211_M_MBSS)
3667                 printf("%-17.17s %4s %5s %5s %7s %4s %4s %4s %6s %6s\n"
3668                         , "ADDR"
3669                         , "CHAN"
3670                         , "LOCAL"
3671                         , "PEER"
3672                         , "STATE"
3673                         , "RATE"
3674                         , "RSSI"
3675                         , "IDLE"
3676                         , "TXSEQ"
3677                         , "RXSEQ"
3678                 );
3679         else 
3680                 printf("%-17.17s %4s %4s %4s %4s %4s %6s %6s %4s %-7s\n"
3681                         , "ADDR"
3682                         , "AID"
3683                         , "CHAN"
3684                         , "RATE"
3685                         , "RSSI"
3686                         , "IDLE"
3687                         , "TXSEQ"
3688                         , "RXSEQ"
3689                         , "CAPS"
3690                         , "FLAG"
3691                 );
3692         cp = (const uint8_t *) u.req.info;
3693         do {
3694                 const struct ieee80211req_sta_info *si;
3695
3696                 si = (const struct ieee80211req_sta_info *) cp;
3697                 if (si->isi_len < sizeof(*si))
3698                         break;
3699                 if (opmode == IEEE80211_M_MBSS)
3700                         printf("%s %4d %5x %5x %7.7s %3dM %4.1f %4d %6d %6d"
3701                                 , ether_ntoa((const struct ether_addr*)
3702                                     si->isi_macaddr)
3703                                 , ieee80211_mhz2ieee(si->isi_freq,
3704                                     si->isi_flags)
3705                                 , si->isi_localid
3706                                 , si->isi_peerid
3707                                 , mesh_linkstate_string(si->isi_peerstate)
3708                                 , si->isi_txmbps/2
3709                                 , si->isi_rssi/2.
3710                                 , si->isi_inact
3711                                 , gettxseq(si)
3712                                 , getrxseq(si)
3713                         );
3714                 else 
3715                         printf("%s %4u %4d %3dM %4.1f %4d %6d %6d %-4.4s %-7.7s"
3716                                 , ether_ntoa((const struct ether_addr*)
3717                                     si->isi_macaddr)
3718                                 , IEEE80211_AID(si->isi_associd)
3719                                 , ieee80211_mhz2ieee(si->isi_freq,
3720                                     si->isi_flags)
3721                                 , si->isi_txmbps/2
3722                                 , si->isi_rssi/2.
3723                                 , si->isi_inact
3724                                 , gettxseq(si)
3725                                 , getrxseq(si)
3726                                 , getcaps(si->isi_capinfo)
3727                                 , getflags(si->isi_state)
3728                         );
3729                 printies(cp + si->isi_ie_off, si->isi_ie_len, 24);
3730                 printmimo(&si->isi_mimo);
3731                 printf("\n");
3732                 cp += si->isi_len, len -= si->isi_len;
3733         } while (len >= sizeof(struct ieee80211req_sta_info));
3734 }
3735
3736 static const char *
3737 mesh_linkstate_string(uint8_t state)
3738 {
3739         static const char *state_names[] = {
3740             [0] = "IDLE",
3741             [1] = "OPEN-TX",
3742             [2] = "OPEN-RX",
3743             [3] = "CONF-RX",
3744             [4] = "ESTAB",
3745             [5] = "HOLDING",
3746         };
3747
3748         if (state >= nitems(state_names)) {
3749                 static char buf[10];
3750                 snprintf(buf, sizeof(buf), "#%u", state);
3751                 return buf;
3752         } else
3753                 return state_names[state];
3754 }
3755
3756 static const char *
3757 get_chaninfo(const struct ieee80211_channel *c, int precise,
3758         char buf[], size_t bsize)
3759 {
3760         buf[0] = '\0';
3761         if (IEEE80211_IS_CHAN_FHSS(c))
3762                 strlcat(buf, " FHSS", bsize);
3763         if (IEEE80211_IS_CHAN_A(c))
3764                 strlcat(buf, " 11a", bsize);
3765         else if (IEEE80211_IS_CHAN_ANYG(c))
3766                 strlcat(buf, " 11g", bsize);
3767         else if (IEEE80211_IS_CHAN_B(c))
3768                 strlcat(buf, " 11b", bsize);
3769         if (IEEE80211_IS_CHAN_HALF(c))
3770                 strlcat(buf, "/10MHz", bsize);
3771         if (IEEE80211_IS_CHAN_QUARTER(c))
3772                 strlcat(buf, "/5MHz", bsize);
3773         if (IEEE80211_IS_CHAN_TURBO(c))
3774                 strlcat(buf, " Turbo", bsize);
3775         if (precise) {
3776                 /* XXX should make VHT80U, VHT80D */
3777                 if (IEEE80211_IS_CHAN_VHT80(c) &&
3778                     IEEE80211_IS_CHAN_HT40D(c))
3779                         strlcat(buf, " vht/80-", bsize);
3780                 else if (IEEE80211_IS_CHAN_VHT80(c) &&
3781                     IEEE80211_IS_CHAN_HT40U(c))
3782                         strlcat(buf, " vht/80+", bsize);
3783                 else if (IEEE80211_IS_CHAN_VHT80(c))
3784                         strlcat(buf, " vht/80", bsize);
3785                 else if (IEEE80211_IS_CHAN_VHT40D(c))
3786                         strlcat(buf, " vht/40-", bsize);
3787                 else if (IEEE80211_IS_CHAN_VHT40U(c))
3788                         strlcat(buf, " vht/40+", bsize);
3789                 else if (IEEE80211_IS_CHAN_VHT20(c))
3790                         strlcat(buf, " vht/20", bsize);
3791                 else if (IEEE80211_IS_CHAN_HT20(c))
3792                         strlcat(buf, " ht/20", bsize);
3793                 else if (IEEE80211_IS_CHAN_HT40D(c))
3794                         strlcat(buf, " ht/40-", bsize);
3795                 else if (IEEE80211_IS_CHAN_HT40U(c))
3796                         strlcat(buf, " ht/40+", bsize);
3797         } else {
3798                 if (IEEE80211_IS_CHAN_VHT(c))
3799                         strlcat(buf, " vht", bsize);
3800                 else if (IEEE80211_IS_CHAN_HT(c))
3801                         strlcat(buf, " ht", bsize);
3802         }
3803         return buf;
3804 }
3805
3806 static void
3807 print_chaninfo(const struct ieee80211_channel *c, int verb)
3808 {
3809         char buf[14];
3810
3811         if (verb)
3812                 printf("Channel %3u : %u%c%c%c%c%c MHz%-14.14s",
3813                     ieee80211_mhz2ieee(c->ic_freq, c->ic_flags), c->ic_freq,
3814                     IEEE80211_IS_CHAN_PASSIVE(c) ? '*' : ' ',
3815                     IEEE80211_IS_CHAN_DFS(c) ? 'D' : ' ',
3816                     IEEE80211_IS_CHAN_RADAR(c) ? 'R' : ' ',
3817                     IEEE80211_IS_CHAN_CWINT(c) ? 'I' : ' ',
3818                     IEEE80211_IS_CHAN_CACDONE(c) ? 'C' : ' ',
3819                     get_chaninfo(c, verb, buf, sizeof(buf)));
3820         else
3821         printf("Channel %3u : %u%c MHz%-14.14s",
3822             ieee80211_mhz2ieee(c->ic_freq, c->ic_flags), c->ic_freq,
3823             IEEE80211_IS_CHAN_PASSIVE(c) ? '*' : ' ',
3824             get_chaninfo(c, verb, buf, sizeof(buf)));
3825
3826 }
3827
3828 static int
3829 chanpref(const struct ieee80211_channel *c)
3830 {
3831         if (IEEE80211_IS_CHAN_VHT160(c))
3832                 return 80;
3833         if (IEEE80211_IS_CHAN_VHT80_80(c))
3834                 return 75;
3835         if (IEEE80211_IS_CHAN_VHT80(c))
3836                 return 70;
3837         if (IEEE80211_IS_CHAN_VHT40(c))
3838                 return 60;
3839         if (IEEE80211_IS_CHAN_VHT20(c))
3840                 return 50;
3841         if (IEEE80211_IS_CHAN_HT40(c))
3842                 return 40;
3843         if (IEEE80211_IS_CHAN_HT20(c))
3844                 return 30;
3845         if (IEEE80211_IS_CHAN_HALF(c))
3846                 return 10;
3847         if (IEEE80211_IS_CHAN_QUARTER(c))
3848                 return 5;
3849         if (IEEE80211_IS_CHAN_TURBO(c))
3850                 return 25;
3851         if (IEEE80211_IS_CHAN_A(c))
3852                 return 20;
3853         if (IEEE80211_IS_CHAN_G(c))
3854                 return 20;
3855         if (IEEE80211_IS_CHAN_B(c))
3856                 return 15;
3857         if (IEEE80211_IS_CHAN_PUREG(c))
3858                 return 15;
3859         return 0;
3860 }
3861
3862 static void
3863 print_channels(int s, const struct ieee80211req_chaninfo *chans,
3864         int allchans, int verb)
3865 {
3866         struct ieee80211req_chaninfo *achans;
3867         uint8_t reported[IEEE80211_CHAN_BYTES];
3868         const struct ieee80211_channel *c;
3869         int i, half;
3870
3871         achans = malloc(IEEE80211_CHANINFO_SPACE(chans));
3872         if (achans == NULL)
3873                 errx(1, "no space for active channel list");
3874         achans->ic_nchans = 0;
3875         memset(reported, 0, sizeof(reported));
3876         if (!allchans) {
3877                 struct ieee80211req_chanlist active;
3878
3879                 if (get80211(s, IEEE80211_IOC_CHANLIST, &active, sizeof(active)) < 0)
3880                         errx(1, "unable to get active channel list");
3881                 for (i = 0; i < chans->ic_nchans; i++) {
3882                         c = &chans->ic_chans[i];
3883                         if (!isset(active.ic_channels, c->ic_ieee))
3884                                 continue;
3885                         /*
3886                          * Suppress compatible duplicates unless
3887                          * verbose.  The kernel gives us it's
3888                          * complete channel list which has separate
3889                          * entries for 11g/11b and 11a/turbo.
3890                          */
3891                         if (isset(reported, c->ic_ieee) && !verb) {
3892                                 /* XXX we assume duplicates are adjacent */
3893                                 achans->ic_chans[achans->ic_nchans-1] = *c;
3894                         } else {
3895                                 achans->ic_chans[achans->ic_nchans++] = *c;
3896                                 setbit(reported, c->ic_ieee);
3897                         }
3898                 }
3899         } else {
3900                 for (i = 0; i < chans->ic_nchans; i++) {
3901                         c = &chans->ic_chans[i];
3902                         /* suppress duplicates as above */
3903                         if (isset(reported, c->ic_ieee) && !verb) {
3904                                 /* XXX we assume duplicates are adjacent */
3905                                 struct ieee80211_channel *a =
3906                                     &achans->ic_chans[achans->ic_nchans-1];
3907                                 if (chanpref(c) > chanpref(a))
3908                                         *a = *c;
3909                         } else {
3910                                 achans->ic_chans[achans->ic_nchans++] = *c;
3911                                 setbit(reported, c->ic_ieee);
3912                         }
3913                 }
3914         }
3915         half = achans->ic_nchans / 2;
3916         if (achans->ic_nchans % 2)
3917                 half++;
3918
3919         for (i = 0; i < achans->ic_nchans / 2; i++) {
3920                 print_chaninfo(&achans->ic_chans[i], verb);
3921                 print_chaninfo(&achans->ic_chans[half+i], verb);
3922                 printf("\n");
3923         }
3924         if (achans->ic_nchans % 2) {
3925                 print_chaninfo(&achans->ic_chans[i], verb);
3926                 printf("\n");
3927         }
3928         free(achans);
3929 }
3930
3931 static void
3932 list_channels(int s, int allchans)
3933 {
3934         getchaninfo(s);
3935         print_channels(s, chaninfo, allchans, verbose);
3936 }
3937
3938 static void
3939 print_txpow(const struct ieee80211_channel *c)
3940 {
3941         printf("Channel %3u : %u MHz %3.1f reg %2d  ",
3942             c->ic_ieee, c->ic_freq,
3943             c->ic_maxpower/2., c->ic_maxregpower);
3944 }
3945
3946 static void
3947 print_txpow_verbose(const struct ieee80211_channel *c)
3948 {
3949         print_chaninfo(c, 1);
3950         printf("min %4.1f dBm  max %3.1f dBm  reg %2d dBm",
3951             c->ic_minpower/2., c->ic_maxpower/2., c->ic_maxregpower);
3952         /* indicate where regulatory cap limits power use */
3953         if (c->ic_maxpower > 2*c->ic_maxregpower)
3954                 printf(" <");
3955 }
3956
3957 static void
3958 list_txpow(int s)
3959 {
3960         struct ieee80211req_chaninfo *achans;
3961         uint8_t reported[IEEE80211_CHAN_BYTES];
3962         struct ieee80211_channel *c, *prev;
3963         int i, half;
3964
3965         getchaninfo(s);
3966         achans = malloc(IEEE80211_CHANINFO_SPACE(chaninfo));
3967         if (achans == NULL)
3968                 errx(1, "no space for active channel list");
3969         achans->ic_nchans = 0;
3970         memset(reported, 0, sizeof(reported));
3971         for (i = 0; i < chaninfo->ic_nchans; i++) {
3972                 c = &chaninfo->ic_chans[i];
3973                 /* suppress duplicates as above */
3974                 if (isset(reported, c->ic_ieee) && !verbose) {
3975                         /* XXX we assume duplicates are adjacent */
3976                         assert(achans->ic_nchans > 0);
3977                         prev = &achans->ic_chans[achans->ic_nchans-1];
3978                         /* display highest power on channel */
3979                         if (c->ic_maxpower > prev->ic_maxpower)
3980                                 *prev = *c;
3981                 } else {
3982                         achans->ic_chans[achans->ic_nchans++] = *c;
3983                         setbit(reported, c->ic_ieee);
3984                 }
3985         }
3986         if (!verbose) {
3987                 half = achans->ic_nchans / 2;
3988                 if (achans->ic_nchans % 2)
3989                         half++;
3990
3991                 for (i = 0; i < achans->ic_nchans / 2; i++) {
3992                         print_txpow(&achans->ic_chans[i]);
3993                         print_txpow(&achans->ic_chans[half+i]);
3994                         printf("\n");
3995                 }
3996                 if (achans->ic_nchans % 2) {
3997                         print_txpow(&achans->ic_chans[i]);
3998                         printf("\n");
3999                 }
4000         } else {
4001                 for (i = 0; i < achans->ic_nchans; i++) {
4002                         print_txpow_verbose(&achans->ic_chans[i]);
4003                         printf("\n");
4004                 }
4005         }
4006         free(achans);
4007 }
4008
4009 static void
4010 list_keys(int s)
4011 {
4012 }
4013
4014 static void
4015 list_capabilities(int s)
4016 {
4017         struct ieee80211_devcaps_req *dc;
4018
4019         if (verbose)
4020                 dc = malloc(IEEE80211_DEVCAPS_SIZE(MAXCHAN));
4021         else
4022                 dc = malloc(IEEE80211_DEVCAPS_SIZE(1));
4023         if (dc == NULL)
4024                 errx(1, "no space for device capabilities");
4025         dc->dc_chaninfo.ic_nchans = verbose ? MAXCHAN : 1;
4026         getdevcaps(s, dc);
4027         printb("drivercaps", dc->dc_drivercaps, IEEE80211_C_BITS);
4028         if (dc->dc_cryptocaps != 0 || verbose) {
4029                 putchar('\n');
4030                 printb("cryptocaps", dc->dc_cryptocaps, IEEE80211_CRYPTO_BITS);
4031         }
4032         if (dc->dc_htcaps != 0 || verbose) {
4033                 putchar('\n');
4034                 printb("htcaps", dc->dc_htcaps, IEEE80211_HTCAP_BITS);
4035         }
4036         if (dc->dc_vhtcaps != 0 || verbose) {
4037                 putchar('\n');
4038                 printb("vhtcaps", dc->dc_vhtcaps, IEEE80211_VHTCAP_BITS);
4039         }
4040
4041         putchar('\n');
4042         if (verbose) {
4043                 chaninfo = &dc->dc_chaninfo;    /* XXX */
4044                 print_channels(s, &dc->dc_chaninfo, 1/*allchans*/, verbose);
4045         }
4046         free(dc);
4047 }
4048
4049 static int
4050 get80211wme(int s, int param, int ac, int *val)
4051 {
4052         struct ieee80211req ireq;
4053
4054         (void) memset(&ireq, 0, sizeof(ireq));
4055         (void) strlcpy(ireq.i_name, name, sizeof(ireq.i_name));
4056         ireq.i_type = param;
4057         ireq.i_len = ac;
4058         if (ioctl(s, SIOCG80211, &ireq) < 0) {
4059                 warn("cannot get WME parameter %d, ac %d%s",
4060                     param, ac & IEEE80211_WMEPARAM_VAL,
4061                     ac & IEEE80211_WMEPARAM_BSS ? " (BSS)" : "");
4062                 return -1;
4063         }
4064         *val = ireq.i_val;
4065         return 0;
4066 }
4067
4068 static void
4069 list_wme_aci(int s, const char *tag, int ac)
4070 {
4071         int val;
4072
4073         printf("\t%s", tag);
4074
4075         /* show WME BSS parameters */
4076         if (get80211wme(s, IEEE80211_IOC_WME_CWMIN, ac, &val) != -1)
4077                 printf(" cwmin %2u", val);
4078         if (get80211wme(s, IEEE80211_IOC_WME_CWMAX, ac, &val) != -1)
4079                 printf(" cwmax %2u", val);
4080         if (get80211wme(s, IEEE80211_IOC_WME_AIFS, ac, &val) != -1)
4081                 printf(" aifs %2u", val);
4082         if (get80211wme(s, IEEE80211_IOC_WME_TXOPLIMIT, ac, &val) != -1)
4083                 printf(" txopLimit %3u", val);
4084         if (get80211wme(s, IEEE80211_IOC_WME_ACM, ac, &val) != -1) {
4085                 if (val)
4086                         printf(" acm");
4087                 else if (verbose)
4088                         printf(" -acm");
4089         }
4090         /* !BSS only */
4091         if ((ac & IEEE80211_WMEPARAM_BSS) == 0) {
4092                 if (get80211wme(s, IEEE80211_IOC_WME_ACKPOLICY, ac, &val) != -1) {
4093                         if (!val)
4094                                 printf(" -ack");
4095                         else if (verbose)
4096                                 printf(" ack");
4097                 }
4098         }
4099         printf("\n");
4100 }
4101
4102 static void
4103 list_wme(int s)
4104 {
4105         static const char *acnames[] = { "AC_BE", "AC_BK", "AC_VI", "AC_VO" };
4106         int ac;
4107
4108         if (verbose) {
4109                 /* display both BSS and local settings */
4110                 for (ac = WME_AC_BE; ac <= WME_AC_VO; ac++) {
4111         again:
4112                         if (ac & IEEE80211_WMEPARAM_BSS)
4113                                 list_wme_aci(s, "     ", ac);
4114                         else
4115                                 list_wme_aci(s, acnames[ac], ac);
4116                         if ((ac & IEEE80211_WMEPARAM_BSS) == 0) {
4117                                 ac |= IEEE80211_WMEPARAM_BSS;
4118                                 goto again;
4119                         } else
4120                                 ac &= ~IEEE80211_WMEPARAM_BSS;
4121                 }
4122         } else {
4123                 /* display only channel settings */
4124                 for (ac = WME_AC_BE; ac <= WME_AC_VO; ac++)
4125                         list_wme_aci(s, acnames[ac], ac);
4126         }
4127 }
4128
4129 static void
4130 list_roam(int s)
4131 {
4132         const struct ieee80211_roamparam *rp;
4133         int mode;
4134
4135         getroam(s);
4136         for (mode = IEEE80211_MODE_11A; mode < IEEE80211_MODE_MAX; mode++) {
4137                 rp = &roamparams.params[mode];
4138                 if (rp->rssi == 0 && rp->rate == 0)
4139                         continue;
4140                 if (mode == IEEE80211_MODE_11NA || mode == IEEE80211_MODE_11NG) {
4141                         if (rp->rssi & 1)
4142                                 LINE_CHECK("roam:%-7.7s rssi %2u.5dBm  MCS %2u    ",
4143                                     modename[mode], rp->rssi/2,
4144                                     rp->rate &~ IEEE80211_RATE_MCS);
4145                         else
4146                                 LINE_CHECK("roam:%-7.7s rssi %4udBm  MCS %2u    ",
4147                                     modename[mode], rp->rssi/2,
4148                                     rp->rate &~ IEEE80211_RATE_MCS);
4149                 } else {
4150                         if (rp->rssi & 1)
4151                                 LINE_CHECK("roam:%-7.7s rssi %2u.5dBm rate %2u Mb/s",
4152                                     modename[mode], rp->rssi/2, rp->rate/2);
4153                         else
4154                                 LINE_CHECK("roam:%-7.7s rssi %4udBm rate %2u Mb/s",
4155                                     modename[mode], rp->rssi/2, rp->rate/2);
4156                 }
4157         }
4158 }
4159
4160 static void
4161 list_txparams(int s)
4162 {
4163         const struct ieee80211_txparam *tp;
4164         int mode;
4165
4166         gettxparams(s);
4167         for (mode = IEEE80211_MODE_11A; mode < IEEE80211_MODE_MAX; mode++) {
4168                 tp = &txparams.params[mode];
4169                 if (tp->mgmtrate == 0 && tp->mcastrate == 0)
4170                         continue;
4171                 if (mode == IEEE80211_MODE_11NA || mode == IEEE80211_MODE_11NG) {
4172                         if (tp->ucastrate == IEEE80211_FIXED_RATE_NONE)
4173                                 LINE_CHECK("%-7.7s ucast NONE    mgmt %2u MCS  "
4174                                     "mcast %2u MCS  maxretry %u",
4175                                     modename[mode],
4176                                     tp->mgmtrate &~ IEEE80211_RATE_MCS,
4177                                     tp->mcastrate &~ IEEE80211_RATE_MCS,
4178                                     tp->maxretry);
4179                         else
4180                                 LINE_CHECK("%-7.7s ucast %2u MCS  mgmt %2u MCS  "
4181                                     "mcast %2u MCS  maxretry %u",
4182                                     modename[mode],
4183                                     tp->ucastrate &~ IEEE80211_RATE_MCS,
4184                                     tp->mgmtrate &~ IEEE80211_RATE_MCS,
4185                                     tp->mcastrate &~ IEEE80211_RATE_MCS,
4186                                     tp->maxretry);
4187                 } else {
4188                         if (tp->ucastrate == IEEE80211_FIXED_RATE_NONE)
4189                                 LINE_CHECK("%-7.7s ucast NONE    mgmt %2u Mb/s "
4190                                     "mcast %2u Mb/s maxretry %u",
4191                                     modename[mode],
4192                                     tp->mgmtrate/2,
4193                                     tp->mcastrate/2, tp->maxretry);
4194                         else
4195                                 LINE_CHECK("%-7.7s ucast %2u Mb/s mgmt %2u Mb/s "
4196                                     "mcast %2u Mb/s maxretry %u",
4197                                     modename[mode],
4198                                     tp->ucastrate/2, tp->mgmtrate/2,
4199                                     tp->mcastrate/2, tp->maxretry);
4200                 }
4201         }
4202 }
4203
4204 static void
4205 printpolicy(int policy)
4206 {
4207         switch (policy) {
4208         case IEEE80211_MACCMD_POLICY_OPEN:
4209                 printf("policy: open\n");
4210                 break;
4211         case IEEE80211_MACCMD_POLICY_ALLOW:
4212                 printf("policy: allow\n");
4213                 break;
4214         case IEEE80211_MACCMD_POLICY_DENY:
4215                 printf("policy: deny\n");
4216                 break;
4217         case IEEE80211_MACCMD_POLICY_RADIUS:
4218                 printf("policy: radius\n");
4219                 break;
4220         default:
4221                 printf("policy: unknown (%u)\n", policy);
4222                 break;
4223         }
4224 }
4225
4226 static void
4227 list_mac(int s)
4228 {
4229         struct ieee80211req ireq;
4230         struct ieee80211req_maclist *acllist;
4231         int i, nacls, policy, len;
4232         uint8_t *data;
4233         char c;
4234
4235         (void) memset(&ireq, 0, sizeof(ireq));
4236         (void) strlcpy(ireq.i_name, name, sizeof(ireq.i_name)); /* XXX ?? */
4237         ireq.i_type = IEEE80211_IOC_MACCMD;
4238         ireq.i_val = IEEE80211_MACCMD_POLICY;
4239         if (ioctl(s, SIOCG80211, &ireq) < 0) {
4240                 if (errno == EINVAL) {
4241                         printf("No acl policy loaded\n");
4242                         return;
4243                 }
4244                 err(1, "unable to get mac policy");
4245         }
4246         policy = ireq.i_val;
4247         if (policy == IEEE80211_MACCMD_POLICY_OPEN) {
4248                 c = '*';
4249         } else if (policy == IEEE80211_MACCMD_POLICY_ALLOW) {
4250                 c = '+';
4251         } else if (policy == IEEE80211_MACCMD_POLICY_DENY) {
4252                 c = '-';
4253         } else if (policy == IEEE80211_MACCMD_POLICY_RADIUS) {
4254                 c = 'r';                /* NB: should never have entries */
4255         } else {
4256                 printf("policy: unknown (%u)\n", policy);
4257                 c = '?';
4258         }
4259         if (verbose || c == '?')
4260                 printpolicy(policy);
4261
4262         ireq.i_val = IEEE80211_MACCMD_LIST;
4263         ireq.i_len = 0;
4264         if (ioctl(s, SIOCG80211, &ireq) < 0)
4265                 err(1, "unable to get mac acl list size");
4266         if (ireq.i_len == 0) {          /* NB: no acls */
4267                 if (!(verbose || c == '?'))
4268                         printpolicy(policy);
4269                 return;
4270         }
4271         len = ireq.i_len;
4272
4273         data = malloc(len);
4274         if (data == NULL)
4275                 err(1, "out of memory for acl list");
4276
4277         ireq.i_data = data;
4278         if (ioctl(s, SIOCG80211, &ireq) < 0)
4279                 err(1, "unable to get mac acl list");
4280         nacls = len / sizeof(*acllist);
4281         acllist = (struct ieee80211req_maclist *) data;
4282         for (i = 0; i < nacls; i++)
4283                 printf("%c%s\n", c, ether_ntoa(
4284                         (const struct ether_addr *) acllist[i].ml_macaddr));
4285         free(data);
4286 }
4287
4288 static void
4289 print_regdomain(const struct ieee80211_regdomain *reg, int verb)
4290 {
4291         if ((reg->regdomain != 0 &&
4292             reg->regdomain != reg->country) || verb) {
4293                 const struct regdomain *rd =
4294                     lib80211_regdomain_findbysku(getregdata(), reg->regdomain);
4295                 if (rd == NULL)
4296                         LINE_CHECK("regdomain %d", reg->regdomain);
4297                 else
4298                         LINE_CHECK("regdomain %s", rd->name);
4299         }
4300         if (reg->country != 0 || verb) {
4301                 const struct country *cc =
4302                     lib80211_country_findbycc(getregdata(), reg->country);
4303                 if (cc == NULL)
4304                         LINE_CHECK("country %d", reg->country);
4305                 else
4306                         LINE_CHECK("country %s", cc->isoname);
4307         }
4308         if (reg->location == 'I')
4309                 LINE_CHECK("indoor");
4310         else if (reg->location == 'O')
4311                 LINE_CHECK("outdoor");
4312         else if (verb)
4313                 LINE_CHECK("anywhere");
4314         if (reg->ecm)
4315                 LINE_CHECK("ecm");
4316         else if (verb)
4317                 LINE_CHECK("-ecm");
4318 }
4319
4320 static void
4321 list_regdomain(int s, int channelsalso)
4322 {
4323         getregdomain(s);
4324         if (channelsalso) {
4325                 getchaninfo(s);
4326                 spacer = ':';
4327                 print_regdomain(&regdomain, 1);
4328                 LINE_BREAK();
4329                 print_channels(s, chaninfo, 1/*allchans*/, 1/*verbose*/);
4330         } else
4331                 print_regdomain(&regdomain, verbose);
4332 }
4333
4334 static void
4335 list_mesh(int s)
4336 {
4337         struct ieee80211req ireq;
4338         struct ieee80211req_mesh_route routes[128];
4339         struct ieee80211req_mesh_route *rt;
4340
4341         (void) memset(&ireq, 0, sizeof(ireq));
4342         (void) strlcpy(ireq.i_name, name, sizeof(ireq.i_name));
4343         ireq.i_type = IEEE80211_IOC_MESH_RTCMD;
4344         ireq.i_val = IEEE80211_MESH_RTCMD_LIST;
4345         ireq.i_data = &routes;
4346         ireq.i_len = sizeof(routes);
4347         if (ioctl(s, SIOCG80211, &ireq) < 0)
4348                 err(1, "unable to get the Mesh routing table");
4349
4350         printf("%-17.17s %-17.17s %4s %4s %4s %6s %s\n"
4351                 , "DEST"
4352                 , "NEXT HOP"
4353                 , "HOPS"
4354                 , "METRIC"
4355                 , "LIFETIME"
4356                 , "MSEQ"
4357                 , "FLAGS");
4358
4359         for (rt = &routes[0]; rt - &routes[0] < ireq.i_len / sizeof(*rt); rt++){
4360                 printf("%s ",
4361                     ether_ntoa((const struct ether_addr *)rt->imr_dest));
4362                 printf("%s %4u   %4u   %6u %6u    %c%c\n",
4363                         ether_ntoa((const struct ether_addr *)rt->imr_nexthop),
4364                         rt->imr_nhops, rt->imr_metric, rt->imr_lifetime,
4365                         rt->imr_lastmseq,
4366                         (rt->imr_flags & IEEE80211_MESHRT_FLAGS_DISCOVER) ?
4367                             'D' :
4368                         (rt->imr_flags & IEEE80211_MESHRT_FLAGS_VALID) ?
4369                             'V' : '!',
4370                         (rt->imr_flags & IEEE80211_MESHRT_FLAGS_PROXY) ?
4371                             'P' :
4372                         (rt->imr_flags & IEEE80211_MESHRT_FLAGS_GATE) ?
4373                             'G' :' ');
4374         }
4375 }
4376
4377 static
4378 DECL_CMD_FUNC(set80211list, arg, d)
4379 {
4380 #define iseq(a,b)       (strncasecmp(a,b,sizeof(b)-1) == 0)
4381
4382         LINE_INIT('\t');
4383
4384         if (iseq(arg, "sta"))
4385                 list_stations(s);
4386         else if (iseq(arg, "scan") || iseq(arg, "ap"))
4387                 list_scan(s);
4388         else if (iseq(arg, "chan") || iseq(arg, "freq"))
4389                 list_channels(s, 1);
4390         else if (iseq(arg, "active"))
4391                 list_channels(s, 0);
4392         else if (iseq(arg, "keys"))
4393                 list_keys(s);
4394         else if (iseq(arg, "caps"))
4395                 list_capabilities(s);
4396         else if (iseq(arg, "wme") || iseq(arg, "wmm"))
4397                 list_wme(s);
4398         else if (iseq(arg, "mac"))
4399                 list_mac(s);
4400         else if (iseq(arg, "txpow"))
4401                 list_txpow(s);
4402         else if (iseq(arg, "roam"))
4403                 list_roam(s);
4404         else if (iseq(arg, "txparam") || iseq(arg, "txparm"))
4405                 list_txparams(s);
4406         else if (iseq(arg, "regdomain"))
4407                 list_regdomain(s, 1);
4408         else if (iseq(arg, "countries"))
4409                 list_countries();
4410         else if (iseq(arg, "mesh"))
4411                 list_mesh(s);
4412         else
4413                 errx(1, "Don't know how to list %s for %s", arg, name);
4414         LINE_BREAK();
4415 #undef iseq
4416 }
4417
4418 static enum ieee80211_opmode
4419 get80211opmode(int s)
4420 {
4421         struct ifmediareq ifmr;
4422
4423         (void) memset(&ifmr, 0, sizeof(ifmr));
4424         (void) strlcpy(ifmr.ifm_name, name, sizeof(ifmr.ifm_name));
4425
4426         if (ioctl(s, SIOCGIFMEDIA, (caddr_t)&ifmr) >= 0) {
4427                 if (ifmr.ifm_current & IFM_IEEE80211_ADHOC) {
4428                         if (ifmr.ifm_current & IFM_FLAG0)
4429                                 return IEEE80211_M_AHDEMO;
4430                         else
4431                                 return IEEE80211_M_IBSS;
4432                 }
4433                 if (ifmr.ifm_current & IFM_IEEE80211_HOSTAP)
4434                         return IEEE80211_M_HOSTAP;
4435                 if (ifmr.ifm_current & IFM_IEEE80211_IBSS)
4436                         return IEEE80211_M_IBSS;
4437                 if (ifmr.ifm_current & IFM_IEEE80211_MONITOR)
4438                         return IEEE80211_M_MONITOR;
4439                 if (ifmr.ifm_current & IFM_IEEE80211_MBSS)
4440                         return IEEE80211_M_MBSS;
4441         }
4442         return IEEE80211_M_STA;
4443 }
4444
4445 #if 0
4446 static void
4447 printcipher(int s, struct ieee80211req *ireq, int keylenop)
4448 {
4449         switch (ireq->i_val) {
4450         case IEEE80211_CIPHER_WEP:
4451                 ireq->i_type = keylenop;
4452                 if (ioctl(s, SIOCG80211, ireq) != -1)
4453                         printf("WEP-%s", 
4454                             ireq->i_len <= 5 ? "40" :
4455                             ireq->i_len <= 13 ? "104" : "128");
4456                 else
4457                         printf("WEP");
4458                 break;
4459         case IEEE80211_CIPHER_TKIP:
4460                 printf("TKIP");
4461                 break;
4462         case IEEE80211_CIPHER_AES_OCB:
4463                 printf("AES-OCB");
4464                 break;
4465         case IEEE80211_CIPHER_AES_CCM:
4466                 printf("AES-CCM");
4467                 break;
4468         case IEEE80211_CIPHER_CKIP:
4469                 printf("CKIP");
4470                 break;
4471         case IEEE80211_CIPHER_NONE:
4472                 printf("NONE");
4473                 break;
4474         default:
4475                 printf("UNKNOWN (0x%x)", ireq->i_val);
4476                 break;
4477         }
4478 }
4479 #endif
4480
4481 static void
4482 printkey(const struct ieee80211req_key *ik)
4483 {
4484         static const uint8_t zerodata[IEEE80211_KEYBUF_SIZE];
4485         u_int keylen = ik->ik_keylen;
4486         int printcontents;
4487
4488         printcontents = printkeys &&
4489                 (memcmp(ik->ik_keydata, zerodata, keylen) != 0 || verbose);
4490         if (printcontents)
4491                 LINE_BREAK();
4492         switch (ik->ik_type) {
4493         case IEEE80211_CIPHER_WEP:
4494                 /* compatibility */
4495                 LINE_CHECK("wepkey %u:%s", ik->ik_keyix+1,
4496                     keylen <= 5 ? "40-bit" :
4497                     keylen <= 13 ? "104-bit" : "128-bit");
4498                 break;
4499         case IEEE80211_CIPHER_TKIP:
4500                 if (keylen > 128/8)
4501                         keylen -= 128/8;        /* ignore MIC for now */
4502                 LINE_CHECK("TKIP %u:%u-bit", ik->ik_keyix+1, 8*keylen);
4503                 break;
4504         case IEEE80211_CIPHER_AES_OCB:
4505                 LINE_CHECK("AES-OCB %u:%u-bit", ik->ik_keyix+1, 8*keylen);
4506                 break;
4507         case IEEE80211_CIPHER_AES_CCM:
4508                 LINE_CHECK("AES-CCM %u:%u-bit", ik->ik_keyix+1, 8*keylen);
4509                 break;
4510         case IEEE80211_CIPHER_CKIP:
4511                 LINE_CHECK("CKIP %u:%u-bit", ik->ik_keyix+1, 8*keylen);
4512                 break;
4513         case IEEE80211_CIPHER_NONE:
4514                 LINE_CHECK("NULL %u:%u-bit", ik->ik_keyix+1, 8*keylen);
4515                 break;
4516         default:
4517                 LINE_CHECK("UNKNOWN (0x%x) %u:%u-bit",
4518                         ik->ik_type, ik->ik_keyix+1, 8*keylen);
4519                 break;
4520         }
4521         if (printcontents) {
4522                 u_int i;
4523
4524                 printf(" <");
4525                 for (i = 0; i < keylen; i++)
4526                         printf("%02x", ik->ik_keydata[i]);
4527                 printf(">");
4528                 if (ik->ik_type != IEEE80211_CIPHER_WEP &&
4529                     (ik->ik_keyrsc != 0 || verbose))
4530                         printf(" rsc %ju", (uintmax_t)ik->ik_keyrsc);
4531                 if (ik->ik_type != IEEE80211_CIPHER_WEP &&
4532                     (ik->ik_keytsc != 0 || verbose))
4533                         printf(" tsc %ju", (uintmax_t)ik->ik_keytsc);
4534                 if (ik->ik_flags != 0 && verbose) {
4535                         const char *sep = " ";
4536
4537                         if (ik->ik_flags & IEEE80211_KEY_XMIT)
4538                                 printf("%stx", sep), sep = "+";
4539                         if (ik->ik_flags & IEEE80211_KEY_RECV)
4540                                 printf("%srx", sep), sep = "+";
4541                         if (ik->ik_flags & IEEE80211_KEY_DEFAULT)
4542                                 printf("%sdef", sep), sep = "+";
4543                 }
4544                 LINE_BREAK();
4545         }
4546 }
4547
4548 static void
4549 printrate(const char *tag, int v, int defrate, int defmcs)
4550 {
4551         if ((v & IEEE80211_RATE_MCS) == 0) {
4552                 if (v != defrate) {
4553                         if (v & 1)
4554                                 LINE_CHECK("%s %d.5", tag, v/2);
4555                         else
4556                                 LINE_CHECK("%s %d", tag, v/2);
4557                 }
4558         } else {
4559                 if (v != defmcs)
4560                         LINE_CHECK("%s %d", tag, v &~ 0x80);
4561         }
4562 }
4563
4564 static int
4565 getid(int s, int ix, void *data, size_t len, int *plen, int mesh)
4566 {
4567         struct ieee80211req ireq;
4568
4569         (void) memset(&ireq, 0, sizeof(ireq));
4570         (void) strlcpy(ireq.i_name, name, sizeof(ireq.i_name));
4571         ireq.i_type = (!mesh) ? IEEE80211_IOC_SSID : IEEE80211_IOC_MESH_ID;
4572         ireq.i_val = ix;
4573         ireq.i_data = data;
4574         ireq.i_len = len;
4575         if (ioctl(s, SIOCG80211, &ireq) < 0)
4576                 return -1;
4577         *plen = ireq.i_len;
4578         return 0;
4579 }
4580
4581 static void
4582 ieee80211_status(int s)
4583 {
4584         static const uint8_t zerobssid[IEEE80211_ADDR_LEN];
4585         enum ieee80211_opmode opmode = get80211opmode(s);
4586         int i, num, wpa, wme, bgscan, bgscaninterval, val, len, wepmode;
4587         uint8_t data[32];
4588         const struct ieee80211_channel *c;
4589         const struct ieee80211_roamparam *rp;
4590         const struct ieee80211_txparam *tp;
4591
4592         if (getid(s, -1, data, sizeof(data), &len, 0) < 0) {
4593                 /* If we can't get the SSID, this isn't an 802.11 device. */
4594                 return;
4595         }
4596
4597         /*
4598          * Invalidate cached state so printing status for multiple
4599          * if's doesn't reuse the first interfaces' cached state.
4600          */
4601         gotcurchan = 0;
4602         gotroam = 0;
4603         gottxparams = 0;
4604         gothtconf = 0;
4605         gotregdomain = 0;
4606
4607         printf("\t");
4608         if (opmode == IEEE80211_M_MBSS) {
4609                 printf("meshid ");
4610                 getid(s, 0, data, sizeof(data), &len, 1);
4611                 print_string(data, len);
4612         } else {
4613                 if (get80211val(s, IEEE80211_IOC_NUMSSIDS, &num) < 0)
4614                         num = 0;
4615                 printf("ssid ");
4616                 if (num > 1) {
4617                         for (i = 0; i < num; i++) {
4618                                 if (getid(s, i, data, sizeof(data), &len, 0) >= 0 && len > 0) {
4619                                         printf(" %d:", i + 1);
4620                                         print_string(data, len);
4621                                 }
4622                         }
4623                 } else
4624                         print_string(data, len);
4625         }
4626         c = getcurchan(s);
4627         if (c->ic_freq != IEEE80211_CHAN_ANY) {
4628                 char buf[14];
4629                 printf(" channel %d (%u MHz%s)", c->ic_ieee, c->ic_freq,
4630                         get_chaninfo(c, 1, buf, sizeof(buf)));
4631         } else if (verbose)
4632                 printf(" channel UNDEF");
4633
4634         if (get80211(s, IEEE80211_IOC_BSSID, data, IEEE80211_ADDR_LEN) >= 0 &&
4635             (memcmp(data, zerobssid, sizeof(zerobssid)) != 0 || verbose))
4636                 printf(" bssid %s", ether_ntoa((struct ether_addr *)data));
4637
4638         if (get80211len(s, IEEE80211_IOC_STATIONNAME, data, sizeof(data), &len) != -1) {
4639                 printf("\n\tstationname ");
4640                 print_string(data, len);
4641         }
4642
4643         spacer = ' ';           /* force first break */
4644         LINE_BREAK();
4645
4646         list_regdomain(s, 0);
4647
4648         wpa = 0;
4649         if (get80211val(s, IEEE80211_IOC_AUTHMODE, &val) != -1) {
4650                 switch (val) {
4651                 case IEEE80211_AUTH_NONE:
4652                         LINE_CHECK("authmode NONE");
4653                         break;
4654                 case IEEE80211_AUTH_OPEN:
4655                         LINE_CHECK("authmode OPEN");
4656                         break;
4657                 case IEEE80211_AUTH_SHARED:
4658                         LINE_CHECK("authmode SHARED");
4659                         break;
4660                 case IEEE80211_AUTH_8021X:
4661                         LINE_CHECK("authmode 802.1x");
4662                         break;
4663                 case IEEE80211_AUTH_WPA:
4664                         if (get80211val(s, IEEE80211_IOC_WPA, &wpa) < 0)
4665                                 wpa = 1;        /* default to WPA1 */
4666                         switch (wpa) {
4667                         case 2:
4668                                 LINE_CHECK("authmode WPA2/802.11i");
4669                                 break;
4670                         case 3:
4671                                 LINE_CHECK("authmode WPA1+WPA2/802.11i");
4672                                 break;
4673                         default:
4674                                 LINE_CHECK("authmode WPA");
4675                                 break;
4676                         }
4677                         break;
4678                 case IEEE80211_AUTH_AUTO:
4679                         LINE_CHECK("authmode AUTO");
4680                         break;
4681                 default:
4682                         LINE_CHECK("authmode UNKNOWN (0x%x)", val);
4683                         break;
4684                 }
4685         }
4686
4687         if (wpa || verbose) {
4688                 if (get80211val(s, IEEE80211_IOC_WPS, &val) != -1) {
4689                         if (val)
4690                                 LINE_CHECK("wps");
4691                         else if (verbose)
4692                                 LINE_CHECK("-wps");
4693                 }
4694                 if (get80211val(s, IEEE80211_IOC_TSN, &val) != -1) {
4695                         if (val)
4696                                 LINE_CHECK("tsn");
4697                         else if (verbose)
4698                                 LINE_CHECK("-tsn");
4699                 }
4700                 if (ioctl(s, IEEE80211_IOC_COUNTERMEASURES, &val) != -1) {
4701                         if (val)
4702                                 LINE_CHECK("countermeasures");
4703                         else if (verbose)
4704                                 LINE_CHECK("-countermeasures");
4705                 }
4706 #if 0
4707                 /* XXX not interesting with WPA done in user space */
4708                 ireq.i_type = IEEE80211_IOC_KEYMGTALGS;
4709                 if (ioctl(s, SIOCG80211, &ireq) != -1) {
4710                 }
4711
4712                 ireq.i_type = IEEE80211_IOC_MCASTCIPHER;
4713                 if (ioctl(s, SIOCG80211, &ireq) != -1) {
4714                         LINE_CHECK("mcastcipher ");
4715                         printcipher(s, &ireq, IEEE80211_IOC_MCASTKEYLEN);
4716                         spacer = ' ';
4717                 }
4718
4719                 ireq.i_type = IEEE80211_IOC_UCASTCIPHER;
4720                 if (ioctl(s, SIOCG80211, &ireq) != -1) {
4721                         LINE_CHECK("ucastcipher ");
4722                         printcipher(s, &ireq, IEEE80211_IOC_UCASTKEYLEN);
4723                 }
4724
4725                 if (wpa & 2) {
4726                         ireq.i_type = IEEE80211_IOC_RSNCAPS;
4727                         if (ioctl(s, SIOCG80211, &ireq) != -1) {
4728                                 LINE_CHECK("RSN caps 0x%x", ireq.i_val);
4729                                 spacer = ' ';
4730                         }
4731                 }
4732
4733                 ireq.i_type = IEEE80211_IOC_UCASTCIPHERS;
4734                 if (ioctl(s, SIOCG80211, &ireq) != -1) {
4735                 }
4736 #endif
4737         }
4738
4739         if (get80211val(s, IEEE80211_IOC_WEP, &wepmode) != -1 &&
4740             wepmode != IEEE80211_WEP_NOSUP) {
4741
4742                 switch (wepmode) {
4743                 case IEEE80211_WEP_OFF:
4744                         LINE_CHECK("privacy OFF");
4745                         break;
4746                 case IEEE80211_WEP_ON:
4747                         LINE_CHECK("privacy ON");
4748                         break;
4749                 case IEEE80211_WEP_MIXED:
4750                         LINE_CHECK("privacy MIXED");
4751                         break;
4752                 default:
4753                         LINE_CHECK("privacy UNKNOWN (0x%x)", wepmode);
4754                         break;
4755                 }
4756
4757                 /*
4758                  * If we get here then we've got WEP support so we need
4759                  * to print WEP status.
4760                  */
4761
4762                 if (get80211val(s, IEEE80211_IOC_WEPTXKEY, &val) < 0) {
4763                         warn("WEP support, but no tx key!");
4764                         goto end;
4765                 }
4766                 if (val != -1)
4767                         LINE_CHECK("deftxkey %d", val+1);
4768                 else if (wepmode != IEEE80211_WEP_OFF || verbose)
4769                         LINE_CHECK("deftxkey UNDEF");
4770
4771                 if (get80211val(s, IEEE80211_IOC_NUMWEPKEYS, &num) < 0) {
4772                         warn("WEP support, but no NUMWEPKEYS support!");
4773                         goto end;
4774                 }
4775
4776                 for (i = 0; i < num; i++) {
4777                         struct ieee80211req_key ik;
4778
4779                         memset(&ik, 0, sizeof(ik));
4780                         ik.ik_keyix = i;
4781                         if (get80211(s, IEEE80211_IOC_WPAKEY, &ik, sizeof(ik)) < 0) {
4782                                 warn("WEP support, but can get keys!");
4783                                 goto end;
4784                         }
4785                         if (ik.ik_keylen != 0) {
4786                                 if (verbose)
4787                                         LINE_BREAK();
4788                                 printkey(&ik);
4789                         }
4790                 }
4791 end:
4792                 ;
4793         }
4794
4795         if (get80211val(s, IEEE80211_IOC_POWERSAVE, &val) != -1 &&
4796             val != IEEE80211_POWERSAVE_NOSUP ) {
4797                 if (val != IEEE80211_POWERSAVE_OFF || verbose) {
4798                         switch (val) {
4799                         case IEEE80211_POWERSAVE_OFF:
4800                                 LINE_CHECK("powersavemode OFF");
4801                                 break;
4802                         case IEEE80211_POWERSAVE_CAM:
4803                                 LINE_CHECK("powersavemode CAM");
4804                                 break;
4805                         case IEEE80211_POWERSAVE_PSP:
4806                                 LINE_CHECK("powersavemode PSP");
4807                                 break;
4808                         case IEEE80211_POWERSAVE_PSP_CAM:
4809                                 LINE_CHECK("powersavemode PSP-CAM");
4810                                 break;
4811                         }
4812                         if (get80211val(s, IEEE80211_IOC_POWERSAVESLEEP, &val) != -1)
4813                                 LINE_CHECK("powersavesleep %d", val);
4814                 }
4815         }
4816
4817         if (get80211val(s, IEEE80211_IOC_TXPOWER, &val) != -1) {
4818                 if (val & 1)
4819                         LINE_CHECK("txpower %d.5", val/2);
4820                 else
4821                         LINE_CHECK("txpower %d", val/2);
4822         }
4823         if (verbose) {
4824                 if (get80211val(s, IEEE80211_IOC_TXPOWMAX, &val) != -1)
4825                         LINE_CHECK("txpowmax %.1f", val/2.);
4826         }
4827
4828         if (get80211val(s, IEEE80211_IOC_DOTD, &val) != -1) {
4829                 if (val)
4830                         LINE_CHECK("dotd");
4831                 else if (verbose)
4832                         LINE_CHECK("-dotd");
4833         }
4834
4835         if (get80211val(s, IEEE80211_IOC_RTSTHRESHOLD, &val) != -1) {
4836                 if (val != IEEE80211_RTS_MAX || verbose)
4837                         LINE_CHECK("rtsthreshold %d", val);
4838         }
4839
4840         if (get80211val(s, IEEE80211_IOC_FRAGTHRESHOLD, &val) != -1) {
4841                 if (val != IEEE80211_FRAG_MAX || verbose)
4842                         LINE_CHECK("fragthreshold %d", val);
4843         }
4844         if (opmode == IEEE80211_M_STA || verbose) {
4845                 if (get80211val(s, IEEE80211_IOC_BMISSTHRESHOLD, &val) != -1) {
4846                         if (val != IEEE80211_HWBMISS_MAX || verbose)
4847                                 LINE_CHECK("bmiss %d", val);
4848                 }
4849         }
4850
4851         if (!verbose) {
4852                 gettxparams(s);
4853                 tp = &txparams.params[chan2mode(c)];
4854                 printrate("ucastrate", tp->ucastrate,
4855                     IEEE80211_FIXED_RATE_NONE, IEEE80211_FIXED_RATE_NONE);
4856                 printrate("mcastrate", tp->mcastrate, 2*1,
4857                     IEEE80211_RATE_MCS|0);
4858                 printrate("mgmtrate", tp->mgmtrate, 2*1,
4859                     IEEE80211_RATE_MCS|0);
4860                 if (tp->maxretry != 6)          /* XXX */
4861                         LINE_CHECK("maxretry %d", tp->maxretry);
4862         } else {
4863                 LINE_BREAK();
4864                 list_txparams(s);
4865         }
4866
4867         bgscaninterval = -1;
4868         (void) get80211val(s, IEEE80211_IOC_BGSCAN_INTERVAL, &bgscaninterval);
4869
4870         if (get80211val(s, IEEE80211_IOC_SCANVALID, &val) != -1) {
4871                 if (val != bgscaninterval || verbose)
4872                         LINE_CHECK("scanvalid %u", val);
4873         }
4874
4875         bgscan = 0;
4876         if (get80211val(s, IEEE80211_IOC_BGSCAN, &bgscan) != -1) {
4877                 if (bgscan)
4878                         LINE_CHECK("bgscan");
4879                 else if (verbose)
4880                         LINE_CHECK("-bgscan");
4881         }
4882         if (bgscan || verbose) {
4883                 if (bgscaninterval != -1)
4884                         LINE_CHECK("bgscanintvl %u", bgscaninterval);
4885                 if (get80211val(s, IEEE80211_IOC_BGSCAN_IDLE, &val) != -1)
4886                         LINE_CHECK("bgscanidle %u", val);
4887                 if (!verbose) {
4888                         getroam(s);
4889                         rp = &roamparams.params[chan2mode(c)];
4890                         if (rp->rssi & 1)
4891                                 LINE_CHECK("roam:rssi %u.5", rp->rssi/2);
4892                         else
4893                                 LINE_CHECK("roam:rssi %u", rp->rssi/2);
4894                         LINE_CHECK("roam:rate %u", rp->rate/2);
4895                 } else {
4896                         LINE_BREAK();
4897                         list_roam(s);
4898                         LINE_BREAK();
4899                 }
4900         }
4901
4902         if (IEEE80211_IS_CHAN_ANYG(c) || verbose) {
4903                 if (get80211val(s, IEEE80211_IOC_PUREG, &val) != -1) {
4904                         if (val)
4905                                 LINE_CHECK("pureg");
4906                         else if (verbose)
4907                                 LINE_CHECK("-pureg");
4908                 }
4909                 if (get80211val(s, IEEE80211_IOC_PROTMODE, &val) != -1) {
4910                         switch (val) {
4911                         case IEEE80211_PROTMODE_OFF:
4912                                 LINE_CHECK("protmode OFF");
4913                                 break;
4914                         case IEEE80211_PROTMODE_CTS:
4915                                 LINE_CHECK("protmode CTS");
4916                                 break;
4917                         case IEEE80211_PROTMODE_RTSCTS:
4918                                 LINE_CHECK("protmode RTSCTS");
4919                                 break;
4920                         default:
4921                                 LINE_CHECK("protmode UNKNOWN (0x%x)", val);
4922                                 break;
4923                         }
4924                 }
4925         }
4926
4927         if (IEEE80211_IS_CHAN_HT(c) || verbose) {
4928                 gethtconf(s);
4929                 switch (htconf & 3) {
4930                 case 0:
4931                 case 2:
4932                         LINE_CHECK("-ht");
4933                         break;
4934                 case 1:
4935                         LINE_CHECK("ht20");
4936                         break;
4937                 case 3:
4938                         if (verbose)
4939                                 LINE_CHECK("ht");
4940                         break;
4941                 }
4942                 if (get80211val(s, IEEE80211_IOC_HTCOMPAT, &val) != -1) {
4943                         if (!val)
4944                                 LINE_CHECK("-htcompat");
4945                         else if (verbose)
4946                                 LINE_CHECK("htcompat");
4947                 }
4948                 if (get80211val(s, IEEE80211_IOC_AMPDU, &val) != -1) {
4949                         switch (val) {
4950                         case 0:
4951                                 LINE_CHECK("-ampdu");
4952                                 break;
4953                         case 1:
4954                                 LINE_CHECK("ampdutx -ampdurx");
4955                                 break;
4956                         case 2:
4957                                 LINE_CHECK("-ampdutx ampdurx");
4958                                 break;
4959                         case 3:
4960                                 if (verbose)
4961                                         LINE_CHECK("ampdu");
4962                                 break;
4963                         }
4964                 }
4965                 /* XXX 11ac density/size is different */
4966                 if (get80211val(s, IEEE80211_IOC_AMPDU_LIMIT, &val) != -1) {
4967                         switch (val) {
4968                         case IEEE80211_HTCAP_MAXRXAMPDU_8K:
4969                                 LINE_CHECK("ampdulimit 8k");
4970                                 break;
4971                         case IEEE80211_HTCAP_MAXRXAMPDU_16K:
4972                                 LINE_CHECK("ampdulimit 16k");
4973                                 break;
4974                         case IEEE80211_HTCAP_MAXRXAMPDU_32K:
4975                                 LINE_CHECK("ampdulimit 32k");
4976                                 break;
4977                         case IEEE80211_HTCAP_MAXRXAMPDU_64K:
4978                                 LINE_CHECK("ampdulimit 64k");
4979                                 break;
4980                         }
4981                 }
4982                 /* XXX 11ac density/size is different */
4983                 if (get80211val(s, IEEE80211_IOC_AMPDU_DENSITY, &val) != -1) {
4984                         switch (val) {
4985                         case IEEE80211_HTCAP_MPDUDENSITY_NA:
4986                                 if (verbose)
4987                                         LINE_CHECK("ampdudensity NA");
4988                                 break;
4989                         case IEEE80211_HTCAP_MPDUDENSITY_025:
4990                                 LINE_CHECK("ampdudensity .25");
4991                                 break;
4992                         case IEEE80211_HTCAP_MPDUDENSITY_05:
4993                                 LINE_CHECK("ampdudensity .5");
4994                                 break;
4995                         case IEEE80211_HTCAP_MPDUDENSITY_1:
4996                                 LINE_CHECK("ampdudensity 1");
4997                                 break;
4998                         case IEEE80211_HTCAP_MPDUDENSITY_2:
4999                                 LINE_CHECK("ampdudensity 2");
5000                                 break;
5001                         case IEEE80211_HTCAP_MPDUDENSITY_4:
5002                                 LINE_CHECK("ampdudensity 4");
5003                                 break;
5004                         case IEEE80211_HTCAP_MPDUDENSITY_8:
5005                                 LINE_CHECK("ampdudensity 8");
5006                                 break;
5007                         case IEEE80211_HTCAP_MPDUDENSITY_16:
5008                                 LINE_CHECK("ampdudensity 16");
5009                                 break;
5010                         }
5011                 }
5012                 if (get80211val(s, IEEE80211_IOC_AMSDU, &val) != -1) {
5013                         switch (val) {
5014                         case 0:
5015                                 LINE_CHECK("-amsdu");
5016                                 break;
5017                         case 1:
5018                                 LINE_CHECK("amsdutx -amsdurx");
5019                                 break;
5020                         case 2:
5021                                 LINE_CHECK("-amsdutx amsdurx");
5022                                 break;
5023                         case 3:
5024                                 if (verbose)
5025                                         LINE_CHECK("amsdu");
5026                                 break;
5027                         }
5028                 }
5029                 /* XXX amsdu limit */
5030                 if (get80211val(s, IEEE80211_IOC_SHORTGI, &val) != -1) {
5031                         if (val)
5032                                 LINE_CHECK("shortgi");
5033                         else if (verbose)
5034                                 LINE_CHECK("-shortgi");
5035                 }
5036                 if (get80211val(s, IEEE80211_IOC_HTPROTMODE, &val) != -1) {
5037                         if (val == IEEE80211_PROTMODE_OFF)
5038                                 LINE_CHECK("htprotmode OFF");
5039                         else if (val != IEEE80211_PROTMODE_RTSCTS)
5040                                 LINE_CHECK("htprotmode UNKNOWN (0x%x)", val);
5041                         else if (verbose)
5042                                 LINE_CHECK("htprotmode RTSCTS");
5043                 }
5044                 if (get80211val(s, IEEE80211_IOC_PUREN, &val) != -1) {
5045                         if (val)
5046                                 LINE_CHECK("puren");
5047                         else if (verbose)
5048                                 LINE_CHECK("-puren");
5049                 }
5050                 if (get80211val(s, IEEE80211_IOC_SMPS, &val) != -1) {
5051                         if (val == IEEE80211_HTCAP_SMPS_DYNAMIC)
5052                                 LINE_CHECK("smpsdyn");
5053                         else if (val == IEEE80211_HTCAP_SMPS_ENA)
5054                                 LINE_CHECK("smps");
5055                         else if (verbose)
5056                                 LINE_CHECK("-smps");
5057                 }
5058                 if (get80211val(s, IEEE80211_IOC_RIFS, &val) != -1) {
5059                         if (val)
5060                                 LINE_CHECK("rifs");
5061                         else if (verbose)
5062                                 LINE_CHECK("-rifs");
5063                 }
5064
5065                 /* XXX VHT STBC? */
5066                 if (get80211val(s, IEEE80211_IOC_STBC, &val) != -1) {
5067                         switch (val) {
5068                         case 0:
5069                                 LINE_CHECK("-stbc");
5070                                 break;
5071                         case 1:
5072                                 LINE_CHECK("stbctx -stbcrx");
5073                                 break;
5074                         case 2:
5075                                 LINE_CHECK("-stbctx stbcrx");
5076                                 break;
5077                         case 3:
5078                                 if (verbose)
5079                                         LINE_CHECK("stbc");
5080                                 break;
5081                         }
5082                 }
5083                 if (get80211val(s, IEEE80211_IOC_LDPC, &val) != -1) {
5084                         switch (val) {
5085                         case 0:
5086                                 LINE_CHECK("-ldpc");
5087                                 break;
5088                         case 1:
5089                                 LINE_CHECK("ldpctx -ldpcrx");
5090                                 break;
5091                         case 2:
5092                                 LINE_CHECK("-ldpctx ldpcrx");
5093                                 break;
5094                         case 3:
5095                                 if (verbose)
5096                                         LINE_CHECK("ldpc");
5097                                 break;
5098                         }
5099                 }
5100         }
5101
5102         if (IEEE80211_IS_CHAN_VHT(c) || verbose) {
5103                 getvhtconf(s);
5104                 if (vhtconf & 0x1)
5105                         LINE_CHECK("vht");
5106                 else
5107                         LINE_CHECK("-vht");
5108                 if (vhtconf & 0x2)
5109                         LINE_CHECK("vht40");
5110                 else
5111                         LINE_CHECK("-vht40");
5112                 if (vhtconf & 0x4)
5113                         LINE_CHECK("vht80");
5114                 else
5115                         LINE_CHECK("-vht80");
5116                 if (vhtconf & 0x8)
5117                         LINE_CHECK("vht80p80");
5118                 else
5119                         LINE_CHECK("-vht80p80");
5120                 if (vhtconf & 0x10)
5121                         LINE_CHECK("vht160");
5122                 else
5123                         LINE_CHECK("-vht160");
5124         }
5125
5126         if (get80211val(s, IEEE80211_IOC_WME, &wme) != -1) {
5127                 if (wme)
5128                         LINE_CHECK("wme");
5129                 else if (verbose)
5130                         LINE_CHECK("-wme");
5131         } else
5132                 wme = 0;
5133
5134         if (get80211val(s, IEEE80211_IOC_BURST, &val) != -1) {
5135                 if (val)
5136                         LINE_CHECK("burst");
5137                 else if (verbose)
5138                         LINE_CHECK("-burst");
5139         }
5140
5141         if (get80211val(s, IEEE80211_IOC_FF, &val) != -1) {
5142                 if (val)
5143                         LINE_CHECK("ff");
5144                 else if (verbose)
5145                         LINE_CHECK("-ff");
5146         }
5147         if (get80211val(s, IEEE80211_IOC_TURBOP, &val) != -1) {
5148                 if (val)
5149                         LINE_CHECK("dturbo");
5150                 else if (verbose)
5151                         LINE_CHECK("-dturbo");
5152         }
5153         if (get80211val(s, IEEE80211_IOC_DWDS, &val) != -1) {
5154                 if (val)
5155                         LINE_CHECK("dwds");
5156                 else if (verbose)
5157                         LINE_CHECK("-dwds");
5158         }
5159
5160         if (opmode == IEEE80211_M_HOSTAP) {
5161                 if (get80211val(s, IEEE80211_IOC_HIDESSID, &val) != -1) {
5162                         if (val)
5163                                 LINE_CHECK("hidessid");
5164                         else if (verbose)
5165                                 LINE_CHECK("-hidessid");
5166                 }
5167                 if (get80211val(s, IEEE80211_IOC_APBRIDGE, &val) != -1) {
5168                         if (!val)
5169                                 LINE_CHECK("-apbridge");
5170                         else if (verbose)
5171                                 LINE_CHECK("apbridge");
5172                 }
5173                 if (get80211val(s, IEEE80211_IOC_DTIM_PERIOD, &val) != -1)
5174                         LINE_CHECK("dtimperiod %u", val);
5175
5176                 if (get80211val(s, IEEE80211_IOC_DOTH, &val) != -1) {
5177                         if (!val)
5178                                 LINE_CHECK("-doth");
5179                         else if (verbose)
5180                                 LINE_CHECK("doth");
5181                 }
5182                 if (get80211val(s, IEEE80211_IOC_DFS, &val) != -1) {
5183                         if (!val)
5184                                 LINE_CHECK("-dfs");
5185                         else if (verbose)
5186                                 LINE_CHECK("dfs");
5187                 }
5188                 if (get80211val(s, IEEE80211_IOC_INACTIVITY, &val) != -1) {
5189                         if (!val)
5190                                 LINE_CHECK("-inact");
5191                         else if (verbose)
5192                                 LINE_CHECK("inact");
5193                 }
5194         } else {
5195                 if (get80211val(s, IEEE80211_IOC_ROAMING, &val) != -1) {
5196                         if (val != IEEE80211_ROAMING_AUTO || verbose) {
5197                                 switch (val) {
5198                                 case IEEE80211_ROAMING_DEVICE:
5199                                         LINE_CHECK("roaming DEVICE");
5200                                         break;
5201                                 case IEEE80211_ROAMING_AUTO:
5202                                         LINE_CHECK("roaming AUTO");
5203                                         break;
5204                                 case IEEE80211_ROAMING_MANUAL:
5205                                         LINE_CHECK("roaming MANUAL");
5206                                         break;
5207                                 default:
5208                                         LINE_CHECK("roaming UNKNOWN (0x%x)",
5209                                                 val);
5210                                         break;
5211                                 }
5212                         }
5213                 }
5214         }
5215
5216         if (opmode == IEEE80211_M_AHDEMO) {
5217                 if (get80211val(s, IEEE80211_IOC_TDMA_SLOT, &val) != -1)
5218                         LINE_CHECK("tdmaslot %u", val);
5219                 if (get80211val(s, IEEE80211_IOC_TDMA_SLOTCNT, &val) != -1)
5220                         LINE_CHECK("tdmaslotcnt %u", val);
5221                 if (get80211val(s, IEEE80211_IOC_TDMA_SLOTLEN, &val) != -1)
5222                         LINE_CHECK("tdmaslotlen %u", val);
5223                 if (get80211val(s, IEEE80211_IOC_TDMA_BINTERVAL, &val) != -1)
5224                         LINE_CHECK("tdmabintval %u", val);
5225         } else if (get80211val(s, IEEE80211_IOC_BEACON_INTERVAL, &val) != -1) {
5226                 /* XXX default define not visible */
5227                 if (val != 100 || verbose)
5228                         LINE_CHECK("bintval %u", val);
5229         }
5230
5231         if (wme && verbose) {
5232                 LINE_BREAK();
5233                 list_wme(s);
5234         }
5235
5236         if (opmode == IEEE80211_M_MBSS) {
5237                 if (get80211val(s, IEEE80211_IOC_MESH_TTL, &val) != -1) {
5238                         LINE_CHECK("meshttl %u", val);
5239                 }
5240                 if (get80211val(s, IEEE80211_IOC_MESH_AP, &val) != -1) {
5241                         if (val)
5242                                 LINE_CHECK("meshpeering");
5243                         else
5244                                 LINE_CHECK("-meshpeering");
5245                 }
5246                 if (get80211val(s, IEEE80211_IOC_MESH_FWRD, &val) != -1) {
5247                         if (val)
5248                                 LINE_CHECK("meshforward");
5249                         else
5250                                 LINE_CHECK("-meshforward");
5251                 }
5252                 if (get80211val(s, IEEE80211_IOC_MESH_GATE, &val) != -1) {
5253                         if (val)
5254                                 LINE_CHECK("meshgate");
5255                         else
5256                                 LINE_CHECK("-meshgate");
5257                 }
5258                 if (get80211len(s, IEEE80211_IOC_MESH_PR_METRIC, data, 12,
5259                     &len) != -1) {
5260                         data[len] = '\0';
5261                         LINE_CHECK("meshmetric %s", data);
5262                 }
5263                 if (get80211len(s, IEEE80211_IOC_MESH_PR_PATH, data, 12,
5264                     &len) != -1) {
5265                         data[len] = '\0';
5266                         LINE_CHECK("meshpath %s", data);
5267                 }
5268                 if (get80211val(s, IEEE80211_IOC_HWMP_ROOTMODE, &val) != -1) {
5269                         switch (val) {
5270                         case IEEE80211_HWMP_ROOTMODE_DISABLED:
5271                                 LINE_CHECK("hwmprootmode DISABLED");
5272                                 break;
5273                         case IEEE80211_HWMP_ROOTMODE_NORMAL:
5274                                 LINE_CHECK("hwmprootmode NORMAL");
5275                                 break;
5276                         case IEEE80211_HWMP_ROOTMODE_PROACTIVE:
5277                                 LINE_CHECK("hwmprootmode PROACTIVE");
5278                                 break;
5279                         case IEEE80211_HWMP_ROOTMODE_RANN:
5280                                 LINE_CHECK("hwmprootmode RANN");
5281                                 break;
5282                         default:
5283                                 LINE_CHECK("hwmprootmode UNKNOWN(%d)", val);
5284                                 break;
5285                         }
5286                 }
5287                 if (get80211val(s, IEEE80211_IOC_HWMP_MAXHOPS, &val) != -1) {
5288                         LINE_CHECK("hwmpmaxhops %u", val);
5289                 }
5290         }
5291
5292         LINE_BREAK();
5293 }
5294
5295 static int
5296 get80211(int s, int type, void *data, int len)
5297 {
5298
5299         return (lib80211_get80211(s, name, type, data, len));
5300 }
5301
5302 static int
5303 get80211len(int s, int type, void *data, int len, int *plen)
5304 {
5305
5306         return (lib80211_get80211len(s, name, type, data, len, plen));
5307 }
5308
5309 static int
5310 get80211val(int s, int type, int *val)
5311 {
5312
5313         return (lib80211_get80211val(s, name, type, val));
5314 }
5315
5316 static void
5317 set80211(int s, int type, int val, int len, void *data)
5318 {
5319         int ret;
5320
5321         ret = lib80211_set80211(s, name, type, val, len, data);
5322         if (ret < 0)
5323                 err(1, "SIOCS80211");
5324 }
5325
5326 static const char *
5327 get_string(const char *val, const char *sep, u_int8_t *buf, int *lenp)
5328 {
5329         int len;
5330         int hexstr;
5331         u_int8_t *p;
5332
5333         len = *lenp;
5334         p = buf;
5335         hexstr = (val[0] == '0' && tolower((u_char)val[1]) == 'x');
5336         if (hexstr)
5337                 val += 2;
5338         for (;;) {
5339                 if (*val == '\0')
5340                         break;
5341                 if (sep != NULL && strchr(sep, *val) != NULL) {
5342                         val++;
5343                         break;
5344                 }
5345                 if (hexstr) {
5346                         if (!isxdigit((u_char)val[0])) {
5347                                 warnx("bad hexadecimal digits");
5348                                 return NULL;
5349                         }
5350                         if (!isxdigit((u_char)val[1])) {
5351                                 warnx("odd count hexadecimal digits");
5352                                 return NULL;
5353                         }
5354                 }
5355                 if (p >= buf + len) {
5356                         if (hexstr)
5357                                 warnx("hexadecimal digits too long");
5358                         else
5359                                 warnx("string too long");
5360                         return NULL;
5361                 }
5362                 if (hexstr) {
5363 #define tohex(x)        (isdigit(x) ? (x) - '0' : tolower(x) - 'a' + 10)
5364                         *p++ = (tohex((u_char)val[0]) << 4) |
5365                             tohex((u_char)val[1]);
5366 #undef tohex
5367                         val += 2;
5368                 } else
5369                         *p++ = *val++;
5370         }
5371         len = p - buf;
5372         /* The string "-" is treated as the empty string. */
5373         if (!hexstr && len == 1 && buf[0] == '-') {
5374                 len = 0;
5375                 memset(buf, 0, *lenp);
5376         } else if (len < *lenp)
5377                 memset(p, 0, *lenp - len);
5378         *lenp = len;
5379         return val;
5380 }
5381
5382 static void
5383 print_string(const u_int8_t *buf, int len)
5384 {
5385         int i;
5386         int hasspc;
5387         int utf8;
5388
5389         i = 0;
5390         hasspc = 0;
5391
5392         setlocale(LC_CTYPE, "");
5393         utf8 = strncmp("UTF-8", nl_langinfo(CODESET), 5) == 0;
5394
5395         for (; i < len; i++) {
5396                 if (!isprint(buf[i]) && buf[i] != '\0' && !utf8)
5397                         break;
5398                 if (isspace(buf[i]))
5399                         hasspc++;
5400         }
5401         if (i == len || utf8) {
5402                 if (hasspc || len == 0 || buf[0] == '\0')
5403                         printf("\"%.*s\"", len, buf);
5404                 else
5405                         printf("%.*s", len, buf);
5406         } else {
5407                 printf("0x");
5408                 for (i = 0; i < len; i++)
5409                         printf("%02x", buf[i]);
5410         }
5411 }
5412
5413 static void
5414 setdefregdomain(int s)
5415 {
5416         struct regdata *rdp = getregdata();
5417         const struct regdomain *rd;
5418
5419         /* Check if regdomain/country was already set by a previous call. */
5420         /* XXX is it possible? */
5421         if (regdomain.regdomain != 0 ||
5422             regdomain.country != CTRY_DEFAULT)
5423                 return;
5424
5425         getregdomain(s);
5426
5427         /* Check if it was already set by the driver. */
5428         if (regdomain.regdomain != 0 ||
5429             regdomain.country != CTRY_DEFAULT)
5430                 return;
5431
5432         /* Set FCC/US as default. */
5433         rd = lib80211_regdomain_findbysku(rdp, SKU_FCC);
5434         if (rd == NULL)
5435                 errx(1, "FCC regdomain was not found");
5436
5437         regdomain.regdomain = rd->sku;
5438         if (rd->cc != NULL)
5439                 defaultcountry(rd);
5440
5441         /* Send changes to net80211. */
5442         setregdomain_cb(s, &regdomain);
5443
5444         /* Cleanup (so it can be overriden by subsequent parameters). */
5445         regdomain.regdomain = 0;
5446         regdomain.country = CTRY_DEFAULT;
5447         regdomain.isocc[0] = 0;
5448         regdomain.isocc[1] = 0;
5449 }
5450
5451 /*
5452  * Virtual AP cloning support.
5453  */
5454 static struct ieee80211_clone_params params = {
5455         .icp_opmode     = IEEE80211_M_STA,      /* default to station mode */
5456 };
5457
5458 static void
5459 wlan_create(int s, struct ifreq *ifr)
5460 {
5461         static const uint8_t zerobssid[IEEE80211_ADDR_LEN];
5462         char orig_name[IFNAMSIZ];
5463
5464         if (params.icp_parent[0] == '\0')
5465                 errx(1, "must specify a parent device (wlandev) when creating "
5466                     "a wlan device");
5467         if (params.icp_opmode == IEEE80211_M_WDS &&
5468             memcmp(params.icp_bssid, zerobssid, sizeof(zerobssid)) == 0)
5469                 errx(1, "no bssid specified for WDS (use wlanbssid)");
5470         ifr->ifr_data = (caddr_t) &params;
5471         if (ioctl(s, SIOCIFCREATE2, ifr) < 0)
5472                 err(1, "SIOCIFCREATE2");
5473
5474         /* XXX preserve original name for ifclonecreate(). */
5475         strlcpy(orig_name, name, sizeof(orig_name));
5476         strlcpy(name, ifr->ifr_name, sizeof(name));
5477
5478         setdefregdomain(s);
5479
5480         strlcpy(name, orig_name, sizeof(name));
5481 }
5482
5483 static
5484 DECL_CMD_FUNC(set80211clone_wlandev, arg, d)
5485 {
5486         strlcpy(params.icp_parent, arg, IFNAMSIZ);
5487 }
5488
5489 static
5490 DECL_CMD_FUNC(set80211clone_wlanbssid, arg, d)
5491 {
5492         const struct ether_addr *ea;
5493
5494         ea = ether_aton(arg);
5495         if (ea == NULL)
5496                 errx(1, "%s: cannot parse bssid", arg);
5497         memcpy(params.icp_bssid, ea->octet, IEEE80211_ADDR_LEN);
5498 }
5499
5500 static
5501 DECL_CMD_FUNC(set80211clone_wlanaddr, arg, d)
5502 {
5503         const struct ether_addr *ea;
5504
5505         ea = ether_aton(arg);
5506         if (ea == NULL)
5507                 errx(1, "%s: cannot parse address", arg);
5508         memcpy(params.icp_macaddr, ea->octet, IEEE80211_ADDR_LEN);
5509         params.icp_flags |= IEEE80211_CLONE_MACADDR;
5510 }
5511
5512 static
5513 DECL_CMD_FUNC(set80211clone_wlanmode, arg, d)
5514 {
5515 #define iseq(a,b)       (strncasecmp(a,b,sizeof(b)-1) == 0)
5516         if (iseq(arg, "sta"))
5517                 params.icp_opmode = IEEE80211_M_STA;
5518         else if (iseq(arg, "ahdemo") || iseq(arg, "adhoc-demo"))
5519                 params.icp_opmode = IEEE80211_M_AHDEMO;
5520         else if (iseq(arg, "ibss") || iseq(arg, "adhoc"))
5521                 params.icp_opmode = IEEE80211_M_IBSS;
5522         else if (iseq(arg, "ap") || iseq(arg, "host"))
5523                 params.icp_opmode = IEEE80211_M_HOSTAP;
5524         else if (iseq(arg, "wds"))
5525                 params.icp_opmode = IEEE80211_M_WDS;
5526         else if (iseq(arg, "monitor"))
5527                 params.icp_opmode = IEEE80211_M_MONITOR;
5528         else if (iseq(arg, "tdma")) {
5529                 params.icp_opmode = IEEE80211_M_AHDEMO;
5530                 params.icp_flags |= IEEE80211_CLONE_TDMA;
5531         } else if (iseq(arg, "mesh") || iseq(arg, "mp")) /* mesh point */
5532                 params.icp_opmode = IEEE80211_M_MBSS;
5533         else
5534                 errx(1, "Don't know to create %s for %s", arg, name);
5535 #undef iseq
5536 }
5537
5538 static void
5539 set80211clone_beacons(const char *val, int d, int s, const struct afswtch *rafp)
5540 {
5541         /* NB: inverted sense */
5542         if (d)
5543                 params.icp_flags &= ~IEEE80211_CLONE_NOBEACONS;
5544         else
5545                 params.icp_flags |= IEEE80211_CLONE_NOBEACONS;
5546 }
5547
5548 static void
5549 set80211clone_bssid(const char *val, int d, int s, const struct afswtch *rafp)
5550 {
5551         if (d)
5552                 params.icp_flags |= IEEE80211_CLONE_BSSID;
5553         else
5554                 params.icp_flags &= ~IEEE80211_CLONE_BSSID;
5555 }
5556
5557 static void
5558 set80211clone_wdslegacy(const char *val, int d, int s, const struct afswtch *rafp)
5559 {
5560         if (d)
5561                 params.icp_flags |= IEEE80211_CLONE_WDSLEGACY;
5562         else
5563                 params.icp_flags &= ~IEEE80211_CLONE_WDSLEGACY;
5564 }
5565
5566 static struct cmd ieee80211_cmds[] = {
5567         DEF_CMD_ARG("ssid",             set80211ssid),
5568         DEF_CMD_ARG("nwid",             set80211ssid),
5569         DEF_CMD_ARG("meshid",           set80211meshid),
5570         DEF_CMD_ARG("stationname",      set80211stationname),
5571         DEF_CMD_ARG("station",          set80211stationname),   /* BSD/OS */
5572         DEF_CMD_ARG("channel",          set80211channel),
5573         DEF_CMD_ARG("authmode",         set80211authmode),
5574         DEF_CMD_ARG("powersavemode",    set80211powersavemode),
5575         DEF_CMD("powersave",    1,      set80211powersave),
5576         DEF_CMD("-powersave",   0,      set80211powersave),
5577         DEF_CMD_ARG("powersavesleep",   set80211powersavesleep),
5578         DEF_CMD_ARG("wepmode",          set80211wepmode),
5579         DEF_CMD("wep",          1,      set80211wep),
5580         DEF_CMD("-wep",         0,      set80211wep),
5581         DEF_CMD_ARG("deftxkey",         set80211weptxkey),
5582         DEF_CMD_ARG("weptxkey",         set80211weptxkey),
5583         DEF_CMD_ARG("wepkey",           set80211wepkey),
5584         DEF_CMD_ARG("nwkey",            set80211nwkey),         /* NetBSD */
5585         DEF_CMD("-nwkey",       0,      set80211wep),           /* NetBSD */
5586         DEF_CMD_ARG("rtsthreshold",     set80211rtsthreshold),
5587         DEF_CMD_ARG("protmode",         set80211protmode),
5588         DEF_CMD_ARG("txpower",          set80211txpower),
5589         DEF_CMD_ARG("roaming",          set80211roaming),
5590         DEF_CMD("wme",          1,      set80211wme),
5591         DEF_CMD("-wme",         0,      set80211wme),
5592         DEF_CMD("wmm",          1,      set80211wme),
5593         DEF_CMD("-wmm",         0,      set80211wme),
5594         DEF_CMD("hidessid",     1,      set80211hidessid),
5595         DEF_CMD("-hidessid",    0,      set80211hidessid),
5596         DEF_CMD("apbridge",     1,      set80211apbridge),
5597         DEF_CMD("-apbridge",    0,      set80211apbridge),
5598         DEF_CMD_ARG("chanlist",         set80211chanlist),
5599         DEF_CMD_ARG("bssid",            set80211bssid),
5600         DEF_CMD_ARG("ap",               set80211bssid),
5601         DEF_CMD("scan", 0,              set80211scan),
5602         DEF_CMD_ARG("list",             set80211list),
5603         DEF_CMD_ARG2("cwmin",           set80211cwmin),
5604         DEF_CMD_ARG2("cwmax",           set80211cwmax),
5605         DEF_CMD_ARG2("aifs",            set80211aifs),
5606         DEF_CMD_ARG2("txoplimit",       set80211txoplimit),
5607         DEF_CMD_ARG("acm",              set80211acm),
5608         DEF_CMD_ARG("-acm",             set80211noacm),
5609         DEF_CMD_ARG("ack",              set80211ackpolicy),
5610         DEF_CMD_ARG("-ack",             set80211noackpolicy),
5611         DEF_CMD_ARG2("bss:cwmin",       set80211bsscwmin),
5612         DEF_CMD_ARG2("bss:cwmax",       set80211bsscwmax),
5613         DEF_CMD_ARG2("bss:aifs",        set80211bssaifs),
5614         DEF_CMD_ARG2("bss:txoplimit",   set80211bsstxoplimit),
5615         DEF_CMD_ARG("dtimperiod",       set80211dtimperiod),
5616         DEF_CMD_ARG("bintval",          set80211bintval),
5617         DEF_CMD("mac:open",     IEEE80211_MACCMD_POLICY_OPEN,   set80211maccmd),
5618         DEF_CMD("mac:allow",    IEEE80211_MACCMD_POLICY_ALLOW,  set80211maccmd),
5619         DEF_CMD("mac:deny",     IEEE80211_MACCMD_POLICY_DENY,   set80211maccmd),
5620         DEF_CMD("mac:radius",   IEEE80211_MACCMD_POLICY_RADIUS, set80211maccmd),
5621         DEF_CMD("mac:flush",    IEEE80211_MACCMD_FLUSH,         set80211maccmd),
5622         DEF_CMD("mac:detach",   IEEE80211_MACCMD_DETACH,        set80211maccmd),
5623         DEF_CMD_ARG("mac:add",          set80211addmac),
5624         DEF_CMD_ARG("mac:del",          set80211delmac),
5625         DEF_CMD_ARG("mac:kick",         set80211kickmac),
5626         DEF_CMD("pureg",        1,      set80211pureg),
5627         DEF_CMD("-pureg",       0,      set80211pureg),
5628         DEF_CMD("ff",           1,      set80211fastframes),
5629         DEF_CMD("-ff",          0,      set80211fastframes),
5630         DEF_CMD("dturbo",       1,      set80211dturbo),
5631         DEF_CMD("-dturbo",      0,      set80211dturbo),
5632         DEF_CMD("bgscan",       1,      set80211bgscan),
5633         DEF_CMD("-bgscan",      0,      set80211bgscan),
5634         DEF_CMD_ARG("bgscanidle",       set80211bgscanidle),
5635         DEF_CMD_ARG("bgscanintvl",      set80211bgscanintvl),
5636         DEF_CMD_ARG("scanvalid",        set80211scanvalid),
5637         DEF_CMD("quiet",        1,      set80211quiet),
5638         DEF_CMD("-quiet",       0,      set80211quiet),
5639         DEF_CMD_ARG("quiet_count",      set80211quietcount),
5640         DEF_CMD_ARG("quiet_period",     set80211quietperiod),
5641         DEF_CMD_ARG("quiet_duration",   set80211quietduration),
5642         DEF_CMD_ARG("quiet_offset",     set80211quietoffset),
5643         DEF_CMD_ARG("roam:rssi",        set80211roamrssi),
5644         DEF_CMD_ARG("roam:rate",        set80211roamrate),
5645         DEF_CMD_ARG("mcastrate",        set80211mcastrate),
5646         DEF_CMD_ARG("ucastrate",        set80211ucastrate),
5647         DEF_CMD_ARG("mgtrate",          set80211mgtrate),
5648         DEF_CMD_ARG("mgmtrate",         set80211mgtrate),
5649         DEF_CMD_ARG("maxretry",         set80211maxretry),
5650         DEF_CMD_ARG("fragthreshold",    set80211fragthreshold),
5651         DEF_CMD("burst",        1,      set80211burst),
5652         DEF_CMD("-burst",       0,      set80211burst),
5653         DEF_CMD_ARG("bmiss",            set80211bmissthreshold),
5654         DEF_CMD_ARG("bmissthreshold",   set80211bmissthreshold),
5655         DEF_CMD("shortgi",      1,      set80211shortgi),
5656         DEF_CMD("-shortgi",     0,      set80211shortgi),
5657         DEF_CMD("ampdurx",      2,      set80211ampdu),
5658         DEF_CMD("-ampdurx",     -2,     set80211ampdu),
5659         DEF_CMD("ampdutx",      1,      set80211ampdu),
5660         DEF_CMD("-ampdutx",     -1,     set80211ampdu),
5661         DEF_CMD("ampdu",        3,      set80211ampdu),         /* NB: tx+rx */
5662         DEF_CMD("-ampdu",       -3,     set80211ampdu),
5663         DEF_CMD_ARG("ampdulimit",       set80211ampdulimit),
5664         DEF_CMD_ARG("ampdudensity",     set80211ampdudensity),
5665         DEF_CMD("amsdurx",      2,      set80211amsdu),
5666         DEF_CMD("-amsdurx",     -2,     set80211amsdu),
5667         DEF_CMD("amsdutx",      1,      set80211amsdu),
5668         DEF_CMD("-amsdutx",     -1,     set80211amsdu),
5669         DEF_CMD("amsdu",        3,      set80211amsdu),         /* NB: tx+rx */
5670         DEF_CMD("-amsdu",       -3,     set80211amsdu),
5671         DEF_CMD_ARG("amsdulimit",       set80211amsdulimit),
5672         DEF_CMD("stbcrx",       2,      set80211stbc),
5673         DEF_CMD("-stbcrx",      -2,     set80211stbc),
5674         DEF_CMD("stbctx",       1,      set80211stbc),
5675         DEF_CMD("-stbctx",      -1,     set80211stbc),
5676         DEF_CMD("stbc",         3,      set80211stbc),          /* NB: tx+rx */
5677         DEF_CMD("-stbc",        -3,     set80211stbc),
5678         DEF_CMD("ldpcrx",       2,      set80211ldpc),
5679         DEF_CMD("-ldpcrx",      -2,     set80211ldpc),
5680         DEF_CMD("ldpctx",       1,      set80211ldpc),
5681         DEF_CMD("-ldpctx",      -1,     set80211ldpc),
5682         DEF_CMD("ldpc",         3,      set80211ldpc),          /* NB: tx+rx */
5683         DEF_CMD("-ldpc",        -3,     set80211ldpc),
5684         DEF_CMD("puren",        1,      set80211puren),
5685         DEF_CMD("-puren",       0,      set80211puren),
5686         DEF_CMD("doth",         1,      set80211doth),
5687         DEF_CMD("-doth",        0,      set80211doth),
5688         DEF_CMD("dfs",          1,      set80211dfs),
5689         DEF_CMD("-dfs",         0,      set80211dfs),
5690         DEF_CMD("htcompat",     1,      set80211htcompat),
5691         DEF_CMD("-htcompat",    0,      set80211htcompat),
5692         DEF_CMD("dwds",         1,      set80211dwds),
5693         DEF_CMD("-dwds",        0,      set80211dwds),
5694         DEF_CMD("inact",        1,      set80211inact),
5695         DEF_CMD("-inact",       0,      set80211inact),
5696         DEF_CMD("tsn",          1,      set80211tsn),
5697         DEF_CMD("-tsn",         0,      set80211tsn),
5698         DEF_CMD_ARG("regdomain",        set80211regdomain),
5699         DEF_CMD_ARG("country",          set80211country),
5700         DEF_CMD("indoor",       'I',    set80211location),
5701         DEF_CMD("-indoor",      'O',    set80211location),
5702         DEF_CMD("outdoor",      'O',    set80211location),
5703         DEF_CMD("-outdoor",     'I',    set80211location),
5704         DEF_CMD("anywhere",     ' ',    set80211location),
5705         DEF_CMD("ecm",          1,      set80211ecm),
5706         DEF_CMD("-ecm",         0,      set80211ecm),
5707         DEF_CMD("dotd",         1,      set80211dotd),
5708         DEF_CMD("-dotd",        0,      set80211dotd),
5709         DEF_CMD_ARG("htprotmode",       set80211htprotmode),
5710         DEF_CMD("ht20",         1,      set80211htconf),
5711         DEF_CMD("-ht20",        0,      set80211htconf),
5712         DEF_CMD("ht40",         3,      set80211htconf),        /* NB: 20+40 */
5713         DEF_CMD("-ht40",        0,      set80211htconf),
5714         DEF_CMD("ht",           3,      set80211htconf),        /* NB: 20+40 */
5715         DEF_CMD("-ht",          0,      set80211htconf),
5716         DEF_CMD("vht",          1,      set80211vhtconf),
5717         DEF_CMD("-vht",         0,      set80211vhtconf),
5718         DEF_CMD("vht40",                2,      set80211vhtconf),
5719         DEF_CMD("-vht40",               -2,     set80211vhtconf),
5720         DEF_CMD("vht80",                4,      set80211vhtconf),
5721         DEF_CMD("-vht80",               -4,     set80211vhtconf),
5722         DEF_CMD("vht80p80",             8,      set80211vhtconf),
5723         DEF_CMD("-vht80p80",            -8,     set80211vhtconf),
5724         DEF_CMD("vht160",               16,     set80211vhtconf),
5725         DEF_CMD("-vht160",              -16,    set80211vhtconf),
5726         DEF_CMD("rifs",         1,      set80211rifs),
5727         DEF_CMD("-rifs",        0,      set80211rifs),
5728         DEF_CMD("smps",         IEEE80211_HTCAP_SMPS_ENA,       set80211smps),
5729         DEF_CMD("smpsdyn",      IEEE80211_HTCAP_SMPS_DYNAMIC,   set80211smps),
5730         DEF_CMD("-smps",        IEEE80211_HTCAP_SMPS_OFF,       set80211smps),
5731         /* XXX for testing */
5732         DEF_CMD_ARG("chanswitch",       set80211chanswitch),
5733
5734         DEF_CMD_ARG("tdmaslot",         set80211tdmaslot),
5735         DEF_CMD_ARG("tdmaslotcnt",      set80211tdmaslotcnt),
5736         DEF_CMD_ARG("tdmaslotlen",      set80211tdmaslotlen),
5737         DEF_CMD_ARG("tdmabintval",      set80211tdmabintval),
5738
5739         DEF_CMD_ARG("meshttl",          set80211meshttl),
5740         DEF_CMD("meshforward",  1,      set80211meshforward),
5741         DEF_CMD("-meshforward", 0,      set80211meshforward),
5742         DEF_CMD("meshgate",     1,      set80211meshgate),
5743         DEF_CMD("-meshgate",    0,      set80211meshgate),
5744         DEF_CMD("meshpeering",  1,      set80211meshpeering),
5745         DEF_CMD("-meshpeering", 0,      set80211meshpeering),
5746         DEF_CMD_ARG("meshmetric",       set80211meshmetric),
5747         DEF_CMD_ARG("meshpath",         set80211meshpath),
5748         DEF_CMD("meshrt:flush", IEEE80211_MESH_RTCMD_FLUSH,     set80211meshrtcmd),
5749         DEF_CMD_ARG("meshrt:add",       set80211addmeshrt),
5750         DEF_CMD_ARG("meshrt:del",       set80211delmeshrt),
5751         DEF_CMD_ARG("hwmprootmode",     set80211hwmprootmode),
5752         DEF_CMD_ARG("hwmpmaxhops",      set80211hwmpmaxhops),
5753
5754         /* vap cloning support */
5755         DEF_CLONE_CMD_ARG("wlanaddr",   set80211clone_wlanaddr),
5756         DEF_CLONE_CMD_ARG("wlanbssid",  set80211clone_wlanbssid),
5757         DEF_CLONE_CMD_ARG("wlandev",    set80211clone_wlandev),
5758         DEF_CLONE_CMD_ARG("wlanmode",   set80211clone_wlanmode),
5759         DEF_CLONE_CMD("beacons", 1,     set80211clone_beacons),
5760         DEF_CLONE_CMD("-beacons", 0,    set80211clone_beacons),
5761         DEF_CLONE_CMD("bssid",  1,      set80211clone_bssid),
5762         DEF_CLONE_CMD("-bssid", 0,      set80211clone_bssid),
5763         DEF_CLONE_CMD("wdslegacy", 1,   set80211clone_wdslegacy),
5764         DEF_CLONE_CMD("-wdslegacy", 0,  set80211clone_wdslegacy),
5765 };
5766 static struct afswtch af_ieee80211 = {
5767         .af_name        = "af_ieee80211",
5768         .af_af          = AF_UNSPEC,
5769         .af_other_status = ieee80211_status,
5770 };
5771
5772 static __constructor void
5773 ieee80211_ctor(void)
5774 {
5775         int i;
5776
5777         for (i = 0; i < nitems(ieee80211_cmds);  i++)
5778                 cmd_register(&ieee80211_cmds[i]);
5779         af_register(&af_ieee80211);
5780         clone_setdefcallback("wlan", wlan_create);
5781 }