xref: /netbsd-src/sbin/ifconfig/ieee80211.c (revision 274254cdae52594c1aa480a736aef78313d15c9c)
1 /*	$NetBSD: ieee80211.c,v 1.23 2009/01/18 00:24:29 lukem Exp $	*/
2 
3 /*
4  * Copyright (c) 1983, 1993
5  *      The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 #ifndef lint
34 __RCSID("$NetBSD: ieee80211.c,v 1.23 2009/01/18 00:24:29 lukem Exp $");
35 #endif /* not lint */
36 
37 #include <sys/param.h>
38 #include <sys/ioctl.h>
39 #include <sys/socket.h>
40 
41 #include <net/if.h>
42 #include <net/if_ether.h>
43 #include <net/if_media.h>
44 #include <net/route.h>
45 #include <net80211/ieee80211.h>
46 #include <net80211/ieee80211_ioctl.h>
47 #include <net80211/ieee80211_netbsd.h>
48 
49 #include <assert.h>
50 #include <ctype.h>
51 #include <err.h>
52 #include <errno.h>
53 #include <netdb.h>
54 #include <string.h>
55 #include <stddef.h>
56 #include <stdlib.h>
57 #include <stdio.h>
58 #include <unistd.h>
59 #include <util.h>
60 
61 #include "extern.h"
62 #include "parse.h"
63 #include "env.h"
64 #include "util.h"
65 
66 static void ieee80211_statistics(prop_dictionary_t);
67 static void ieee80211_status(prop_dictionary_t, prop_dictionary_t);
68 static void ieee80211_constructor(void) __attribute__((constructor));
69 static int set80211(prop_dictionary_t env, uint16_t, int16_t, int16_t,
70     u_int8_t *);
71 static u_int ieee80211_mhz2ieee(u_int, u_int);
72 static int getmaxrate(const uint8_t [15], u_int8_t);
73 static const char * getcaps(int);
74 static void printie(const char*, const uint8_t *, size_t, int);
75 static int copy_essid(char [], size_t, const u_int8_t *, size_t);
76 static void scan_and_wait(prop_dictionary_t);
77 static void list_scan(prop_dictionary_t);
78 static int mappsb(u_int , u_int);
79 static int mapgsm(u_int , u_int);
80 
81 static int sethidessid(prop_dictionary_t, prop_dictionary_t);
82 static int setapbridge(prop_dictionary_t, prop_dictionary_t);
83 static int setifssid(prop_dictionary_t, prop_dictionary_t);
84 static int setifnwkey(prop_dictionary_t, prop_dictionary_t);
85 static int unsetifnwkey(prop_dictionary_t, prop_dictionary_t);
86 static int unsetifbssid(prop_dictionary_t, prop_dictionary_t);
87 static int setifbssid(prop_dictionary_t, prop_dictionary_t);
88 static int setifchan(prop_dictionary_t, prop_dictionary_t);
89 static int setiffrag(prop_dictionary_t, prop_dictionary_t);
90 static int setifpowersave(prop_dictionary_t, prop_dictionary_t);
91 static int setifpowersavesleep(prop_dictionary_t, prop_dictionary_t);
92 static int setifrts(prop_dictionary_t, prop_dictionary_t);
93 static int scan_exec(prop_dictionary_t, prop_dictionary_t);
94 
95 static void printies(const u_int8_t *, int, int);
96 static void printwmeparam(const char *, const u_int8_t *, size_t , int);
97 static void printwmeinfo(const char *, const u_int8_t *, size_t , int);
98 static const char * wpa_cipher(const u_int8_t *);
99 static const char * wpa_keymgmt(const u_int8_t *);
100 static void printwpaie(const char *, const u_int8_t *, size_t , int);
101 static const char * rsn_cipher(const u_int8_t *);
102 static const char * rsn_keymgmt(const u_int8_t *);
103 static void printrsnie(const char *, const u_int8_t *, size_t , int);
104 static void printssid(const char *, const u_int8_t *, size_t , int);
105 static void printrates(const char *, const u_int8_t *, size_t , int);
106 static void printcountry(const char *, const u_int8_t *, size_t , int);
107 static int iswpaoui(const u_int8_t *);
108 static int iswmeinfo(const u_int8_t *);
109 static int iswmeparam(const u_int8_t *);
110 static const char * iename(int);
111 
112 extern struct pinteger parse_chan, parse_frag, parse_rts;
113 extern struct pstr parse_bssid, parse_ssid, parse_nwkey;
114 extern struct pinteger parse_powersavesleep;
115 
116 static const struct kwinst ieee80211boolkw[] = {
117 	  {.k_word = "hidessid", .k_key = "hidessid", .k_neg = true,
118 	   .k_type = KW_T_BOOL, .k_bool = true, .k_negbool = false,
119 	   .k_exec = sethidessid}
120 	, {.k_word = "apbridge", .k_key = "apbridge", .k_neg = true,
121 	   .k_type = KW_T_BOOL, .k_bool = true, .k_negbool = false,
122 	   .k_exec = setapbridge}
123 	, {.k_word = "powersave", .k_key = "powersave", .k_neg = true,
124 	   .k_type = KW_T_BOOL, .k_bool = true, .k_negbool = false,
125 	   .k_exec = setifpowersave}
126 };
127 
128 static const struct kwinst listskw[] = {
129 	{.k_word = "scan", .k_exec = scan_exec}
130 };
131 
132 static struct pkw lists = PKW_INITIALIZER(&lists, "ieee80211 lists", NULL,
133     "list", listskw, __arraycount(listskw), &command_root.pb_parser);
134 
135 static const struct kwinst kw80211kw[] = {
136 	  {.k_word = "bssid", .k_nextparser = &parse_bssid.ps_parser}
137 	, {.k_word = "-bssid", .k_exec = unsetifbssid,
138 	   .k_nextparser = &command_root.pb_parser}
139 	, {.k_word = "chan", .k_nextparser = &parse_chan.pi_parser}
140 	, {.k_word = "-chan", .k_key = "chan", .k_type = KW_T_UINT,
141 	   .k_uint = IEEE80211_CHAN_ANY, .k_exec = setifchan,
142 	   .k_nextparser = &command_root.pb_parser}
143 	, {.k_word = "frag", .k_nextparser = &parse_frag.pi_parser}
144 	, {.k_word = "-frag", .k_key = "frag", .k_type = KW_T_INT,
145 	   .k_int = IEEE80211_FRAG_MAX, .k_exec = setiffrag,
146 	   .k_nextparser = &command_root.pb_parser}
147 	, {.k_word = "list", .k_nextparser = &lists.pk_parser}
148 	, {.k_word = "nwid", .k_nextparser = &parse_ssid.ps_parser}
149 	, {.k_word = "nwkey", .k_nextparser = &parse_nwkey.ps_parser}
150 	, {.k_word = "-nwkey", .k_exec = unsetifnwkey,
151 	   .k_nextparser = &command_root.pb_parser}
152 	, {.k_word = "rts", .k_nextparser = &parse_rts.pi_parser}
153 	, {.k_word = "-rts", .k_key = "rts", .k_type = KW_T_INT,
154 	   .k_int = IEEE80211_RTS_MAX, .k_exec = setifrts,
155 	   .k_nextparser = &command_root.pb_parser}
156 	, {.k_word = "ssid", .k_nextparser = &parse_ssid.ps_parser}
157 	, {.k_word = "powersavesleep",
158 	   .k_nextparser = &parse_powersavesleep.pi_parser}
159 };
160 
161 struct pkw kw80211 = PKW_INITIALIZER(&kw80211, "802.11 keywords", NULL, NULL,
162     kw80211kw, __arraycount(kw80211kw), NULL);
163 
164 struct pkw ieee80211bool = PKW_INITIALIZER(&ieee80211bool, "ieee80211 boolean",
165     NULL, NULL, ieee80211boolkw, __arraycount(ieee80211boolkw),
166     &command_root.pb_parser);
167 
168 struct pinteger parse_chan = PINTEGER_INITIALIZER1(&parse_chan, "chan",
169     0, UINT16_MAX, 10, setifchan, "chan", &command_root.pb_parser);
170 
171 struct pinteger parse_rts = PINTEGER_INITIALIZER1(&parse_rts, "rts",
172     IEEE80211_RTS_MIN, IEEE80211_RTS_MAX, 10,
173     setifrts, "rts", &command_root.pb_parser);
174 
175 struct pinteger parse_frag = PINTEGER_INITIALIZER1(&parse_frag, "frag",
176     IEEE80211_FRAG_MIN, IEEE80211_FRAG_MAX, 10,
177     setiffrag, "frag", &command_root.pb_parser);
178 
179 struct pstr parse_ssid = PSTR_INITIALIZER(&parse_pass, "ssid", setifssid,
180     "ssid", &command_root.pb_parser);
181 
182 struct pinteger parse_powersavesleep =
183     PINTEGER_INITIALIZER1(&parse_powersavesleep, "powersavesleep",
184     0, INT_MAX, 10, setifpowersavesleep, "powersavesleep",
185     &command_root.pb_parser);
186 
187 struct pstr parse_nwkey = PSTR_INITIALIZER(&parse_nwkey, "nwkey", setifnwkey,
188     "nwkey", &command_root.pb_parser);
189 
190 struct pstr parse_bssid = PSTR_INITIALIZER(&parse_bssid, "bssid", setifbssid,
191     "bssid", &command_root.pb_parser);
192 
193 static int
194 set80211(prop_dictionary_t env, uint16_t type, int16_t val, int16_t len,
195     u_int8_t *data)
196 {
197 	struct ieee80211req	ireq;
198 
199 	memset(&ireq, 0, sizeof(ireq));
200 	ireq.i_type = type;
201 	ireq.i_val = val;
202 	ireq.i_len = len;
203 	ireq.i_data = data;
204 	if (direct_ioctl(env, SIOCS80211, &ireq) == -1) {
205 		warn("SIOCS80211");
206 		return -1;
207 	}
208 	return 0;
209 }
210 
211 static int
212 sethidessid(prop_dictionary_t env, prop_dictionary_t oenv)
213 {
214 	bool on, rc;
215 
216 	rc = prop_dictionary_get_bool(env, "hidessid", &on);
217 	assert(rc);
218 	return set80211(env, IEEE80211_IOC_HIDESSID, on ? 1 : 0, 0, NULL);
219 }
220 
221 static int
222 setapbridge(prop_dictionary_t env, prop_dictionary_t oenv)
223 {
224 	bool on, rc;
225 
226 	rc = prop_dictionary_get_bool(env, "apbridge", &on);
227 	assert(rc);
228 	return set80211(env, IEEE80211_IOC_APBRIDGE, on ? 1 : 0, 0, NULL);
229 }
230 
231 static enum ieee80211_opmode
232 get80211opmode(prop_dictionary_t env)
233 {
234 	struct ifmediareq ifmr;
235 
236 	memset(&ifmr, 0, sizeof(ifmr));
237 	if (direct_ioctl(env, SIOCGIFMEDIA, &ifmr) == -1)
238 		;
239 	else if (ifmr.ifm_current & IFM_IEEE80211_ADHOC)
240 		return IEEE80211_M_IBSS;        /* XXX ahdemo */
241 	else if (ifmr.ifm_current & IFM_IEEE80211_HOSTAP)
242 		return IEEE80211_M_HOSTAP;
243 	else if (ifmr.ifm_current & IFM_IEEE80211_MONITOR)
244 		return IEEE80211_M_MONITOR;
245 
246 	return IEEE80211_M_STA;
247 }
248 
249 static int
250 setifssid(prop_dictionary_t env, prop_dictionary_t oenv)
251 {
252 	struct ieee80211_nwid nwid;
253 	ssize_t len;
254 
255 	memset(&nwid, 0, sizeof(nwid));
256 	if ((len = getargdata(env, "ssid", nwid.i_nwid,
257 	    sizeof(nwid.i_nwid))) == -1)
258 		errx(EXIT_FAILURE, "%s: SSID too long", __func__);
259 	nwid.i_len = (uint8_t)len;
260 	if (indirect_ioctl(env, SIOCS80211NWID, &nwid) == -1)
261 		err(EXIT_FAILURE, "SIOCS80211NWID");
262 	return 0;
263 }
264 
265 static int
266 unsetifbssid(prop_dictionary_t env, prop_dictionary_t oenv)
267 {
268 	struct ieee80211_bssid bssid;
269 
270 	memset(&bssid, 0, sizeof(bssid));
271 
272 	if (direct_ioctl(env, SIOCS80211BSSID, &bssid) == -1)
273 		err(EXIT_FAILURE, "SIOCS80211BSSID");
274 	return 0;
275 }
276 
277 static int
278 setifbssid(prop_dictionary_t env, prop_dictionary_t oenv)
279 {
280 	char buf[24];
281 	struct ieee80211_bssid bssid;
282 	struct ether_addr *ea;
283 
284 	if (getargstr(env, "bssid", buf, sizeof(buf)) == -1)
285 		errx(EXIT_FAILURE, "%s: BSSID too long", __func__);
286 
287 	ea = ether_aton(buf);
288 	if (ea == NULL) {
289 		errx(EXIT_FAILURE, "malformed BSSID: %s", buf);
290 		return -1;
291 	}
292 	memcpy(&bssid.i_bssid, ea->ether_addr_octet,
293 	    sizeof(bssid.i_bssid));
294 
295 	if (direct_ioctl(env, SIOCS80211BSSID, &bssid) == -1)
296 		err(EXIT_FAILURE, "SIOCS80211BSSID");
297 	return 0;
298 }
299 
300 static int
301 setifrts(prop_dictionary_t env, prop_dictionary_t oenv)
302 {
303 	bool rc;
304 	int16_t val;
305 
306 	rc = prop_dictionary_get_int16(env, "rts", &val);
307 	assert(rc);
308 	if (set80211(env, IEEE80211_IOC_RTSTHRESHOLD, val, 0, NULL) == -1)
309 		err(EXIT_FAILURE, "IEEE80211_IOC_RTSTHRESHOLD");
310 	return 0;
311 }
312 
313 static int
314 setiffrag(prop_dictionary_t env, prop_dictionary_t oenv)
315 {
316 	bool rc;
317 	int16_t val;
318 
319 	rc = prop_dictionary_get_int16(env, "frag", &val);
320 	assert(rc);
321 	if (set80211(env, IEEE80211_IOC_FRAGTHRESHOLD, val, 0, NULL) == -1)
322 		err(EXIT_FAILURE, "IEEE80211_IOC_FRAGTHRESHOLD");
323 	return 0;
324 }
325 
326 static int
327 setifchan(prop_dictionary_t env, prop_dictionary_t oenv)
328 {
329 	bool rc;
330 	struct ieee80211chanreq channel;
331 
332 	rc = prop_dictionary_get_uint16(env, "chan", &channel.i_channel);
333 	assert(rc);
334 	if (direct_ioctl(env, SIOCS80211CHANNEL, &channel) == -1)
335 		err(EXIT_FAILURE, "SIOCS80211CHANNEL");
336 	return 0;
337 }
338 
339 static int
340 setifnwkey(prop_dictionary_t env, prop_dictionary_t oenv)
341 {
342 	const char *val;
343 	char buf[256];
344 	struct ieee80211_nwkey nwkey;
345 	int i;
346 	u_int8_t keybuf[IEEE80211_WEP_NKID][16];
347 
348 	if (getargstr(env, "nwkey", buf, sizeof(buf)) == -1)
349 		errx(EXIT_FAILURE, "%s: nwkey too long", __func__);
350 
351 	val = buf;
352 
353 	nwkey.i_wepon = IEEE80211_NWKEY_WEP;
354 	nwkey.i_defkid = 1;
355 	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
356 		nwkey.i_key[i].i_keylen = sizeof(keybuf[i]);
357 		nwkey.i_key[i].i_keydat = keybuf[i];
358 	}
359 	if (strcasecmp("persist", val) == 0) {
360 		/* use all values from persistent memory */
361 		nwkey.i_wepon |= IEEE80211_NWKEY_PERSIST;
362 		nwkey.i_defkid = 0;
363 		for (i = 0; i < IEEE80211_WEP_NKID; i++)
364 			nwkey.i_key[i].i_keylen = -1;
365 	} else if (strncasecmp("persist:", val, 8) == 0) {
366 		val += 8;
367 		/* program keys in persistent memory */
368 		nwkey.i_wepon |= IEEE80211_NWKEY_PERSIST;
369 		goto set_nwkey;
370 	} else {
371   set_nwkey:
372 		if (isdigit((unsigned char)val[0]) && val[1] == ':') {
373 			/* specifying a full set of four keys */
374 			nwkey.i_defkid = val[0] - '0';
375 			val += 2;
376 			for (i = 0; i < IEEE80211_WEP_NKID; i++) {
377 				val = get_string(val, ",", keybuf[i],
378 				    &nwkey.i_key[i].i_keylen);
379 				if (val == NULL) {
380 					errno = EINVAL;
381 					return -1;
382 				}
383 			}
384 			if (*val != '\0') {
385 				errx(EXIT_FAILURE, "SIOCS80211NWKEY: too many keys.");
386 			}
387 		} else {
388 			val = get_string(val, NULL, keybuf[0],
389 			    &nwkey.i_key[0].i_keylen);
390 			if (val == NULL) {
391 				errno = EINVAL;
392 				return -1;
393 			}
394 			i = 1;
395 		}
396 	}
397 	for (; i < IEEE80211_WEP_NKID; i++)
398 		nwkey.i_key[i].i_keylen = 0;
399 
400 	if (direct_ioctl(env, SIOCS80211NWKEY, &nwkey) == -1)
401 		err(EXIT_FAILURE, "SIOCS80211NWKEY");
402 	return 0;
403 }
404 
405 static int
406 unsetifnwkey(prop_dictionary_t env, prop_dictionary_t oenv)
407 {
408 	struct ieee80211_nwkey nwkey;
409 	int i;
410 
411 	nwkey.i_wepon = 0;
412 	nwkey.i_defkid = 1;
413 	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
414 		nwkey.i_key[i].i_keylen = 0;
415 		nwkey.i_key[i].i_keydat = NULL;
416 	}
417 
418 	if (direct_ioctl(env, SIOCS80211NWKEY, &nwkey) == -1)
419 		err(EXIT_FAILURE, "SIOCS80211NWKEY");
420 	return 0;
421 }
422 
423 static int
424 setifpowersave(prop_dictionary_t env, prop_dictionary_t oenv)
425 {
426 	struct ieee80211_power power;
427 	bool on, rc;
428 
429 	if (direct_ioctl(env, SIOCG80211POWER, &power) == -1)
430 		err(EXIT_FAILURE, "SIOCG80211POWER");
431 
432 	rc = prop_dictionary_get_bool(env, "powersave", &on);
433 	assert(rc);
434 
435 	power.i_enabled = on ? 1 : 0;
436 	if (direct_ioctl(env, SIOCS80211POWER, &power) == -1) {
437 		warn("SIOCS80211POWER");
438 		return -1;
439 	}
440 	return 0;
441 }
442 
443 static int
444 setifpowersavesleep(prop_dictionary_t env, prop_dictionary_t oenv)
445 {
446 	struct ieee80211_power power;
447 	int64_t maxsleep;
448 	bool rc;
449 
450 	rc = prop_dictionary_get_int64(env, "powersavesleep", &maxsleep);
451 	assert(rc);
452 
453 	if (direct_ioctl(env, SIOCG80211POWER, &power) == -1)
454 		err(EXIT_FAILURE, "SIOCG80211POWER");
455 
456 	power.i_maxsleep = maxsleep;
457 	if (direct_ioctl(env, SIOCS80211POWER, &power) == -1)
458 		err(EXIT_FAILURE, "SIOCS80211POWER");
459 	return 0;
460 }
461 
462 static int
463 scan_exec(prop_dictionary_t env, prop_dictionary_t oenv)
464 {
465 	scan_and_wait(env);
466 	list_scan(env);
467 	return 0;
468 }
469 
470 static void
471 ieee80211_statistics(prop_dictionary_t env)
472 {
473 	struct ieee80211_stats stats;
474 	struct ifreq ifr;
475 
476 	memset(&ifr, 0, sizeof(ifr));
477 	ifr.ifr_buflen = sizeof(stats);
478 	ifr.ifr_buf = (caddr_t)&stats;
479 	if (direct_ioctl(env, (zflag) ? SIOCG80211ZSTATS : SIOCG80211STATS,
480 	    &ifr) == -1)
481 		return;
482 #define	STAT_PRINT(_member, _desc)	\
483 	printf("\t" _desc ": %" PRIu32 "\n", stats._member)
484 
485 	STAT_PRINT(is_rx_badversion, "rx frame with bad version");
486 	STAT_PRINT(is_rx_tooshort, "rx frame too short");
487 	STAT_PRINT(is_rx_wrongbss, "rx from wrong bssid");
488 	STAT_PRINT(is_rx_dup, "rx discard 'cuz dup");
489 	STAT_PRINT(is_rx_wrongdir, "rx w/ wrong direction");
490 	STAT_PRINT(is_rx_mcastecho, "rx discard 'cuz mcast echo");
491 	STAT_PRINT(is_rx_notassoc, "rx discard 'cuz sta !assoc");
492 	STAT_PRINT(is_rx_noprivacy, "rx w/ wep but privacy off");
493 	STAT_PRINT(is_rx_unencrypted, "rx w/o wep and privacy on");
494 	STAT_PRINT(is_rx_wepfail, "rx wep processing failed");
495 	STAT_PRINT(is_rx_decap, "rx decapsulation failed");
496 	STAT_PRINT(is_rx_mgtdiscard, "rx discard mgt frames");
497 	STAT_PRINT(is_rx_ctl, "rx discard ctrl frames");
498 	STAT_PRINT(is_rx_beacon, "rx beacon frames");
499 	STAT_PRINT(is_rx_rstoobig, "rx rate set truncated");
500 	STAT_PRINT(is_rx_elem_missing, "rx required element missing");
501 	STAT_PRINT(is_rx_elem_toobig, "rx element too big");
502 	STAT_PRINT(is_rx_elem_toosmall, "rx element too small");
503 	STAT_PRINT(is_rx_elem_unknown, "rx element unknown");
504 	STAT_PRINT(is_rx_badchan, "rx frame w/ invalid chan");
505 	STAT_PRINT(is_rx_chanmismatch, "rx frame chan mismatch");
506 	STAT_PRINT(is_rx_nodealloc, "rx frame dropped");
507 	STAT_PRINT(is_rx_ssidmismatch, "rx frame ssid mismatch ");
508 	STAT_PRINT(is_rx_auth_unsupported, "rx w/ unsupported auth alg");
509 	STAT_PRINT(is_rx_auth_fail, "rx sta auth failure");
510 	STAT_PRINT(is_rx_auth_countermeasures, "rx auth discard 'cuz CM");
511 	STAT_PRINT(is_rx_assoc_bss, "rx assoc from wrong bssid");
512 	STAT_PRINT(is_rx_assoc_notauth, "rx assoc w/o auth");
513 	STAT_PRINT(is_rx_assoc_capmismatch, "rx assoc w/ cap mismatch");
514 	STAT_PRINT(is_rx_assoc_norate, "rx assoc w/ no rate match");
515 	STAT_PRINT(is_rx_assoc_badwpaie, "rx assoc w/ bad WPA IE");
516 	STAT_PRINT(is_rx_deauth, "rx deauthentication");
517 	STAT_PRINT(is_rx_disassoc, "rx disassociation");
518 	STAT_PRINT(is_rx_badsubtype, "rx frame w/ unknown subtyp");
519 	STAT_PRINT(is_rx_nobuf, "rx failed for lack of buf");
520 	STAT_PRINT(is_rx_decryptcrc, "rx decrypt failed on crc");
521 	STAT_PRINT(is_rx_ahdemo_mgt, "rx discard ahdemo mgt fram");
522 	STAT_PRINT(is_rx_bad_auth, "rx bad auth request");
523 	STAT_PRINT(is_rx_unauth, "rx on unauthorized port");
524 	STAT_PRINT(is_rx_badkeyid, "rx w/ incorrect keyid");
525 	STAT_PRINT(is_rx_ccmpreplay, "rx seq# violation (CCMP)");
526 	STAT_PRINT(is_rx_ccmpformat, "rx format bad (CCMP)");
527 	STAT_PRINT(is_rx_ccmpmic, "rx MIC check failed (CCMP)");
528 	STAT_PRINT(is_rx_tkipreplay, "rx seq# violation (TKIP)");
529 	STAT_PRINT(is_rx_tkipformat, "rx format bad (TKIP)");
530 	STAT_PRINT(is_rx_tkipmic, "rx MIC check failed (TKIP)");
531 	STAT_PRINT(is_rx_tkipicv, "rx ICV check failed (TKIP)");
532 	STAT_PRINT(is_rx_badcipher, "rx failed 'cuz key type");
533 	STAT_PRINT(is_rx_nocipherctx, "rx failed 'cuz key !setup");
534 	STAT_PRINT(is_rx_acl, "rx discard 'cuz acl policy");
535 
536 	STAT_PRINT(is_tx_nobuf, "tx failed for lack of buf");
537 	STAT_PRINT(is_tx_nonode, "tx failed for no node");
538 	STAT_PRINT(is_tx_unknownmgt, "tx of unknown mgt frame");
539 	STAT_PRINT(is_tx_badcipher, "tx failed 'cuz key type");
540 	STAT_PRINT(is_tx_nodefkey, "tx failed 'cuz no defkey");
541 	STAT_PRINT(is_tx_noheadroom, "tx failed 'cuz no space");
542 	STAT_PRINT(is_tx_fragframes, "tx frames fragmented");
543 	STAT_PRINT(is_tx_frags, "tx fragments created");
544 
545 	STAT_PRINT(is_scan_active, "active scans started");
546 	STAT_PRINT(is_scan_passive, "passive scans started");
547 	STAT_PRINT(is_node_timeout, "nodes timed out inactivity");
548 	STAT_PRINT(is_crypto_nomem, "no memory for crypto ctx");
549 	STAT_PRINT(is_crypto_tkip, "tkip crypto done in s/w");
550 	STAT_PRINT(is_crypto_tkipenmic, "tkip en-MIC done in s/w");
551 	STAT_PRINT(is_crypto_tkipdemic, "tkip de-MIC done in s/w");
552 	STAT_PRINT(is_crypto_tkipcm, "tkip counter measures");
553 	STAT_PRINT(is_crypto_ccmp, "ccmp crypto done in s/w");
554 	STAT_PRINT(is_crypto_wep, "wep crypto done in s/w");
555 	STAT_PRINT(is_crypto_setkey_cipher, "cipher rejected key");
556 	STAT_PRINT(is_crypto_setkey_nokey, "no key index for setkey");
557 	STAT_PRINT(is_crypto_delkey, "driver key delete failed");
558 	STAT_PRINT(is_crypto_badcipher, "unknown cipher");
559 	STAT_PRINT(is_crypto_nocipher, "cipher not available");
560 	STAT_PRINT(is_crypto_attachfail, "cipher attach failed");
561 	STAT_PRINT(is_crypto_swfallback, "cipher fallback to s/w");
562 	STAT_PRINT(is_crypto_keyfail, "driver key alloc failed");
563 	STAT_PRINT(is_crypto_enmicfail, "en-MIC failed");
564 	STAT_PRINT(is_ibss_capmismatch, "merge failed-cap mismatch");
565 	STAT_PRINT(is_ibss_norate, "merge failed-rate mismatch");
566 	STAT_PRINT(is_ps_unassoc, "ps-poll for unassoc. sta");
567 	STAT_PRINT(is_ps_badaid, "ps-poll w/ incorrect aid");
568 	STAT_PRINT(is_ps_qempty, "ps-poll w/ nothing to send");
569 	STAT_PRINT(is_ff_badhdr, "fast frame rx'd w/ bad hdr");
570 	STAT_PRINT(is_ff_tooshort, "fast frame rx decap error");
571 	STAT_PRINT(is_ff_split, "fast frame rx split error");
572 	STAT_PRINT(is_ff_decap, "fast frames decap'd");
573 	STAT_PRINT(is_ff_encap, "fast frames encap'd for tx");
574 	STAT_PRINT(is_rx_badbintval, "rx frame w/ bogus bintval");
575 }
576 
577 static void
578 ieee80211_status(prop_dictionary_t env, prop_dictionary_t oenv)
579 {
580 	int i, nwkey_verbose;
581 	struct ieee80211_nwid nwid;
582 	struct ieee80211_nwkey nwkey;
583 	struct ieee80211_power power;
584 	u_int8_t keybuf[IEEE80211_WEP_NKID][16];
585 	struct ieee80211_bssid bssid;
586 	struct ieee80211chanreq channel;
587 	struct ieee80211req ireq;
588 	struct ether_addr ea;
589 	static const u_int8_t zero_macaddr[IEEE80211_ADDR_LEN];
590 	enum ieee80211_opmode opmode = get80211opmode(env);
591 
592 	memset(&bssid, 0, sizeof(bssid));
593 	memset(&nwkey, 0, sizeof(nwkey));
594 	memset(&nwid, 0, sizeof(nwid));
595 	memset(&nwid, 0, sizeof(nwid));
596 
597 	if (indirect_ioctl(env, SIOCG80211NWID, &nwid) == -1)
598 		return;
599 	if (nwid.i_len > IEEE80211_NWID_LEN) {
600 		errx(EXIT_FAILURE, "SIOCG80211NWID: wrong length of nwid (%d)", nwid.i_len);
601 	}
602 	printf("\tssid ");
603 	print_string(nwid.i_nwid, nwid.i_len);
604 
605 	if (opmode == IEEE80211_M_HOSTAP) {
606 		ireq.i_type = IEEE80211_IOC_HIDESSID;
607 		if (direct_ioctl(env, SIOCG80211, &ireq) != -1) {
608                         if (ireq.i_val)
609                                 printf(" [hidden]");
610                         else if (vflag)
611                                 printf(" [shown]");
612                 }
613 
614 		ireq.i_type = IEEE80211_IOC_APBRIDGE;
615 		if (direct_ioctl(env, SIOCG80211, &ireq) != -1) {
616 			if (ireq.i_val)
617 				printf(" apbridge");
618 			else if (vflag)
619 				printf(" -apbridge");
620 		}
621         }
622 
623 	ireq.i_type = IEEE80211_IOC_RTSTHRESHOLD;
624 	if (direct_ioctl(env, SIOCG80211, &ireq) == -1)
625 		;
626 	else if (ireq.i_val < IEEE80211_RTS_MAX)
627 		printf(" rts %d", ireq.i_val);
628 	else if (vflag)
629 		printf(" -rts");
630 
631 	ireq.i_type = IEEE80211_IOC_FRAGTHRESHOLD;
632 	if (direct_ioctl(env, SIOCG80211, &ireq) == -1)
633 		;
634 	else if (ireq.i_val < IEEE80211_FRAG_MAX)
635 		printf(" frag %d", ireq.i_val);
636 	else if (vflag)
637 		printf(" -frag");
638 
639 	memset(&nwkey, 0, sizeof(nwkey));
640 	/* show nwkey only when WEP is enabled */
641 	if (direct_ioctl(env, SIOCG80211NWKEY, &nwkey) == -1 ||
642 	    nwkey.i_wepon == 0) {
643 		printf("\n");
644 		goto skip_wep;
645 	}
646 
647 	printf(" nwkey ");
648 	/* try to retrieve WEP keys */
649 	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
650 		nwkey.i_key[i].i_keydat = keybuf[i];
651 		nwkey.i_key[i].i_keylen = sizeof(keybuf[i]);
652 	}
653 	if (direct_ioctl(env, SIOCG80211NWKEY, &nwkey) == -1) {
654 		printf("*****");
655 	} else {
656 		nwkey_verbose = 0;
657 		/* check to see non default key or multiple keys defined */
658 		if (nwkey.i_defkid != 1) {
659 			nwkey_verbose = 1;
660 		} else {
661 			for (i = 1; i < IEEE80211_WEP_NKID; i++) {
662 				if (nwkey.i_key[i].i_keylen != 0) {
663 					nwkey_verbose = 1;
664 					break;
665 				}
666 			}
667 		}
668 		/* check extra ambiguity with keywords */
669 		if (!nwkey_verbose) {
670 			if (nwkey.i_key[0].i_keylen >= 2 &&
671 			    isdigit(nwkey.i_key[0].i_keydat[0]) &&
672 			    nwkey.i_key[0].i_keydat[1] == ':')
673 				nwkey_verbose = 1;
674 			else if (nwkey.i_key[0].i_keylen >= 7 &&
675 			    strncasecmp("persist",
676 			    (const char *)nwkey.i_key[0].i_keydat, 7) == 0)
677 				nwkey_verbose = 1;
678 		}
679 		if (nwkey_verbose)
680 			printf("%d:", nwkey.i_defkid);
681 		for (i = 0; i < IEEE80211_WEP_NKID; i++) {
682 			if (i > 0)
683 				printf(",");
684 			if (nwkey.i_key[i].i_keylen < 0)
685 				printf("persist");
686 			else
687 				print_string(nwkey.i_key[i].i_keydat,
688 				    nwkey.i_key[i].i_keylen);
689 			if (!nwkey_verbose)
690 				break;
691 		}
692 	}
693 	printf("\n");
694 
695  skip_wep:
696 	if (direct_ioctl(env, SIOCG80211POWER, &power) == -1)
697 		goto skip_power;
698 	printf("\tpowersave ");
699 	if (power.i_enabled)
700 		printf("on (%dms sleep)", power.i_maxsleep);
701 	else
702 		printf("off");
703 	printf("\n");
704 
705  skip_power:
706 	if (direct_ioctl(env, SIOCG80211BSSID, &bssid) == -1)
707 		return;
708 	if (direct_ioctl(env, SIOCG80211CHANNEL, &channel) == -1)
709 		return;
710 	if (memcmp(bssid.i_bssid, zero_macaddr, IEEE80211_ADDR_LEN) == 0) {
711 		if (channel.i_channel != (u_int16_t)-1)
712 			printf("\tchan %d\n", channel.i_channel);
713 	} else {
714 		memcpy(ea.ether_addr_octet, bssid.i_bssid,
715 		    sizeof(ea.ether_addr_octet));
716 		printf("\tbssid %s", ether_ntoa(&ea));
717 		if (channel.i_channel != IEEE80211_CHAN_ANY)
718 			printf(" chan %d", channel.i_channel);
719 		printf("\n");
720 	}
721 }
722 
723 static void
724 scan_and_wait(prop_dictionary_t env)
725 {
726 	int sroute;
727 
728 	sroute = socket(PF_ROUTE, SOCK_RAW, 0);
729 	if (sroute < 0) {
730 		perror("socket(PF_ROUTE,SOCK_RAW)");
731 		return;
732 	}
733 	/* NB: only root can trigger a scan so ignore errors */
734 	if (set80211(env, IEEE80211_IOC_SCAN_REQ, 0, 0, NULL) >= 0) {
735 		char buf[2048];
736 		struct if_announcemsghdr *ifan;
737 		struct rt_msghdr *rtm;
738 
739 		do {
740 			if (read(sroute, buf, sizeof(buf)) < 0) {
741 				perror("read(PF_ROUTE)");
742 				break;
743 			}
744 			rtm = (struct rt_msghdr *) buf;
745 			if (rtm->rtm_version != RTM_VERSION)
746 				break;
747 			ifan = (struct if_announcemsghdr *) rtm;
748 		} while (rtm->rtm_type != RTM_IEEE80211 ||
749 		    ifan->ifan_what != RTM_IEEE80211_SCAN);
750 	}
751 	close(sroute);
752 }
753 
754 static void
755 list_scan(prop_dictionary_t env)
756 {
757 	u_int8_t buf[24*1024];
758 	struct ieee80211req ireq;
759 	char ssid[IEEE80211_NWID_LEN+1];
760 	const u_int8_t *cp;
761 	int len, ssidmax;
762 
763 	memset(&ireq, 0, sizeof(ireq));
764 	ireq.i_type = IEEE80211_IOC_SCAN_RESULTS;
765 	ireq.i_data = buf;
766 	ireq.i_len = sizeof(buf);
767 	if (direct_ioctl(env, SIOCG80211, &ireq) < 0)
768 		errx(EXIT_FAILURE, "unable to get scan results");
769 	len = ireq.i_len;
770 	if (len < (int)sizeof(struct ieee80211req_scan_result))
771 		return;
772 
773 	ssidmax = IEEE80211_NWID_LEN;
774 	printf("%-*.*s  %-17.17s  %4s %4s  %-7s %3s %4s\n"
775 		, ssidmax, ssidmax, "SSID"
776 		, "BSSID"
777 		, "CHAN"
778 		, "RATE"
779 		, "S:N"
780 		, "INT"
781 		, "CAPS"
782 	);
783 	cp = buf;
784 	do {
785 		const struct ieee80211req_scan_result *sr;
786 		const uint8_t *vp;
787 
788 		sr = (const struct ieee80211req_scan_result *) cp;
789 		vp = (const u_int8_t *)(sr+1);
790 		printf("%-*.*s  %s  %3d  %3dM %3d:%-3d  %3d %-4.4s"
791 			, ssidmax
792 			  , copy_essid(ssid, ssidmax, vp, sr->isr_ssid_len)
793 			  , ssid
794 			, ether_ntoa((const struct ether_addr *) sr->isr_bssid)
795 			, ieee80211_mhz2ieee(sr->isr_freq, sr->isr_flags)
796 			, getmaxrate(sr->isr_rates, sr->isr_nrates)
797 			, sr->isr_rssi, sr->isr_noise
798 			, sr->isr_intval
799 			, getcaps(sr->isr_capinfo)
800 		);
801 		printies(vp + sr->isr_ssid_len, sr->isr_ie_len, 24);
802 		printf("\n");
803 		cp += sr->isr_len, len -= sr->isr_len;
804 	} while (len >= (int)sizeof(struct ieee80211req_scan_result));
805 }
806 /*
807  * Convert MHz frequency to IEEE channel number.
808  */
809 static u_int
810 ieee80211_mhz2ieee(u_int isrfreq, u_int isrflags)
811 {
812 	if ((isrflags & IEEE80211_CHAN_GSM) || (907 <= isrfreq && isrfreq <= 922))
813 		return mapgsm(isrfreq, isrflags);
814 	if (isrfreq == 2484)
815 		return 14;
816 	if (isrfreq < 2484)
817 		return (isrfreq - 2407) / 5;
818 	if (isrfreq < 5000) {
819 		if (isrflags & (IEEE80211_CHAN_HALF|IEEE80211_CHAN_QUARTER))
820 			return mappsb(isrfreq, isrflags);
821 		else if (isrfreq > 4900)
822 			return (isrfreq - 4000) / 5;
823 		else
824 			return 15 + ((isrfreq - 2512) / 20);
825 	}
826 	return (isrfreq - 5000) / 5;
827 }
828 
829 static int
830 getmaxrate(const u_int8_t rates[15], u_int8_t nrates)
831 {
832 	int i, maxrate = -1;
833 
834 	for (i = 0; i < nrates; i++) {
835 		int rate = rates[i] & IEEE80211_RATE_VAL;
836 		if (rate > maxrate)
837 			maxrate = rate;
838 	}
839 	return maxrate / 2;
840 }
841 
842 static const char *
843 getcaps(int capinfo)
844 {
845 	static char capstring[32];
846 	char *cp = capstring;
847 
848 	if (capinfo & IEEE80211_CAPINFO_ESS)
849 		*cp++ = 'E';
850 	if (capinfo & IEEE80211_CAPINFO_IBSS)
851 		*cp++ = 'I';
852 	if (capinfo & IEEE80211_CAPINFO_CF_POLLABLE)
853 		*cp++ = 'c';
854 	if (capinfo & IEEE80211_CAPINFO_CF_POLLREQ)
855 		*cp++ = 'C';
856 	if (capinfo & IEEE80211_CAPINFO_PRIVACY)
857 		*cp++ = 'P';
858 	if (capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE)
859 		*cp++ = 'S';
860 	if (capinfo & IEEE80211_CAPINFO_PBCC)
861 		*cp++ = 'B';
862 	if (capinfo & IEEE80211_CAPINFO_CHNL_AGILITY)
863 		*cp++ = 'A';
864 	if (capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME)
865 		*cp++ = 's';
866 	if (capinfo & IEEE80211_CAPINFO_RSN)
867 		*cp++ = 'R';
868 	if (capinfo & IEEE80211_CAPINFO_DSSSOFDM)
869 		*cp++ = 'D';
870 	*cp = '\0';
871 	return capstring;
872 }
873 
874 static void
875 printie(const char* tag, const uint8_t *ie, size_t ielen, int maxlen)
876 {
877 	printf("%s", tag);
878 
879 	maxlen -= strlen(tag)+2;
880 	if ((int)(2*ielen) > maxlen)
881 		maxlen--;
882 	printf("<");
883 	for (; ielen > 0; ie++, ielen--) {
884 		if (maxlen-- <= 0)
885 			break;
886 		printf("%02x", *ie);
887 	}
888 	if (ielen != 0)
889 		printf("-");
890 	printf(">");
891 }
892 
893 #define LE_READ_2(p)					\
894 	((u_int16_t)					\
895 	 ((((const u_int8_t *)(p))[0]      ) |		\
896 	  (((const u_int8_t *)(p))[1] <<  8)))
897 #define LE_READ_4(p)					\
898 	((u_int32_t)					\
899 	 ((((const u_int8_t *)(p))[0]      ) |		\
900 	  (((const u_int8_t *)(p))[1] <<  8) |		\
901 	  (((const u_int8_t *)(p))[2] << 16) |		\
902 	  (((const u_int8_t *)(p))[3] << 24)))
903 
904 /*
905  * NB: The decoding routines assume a properly formatted ie
906  *     which should be safe as the kernel only retains them
907  *     if they parse ok.
908  */
909 
910 static void
911 printwmeparam(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
912 {
913 #define	MS(_v, _f)	(((_v) & _f) >> _f##_S)
914 	static const char *acnames[] = { "BE", "BK", "VO", "VI" };
915 	const struct ieee80211_wme_param *wme =
916 	    (const struct ieee80211_wme_param *) ie;
917 	int i;
918 
919 	printf("%s", tag);
920 	if (!vflag)
921 		return;
922 	printf("<qosinfo 0x%x", wme->param_qosInfo);
923 	ie += offsetof(struct ieee80211_wme_param, params_acParams);
924 	for (i = 0; i < WME_NUM_AC; i++) {
925 		const struct ieee80211_wme_acparams *ac =
926 		    &wme->params_acParams[i];
927 
928 		printf(" %s[%saifsn %u cwmin %u cwmax %u txop %u]"
929 			, acnames[i]
930 			, MS(ac->acp_aci_aifsn, WME_PARAM_ACM) ? "acm " : ""
931 			, MS(ac->acp_aci_aifsn, WME_PARAM_AIFSN)
932 			, MS(ac->acp_logcwminmax, WME_PARAM_LOGCWMIN)
933 			, MS(ac->acp_logcwminmax, WME_PARAM_LOGCWMAX)
934 			, LE_READ_2(&ac->acp_txop)
935 		);
936 	}
937 	printf(">");
938 #undef MS
939 }
940 
941 static void
942 printwmeinfo(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
943 {
944 	printf("%s", tag);
945 	if (vflag) {
946 		const struct ieee80211_wme_info *wme =
947 		    (const struct ieee80211_wme_info *) ie;
948 		printf("<version 0x%x info 0x%x>",
949 		    wme->wme_version, wme->wme_info);
950 	}
951 }
952 
953 static const char *
954 wpa_cipher(const u_int8_t *sel)
955 {
956 #define	WPA_SEL(x)	(((x)<<24)|WPA_OUI)
957 	u_int32_t w = LE_READ_4(sel);
958 
959 	switch (w) {
960 	case WPA_SEL(WPA_CSE_NULL):
961 		return "NONE";
962 	case WPA_SEL(WPA_CSE_WEP40):
963 		return "WEP40";
964 	case WPA_SEL(WPA_CSE_WEP104):
965 		return "WEP104";
966 	case WPA_SEL(WPA_CSE_TKIP):
967 		return "TKIP";
968 	case WPA_SEL(WPA_CSE_CCMP):
969 		return "AES-CCMP";
970 	}
971 	return "?";		/* NB: so 1<< is discarded */
972 #undef WPA_SEL
973 }
974 
975 static const char *
976 wpa_keymgmt(const u_int8_t *sel)
977 {
978 #define	WPA_SEL(x)	(((x)<<24)|WPA_OUI)
979 	u_int32_t w = LE_READ_4(sel);
980 
981 	switch (w) {
982 	case WPA_SEL(WPA_ASE_8021X_UNSPEC):
983 		return "8021X-UNSPEC";
984 	case WPA_SEL(WPA_ASE_8021X_PSK):
985 		return "8021X-PSK";
986 	case WPA_SEL(WPA_ASE_NONE):
987 		return "NONE";
988 	}
989 	return "?";
990 #undef WPA_SEL
991 }
992 
993 static void
994 printwpaie(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
995 {
996 	u_int8_t len = ie[1];
997 
998 	printf("%s", tag);
999 	if (vflag) {
1000 		const char *sep;
1001 		int n;
1002 
1003 		ie += 6, len -= 4;		/* NB: len is payload only */
1004 
1005 		printf("<v%u", LE_READ_2(ie));
1006 		ie += 2, len -= 2;
1007 
1008 		printf(" mc:%s", wpa_cipher(ie));
1009 		ie += 4, len -= 4;
1010 
1011 		/* unicast ciphers */
1012 		n = LE_READ_2(ie);
1013 		ie += 2, len -= 2;
1014 		sep = " uc:";
1015 		for (; n > 0; n--) {
1016 			printf("%s%s", sep, wpa_cipher(ie));
1017 			ie += 4, len -= 4;
1018 			sep = "+";
1019 		}
1020 
1021 		/* key management algorithms */
1022 		n = LE_READ_2(ie);
1023 		ie += 2, len -= 2;
1024 		sep = " km:";
1025 		for (; n > 0; n--) {
1026 			printf("%s%s", sep, wpa_keymgmt(ie));
1027 			ie += 4, len -= 4;
1028 			sep = "+";
1029 		}
1030 
1031 		if (len > 2)		/* optional capabilities */
1032 			printf(", caps 0x%x", LE_READ_2(ie));
1033 		printf(">");
1034 	}
1035 }
1036 
1037 static const char *
1038 rsn_cipher(const u_int8_t *sel)
1039 {
1040 #define	RSN_SEL(x)	(((x)<<24)|RSN_OUI)
1041 	u_int32_t w = LE_READ_4(sel);
1042 
1043 	switch (w) {
1044 	case RSN_SEL(RSN_CSE_NULL):
1045 		return "NONE";
1046 	case RSN_SEL(RSN_CSE_WEP40):
1047 		return "WEP40";
1048 	case RSN_SEL(RSN_CSE_WEP104):
1049 		return "WEP104";
1050 	case RSN_SEL(RSN_CSE_TKIP):
1051 		return "TKIP";
1052 	case RSN_SEL(RSN_CSE_CCMP):
1053 		return "AES-CCMP";
1054 	case RSN_SEL(RSN_CSE_WRAP):
1055 		return "AES-OCB";
1056 	}
1057 	return "?";
1058 #undef WPA_SEL
1059 }
1060 
1061 static const char *
1062 rsn_keymgmt(const u_int8_t *sel)
1063 {
1064 #define	RSN_SEL(x)	(((x)<<24)|RSN_OUI)
1065 	u_int32_t w = LE_READ_4(sel);
1066 
1067 	switch (w) {
1068 	case RSN_SEL(RSN_ASE_8021X_UNSPEC):
1069 		return "8021X-UNSPEC";
1070 	case RSN_SEL(RSN_ASE_8021X_PSK):
1071 		return "8021X-PSK";
1072 	case RSN_SEL(RSN_ASE_NONE):
1073 		return "NONE";
1074 	}
1075 	return "?";
1076 #undef RSN_SEL
1077 }
1078 
1079 static void
1080 printrsnie(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
1081 {
1082 	const char *sep;
1083 	int n;
1084 
1085 	printf("%s", tag);
1086 	if (!vflag)
1087 		return;
1088 
1089 	ie += 2, ielen -= 2;
1090 
1091 	printf("<v%u", LE_READ_2(ie));
1092 	ie += 2, ielen -= 2;
1093 
1094 	printf(" mc:%s", rsn_cipher(ie));
1095 	ie += 4, ielen -= 4;
1096 
1097 	/* unicast ciphers */
1098 	n = LE_READ_2(ie);
1099 	ie += 2, ielen -= 2;
1100 	sep = " uc:";
1101 	for (; n > 0; n--) {
1102 		printf("%s%s", sep, rsn_cipher(ie));
1103 		ie += 4, ielen -= 4;
1104 		sep = "+";
1105 	}
1106 
1107 	/* key management algorithms */
1108 	n = LE_READ_2(ie);
1109 	ie += 2, ielen -= 2;
1110 	sep = " km:";
1111 	for (; n > 0; n--) {
1112 		printf("%s%s", sep, rsn_keymgmt(ie));
1113 		ie += 4, ielen -= 4;
1114 		sep = "+";
1115 	}
1116 
1117 	if (ielen > 2)		/* optional capabilities */
1118 		printf(", caps 0x%x", LE_READ_2(ie));
1119 	/* XXXPMKID */
1120 	printf(">");
1121 }
1122 
1123 /*
1124  * Copy the ssid string contents into buf, truncating to fit.  If the
1125  * ssid is entirely printable then just copy intact.  Otherwise convert
1126  * to hexadecimal.  If the result is truncated then replace the last
1127  * three characters with "...".
1128  */
1129 static int
1130 copy_essid(char buf[], size_t bufsize, const u_int8_t *essid, size_t essid_len)
1131 {
1132 	const u_int8_t *p;
1133 	size_t maxlen, i;
1134 
1135 	if (essid_len > bufsize)
1136 		maxlen = bufsize;
1137 	else
1138 		maxlen = essid_len;
1139 	/* determine printable or not */
1140 	for (i = 0, p = essid; i < maxlen; i++, p++) {
1141 		if (*p < ' ' || *p > 0x7e)
1142 			break;
1143 	}
1144 	if (i != maxlen) {		/* not printable, print as hex */
1145 		if (bufsize < 3)
1146 			return 0;
1147 		strlcpy(buf, "0x", bufsize);
1148 		bufsize -= 2;
1149 		p = essid;
1150 		for (i = 0; i < maxlen && bufsize >= 2; i++) {
1151 			sprintf(&buf[2+2*i], "%02x", p[i]);
1152 			bufsize -= 2;
1153 		}
1154 		if (i != essid_len)
1155 			memcpy(&buf[2+2*i-3], "...", 3);
1156 	} else {			/* printable, truncate as needed */
1157 		memcpy(buf, essid, maxlen);
1158 		if (maxlen != essid_len)
1159 			memcpy(&buf[maxlen-3], "...", 3);
1160 	}
1161 	return maxlen;
1162 }
1163 
1164 static void
1165 printssid(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
1166 {
1167 	char ssid[2*IEEE80211_NWID_LEN+1];
1168 
1169 	printf("%s<%.*s>", tag, copy_essid(ssid, maxlen, ie+2, ie[1]), ssid);
1170 }
1171 
1172 static void
1173 printrates(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
1174 {
1175 	const char *sep;
1176 	size_t i;
1177 
1178 	printf("%s", tag);
1179 	sep = "<";
1180 	for (i = 2; i < ielen; i++) {
1181 		printf("%s%s%d", sep,
1182 		    ie[i] & IEEE80211_RATE_BASIC ? "B" : "",
1183 		    ie[i] & IEEE80211_RATE_VAL);
1184 		sep = ",";
1185 	}
1186 	printf(">");
1187 }
1188 
1189 static void
1190 printcountry(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
1191 {
1192 	const struct ieee80211_country_ie *cie =
1193 	   (const struct ieee80211_country_ie *) ie;
1194 	int i, nbands, schan, nchan;
1195 
1196 	printf("%s<%c%c%c", tag, cie->cc[0], cie->cc[1], cie->cc[2]);
1197 	nbands = (cie->len - 3) / sizeof(cie->band[0]);
1198 	for (i = 0; i < nbands; i++) {
1199 		schan = cie->band[i].schan;
1200 		nchan = cie->band[i].nchan;
1201 		if (nchan != 1)
1202 			printf(" %u-%u,%u", schan, schan + nchan-1,
1203 			    cie->band[i].maxtxpwr);
1204 		else
1205 			printf(" %u,%u", schan, cie->band[i].maxtxpwr);
1206 	}
1207 	printf(">");
1208 }
1209 
1210 /* unaligned little endian access */
1211 #define LE_READ_4(p)					\
1212 	((u_int32_t)					\
1213 	 ((((const u_int8_t *)(p))[0]      ) |		\
1214 	  (((const u_int8_t *)(p))[1] <<  8) |		\
1215 	  (((const u_int8_t *)(p))[2] << 16) |		\
1216 	  (((const u_int8_t *)(p))[3] << 24)))
1217 
1218 static int
1219 iswpaoui(const u_int8_t *frm)
1220 {
1221 	return frm[1] > 3 && LE_READ_4(frm+2) == ((WPA_OUI_TYPE<<24)|WPA_OUI);
1222 }
1223 
1224 static int
1225 iswmeinfo(const u_int8_t *frm)
1226 {
1227 	return frm[1] > 5 && LE_READ_4(frm+2) == ((WME_OUI_TYPE<<24)|WME_OUI) &&
1228 		frm[6] == WME_INFO_OUI_SUBTYPE;
1229 }
1230 
1231 static int
1232 iswmeparam(const u_int8_t *frm)
1233 {
1234 	return frm[1] > 5 && LE_READ_4(frm+2) == ((WME_OUI_TYPE<<24)|WME_OUI) &&
1235 		frm[6] == WME_PARAM_OUI_SUBTYPE;
1236 }
1237 
1238 static const char *
1239 iename(int elemid)
1240 {
1241 	switch (elemid) {
1242 	case IEEE80211_ELEMID_FHPARMS:	return " FHPARMS";
1243 	case IEEE80211_ELEMID_CFPARMS:	return " CFPARMS";
1244 	case IEEE80211_ELEMID_TIM:	return " TIM";
1245 	case IEEE80211_ELEMID_IBSSPARMS:return " IBSSPARMS";
1246 	case IEEE80211_ELEMID_CHALLENGE:return " CHALLENGE";
1247 	case IEEE80211_ELEMID_PWRCNSTR:	return " PWRCNSTR";
1248 	case IEEE80211_ELEMID_PWRCAP:	return " PWRCAP";
1249 	case IEEE80211_ELEMID_TPCREQ:	return " TPCREQ";
1250 	case IEEE80211_ELEMID_TPCREP:	return " TPCREP";
1251 	case IEEE80211_ELEMID_SUPPCHAN:	return " SUPPCHAN";
1252 	case IEEE80211_ELEMID_CHANSWITCHANN:return " CSA";
1253 	case IEEE80211_ELEMID_MEASREQ:	return " MEASREQ";
1254 	case IEEE80211_ELEMID_MEASREP:	return " MEASREP";
1255 	case IEEE80211_ELEMID_QUIET:	return " QUIET";
1256 	case IEEE80211_ELEMID_IBSSDFS:	return " IBSSDFS";
1257 	case IEEE80211_ELEMID_TPC:	return " TPC";
1258 	case IEEE80211_ELEMID_CCKM:	return " CCKM";
1259 	}
1260 	return " ???";
1261 }
1262 
1263 static void
1264 printies(const u_int8_t *vp, int ielen, int maxcols)
1265 {
1266 	while (ielen > 0) {
1267 		switch (vp[0]) {
1268 		case IEEE80211_ELEMID_SSID:
1269 			if (vflag)
1270 				printssid(" SSID", vp, 2+vp[1], maxcols);
1271 			break;
1272 		case IEEE80211_ELEMID_RATES:
1273 		case IEEE80211_ELEMID_XRATES:
1274 			if (vflag)
1275 				printrates(vp[0] == IEEE80211_ELEMID_RATES ?
1276 				    " RATES" : " XRATES", vp, 2+vp[1], maxcols);
1277 			break;
1278 		case IEEE80211_ELEMID_DSPARMS:
1279 			if (vflag)
1280 				printf(" DSPARMS<%u>", vp[2]);
1281 			break;
1282 		case IEEE80211_ELEMID_COUNTRY:
1283 			if (vflag)
1284 				printcountry(" COUNTRY", vp, 2+vp[1], maxcols);
1285 			break;
1286 		case IEEE80211_ELEMID_ERP:
1287 			if (vflag)
1288 				printf(" ERP<0x%x>", vp[2]);
1289 			break;
1290 		case IEEE80211_ELEMID_VENDOR:
1291 			if (iswpaoui(vp))
1292 				printwpaie(" WPA", vp, 2+vp[1], maxcols);
1293 			else if (iswmeinfo(vp))
1294 				printwmeinfo(" WME", vp, 2+vp[1], maxcols);
1295 			else if (iswmeparam(vp))
1296 				printwmeparam(" WME", vp, 2+vp[1], maxcols);
1297 			else if (vflag)
1298 				printie(" VEN", vp, 2+vp[1], maxcols);
1299 			break;
1300 		case IEEE80211_ELEMID_RSN:
1301 			printrsnie(" RSN", vp, 2+vp[1], maxcols);
1302 			break;
1303 		default:
1304 			if (vflag)
1305 				printie(iename(vp[0]), vp, 2+vp[1], maxcols);
1306 			break;
1307 		}
1308 		ielen -= 2+vp[1];
1309 		vp += 2+vp[1];
1310 	}
1311 }
1312 
1313 static int
1314 mapgsm(u_int isrfreq, u_int isrflags)
1315 {
1316 	isrfreq *= 10;
1317 	if (isrflags & IEEE80211_CHAN_QUARTER)
1318 		isrfreq += 5;
1319 	else if (isrflags & IEEE80211_CHAN_HALF)
1320 		isrfreq += 10;
1321 	else
1322 		isrfreq += 20;
1323 	/* NB: there is no 907/20 wide but leave room */
1324 	return (isrfreq - 906*10) / 5;
1325 }
1326 
1327 static int
1328 mappsb(u_int isrfreq, u_int isrflags)
1329 {
1330 	return 37 + ((isrfreq * 10) + ((isrfreq % 5) == 2 ? 5 : 0) - 49400) / 5;
1331 }
1332 
1333 static status_func_t status;
1334 static usage_func_t usage;
1335 static statistics_func_t statistics;
1336 static cmdloop_branch_t branch[2];
1337 
1338 static void
1339 ieee80211_usage(prop_dictionary_t env)
1340 {
1341 	fprintf(stderr,
1342 	    "\t[ nwid network_id ] [ nwkey network_key | -nwkey ]\n"
1343 	    "\t[ list scan ]\n"
1344 	    "\t[ powersave | -powersave ] [ powersavesleep duration ]\n"
1345 	    "\t[ hidessid | -hidessid ] [ apbridge | -apbridge ]\n");
1346 }
1347 
1348 static void
1349 ieee80211_constructor(void)
1350 {
1351 	cmdloop_branch_init(&branch[0], &ieee80211bool.pk_parser);
1352 	cmdloop_branch_init(&branch[1], &kw80211.pk_parser);
1353 	register_cmdloop_branch(&branch[0]);
1354 	register_cmdloop_branch(&branch[1]);
1355 	status_func_init(&status, ieee80211_status);
1356 	statistics_func_init(&statistics, ieee80211_statistics);
1357 	usage_func_init(&usage, ieee80211_usage);
1358 	register_status(&status);
1359 	register_statistics(&statistics);
1360 	register_usage(&usage);
1361 }
1362