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