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