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