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