xref: /netbsd-src/sbin/ifconfig/ieee80211.c (revision b7b7574d3bf8eeb51a1fa3977b59142ec6434a55)
1 /*	$NetBSD: ieee80211.c,v 1.27 2014/01/08 01:56:20 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.27 2014/01/08 01:56:20 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 	struct ieee80211_stats stats;
486 	struct ifreq ifr;
487 
488 	memset(&ifr, 0, sizeof(ifr));
489 	ifr.ifr_buflen = sizeof(stats);
490 	ifr.ifr_buf = (caddr_t)&stats;
491 	if (direct_ioctl(env, (zflag) ? SIOCG80211ZSTATS : SIOCG80211STATS,
492 	    &ifr) == -1)
493 		return;
494 #define	STAT_PRINT(_member, _desc)	\
495 	printf("\t" _desc ": %" PRIu32 "\n", stats._member)
496 
497 	STAT_PRINT(is_rx_badversion, "rx frame with bad version");
498 	STAT_PRINT(is_rx_tooshort, "rx frame too short");
499 	STAT_PRINT(is_rx_wrongbss, "rx from wrong bssid");
500 	STAT_PRINT(is_rx_dup, "rx discard 'cuz dup");
501 	STAT_PRINT(is_rx_wrongdir, "rx w/ wrong direction");
502 	STAT_PRINT(is_rx_mcastecho, "rx discard 'cuz mcast echo");
503 	STAT_PRINT(is_rx_notassoc, "rx discard 'cuz sta !assoc");
504 	STAT_PRINT(is_rx_noprivacy, "rx w/ wep but privacy off");
505 	STAT_PRINT(is_rx_unencrypted, "rx w/o wep and privacy on");
506 	STAT_PRINT(is_rx_wepfail, "rx wep processing failed");
507 	STAT_PRINT(is_rx_decap, "rx decapsulation failed");
508 	STAT_PRINT(is_rx_mgtdiscard, "rx discard mgt frames");
509 	STAT_PRINT(is_rx_ctl, "rx discard ctrl frames");
510 	STAT_PRINT(is_rx_beacon, "rx beacon frames");
511 	STAT_PRINT(is_rx_rstoobig, "rx rate set truncated");
512 	STAT_PRINT(is_rx_elem_missing, "rx required element missing");
513 	STAT_PRINT(is_rx_elem_toobig, "rx element too big");
514 	STAT_PRINT(is_rx_elem_toosmall, "rx element too small");
515 	STAT_PRINT(is_rx_elem_unknown, "rx element unknown");
516 	STAT_PRINT(is_rx_badchan, "rx frame w/ invalid chan");
517 	STAT_PRINT(is_rx_chanmismatch, "rx frame chan mismatch");
518 	STAT_PRINT(is_rx_nodealloc, "rx frame dropped");
519 	STAT_PRINT(is_rx_ssidmismatch, "rx frame ssid mismatch ");
520 	STAT_PRINT(is_rx_auth_unsupported, "rx w/ unsupported auth alg");
521 	STAT_PRINT(is_rx_auth_fail, "rx sta auth failure");
522 	STAT_PRINT(is_rx_auth_countermeasures, "rx auth discard 'cuz CM");
523 	STAT_PRINT(is_rx_assoc_bss, "rx assoc from wrong bssid");
524 	STAT_PRINT(is_rx_assoc_notauth, "rx assoc w/o auth");
525 	STAT_PRINT(is_rx_assoc_capmismatch, "rx assoc w/ cap mismatch");
526 	STAT_PRINT(is_rx_assoc_norate, "rx assoc w/ no rate match");
527 	STAT_PRINT(is_rx_assoc_badwpaie, "rx assoc w/ bad WPA IE");
528 	STAT_PRINT(is_rx_deauth, "rx deauthentication");
529 	STAT_PRINT(is_rx_disassoc, "rx disassociation");
530 	STAT_PRINT(is_rx_badsubtype, "rx frame w/ unknown subtyp");
531 	STAT_PRINT(is_rx_nobuf, "rx failed for lack of buf");
532 	STAT_PRINT(is_rx_decryptcrc, "rx decrypt failed on crc");
533 	STAT_PRINT(is_rx_ahdemo_mgt, "rx discard ahdemo mgt fram");
534 	STAT_PRINT(is_rx_bad_auth, "rx bad auth request");
535 	STAT_PRINT(is_rx_unauth, "rx on unauthorized port");
536 	STAT_PRINT(is_rx_badkeyid, "rx w/ incorrect keyid");
537 	STAT_PRINT(is_rx_ccmpreplay, "rx seq# violation (CCMP)");
538 	STAT_PRINT(is_rx_ccmpformat, "rx format bad (CCMP)");
539 	STAT_PRINT(is_rx_ccmpmic, "rx MIC check failed (CCMP)");
540 	STAT_PRINT(is_rx_tkipreplay, "rx seq# violation (TKIP)");
541 	STAT_PRINT(is_rx_tkipformat, "rx format bad (TKIP)");
542 	STAT_PRINT(is_rx_tkipmic, "rx MIC check failed (TKIP)");
543 	STAT_PRINT(is_rx_tkipicv, "rx ICV check failed (TKIP)");
544 	STAT_PRINT(is_rx_badcipher, "rx failed 'cuz key type");
545 	STAT_PRINT(is_rx_nocipherctx, "rx failed 'cuz key !setup");
546 	STAT_PRINT(is_rx_acl, "rx discard 'cuz acl policy");
547 
548 	STAT_PRINT(is_tx_nobuf, "tx failed for lack of buf");
549 	STAT_PRINT(is_tx_nonode, "tx failed for no node");
550 	STAT_PRINT(is_tx_unknownmgt, "tx of unknown mgt frame");
551 	STAT_PRINT(is_tx_badcipher, "tx failed 'cuz key type");
552 	STAT_PRINT(is_tx_nodefkey, "tx failed 'cuz no defkey");
553 	STAT_PRINT(is_tx_noheadroom, "tx failed 'cuz no space");
554 	STAT_PRINT(is_tx_fragframes, "tx frames fragmented");
555 	STAT_PRINT(is_tx_frags, "tx fragments created");
556 
557 	STAT_PRINT(is_scan_active, "active scans started");
558 	STAT_PRINT(is_scan_passive, "passive scans started");
559 	STAT_PRINT(is_node_timeout, "nodes timed out inactivity");
560 	STAT_PRINT(is_crypto_nomem, "no memory for crypto ctx");
561 	STAT_PRINT(is_crypto_tkip, "tkip crypto done in s/w");
562 	STAT_PRINT(is_crypto_tkipenmic, "tkip en-MIC done in s/w");
563 	STAT_PRINT(is_crypto_tkipdemic, "tkip de-MIC done in s/w");
564 	STAT_PRINT(is_crypto_tkipcm, "tkip counter measures");
565 	STAT_PRINT(is_crypto_ccmp, "ccmp crypto done in s/w");
566 	STAT_PRINT(is_crypto_wep, "wep crypto done in s/w");
567 	STAT_PRINT(is_crypto_setkey_cipher, "cipher rejected key");
568 	STAT_PRINT(is_crypto_setkey_nokey, "no key index for setkey");
569 	STAT_PRINT(is_crypto_delkey, "driver key delete failed");
570 	STAT_PRINT(is_crypto_badcipher, "unknown cipher");
571 	STAT_PRINT(is_crypto_nocipher, "cipher not available");
572 	STAT_PRINT(is_crypto_attachfail, "cipher attach failed");
573 	STAT_PRINT(is_crypto_swfallback, "cipher fallback to s/w");
574 	STAT_PRINT(is_crypto_keyfail, "driver key alloc failed");
575 	STAT_PRINT(is_crypto_enmicfail, "en-MIC failed");
576 	STAT_PRINT(is_ibss_capmismatch, "merge failed-cap mismatch");
577 	STAT_PRINT(is_ibss_norate, "merge failed-rate mismatch");
578 	STAT_PRINT(is_ps_unassoc, "ps-poll for unassoc. sta");
579 	STAT_PRINT(is_ps_badaid, "ps-poll w/ incorrect aid");
580 	STAT_PRINT(is_ps_qempty, "ps-poll w/ nothing to send");
581 	STAT_PRINT(is_ff_badhdr, "fast frame rx'd w/ bad hdr");
582 	STAT_PRINT(is_ff_tooshort, "fast frame rx decap error");
583 	STAT_PRINT(is_ff_split, "fast frame rx split error");
584 	STAT_PRINT(is_ff_decap, "fast frames decap'd");
585 	STAT_PRINT(is_ff_encap, "fast frames encap'd for tx");
586 	STAT_PRINT(is_rx_badbintval, "rx frame w/ bogus bintval");
587 }
588 
589 static void
590 ieee80211_status(prop_dictionary_t env, prop_dictionary_t oenv)
591 {
592 	int i, nwkey_verbose;
593 	struct ieee80211_nwid nwid;
594 	struct ieee80211_nwkey nwkey;
595 	struct ieee80211_power power;
596 	u_int8_t keybuf[IEEE80211_WEP_NKID][16];
597 	struct ieee80211_bssid bssid;
598 	struct ieee80211chanreq channel;
599 	struct ieee80211req ireq;
600 	struct ether_addr ea;
601 	static const u_int8_t zero_macaddr[IEEE80211_ADDR_LEN];
602 	enum ieee80211_opmode opmode = get80211opmode(env);
603 
604 	memset(&bssid, 0, sizeof(bssid));
605 	memset(&nwkey, 0, sizeof(nwkey));
606 	memset(&nwid, 0, sizeof(nwid));
607 	memset(&nwid, 0, sizeof(nwid));
608 
609 	if (indirect_ioctl(env, SIOCG80211NWID, &nwid) == -1)
610 		return;
611 	if (nwid.i_len > IEEE80211_NWID_LEN) {
612 		errx(EXIT_FAILURE, "SIOCG80211NWID: wrong length of nwid (%d)", nwid.i_len);
613 	}
614 	printf("\tssid ");
615 	print_string(nwid.i_nwid, nwid.i_len);
616 
617 	if (opmode == IEEE80211_M_HOSTAP) {
618 		ireq.i_type = IEEE80211_IOC_HIDESSID;
619 		if (direct_ioctl(env, SIOCG80211, &ireq) != -1) {
620                         if (ireq.i_val)
621                                 printf(" [hidden]");
622                         else if (vflag)
623                                 printf(" [shown]");
624                 }
625 
626 		ireq.i_type = IEEE80211_IOC_APBRIDGE;
627 		if (direct_ioctl(env, SIOCG80211, &ireq) != -1) {
628 			if (ireq.i_val)
629 				printf(" apbridge");
630 			else if (vflag)
631 				printf(" -apbridge");
632 		}
633         }
634 
635 	ireq.i_type = IEEE80211_IOC_RTSTHRESHOLD;
636 	if (direct_ioctl(env, SIOCG80211, &ireq) == -1)
637 		;
638 	else if (ireq.i_val < IEEE80211_RTS_MAX)
639 		printf(" rts %d", ireq.i_val);
640 	else if (vflag)
641 		printf(" -rts");
642 
643 	ireq.i_type = IEEE80211_IOC_FRAGTHRESHOLD;
644 	if (direct_ioctl(env, SIOCG80211, &ireq) == -1)
645 		;
646 	else if (ireq.i_val < IEEE80211_FRAG_MAX)
647 		printf(" frag %d", ireq.i_val);
648 	else if (vflag)
649 		printf(" -frag");
650 
651 	memset(&nwkey, 0, sizeof(nwkey));
652 	/* show nwkey only when WEP is enabled */
653 	if (direct_ioctl(env, SIOCG80211NWKEY, &nwkey) == -1 ||
654 	    nwkey.i_wepon == 0) {
655 		printf("\n");
656 		goto skip_wep;
657 	}
658 
659 	printf(" nwkey ");
660 	/* try to retrieve WEP keys */
661 	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
662 		nwkey.i_key[i].i_keydat = keybuf[i];
663 		nwkey.i_key[i].i_keylen = sizeof(keybuf[i]);
664 	}
665 	if (direct_ioctl(env, SIOCG80211NWKEY, &nwkey) == -1) {
666 		printf("*****");
667 	} else {
668 		nwkey_verbose = 0;
669 		/* check to see non default key or multiple keys defined */
670 		if (nwkey.i_defkid != 1) {
671 			nwkey_verbose = 1;
672 		} else {
673 			for (i = 1; i < IEEE80211_WEP_NKID; i++) {
674 				if (nwkey.i_key[i].i_keylen != 0) {
675 					nwkey_verbose = 1;
676 					break;
677 				}
678 			}
679 		}
680 		/* check extra ambiguity with keywords */
681 		if (!nwkey_verbose) {
682 			if (nwkey.i_key[0].i_keylen >= 2 &&
683 			    isdigit(nwkey.i_key[0].i_keydat[0]) &&
684 			    nwkey.i_key[0].i_keydat[1] == ':')
685 				nwkey_verbose = 1;
686 			else if (nwkey.i_key[0].i_keylen >= 7 &&
687 			    strncasecmp("persist",
688 			    (const char *)nwkey.i_key[0].i_keydat, 7) == 0)
689 				nwkey_verbose = 1;
690 		}
691 		if (nwkey_verbose)
692 			printf("%d:", nwkey.i_defkid);
693 		for (i = 0; i < IEEE80211_WEP_NKID; i++) {
694 			if (i > 0)
695 				printf(",");
696 			if (nwkey.i_key[i].i_keylen < 0)
697 				printf("persist");
698 			else
699 				print_string(nwkey.i_key[i].i_keydat,
700 				    nwkey.i_key[i].i_keylen);
701 			if (!nwkey_verbose)
702 				break;
703 		}
704 	}
705 	printf("\n");
706 
707  skip_wep:
708 	if (direct_ioctl(env, SIOCG80211POWER, &power) == -1)
709 		goto skip_power;
710 	printf("\tpowersave ");
711 	if (power.i_enabled)
712 		printf("on (%dms sleep)", power.i_maxsleep);
713 	else
714 		printf("off");
715 	printf("\n");
716 
717  skip_power:
718 	if (direct_ioctl(env, SIOCG80211BSSID, &bssid) == -1)
719 		return;
720 	if (direct_ioctl(env, SIOCG80211CHANNEL, &channel) == -1)
721 		return;
722 	if (memcmp(bssid.i_bssid, zero_macaddr, IEEE80211_ADDR_LEN) == 0) {
723 		if (channel.i_channel != (u_int16_t)-1)
724 			printf("\tchan %d\n", channel.i_channel);
725 	} else {
726 		memcpy(ea.ether_addr_octet, bssid.i_bssid,
727 		    sizeof(ea.ether_addr_octet));
728 		printf("\tbssid %s", ether_ntoa(&ea));
729 		if (channel.i_channel != IEEE80211_CHAN_ANY)
730 			printf(" chan %d", channel.i_channel);
731 		printf("\n");
732 	}
733 }
734 
735 static void
736 scan_and_wait(prop_dictionary_t env)
737 {
738 	int sroute;
739 
740 	sroute = prog_socket(PF_ROUTE, SOCK_RAW, 0);
741 	if (sroute < 0) {
742 		warn("socket(PF_ROUTE,SOCK_RAW)");
743 		return;
744 	}
745 	/* NB: only root can trigger a scan so ignore errors */
746 	if (set80211(env, IEEE80211_IOC_SCAN_REQ, 0, 0, NULL) >= 0) {
747 		char buf[2048];
748 		struct if_announcemsghdr *ifan;
749 		struct rt_msghdr *rtm;
750 
751 		do {
752 			if (prog_read(sroute, buf, sizeof(buf)) < 0) {
753 				warn("read(PF_ROUTE)");
754 				break;
755 			}
756 			rtm = (struct rt_msghdr *) buf;
757 			if (rtm->rtm_version != RTM_VERSION)
758 				break;
759 			ifan = (struct if_announcemsghdr *) rtm;
760 		} while (rtm->rtm_type != RTM_IEEE80211 ||
761 		    ifan->ifan_what != RTM_IEEE80211_SCAN);
762 	}
763 	prog_close(sroute);
764 }
765 
766 static void
767 list_scan(prop_dictionary_t env)
768 {
769 	u_int8_t buf[24*1024];
770 	struct ieee80211req ireq;
771 	char ssid[IEEE80211_NWID_LEN+1];
772 	const u_int8_t *cp;
773 	int len, ssidmax;
774 
775 	memset(&ireq, 0, sizeof(ireq));
776 	ireq.i_type = IEEE80211_IOC_SCAN_RESULTS;
777 	ireq.i_data = buf;
778 	ireq.i_len = sizeof(buf);
779 	if (direct_ioctl(env, SIOCG80211, &ireq) < 0)
780 		errx(EXIT_FAILURE, "unable to get scan results");
781 	len = ireq.i_len;
782 	if (len < (int)sizeof(struct ieee80211req_scan_result))
783 		return;
784 
785 	ssidmax = IEEE80211_NWID_LEN;
786 	printf("%-*.*s  %-17.17s  %4s %4s  %-7s %3s %4s\n"
787 		, ssidmax, ssidmax, "SSID"
788 		, "BSSID"
789 		, "CHAN"
790 		, "RATE"
791 		, "S:N"
792 		, "INT"
793 		, "CAPS"
794 	);
795 	cp = buf;
796 	do {
797 		const struct ieee80211req_scan_result *sr;
798 		const uint8_t *vp;
799 
800 		sr = (const struct ieee80211req_scan_result *) cp;
801 		vp = (const u_int8_t *)(sr+1);
802 		printf("%-*.*s  %s  %3d  %3dM %3d:%-3d  %3d %-4.4s"
803 			, ssidmax
804 			  , copy_essid(ssid, ssidmax, vp, sr->isr_ssid_len)
805 			  , ssid
806 			, ether_ntoa((const struct ether_addr *) sr->isr_bssid)
807 			, ieee80211_mhz2ieee(sr->isr_freq, sr->isr_flags)
808 			, getmaxrate(sr->isr_rates, sr->isr_nrates)
809 			, sr->isr_rssi, sr->isr_noise
810 			, sr->isr_intval
811 			, getcaps(sr->isr_capinfo)
812 		);
813 		printies(vp + sr->isr_ssid_len, sr->isr_ie_len, 24);
814 		printf("\n");
815 		cp += sr->isr_len, len -= sr->isr_len;
816 	} while (len >= (int)sizeof(struct ieee80211req_scan_result));
817 }
818 /*
819  * Convert MHz frequency to IEEE channel number.
820  */
821 static u_int
822 ieee80211_mhz2ieee(u_int isrfreq, u_int isrflags)
823 {
824 	if ((isrflags & IEEE80211_CHAN_GSM) || (907 <= isrfreq && isrfreq <= 922))
825 		return mapgsm(isrfreq, isrflags);
826 	if (isrfreq == 2484)
827 		return 14;
828 	if (isrfreq < 2484)
829 		return (isrfreq - 2407) / 5;
830 	if (isrfreq < 5000) {
831 		if (isrflags & (IEEE80211_CHAN_HALF|IEEE80211_CHAN_QUARTER))
832 			return mappsb(isrfreq, isrflags);
833 		else if (isrfreq > 4900)
834 			return (isrfreq - 4000) / 5;
835 		else
836 			return 15 + ((isrfreq - 2512) / 20);
837 	}
838 	return (isrfreq - 5000) / 5;
839 }
840 
841 static int
842 getmaxrate(const u_int8_t rates[15], u_int8_t nrates)
843 {
844 	int i, maxrate = -1;
845 
846 	for (i = 0; i < nrates; i++) {
847 		int rate = rates[i] & IEEE80211_RATE_VAL;
848 		if (rate > maxrate)
849 			maxrate = rate;
850 	}
851 	return maxrate / 2;
852 }
853 
854 static const char *
855 getcaps(int capinfo)
856 {
857 	static char capstring[32];
858 	char *cp = capstring;
859 
860 	if (capinfo & IEEE80211_CAPINFO_ESS)
861 		*cp++ = 'E';
862 	if (capinfo & IEEE80211_CAPINFO_IBSS)
863 		*cp++ = 'I';
864 	if (capinfo & IEEE80211_CAPINFO_CF_POLLABLE)
865 		*cp++ = 'c';
866 	if (capinfo & IEEE80211_CAPINFO_CF_POLLREQ)
867 		*cp++ = 'C';
868 	if (capinfo & IEEE80211_CAPINFO_PRIVACY)
869 		*cp++ = 'P';
870 	if (capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE)
871 		*cp++ = 'S';
872 	if (capinfo & IEEE80211_CAPINFO_PBCC)
873 		*cp++ = 'B';
874 	if (capinfo & IEEE80211_CAPINFO_CHNL_AGILITY)
875 		*cp++ = 'A';
876 	if (capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME)
877 		*cp++ = 's';
878 	if (capinfo & IEEE80211_CAPINFO_RSN)
879 		*cp++ = 'R';
880 	if (capinfo & IEEE80211_CAPINFO_DSSSOFDM)
881 		*cp++ = 'D';
882 	*cp = '\0';
883 	return capstring;
884 }
885 
886 static void
887 printie(const char* tag, const uint8_t *ie, size_t ielen, int maxlen)
888 {
889 	printf("%s", tag);
890 
891 	maxlen -= strlen(tag)+2;
892 	if ((int)(2*ielen) > maxlen)
893 		maxlen--;
894 	printf("<");
895 	for (; ielen > 0; ie++, ielen--) {
896 		if (maxlen-- <= 0)
897 			break;
898 		printf("%02x", *ie);
899 	}
900 	if (ielen != 0)
901 		printf("-");
902 	printf(">");
903 }
904 
905 #define LE_READ_2(p)					\
906 	((u_int16_t)					\
907 	 ((((const u_int8_t *)(p))[0]      ) |		\
908 	  (((const u_int8_t *)(p))[1] <<  8)))
909 #define LE_READ_4(p)					\
910 	((u_int32_t)					\
911 	 ((((const u_int8_t *)(p))[0]      ) |		\
912 	  (((const u_int8_t *)(p))[1] <<  8) |		\
913 	  (((const u_int8_t *)(p))[2] << 16) |		\
914 	  (((const u_int8_t *)(p))[3] << 24)))
915 
916 /*
917  * NB: The decoding routines assume a properly formatted ie
918  *     which should be safe as the kernel only retains them
919  *     if they parse ok.
920  */
921 
922 static void
923 printwmeparam(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
924 {
925 #define	MS(_v, _f)	(((_v) & _f) >> _f##_S)
926 	static const char *acnames[] = { "BE", "BK", "VO", "VI" };
927 	const struct ieee80211_wme_param *wme =
928 	    (const struct ieee80211_wme_param *) ie;
929 	int i;
930 
931 	printf("%s", tag);
932 	if (!vflag)
933 		return;
934 	printf("<qosinfo 0x%x", wme->param_qosInfo);
935 	ie += offsetof(struct ieee80211_wme_param, params_acParams);
936 	for (i = 0; i < WME_NUM_AC; i++) {
937 		const struct ieee80211_wme_acparams *ac =
938 		    &wme->params_acParams[i];
939 
940 		printf(" %s[%saifsn %u cwmin %u cwmax %u txop %u]"
941 			, acnames[i]
942 			, MS(ac->acp_aci_aifsn, WME_PARAM_ACM) ? "acm " : ""
943 			, MS(ac->acp_aci_aifsn, WME_PARAM_AIFSN)
944 			, MS(ac->acp_logcwminmax, WME_PARAM_LOGCWMIN)
945 			, MS(ac->acp_logcwminmax, WME_PARAM_LOGCWMAX)
946 			, LE_READ_2(&ac->acp_txop)
947 		);
948 	}
949 	printf(">");
950 #undef MS
951 }
952 
953 static void
954 printwmeinfo(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
955 {
956 	printf("%s", tag);
957 	if (vflag) {
958 		const struct ieee80211_wme_info *wme =
959 		    (const struct ieee80211_wme_info *) ie;
960 		printf("<version 0x%x info 0x%x>",
961 		    wme->wme_version, wme->wme_info);
962 	}
963 }
964 
965 static const char *
966 wpa_cipher(const u_int8_t *sel)
967 {
968 #define	WPA_SEL(x)	(((x)<<24)|WPA_OUI)
969 	u_int32_t w = LE_READ_4(sel);
970 
971 	switch (w) {
972 	case WPA_SEL(WPA_CSE_NULL):
973 		return "NONE";
974 	case WPA_SEL(WPA_CSE_WEP40):
975 		return "WEP40";
976 	case WPA_SEL(WPA_CSE_WEP104):
977 		return "WEP104";
978 	case WPA_SEL(WPA_CSE_TKIP):
979 		return "TKIP";
980 	case WPA_SEL(WPA_CSE_CCMP):
981 		return "AES-CCMP";
982 	}
983 	return "?";		/* NB: so 1<< is discarded */
984 #undef WPA_SEL
985 }
986 
987 static const char *
988 wpa_keymgmt(const u_int8_t *sel)
989 {
990 #define	WPA_SEL(x)	(((x)<<24)|WPA_OUI)
991 	u_int32_t w = LE_READ_4(sel);
992 
993 	switch (w) {
994 	case WPA_SEL(WPA_ASE_8021X_UNSPEC):
995 		return "8021X-UNSPEC";
996 	case WPA_SEL(WPA_ASE_8021X_PSK):
997 		return "8021X-PSK";
998 	case WPA_SEL(WPA_ASE_NONE):
999 		return "NONE";
1000 	}
1001 	return "?";
1002 #undef WPA_SEL
1003 }
1004 
1005 static void
1006 printwpaie(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
1007 {
1008 	u_int8_t len = ie[1];
1009 
1010 	printf("%s", tag);
1011 	if (vflag) {
1012 		const char *sep;
1013 		int n;
1014 
1015 		ie += 6, len -= 4;		/* NB: len is payload only */
1016 
1017 		printf("<v%u", LE_READ_2(ie));
1018 		ie += 2, len -= 2;
1019 
1020 		printf(" mc:%s", wpa_cipher(ie));
1021 		ie += 4, len -= 4;
1022 
1023 		/* unicast ciphers */
1024 		n = LE_READ_2(ie);
1025 		ie += 2, len -= 2;
1026 		sep = " uc:";
1027 		for (; n > 0; n--) {
1028 			printf("%s%s", sep, wpa_cipher(ie));
1029 			ie += 4, len -= 4;
1030 			sep = "+";
1031 		}
1032 
1033 		/* key management algorithms */
1034 		n = LE_READ_2(ie);
1035 		ie += 2, len -= 2;
1036 		sep = " km:";
1037 		for (; n > 0; n--) {
1038 			printf("%s%s", sep, wpa_keymgmt(ie));
1039 			ie += 4, len -= 4;
1040 			sep = "+";
1041 		}
1042 
1043 		if (len > 2)		/* optional capabilities */
1044 			printf(", caps 0x%x", LE_READ_2(ie));
1045 		printf(">");
1046 	}
1047 }
1048 
1049 static const char *
1050 rsn_cipher(const u_int8_t *sel)
1051 {
1052 #define	RSN_SEL(x)	(((x)<<24)|RSN_OUI)
1053 	u_int32_t w = LE_READ_4(sel);
1054 
1055 	switch (w) {
1056 	case RSN_SEL(RSN_CSE_NULL):
1057 		return "NONE";
1058 	case RSN_SEL(RSN_CSE_WEP40):
1059 		return "WEP40";
1060 	case RSN_SEL(RSN_CSE_WEP104):
1061 		return "WEP104";
1062 	case RSN_SEL(RSN_CSE_TKIP):
1063 		return "TKIP";
1064 	case RSN_SEL(RSN_CSE_CCMP):
1065 		return "AES-CCMP";
1066 	case RSN_SEL(RSN_CSE_WRAP):
1067 		return "AES-OCB";
1068 	}
1069 	return "?";
1070 #undef WPA_SEL
1071 }
1072 
1073 static const char *
1074 rsn_keymgmt(const u_int8_t *sel)
1075 {
1076 #define	RSN_SEL(x)	(((x)<<24)|RSN_OUI)
1077 	u_int32_t w = LE_READ_4(sel);
1078 
1079 	switch (w) {
1080 	case RSN_SEL(RSN_ASE_8021X_UNSPEC):
1081 		return "8021X-UNSPEC";
1082 	case RSN_SEL(RSN_ASE_8021X_PSK):
1083 		return "8021X-PSK";
1084 	case RSN_SEL(RSN_ASE_NONE):
1085 		return "NONE";
1086 	}
1087 	return "?";
1088 #undef RSN_SEL
1089 }
1090 
1091 static void
1092 printrsnie(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
1093 {
1094 	const char *sep;
1095 	int n;
1096 
1097 	printf("%s", tag);
1098 	if (!vflag)
1099 		return;
1100 
1101 	ie += 2, ielen -= 2;
1102 
1103 	printf("<v%u", LE_READ_2(ie));
1104 	ie += 2, ielen -= 2;
1105 
1106 	printf(" mc:%s", rsn_cipher(ie));
1107 	ie += 4, ielen -= 4;
1108 
1109 	/* unicast ciphers */
1110 	n = LE_READ_2(ie);
1111 	ie += 2, ielen -= 2;
1112 	sep = " uc:";
1113 	for (; n > 0; n--) {
1114 		printf("%s%s", sep, rsn_cipher(ie));
1115 		ie += 4, ielen -= 4;
1116 		sep = "+";
1117 	}
1118 
1119 	/* key management algorithms */
1120 	n = LE_READ_2(ie);
1121 	ie += 2, ielen -= 2;
1122 	sep = " km:";
1123 	for (; n > 0; n--) {
1124 		printf("%s%s", sep, rsn_keymgmt(ie));
1125 		ie += 4, ielen -= 4;
1126 		sep = "+";
1127 	}
1128 
1129 	if (ielen > 2)		/* optional capabilities */
1130 		printf(", caps 0x%x", LE_READ_2(ie));
1131 	/* XXXPMKID */
1132 	printf(">");
1133 }
1134 
1135 /*
1136  * Copy the ssid string contents into buf, truncating to fit.  If the
1137  * ssid is entirely printable then just copy intact.  Otherwise convert
1138  * to hexadecimal.  If the result is truncated then replace the last
1139  * three characters with "...".
1140  */
1141 static int
1142 copy_essid(char buf[], size_t bufsize, const u_int8_t *essid, size_t essid_len)
1143 {
1144 	const u_int8_t *p;
1145 	size_t maxlen, i;
1146 
1147 	if (essid_len > bufsize)
1148 		maxlen = bufsize;
1149 	else
1150 		maxlen = essid_len;
1151 	/* determine printable or not */
1152 	for (i = 0, p = essid; i < maxlen; i++, p++) {
1153 		if (*p < ' ' || *p > 0x7e)
1154 			break;
1155 	}
1156 	if (i != maxlen) {		/* not printable, print as hex */
1157 		if (bufsize < 3)
1158 			return 0;
1159 		strlcpy(buf, "0x", bufsize);
1160 		bufsize -= 2;
1161 		p = essid;
1162 		for (i = 0; i < maxlen && bufsize >= 2; i++) {
1163 			sprintf(&buf[2+2*i], "%02x", p[i]);
1164 			bufsize -= 2;
1165 		}
1166 		if (i != essid_len)
1167 			memcpy(&buf[2+2*i-3], "...", 3);
1168 	} else {			/* printable, truncate as needed */
1169 		memcpy(buf, essid, maxlen);
1170 		if (maxlen != essid_len)
1171 			memcpy(&buf[maxlen-3], "...", 3);
1172 	}
1173 	return maxlen;
1174 }
1175 
1176 static void
1177 printssid(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
1178 {
1179 	char ssid[2*IEEE80211_NWID_LEN+1];
1180 
1181 	printf("%s<%.*s>", tag, copy_essid(ssid, maxlen, ie+2, ie[1]), ssid);
1182 }
1183 
1184 static void
1185 printrates(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
1186 {
1187 	const char *sep;
1188 	size_t i;
1189 
1190 	printf("%s", tag);
1191 	sep = "<";
1192 	for (i = 2; i < ielen; i++) {
1193 		printf("%s%s%d", sep,
1194 		    ie[i] & IEEE80211_RATE_BASIC ? "B" : "",
1195 		    ie[i] & IEEE80211_RATE_VAL);
1196 		sep = ",";
1197 	}
1198 	printf(">");
1199 }
1200 
1201 static void
1202 printcountry(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
1203 {
1204 	const struct ieee80211_country_ie *cie =
1205 	   (const struct ieee80211_country_ie *) ie;
1206 	int i, nbands, schan, nchan;
1207 
1208 	printf("%s<%c%c%c", tag, cie->cc[0], cie->cc[1], cie->cc[2]);
1209 	nbands = (cie->len - 3) / sizeof(cie->band[0]);
1210 	for (i = 0; i < nbands; i++) {
1211 		schan = cie->band[i].schan;
1212 		nchan = cie->band[i].nchan;
1213 		if (nchan != 1)
1214 			printf(" %u-%u,%u", schan, schan + nchan-1,
1215 			    cie->band[i].maxtxpwr);
1216 		else
1217 			printf(" %u,%u", schan, cie->band[i].maxtxpwr);
1218 	}
1219 	printf(">");
1220 }
1221 
1222 /* unaligned little endian access */
1223 #define LE_READ_4(p)					\
1224 	((u_int32_t)					\
1225 	 ((((const u_int8_t *)(p))[0]      ) |		\
1226 	  (((const u_int8_t *)(p))[1] <<  8) |		\
1227 	  (((const u_int8_t *)(p))[2] << 16) |		\
1228 	  (((const u_int8_t *)(p))[3] << 24)))
1229 
1230 static int
1231 iswpaoui(const u_int8_t *frm)
1232 {
1233 	return frm[1] > 3 && LE_READ_4(frm+2) == ((WPA_OUI_TYPE<<24)|WPA_OUI);
1234 }
1235 
1236 static int
1237 iswmeinfo(const u_int8_t *frm)
1238 {
1239 	return frm[1] > 5 && LE_READ_4(frm+2) == ((WME_OUI_TYPE<<24)|WME_OUI) &&
1240 		frm[6] == WME_INFO_OUI_SUBTYPE;
1241 }
1242 
1243 static int
1244 iswmeparam(const u_int8_t *frm)
1245 {
1246 	return frm[1] > 5 && LE_READ_4(frm+2) == ((WME_OUI_TYPE<<24)|WME_OUI) &&
1247 		frm[6] == WME_PARAM_OUI_SUBTYPE;
1248 }
1249 
1250 static const char *
1251 iename(int elemid)
1252 {
1253 	switch (elemid) {
1254 	case IEEE80211_ELEMID_FHPARMS:	return " FHPARMS";
1255 	case IEEE80211_ELEMID_CFPARMS:	return " CFPARMS";
1256 	case IEEE80211_ELEMID_TIM:	return " TIM";
1257 	case IEEE80211_ELEMID_IBSSPARMS:return " IBSSPARMS";
1258 	case IEEE80211_ELEMID_CHALLENGE:return " CHALLENGE";
1259 	case IEEE80211_ELEMID_PWRCNSTR:	return " PWRCNSTR";
1260 	case IEEE80211_ELEMID_PWRCAP:	return " PWRCAP";
1261 	case IEEE80211_ELEMID_TPCREQ:	return " TPCREQ";
1262 	case IEEE80211_ELEMID_TPCREP:	return " TPCREP";
1263 	case IEEE80211_ELEMID_SUPPCHAN:	return " SUPPCHAN";
1264 	case IEEE80211_ELEMID_CHANSWITCHANN:return " CSA";
1265 	case IEEE80211_ELEMID_MEASREQ:	return " MEASREQ";
1266 	case IEEE80211_ELEMID_MEASREP:	return " MEASREP";
1267 	case IEEE80211_ELEMID_QUIET:	return " QUIET";
1268 	case IEEE80211_ELEMID_IBSSDFS:	return " IBSSDFS";
1269 	case IEEE80211_ELEMID_TPC:	return " TPC";
1270 	case IEEE80211_ELEMID_CCKM:	return " CCKM";
1271 	}
1272 	return " ???";
1273 }
1274 
1275 static void
1276 printies(const u_int8_t *vp, int ielen, int maxcols)
1277 {
1278 	while (ielen > 0) {
1279 		switch (vp[0]) {
1280 		case IEEE80211_ELEMID_SSID:
1281 			if (vflag)
1282 				printssid(" SSID", vp, 2+vp[1], maxcols);
1283 			break;
1284 		case IEEE80211_ELEMID_RATES:
1285 		case IEEE80211_ELEMID_XRATES:
1286 			if (vflag)
1287 				printrates(vp[0] == IEEE80211_ELEMID_RATES ?
1288 				    " RATES" : " XRATES", vp, 2+vp[1], maxcols);
1289 			break;
1290 		case IEEE80211_ELEMID_DSPARMS:
1291 			if (vflag)
1292 				printf(" DSPARMS<%u>", vp[2]);
1293 			break;
1294 		case IEEE80211_ELEMID_COUNTRY:
1295 			if (vflag)
1296 				printcountry(" COUNTRY", vp, 2+vp[1], maxcols);
1297 			break;
1298 		case IEEE80211_ELEMID_ERP:
1299 			if (vflag)
1300 				printf(" ERP<0x%x>", vp[2]);
1301 			break;
1302 		case IEEE80211_ELEMID_VENDOR:
1303 			if (iswpaoui(vp))
1304 				printwpaie(" WPA", vp, 2+vp[1], maxcols);
1305 			else if (iswmeinfo(vp))
1306 				printwmeinfo(" WME", vp, 2+vp[1], maxcols);
1307 			else if (iswmeparam(vp))
1308 				printwmeparam(" WME", vp, 2+vp[1], maxcols);
1309 			else if (vflag)
1310 				printie(" VEN", vp, 2+vp[1], maxcols);
1311 			break;
1312 		case IEEE80211_ELEMID_RSN:
1313 			printrsnie(" RSN", vp, 2+vp[1], maxcols);
1314 			break;
1315 		default:
1316 			if (vflag)
1317 				printie(iename(vp[0]), vp, 2+vp[1], maxcols);
1318 			break;
1319 		}
1320 		ielen -= 2+vp[1];
1321 		vp += 2+vp[1];
1322 	}
1323 }
1324 
1325 static int
1326 mapgsm(u_int isrfreq, u_int isrflags)
1327 {
1328 	isrfreq *= 10;
1329 	if (isrflags & IEEE80211_CHAN_QUARTER)
1330 		isrfreq += 5;
1331 	else if (isrflags & IEEE80211_CHAN_HALF)
1332 		isrfreq += 10;
1333 	else
1334 		isrfreq += 20;
1335 	/* NB: there is no 907/20 wide but leave room */
1336 	return (isrfreq - 906*10) / 5;
1337 }
1338 
1339 static int
1340 mappsb(u_int isrfreq, u_int isrflags)
1341 {
1342 	return 37 + ((isrfreq * 10) + ((isrfreq % 5) == 2 ? 5 : 0) - 49400) / 5;
1343 }
1344 
1345 static status_func_t status;
1346 static usage_func_t usage;
1347 static statistics_func_t statistics;
1348 static cmdloop_branch_t branch[2];
1349 
1350 static void
1351 ieee80211_usage(prop_dictionary_t env)
1352 {
1353 	fprintf(stderr,
1354 	    "\t[ nwid network_id ] [ nwkey network_key | -nwkey ]\n"
1355 	    "\t[ list scan ]\n"
1356 	    "\t[ powersave | -powersave ] [ powersavesleep duration ]\n"
1357 	    "\t[ hidessid | -hidessid ] [ apbridge | -apbridge ]\n");
1358 }
1359 
1360 static void
1361 ieee80211_constructor(void)
1362 {
1363 	cmdloop_branch_init(&branch[0], &ieee80211bool.pk_parser);
1364 	cmdloop_branch_init(&branch[1], &kw80211.pk_parser);
1365 	register_cmdloop_branch(&branch[0]);
1366 	register_cmdloop_branch(&branch[1]);
1367 	status_func_init(&status, ieee80211_status);
1368 	statistics_func_init(&statistics, ieee80211_statistics);
1369 	usage_func_init(&usage, ieee80211_usage);
1370 	register_status(&status);
1371 	register_statistics(&statistics);
1372 	register_usage(&usage);
1373 }
1374