xref: /freebsd/contrib/wpa/wpa_supplicant/rrm.c (revision 031beb4e239bfce798af17f5fe8dba8bcaf13d99)
1 /*
2  * wpa_supplicant - Radio Measurements
3  * Copyright (c) 2003-2016, Jouni Malinen <j@w1.fi>
4  *
5  * This software may be distributed under the terms of the BSD license.
6  * See README for more details.
7  */
8 
9 #include "includes.h"
10 
11 #include "utils/common.h"
12 #include "utils/eloop.h"
13 #include "common/ieee802_11_common.h"
14 #include "wpa_supplicant_i.h"
15 #include "driver_i.h"
16 #include "bss.h"
17 #include "scan.h"
18 #include "p2p_supplicant.h"
19 
20 
21 static void wpas_rrm_neighbor_rep_timeout_handler(void *data, void *user_ctx)
22 {
23 	struct rrm_data *rrm = data;
24 
25 	if (!rrm->notify_neighbor_rep) {
26 		wpa_printf(MSG_ERROR,
27 			   "RRM: Unexpected neighbor report timeout");
28 		return;
29 	}
30 
31 	wpa_printf(MSG_DEBUG, "RRM: Notifying neighbor report - NONE");
32 	rrm->notify_neighbor_rep(rrm->neighbor_rep_cb_ctx, NULL);
33 
34 	rrm->notify_neighbor_rep = NULL;
35 	rrm->neighbor_rep_cb_ctx = NULL;
36 }
37 
38 
39 /*
40  * wpas_rrm_reset - Clear and reset all RRM data in wpa_supplicant
41  * @wpa_s: Pointer to wpa_supplicant
42  */
43 void wpas_rrm_reset(struct wpa_supplicant *wpa_s)
44 {
45 	wpa_s->rrm.rrm_used = 0;
46 
47 	eloop_cancel_timeout(wpas_rrm_neighbor_rep_timeout_handler, &wpa_s->rrm,
48 			     NULL);
49 	if (wpa_s->rrm.notify_neighbor_rep)
50 		wpas_rrm_neighbor_rep_timeout_handler(&wpa_s->rrm, NULL);
51 	wpa_s->rrm.next_neighbor_rep_token = 1;
52 	wpas_clear_beacon_rep_data(wpa_s);
53 }
54 
55 
56 /*
57  * wpas_rrm_process_neighbor_rep - Handle incoming neighbor report
58  * @wpa_s: Pointer to wpa_supplicant
59  * @report: Neighbor report buffer, prefixed by a 1-byte dialog token
60  * @report_len: Length of neighbor report buffer
61  */
62 void wpas_rrm_process_neighbor_rep(struct wpa_supplicant *wpa_s,
63 				   const u8 *report, size_t report_len)
64 {
65 	struct wpabuf *neighbor_rep;
66 
67 	wpa_hexdump(MSG_DEBUG, "RRM: New Neighbor Report", report, report_len);
68 	if (report_len < 1)
69 		return;
70 
71 	if (report[0] != wpa_s->rrm.next_neighbor_rep_token - 1) {
72 		wpa_printf(MSG_DEBUG,
73 			   "RRM: Discarding neighbor report with token %d (expected %d)",
74 			   report[0], wpa_s->rrm.next_neighbor_rep_token - 1);
75 		return;
76 	}
77 
78 	eloop_cancel_timeout(wpas_rrm_neighbor_rep_timeout_handler, &wpa_s->rrm,
79 			     NULL);
80 
81 	if (!wpa_s->rrm.notify_neighbor_rep) {
82 		wpa_msg(wpa_s, MSG_INFO, "RRM: Unexpected neighbor report");
83 		return;
84 	}
85 
86 	/* skipping the first byte, which is only an id (dialog token) */
87 	neighbor_rep = wpabuf_alloc(report_len - 1);
88 	if (!neighbor_rep) {
89 		wpas_rrm_neighbor_rep_timeout_handler(&wpa_s->rrm, NULL);
90 		return;
91 	}
92 	wpabuf_put_data(neighbor_rep, report + 1, report_len - 1);
93 	wpa_dbg(wpa_s, MSG_DEBUG, "RRM: Notifying neighbor report (token = %d)",
94 		report[0]);
95 	wpa_s->rrm.notify_neighbor_rep(wpa_s->rrm.neighbor_rep_cb_ctx,
96 				       neighbor_rep);
97 	wpa_s->rrm.notify_neighbor_rep = NULL;
98 	wpa_s->rrm.neighbor_rep_cb_ctx = NULL;
99 }
100 
101 
102 #if defined(__CYGWIN__) || defined(CONFIG_NATIVE_WINDOWS)
103 /* Workaround different, undefined for Windows, error codes used here */
104 #ifndef ENOTCONN
105 #define ENOTCONN -1
106 #endif
107 #ifndef EOPNOTSUPP
108 #define EOPNOTSUPP -1
109 #endif
110 #ifndef ECANCELED
111 #define ECANCELED -1
112 #endif
113 #endif
114 
115 /* Measurement Request element + Location Subject + Maximum Age subelement */
116 #define MEASURE_REQUEST_LCI_LEN (3 + 1 + 4)
117 /* Measurement Request element + Location Civic Request */
118 #define MEASURE_REQUEST_CIVIC_LEN (3 + 5)
119 
120 
121 /**
122  * wpas_rrm_send_neighbor_rep_request - Request a neighbor report from our AP
123  * @wpa_s: Pointer to wpa_supplicant
124  * @ssid: if not null, this is sent in the request. Otherwise, no SSID IE
125  *	  is sent in the request.
126  * @lci: if set, neighbor request will include LCI request
127  * @civic: if set, neighbor request will include civic location request
128  * @cb: Callback function to be called once the requested report arrives, or
129  *	timed out after RRM_NEIGHBOR_REPORT_TIMEOUT seconds.
130  *	In the former case, 'neighbor_rep' is a newly allocated wpabuf, and it's
131  *	the requester's responsibility to free it.
132  *	In the latter case NULL will be sent in 'neighbor_rep'.
133  * @cb_ctx: Context value to send the callback function
134  * Returns: 0 in case of success, negative error code otherwise
135  *
136  * In case there is a previous request which has not been answered yet, the
137  * new request fails. The caller may retry after RRM_NEIGHBOR_REPORT_TIMEOUT.
138  * Request must contain a callback function.
139  */
140 int wpas_rrm_send_neighbor_rep_request(struct wpa_supplicant *wpa_s,
141 				       const struct wpa_ssid_value *ssid,
142 				       int lci, int civic,
143 				       void (*cb)(void *ctx,
144 						  struct wpabuf *neighbor_rep),
145 				       void *cb_ctx)
146 {
147 	struct wpabuf *buf;
148 	const u8 *rrm_ie;
149 
150 	if (wpa_s->wpa_state != WPA_COMPLETED || wpa_s->current_ssid == NULL) {
151 		wpa_dbg(wpa_s, MSG_DEBUG, "RRM: No connection, no RRM.");
152 		return -ENOTCONN;
153 	}
154 
155 	if (!wpa_s->rrm.rrm_used) {
156 		wpa_dbg(wpa_s, MSG_DEBUG, "RRM: No RRM in current connection.");
157 		return -EOPNOTSUPP;
158 	}
159 
160 	rrm_ie = wpa_bss_get_ie(wpa_s->current_bss,
161 				WLAN_EID_RRM_ENABLED_CAPABILITIES);
162 	if (!rrm_ie || !(wpa_s->current_bss->caps & IEEE80211_CAP_RRM) ||
163 	    !(rrm_ie[2] & WLAN_RRM_CAPS_NEIGHBOR_REPORT)) {
164 		wpa_dbg(wpa_s, MSG_DEBUG,
165 			"RRM: No network support for Neighbor Report.");
166 		return -EOPNOTSUPP;
167 	}
168 
169 	/* Refuse if there's a live request */
170 	if (wpa_s->rrm.notify_neighbor_rep) {
171 		wpa_dbg(wpa_s, MSG_DEBUG,
172 			"RRM: Currently handling previous Neighbor Report.");
173 		return -EBUSY;
174 	}
175 
176 	/* 3 = action category + action code + dialog token */
177 	buf = wpabuf_alloc(3 + (ssid ? 2 + ssid->ssid_len : 0) +
178 			   (lci ? 2 + MEASURE_REQUEST_LCI_LEN : 0) +
179 			   (civic ? 2 + MEASURE_REQUEST_CIVIC_LEN : 0));
180 	if (buf == NULL) {
181 		wpa_dbg(wpa_s, MSG_DEBUG,
182 			"RRM: Failed to allocate Neighbor Report Request");
183 		return -ENOMEM;
184 	}
185 
186 	wpa_dbg(wpa_s, MSG_DEBUG,
187 		"RRM: Neighbor report request (for %s), token=%d",
188 		(ssid ? wpa_ssid_txt(ssid->ssid, ssid->ssid_len) : ""),
189 		wpa_s->rrm.next_neighbor_rep_token);
190 
191 	wpabuf_put_u8(buf, WLAN_ACTION_RADIO_MEASUREMENT);
192 	wpabuf_put_u8(buf, WLAN_RRM_NEIGHBOR_REPORT_REQUEST);
193 	wpabuf_put_u8(buf, wpa_s->rrm.next_neighbor_rep_token);
194 	if (ssid) {
195 		wpabuf_put_u8(buf, WLAN_EID_SSID);
196 		wpabuf_put_u8(buf, ssid->ssid_len);
197 		wpabuf_put_data(buf, ssid->ssid, ssid->ssid_len);
198 	}
199 
200 	if (lci) {
201 		/* IEEE P802.11-REVmc/D5.0 9.4.2.21 */
202 		wpabuf_put_u8(buf, WLAN_EID_MEASURE_REQUEST);
203 		wpabuf_put_u8(buf, MEASURE_REQUEST_LCI_LEN);
204 
205 		/*
206 		 * Measurement token; nonzero number that is unique among the
207 		 * Measurement Request elements in a particular frame.
208 		 */
209 		wpabuf_put_u8(buf, 1); /* Measurement Token */
210 
211 		/*
212 		 * Parallel, Enable, Request, and Report bits are 0, Duration is
213 		 * reserved.
214 		 */
215 		wpabuf_put_u8(buf, 0); /* Measurement Request Mode */
216 		wpabuf_put_u8(buf, MEASURE_TYPE_LCI); /* Measurement Type */
217 
218 		/* IEEE P802.11-REVmc/D5.0 9.4.2.21.10 - LCI request */
219 		/* Location Subject */
220 		wpabuf_put_u8(buf, LOCATION_SUBJECT_REMOTE);
221 
222 		/* Optional Subelements */
223 		/*
224 		 * IEEE P802.11-REVmc/D5.0 Figure 9-170
225 		 * The Maximum Age subelement is required, otherwise the AP can
226 		 * send only data that was determined after receiving the
227 		 * request. Setting it here to unlimited age.
228 		 */
229 		wpabuf_put_u8(buf, LCI_REQ_SUBELEM_MAX_AGE);
230 		wpabuf_put_u8(buf, 2);
231 		wpabuf_put_le16(buf, 0xffff);
232 	}
233 
234 	if (civic) {
235 		/* IEEE P802.11-REVmc/D5.0 9.4.2.21 */
236 		wpabuf_put_u8(buf, WLAN_EID_MEASURE_REQUEST);
237 		wpabuf_put_u8(buf, MEASURE_REQUEST_CIVIC_LEN);
238 
239 		/*
240 		 * Measurement token; nonzero number that is unique among the
241 		 * Measurement Request elements in a particular frame.
242 		 */
243 		wpabuf_put_u8(buf, 2); /* Measurement Token */
244 
245 		/*
246 		 * Parallel, Enable, Request, and Report bits are 0, Duration is
247 		 * reserved.
248 		 */
249 		wpabuf_put_u8(buf, 0); /* Measurement Request Mode */
250 		/* Measurement Type */
251 		wpabuf_put_u8(buf, MEASURE_TYPE_LOCATION_CIVIC);
252 
253 		/* IEEE P802.11-REVmc/D5.0 9.4.2.21.14:
254 		 * Location Civic request */
255 		/* Location Subject */
256 		wpabuf_put_u8(buf, LOCATION_SUBJECT_REMOTE);
257 		wpabuf_put_u8(buf, 0); /* Civic Location Type: IETF RFC 4776 */
258 		/* Location Service Interval Units: Seconds */
259 		wpabuf_put_u8(buf, 0);
260 		/* Location Service Interval: 0 - Only one report is requested
261 		 */
262 		wpabuf_put_le16(buf, 0);
263 		/* No optional subelements */
264 	}
265 
266 	wpa_s->rrm.next_neighbor_rep_token++;
267 
268 	if (wpa_drv_send_action(wpa_s, wpa_s->assoc_freq, 0, wpa_s->bssid,
269 				wpa_s->own_addr, wpa_s->bssid,
270 				wpabuf_head(buf), wpabuf_len(buf), 0) < 0) {
271 		wpa_dbg(wpa_s, MSG_DEBUG,
272 			"RRM: Failed to send Neighbor Report Request");
273 		wpabuf_free(buf);
274 		return -ECANCELED;
275 	}
276 
277 	wpa_s->rrm.neighbor_rep_cb_ctx = cb_ctx;
278 	wpa_s->rrm.notify_neighbor_rep = cb;
279 	eloop_register_timeout(RRM_NEIGHBOR_REPORT_TIMEOUT, 0,
280 			       wpas_rrm_neighbor_rep_timeout_handler,
281 			       &wpa_s->rrm, NULL);
282 
283 	wpabuf_free(buf);
284 	return 0;
285 }
286 
287 
288 static int wpas_rrm_report_elem(struct wpabuf **buf, u8 token, u8 mode, u8 type,
289 				const u8 *data, size_t data_len)
290 {
291 	if (wpabuf_resize(buf, 5 + data_len))
292 		return -1;
293 
294 	wpabuf_put_u8(*buf, WLAN_EID_MEASURE_REPORT);
295 	wpabuf_put_u8(*buf, 3 + data_len);
296 	wpabuf_put_u8(*buf, token);
297 	wpabuf_put_u8(*buf, mode);
298 	wpabuf_put_u8(*buf, type);
299 
300 	if (data_len)
301 		wpabuf_put_data(*buf, data, data_len);
302 
303 	return 0;
304 }
305 
306 
307 static int
308 wpas_rrm_build_lci_report(struct wpa_supplicant *wpa_s,
309 			  const struct rrm_measurement_request_element *req,
310 			  struct wpabuf **buf)
311 {
312 	u8 subject;
313 	u16 max_age = 0;
314 	struct os_reltime t, diff;
315 	unsigned long diff_l;
316 	const u8 *subelem;
317 	const u8 *request = req->variable;
318 	size_t len = req->len - 3;
319 
320 	if (len < 1)
321 		return -1;
322 
323 	if (!wpa_s->lci)
324 		goto reject;
325 
326 	subject = *request++;
327 	len--;
328 
329 	wpa_printf(MSG_DEBUG, "Measurement request location subject=%u",
330 		   subject);
331 
332 	if (subject != LOCATION_SUBJECT_REMOTE) {
333 		wpa_printf(MSG_INFO,
334 			   "Not building LCI report - bad location subject");
335 		return 0;
336 	}
337 
338 	/* Subelements are formatted exactly like elements */
339 	wpa_hexdump(MSG_DEBUG, "LCI request subelements", request, len);
340 	subelem = get_ie(request, len, LCI_REQ_SUBELEM_MAX_AGE);
341 	if (subelem && subelem[1] == 2)
342 		max_age = WPA_GET_LE16(subelem + 2);
343 
344 	if (os_get_reltime(&t))
345 		goto reject;
346 
347 	os_reltime_sub(&t, &wpa_s->lci_time, &diff);
348 	/* LCI age is calculated in 10th of a second units. */
349 	diff_l = diff.sec * 10 + diff.usec / 100000;
350 
351 	if (max_age != 0xffff && max_age < diff_l)
352 		goto reject;
353 
354 	if (wpas_rrm_report_elem(buf, req->token,
355 				 MEASUREMENT_REPORT_MODE_ACCEPT, req->type,
356 				 wpabuf_head_u8(wpa_s->lci),
357 				 wpabuf_len(wpa_s->lci)) < 0) {
358 		wpa_printf(MSG_DEBUG, "Failed to add LCI report element");
359 		return -1;
360 	}
361 
362 	return 0;
363 
364 reject:
365 	if (!is_multicast_ether_addr(wpa_s->rrm.dst_addr) &&
366 	    wpas_rrm_report_elem(buf, req->token,
367 				 MEASUREMENT_REPORT_MODE_REJECT_INCAPABLE,
368 				 req->type, NULL, 0) < 0) {
369 		wpa_printf(MSG_DEBUG, "RRM: Failed to add report element");
370 		return -1;
371 	}
372 
373 	return 0;
374 }
375 
376 
377 static void wpas_rrm_send_msr_report_mpdu(struct wpa_supplicant *wpa_s,
378 					  const u8 *data, size_t len)
379 {
380 	struct wpabuf *report = wpabuf_alloc(len + 3);
381 
382 	if (!report)
383 		return;
384 
385 	wpabuf_put_u8(report, WLAN_ACTION_RADIO_MEASUREMENT);
386 	wpabuf_put_u8(report, WLAN_RRM_RADIO_MEASUREMENT_REPORT);
387 	wpabuf_put_u8(report, wpa_s->rrm.token);
388 
389 	wpabuf_put_data(report, data, len);
390 
391 	if (wpa_drv_send_action(wpa_s, wpa_s->assoc_freq, 0, wpa_s->bssid,
392 				wpa_s->own_addr, wpa_s->bssid,
393 				wpabuf_head(report), wpabuf_len(report), 0)) {
394 		wpa_printf(MSG_ERROR,
395 			   "RRM: Radio measurement report failed: Sending Action frame failed");
396 	}
397 
398 	wpabuf_free(report);
399 }
400 
401 
402 static int wpas_rrm_beacon_rep_update_last_frame(u8 *pos, size_t len)
403 {
404 	struct rrm_measurement_report_element *msr_rep;
405 	u8 *end = pos + len;
406 	u8 *msr_rep_end;
407 	struct rrm_measurement_beacon_report *rep = NULL;
408 	u8 *subelem;
409 
410 	/* Find the last beacon report element */
411 	while (end - pos >= (int) sizeof(*msr_rep)) {
412 		msr_rep = (struct rrm_measurement_report_element *) pos;
413 		msr_rep_end = pos + msr_rep->len + 2;
414 
415 		if (msr_rep->eid != WLAN_EID_MEASURE_REPORT ||
416 		    msr_rep_end > end) {
417 			/* Should not happen. This indicates a bug. */
418 			wpa_printf(MSG_ERROR,
419 				   "RRM: non-measurement report element in measurement report frame");
420 			return -1;
421 		}
422 
423 		if (msr_rep->type == MEASURE_TYPE_BEACON)
424 			rep = (struct rrm_measurement_beacon_report *)
425 				msr_rep->variable;
426 
427 		pos += pos[1] + 2;
428 	}
429 
430 	if (!rep)
431 		return 0;
432 
433 	subelem = rep->variable;
434 	while (subelem + 2 < msr_rep_end &&
435 	       subelem[0] != WLAN_BEACON_REPORT_SUBELEM_LAST_INDICATION)
436 		subelem += 2 + subelem[1];
437 
438 	if (subelem + 2 < msr_rep_end &&
439 	    subelem[0] == WLAN_BEACON_REPORT_SUBELEM_LAST_INDICATION &&
440 	    subelem[1] == 1 &&
441 	    subelem + BEACON_REPORT_LAST_INDICATION_SUBELEM_LEN <= end)
442 		subelem[2] = 1;
443 
444 	return 0;
445 }
446 
447 
448 static void wpas_rrm_send_msr_report(struct wpa_supplicant *wpa_s,
449 				     struct wpabuf *buf)
450 {
451 	int len = wpabuf_len(buf);
452 	u8 *pos = wpabuf_mhead_u8(buf), *next = pos;
453 
454 #define MPDU_REPORT_LEN (int) (IEEE80211_MAX_MMPDU_SIZE - IEEE80211_HDRLEN - 3)
455 
456 	while (len) {
457 		int send_len = (len > MPDU_REPORT_LEN) ? next - pos : len;
458 
459 		if (send_len == len)
460 			wpas_rrm_beacon_rep_update_last_frame(pos, len);
461 
462 		if (send_len == len ||
463 		    (send_len + next[1] + 2) > MPDU_REPORT_LEN) {
464 			wpas_rrm_send_msr_report_mpdu(wpa_s, pos, send_len);
465 			len -= send_len;
466 			pos = next;
467 		}
468 
469 		if (len)
470 			next += next[1] + 2;
471 	}
472 #undef MPDU_REPORT_LEN
473 }
474 
475 
476 static int wpas_add_channel(u8 op_class, u8 chan, u8 num_primary_channels,
477 			    int *freqs)
478 {
479 	size_t i;
480 
481 	for (i = 0; i < num_primary_channels; i++) {
482 		u8 primary_chan = chan - (2 * num_primary_channels - 2) + i * 4;
483 
484 		freqs[i] = ieee80211_chan_to_freq(NULL, op_class, primary_chan);
485 		/* ieee80211_chan_to_freq() is not really meant for this
486 		 * conversion of 20 MHz primary channel numbers for wider VHT
487 		 * channels, so handle those as special cases here for now. */
488 		if (freqs[i] < 0 &&
489 		    (op_class == 128 || op_class == 129 || op_class == 130))
490 			freqs[i] = 5000 + 5 * primary_chan;
491 		if (freqs[i] < 0) {
492 			wpa_printf(MSG_DEBUG,
493 				   "Beacon Report: Invalid channel %u",
494 				   chan);
495 			return -1;
496 		}
497 	}
498 
499 	return 0;
500 }
501 
502 
503 static int * wpas_add_channels(const struct oper_class_map *op,
504 			       struct hostapd_hw_modes *mode, int active,
505 			       const u8 *channels, const u8 size)
506 {
507 	int *freqs, *next_freq;
508 	u8 num_primary_channels, i;
509 	u8 num_chans;
510 
511 	num_chans = channels ? size :
512 		(op->max_chan - op->min_chan) / op->inc + 1;
513 
514 	if (op->bw == BW80 || op->bw == BW80P80)
515 		num_primary_channels = 4;
516 	else if (op->bw == BW160)
517 		num_primary_channels = 8;
518 	else
519 		num_primary_channels = 1;
520 
521 	/* one extra place for the zero-terminator */
522 	freqs = os_calloc(num_chans * num_primary_channels + 1, sizeof(*freqs));
523 	if (!freqs) {
524 		wpa_printf(MSG_ERROR,
525 			   "Beacon Report: Failed to allocate freqs array");
526 		return NULL;
527 	}
528 
529 	next_freq = freqs;
530 	for  (i = 0; i < num_chans; i++) {
531 		u8 chan = channels ? channels[i] : op->min_chan + i * op->inc;
532 		enum chan_allowed res = verify_channel(mode, op->op_class, chan,
533 						       op->bw);
534 
535 		if (res == NOT_ALLOWED || (res == NO_IR && active))
536 			continue;
537 
538 		if (wpas_add_channel(op->op_class, chan, num_primary_channels,
539 				     next_freq) < 0) {
540 			os_free(freqs);
541 			return NULL;
542 		}
543 
544 		next_freq += num_primary_channels;
545 	}
546 
547 	if (!freqs[0]) {
548 		os_free(freqs);
549 		return NULL;
550 	}
551 
552 	return freqs;
553 }
554 
555 
556 static int * wpas_op_class_freqs(const struct oper_class_map *op,
557 				 struct hostapd_hw_modes *mode, int active)
558 {
559 	u8 channels_80mhz_5ghz[] = { 42, 58, 106, 122, 138, 155, 171 };
560 	u8 channels_160mhz_5ghz[] = { 50, 114, 163 };
561 	u8 channels_80mhz_6ghz[] = { 7, 23, 39, 55, 71, 87, 103, 119, 135, 151,
562 				     167, 183, 199, 215 };
563 	u8 channels_160mhz_6ghz[] = { 15, 47, 79, 111, 143, 175, 207 };
564 	const u8 *channels = NULL;
565 	size_t num_chan = 0;
566 	bool is_6ghz = is_6ghz_op_class(op->op_class);
567 
568 	/*
569 	 * When adding all channels in the operating class, 80 + 80 MHz
570 	 * operating classes are like 80 MHz channels because we add all valid
571 	 * channels anyway.
572 	 */
573 	if (op->bw == BW80 || op->bw == BW80P80) {
574 		channels = is_6ghz ? channels_80mhz_6ghz : channels_80mhz_5ghz;
575 		num_chan = is_6ghz ? ARRAY_SIZE(channels_80mhz_6ghz) :
576 			ARRAY_SIZE(channels_80mhz_5ghz);
577 	} else if (op->bw == BW160) {
578 		channels = is_6ghz ? channels_160mhz_6ghz :
579 			channels_160mhz_5ghz;
580 		num_chan =  is_6ghz ? ARRAY_SIZE(channels_160mhz_6ghz) :
581 			ARRAY_SIZE(channels_160mhz_5ghz);
582 	}
583 
584 	return wpas_add_channels(op, mode, active, channels, num_chan);
585 }
586 
587 
588 static int * wpas_channel_report_freqs(struct wpa_supplicant *wpa_s, int active,
589 				       const char *country, const u8 *subelems,
590 				       size_t len)
591 {
592 	int *freqs = NULL, *new_freqs;
593 	const u8 *end = subelems + len;
594 
595 	while (end - subelems > 2) {
596 		const struct oper_class_map *op;
597 		const u8 *ap_chan_elem, *pos;
598 		u8 left;
599 		struct hostapd_hw_modes *mode;
600 
601 		ap_chan_elem = get_ie(subelems, end - subelems,
602 				      WLAN_BEACON_REQUEST_SUBELEM_AP_CHANNEL);
603 		if (!ap_chan_elem)
604 			break;
605 		pos = ap_chan_elem + 2;
606 		left = ap_chan_elem[1];
607 		if (left < 1)
608 			break;
609 		subelems = ap_chan_elem + 2 + left;
610 
611 		op = get_oper_class(country, *pos);
612 		if (!op) {
613 			wpa_printf(MSG_DEBUG,
614 				   "Beacon request: unknown operating class in AP Channel Report subelement %u",
615 				   *pos);
616 			goto out;
617 		}
618 		pos++;
619 		left--;
620 
621 		mode = get_mode(wpa_s->hw.modes, wpa_s->hw.num_modes, op->mode,
622 				is_6ghz_op_class(op->op_class));
623 		if (!mode)
624 			continue;
625 
626 		/*
627 		 * For 80 + 80 MHz operating classes, this AP Channel Report
628 		 * element should be followed by another element specifying
629 		 * the second 80 MHz channel. For now just add this 80 MHz
630 		 * channel, the second 80 MHz channel will be added when the
631 		 * next element is parsed.
632 		 * TODO: Verify that this AP Channel Report element is followed
633 		 * by a corresponding AP Channel Report element as specified in
634 		 * IEEE Std 802.11-2016, 11.11.9.1.
635 		 */
636 		new_freqs = wpas_add_channels(op, mode, active, pos, left);
637 		if (new_freqs)
638 			int_array_concat(&freqs, new_freqs);
639 
640 		os_free(new_freqs);
641 	}
642 
643 	return freqs;
644 out:
645 	os_free(freqs);
646 	return NULL;
647 }
648 
649 
650 static int * wpas_beacon_request_freqs(struct wpa_supplicant *wpa_s,
651 				       u8 op_class, u8 chan, int active,
652 				       const u8 *subelems, size_t len)
653 {
654 	int *freqs = NULL, *ext_freqs = NULL;
655 	struct hostapd_hw_modes *mode;
656 	const char *country = NULL;
657 	const struct oper_class_map *op;
658 	const u8 *elem;
659 
660 	if (!wpa_s->current_bss)
661 		return NULL;
662 	elem = wpa_bss_get_ie(wpa_s->current_bss, WLAN_EID_COUNTRY);
663 	if (elem && elem[1] >= 2)
664 		country = (const char *) (elem + 2);
665 
666 	op = get_oper_class(country, op_class);
667 	if (!op) {
668 		wpa_printf(MSG_DEBUG,
669 			   "Beacon request: invalid operating class %d",
670 			   op_class);
671 		return NULL;
672 	}
673 
674 	mode = get_mode(wpa_s->hw.modes, wpa_s->hw.num_modes, op->mode,
675 			is_6ghz_op_class(op->op_class));
676 	if (!mode)
677 		return NULL;
678 
679 	switch (chan) {
680 	case 0:
681 		freqs = wpas_op_class_freqs(op, mode, active);
682 		if (!freqs)
683 			return NULL;
684 		break;
685 	case 255:
686 		/* freqs will be added from AP channel subelements */
687 		break;
688 	default:
689 		freqs = wpas_add_channels(op, mode, active, &chan, 1);
690 		if (!freqs)
691 			return NULL;
692 		break;
693 	}
694 
695 	ext_freqs = wpas_channel_report_freqs(wpa_s, active, country, subelems,
696 					      len);
697 	if (ext_freqs) {
698 		int_array_concat(&freqs, ext_freqs);
699 		os_free(ext_freqs);
700 		int_array_sort_unique(freqs);
701 	}
702 
703 	return freqs;
704 }
705 
706 
707 int wpas_get_op_chan_phy(int freq, const u8 *ies, size_t ies_len,
708 			 u8 *op_class, u8 *chan, u8 *phy_type)
709 {
710 	const u8 *ie;
711 	int sec_chan = 0, vht = 0;
712 	struct ieee80211_ht_operation *ht_oper = NULL;
713 	struct ieee80211_vht_operation *vht_oper = NULL;
714 	u8 seg0, seg1;
715 
716 	ie = get_ie(ies, ies_len, WLAN_EID_HT_OPERATION);
717 	if (ie && ie[1] >= sizeof(struct ieee80211_ht_operation)) {
718 		u8 sec_chan_offset;
719 
720 		ht_oper = (struct ieee80211_ht_operation *) (ie + 2);
721 		sec_chan_offset = ht_oper->ht_param &
722 			HT_INFO_HT_PARAM_SECONDARY_CHNL_OFF_MASK;
723 		if (sec_chan_offset == HT_INFO_HT_PARAM_SECONDARY_CHNL_ABOVE)
724 			sec_chan = 1;
725 		else if (sec_chan_offset ==
726 			 HT_INFO_HT_PARAM_SECONDARY_CHNL_BELOW)
727 			sec_chan = -1;
728 	}
729 
730 	ie = get_ie(ies, ies_len, WLAN_EID_VHT_OPERATION);
731 	if (ie && ie[1] >= sizeof(struct ieee80211_vht_operation)) {
732 		vht_oper = (struct ieee80211_vht_operation *) (ie + 2);
733 
734 		switch (vht_oper->vht_op_info_chwidth) {
735 		case 1:
736 			seg0 = vht_oper->vht_op_info_chan_center_freq_seg0_idx;
737 			seg1 = vht_oper->vht_op_info_chan_center_freq_seg1_idx;
738 			if (seg1 && abs(seg1 - seg0) == 8)
739 				vht = CHANWIDTH_160MHZ;
740 			else if (seg1)
741 				vht = CHANWIDTH_80P80MHZ;
742 			else
743 				vht = CHANWIDTH_80MHZ;
744 			break;
745 		case 2:
746 			vht = CHANWIDTH_160MHZ;
747 			break;
748 		case 3:
749 			vht = CHANWIDTH_80P80MHZ;
750 			break;
751 		default:
752 			vht = CHANWIDTH_USE_HT;
753 			break;
754 		}
755 	}
756 
757 	if (ieee80211_freq_to_channel_ext(freq, sec_chan, vht, op_class,
758 					  chan) == NUM_HOSTAPD_MODES) {
759 		wpa_printf(MSG_DEBUG,
760 			   "Cannot determine operating class and channel");
761 		return -1;
762 	}
763 
764 	*phy_type = ieee80211_get_phy_type(freq, ht_oper != NULL,
765 					   vht_oper != NULL);
766 	if (*phy_type == PHY_TYPE_UNSPECIFIED) {
767 		wpa_printf(MSG_DEBUG, "Cannot determine phy type");
768 		return -1;
769 	}
770 
771 	return 0;
772 }
773 
774 
775 static int wpas_beacon_rep_add_frame_body(struct bitfield *eids,
776 					  enum beacon_report_detail detail,
777 					  struct wpa_bss *bss, u8 *buf,
778 					  size_t buf_len, const u8 **ies_buf,
779 					  size_t *ie_len, int add_fixed)
780 {
781 	const u8 *ies = *ies_buf;
782 	size_t ies_len = *ie_len;
783 	u8 *pos = buf;
784 	int rem_len;
785 
786 	rem_len = 255 - sizeof(struct rrm_measurement_beacon_report) -
787 		sizeof(struct rrm_measurement_report_element) - 2 -
788 		REPORTED_FRAME_BODY_SUBELEM_LEN;
789 
790 	if (detail > BEACON_REPORT_DETAIL_ALL_FIELDS_AND_ELEMENTS) {
791 		wpa_printf(MSG_DEBUG,
792 			   "Beacon Request: Invalid reporting detail: %d",
793 			   detail);
794 		return -1;
795 	}
796 
797 	if (detail == BEACON_REPORT_DETAIL_NONE)
798 		return 0;
799 
800 	/*
801 	 * Minimal frame body subelement size: EID(1) + length(1) + TSF(8) +
802 	 * beacon interval(2) + capabilities(2) = 14 bytes
803 	 */
804 	if (add_fixed && buf_len < 14)
805 		return -1;
806 
807 	*pos++ = WLAN_BEACON_REPORT_SUBELEM_FRAME_BODY;
808 	/* The length will be filled later */
809 	pos++;
810 
811 	if (add_fixed) {
812 		WPA_PUT_LE64(pos, bss->tsf);
813 		pos += sizeof(bss->tsf);
814 		WPA_PUT_LE16(pos, bss->beacon_int);
815 		pos += 2;
816 		WPA_PUT_LE16(pos, bss->caps);
817 		pos += 2;
818 	}
819 
820 	rem_len -= pos - buf;
821 
822 	/*
823 	 * According to IEEE Std 802.11-2016, 9.4.2.22.7, if the reported frame
824 	 * body subelement causes the element to exceed the maximum element
825 	 * size, the subelement is truncated so that the last IE is a complete
826 	 * IE. So even when required to report all IEs, add elements one after
827 	 * the other and stop once there is no more room in the measurement
828 	 * element.
829 	 */
830 	while (ies_len > 2 && 2U + ies[1] <= ies_len && rem_len > 0) {
831 		if (detail == BEACON_REPORT_DETAIL_ALL_FIELDS_AND_ELEMENTS ||
832 		    (eids && bitfield_is_set(eids, ies[0]))) {
833 			u8 elen = ies[1];
834 
835 			if (2 + elen > buf + buf_len - pos ||
836 			    2 + elen > rem_len)
837 				break;
838 
839 			*pos++ = ies[0];
840 			*pos++ = elen;
841 			os_memcpy(pos, ies + 2, elen);
842 			pos += elen;
843 			rem_len -= 2 + elen;
844 		}
845 
846 		ies_len -= 2 + ies[1];
847 		ies += 2 + ies[1];
848 	}
849 
850 	*ie_len = ies_len;
851 	*ies_buf = ies;
852 
853 	/* Now the length is known */
854 	buf[1] = pos - buf - 2;
855 	return pos - buf;
856 }
857 
858 
859 static int wpas_add_beacon_rep_elem(struct beacon_rep_data *data,
860 				    struct wpa_bss *bss,
861 				    struct wpabuf **wpa_buf,
862 				    struct rrm_measurement_beacon_report *rep,
863 				    const u8 **ie, size_t *ie_len, u8 idx)
864 {
865 	int ret;
866 	u8 *buf, *pos;
867 	u32 subelems_len = REPORTED_FRAME_BODY_SUBELEM_LEN +
868 		(data->last_indication ?
869 		 BEACON_REPORT_LAST_INDICATION_SUBELEM_LEN : 0);
870 
871 	/* Maximum element length: Beacon Report element + Reported Frame Body
872 	 * subelement + all IEs of the reported Beacon frame + Reported Frame
873 	 * Body Fragment ID subelement */
874 	buf = os_malloc(sizeof(*rep) + 14 + *ie_len + subelems_len);
875 	if (!buf)
876 		return -1;
877 
878 	os_memcpy(buf, rep, sizeof(*rep));
879 
880 	ret = wpas_beacon_rep_add_frame_body(data->eids, data->report_detail,
881 					     bss, buf + sizeof(*rep),
882 					     14 + *ie_len, ie, ie_len,
883 					     idx == 0);
884 	if (ret < 0)
885 		goto out;
886 
887 	pos = buf + ret + sizeof(*rep);
888 	pos[0] = WLAN_BEACON_REPORT_SUBELEM_FRAME_BODY_FRAGMENT_ID;
889 	pos[1] = 2;
890 
891 	/*
892 	 * Only one Beacon Report Measurement is supported at a time, so
893 	 * the Beacon Report ID can always be set to 1.
894 	 */
895 	pos[2] = 1;
896 
897 	/* Fragment ID Number (bits 0..6) and More Frame Body Fragments (bit 7)
898  */
899 	pos[3] = idx;
900 	if (data->report_detail != BEACON_REPORT_DETAIL_NONE && *ie_len)
901 		pos[3] |= REPORTED_FRAME_BODY_MORE_FRAGMENTS;
902 	else
903 		pos[3] &= ~REPORTED_FRAME_BODY_MORE_FRAGMENTS;
904 
905 	pos += REPORTED_FRAME_BODY_SUBELEM_LEN;
906 
907 	if (data->last_indication) {
908 		pos[0] = WLAN_BEACON_REPORT_SUBELEM_LAST_INDICATION;
909 		pos[1] = 1;
910 
911 		/* This field will be updated later if this is the last frame */
912 		pos[2] = 0;
913 	}
914 
915 	ret = wpas_rrm_report_elem(wpa_buf, data->token,
916 				   MEASUREMENT_REPORT_MODE_ACCEPT,
917 				   MEASURE_TYPE_BEACON, buf,
918 				   ret + sizeof(*rep) + subelems_len);
919 out:
920 	os_free(buf);
921 	return ret;
922 }
923 
924 
925 static int wpas_add_beacon_rep(struct wpa_supplicant *wpa_s,
926 			       struct wpabuf **wpa_buf, struct wpa_bss *bss,
927 			       u64 start, u64 parent_tsf)
928 {
929 	struct beacon_rep_data *data = &wpa_s->beacon_rep_data;
930 	const u8 *ies = wpa_bss_ie_ptr(bss);
931 	const u8 *pos = ies;
932 	size_t ies_len = bss->ie_len ? bss->ie_len : bss->beacon_ie_len;
933 	struct rrm_measurement_beacon_report rep;
934 	u8 idx = 0;
935 
936 	if (os_memcmp(data->bssid, broadcast_ether_addr, ETH_ALEN) != 0 &&
937 	    os_memcmp(data->bssid, bss->bssid, ETH_ALEN) != 0)
938 		return 0;
939 
940 	if (data->ssid_len &&
941 	    (data->ssid_len != bss->ssid_len ||
942 	     os_memcmp(data->ssid, bss->ssid, bss->ssid_len) != 0))
943 		return 0;
944 
945 	if (wpas_get_op_chan_phy(bss->freq, ies, ies_len, &rep.op_class,
946 				 &rep.channel, &rep.report_info) < 0)
947 		return 0;
948 
949 	rep.start_time = host_to_le64(start);
950 	rep.duration = host_to_le16(data->scan_params.duration);
951 	rep.rcpi = rssi_to_rcpi(bss->level);
952 	rep.rsni = 255; /* 255 indicates that RSNI is not available */
953 	os_memcpy(rep.bssid, bss->bssid, ETH_ALEN);
954 	rep.antenna_id = 0; /* unknown */
955 	rep.parent_tsf = host_to_le32(parent_tsf);
956 
957 	do {
958 		int ret;
959 
960 		ret = wpas_add_beacon_rep_elem(data, bss, wpa_buf, &rep,
961 					       &pos, &ies_len, idx++);
962 		if (ret)
963 			return ret;
964 	} while (data->report_detail != BEACON_REPORT_DETAIL_NONE &&
965 		 ies_len >= 2);
966 
967 	return 0;
968 }
969 
970 
971 static int wpas_beacon_rep_no_results(struct wpa_supplicant *wpa_s,
972 				      struct wpabuf **buf)
973 {
974 	return wpas_rrm_report_elem(buf, wpa_s->beacon_rep_data.token,
975 				    MEASUREMENT_REPORT_MODE_ACCEPT,
976 				    MEASURE_TYPE_BEACON, NULL, 0);
977 }
978 
979 
980 static void wpas_beacon_rep_table(struct wpa_supplicant *wpa_s,
981 				  struct wpabuf **buf)
982 {
983 	size_t i;
984 
985 	for (i = 0; i < wpa_s->last_scan_res_used; i++) {
986 		if (wpas_add_beacon_rep(wpa_s, buf, wpa_s->last_scan_res[i],
987 					0, 0) < 0)
988 			break;
989 	}
990 
991 	if (!(*buf))
992 		wpas_beacon_rep_no_results(wpa_s, buf);
993 
994 	wpa_hexdump_buf(MSG_DEBUG, "RRM: Radio Measurement report", *buf);
995 }
996 
997 
998 void wpas_rrm_refuse_request(struct wpa_supplicant *wpa_s)
999 {
1000 	if (!is_multicast_ether_addr(wpa_s->rrm.dst_addr)) {
1001 		struct wpabuf *buf = NULL;
1002 
1003 		if (wpas_rrm_report_elem(&buf, wpa_s->beacon_rep_data.token,
1004 					 MEASUREMENT_REPORT_MODE_REJECT_REFUSED,
1005 					 MEASURE_TYPE_BEACON, NULL, 0)) {
1006 			wpa_printf(MSG_ERROR, "RRM: Memory allocation failed");
1007 			wpabuf_free(buf);
1008 			return;
1009 		}
1010 
1011 		wpas_rrm_send_msr_report(wpa_s, buf);
1012 		wpabuf_free(buf);
1013 	}
1014 
1015 	wpas_clear_beacon_rep_data(wpa_s);
1016 }
1017 
1018 
1019 static void wpas_rrm_scan_timeout(void *eloop_ctx, void *timeout_ctx)
1020 {
1021 	struct wpa_supplicant *wpa_s = eloop_ctx;
1022 	struct wpa_driver_scan_params *params =
1023 		&wpa_s->beacon_rep_data.scan_params;
1024 	u16 prev_duration = params->duration;
1025 
1026 	if (!wpa_s->current_bss)
1027 		return;
1028 
1029 	if (!(wpa_s->drv_rrm_flags & WPA_DRIVER_FLAGS_SUPPORT_SET_SCAN_DWELL) &&
1030 	    params->duration) {
1031 		wpa_printf(MSG_DEBUG,
1032 			   "RRM: Cannot set scan duration due to missing driver support");
1033 		params->duration = 0;
1034 	}
1035 	os_get_reltime(&wpa_s->beacon_rep_scan);
1036 	if (wpa_s->scanning || wpas_p2p_in_progress(wpa_s) ||
1037 	    wpa_supplicant_trigger_scan(wpa_s, params))
1038 		wpas_rrm_refuse_request(wpa_s);
1039 	params->duration = prev_duration;
1040 }
1041 
1042 
1043 static int wpas_rm_handle_beacon_req_subelem(struct wpa_supplicant *wpa_s,
1044 					     struct beacon_rep_data *data,
1045 					     u8 sid, u8 slen, const u8 *subelem)
1046 {
1047 	u8 report_info, i;
1048 
1049 	switch (sid) {
1050 	case WLAN_BEACON_REQUEST_SUBELEM_SSID:
1051 		if (!slen) {
1052 			wpa_printf(MSG_DEBUG,
1053 				   "SSID subelement with zero length - wildcard SSID");
1054 			break;
1055 		}
1056 
1057 		if (slen > SSID_MAX_LEN) {
1058 			wpa_printf(MSG_DEBUG,
1059 				   "Invalid SSID subelement length: %u", slen);
1060 			return -1;
1061 		}
1062 
1063 		data->ssid_len = slen;
1064 		os_memcpy(data->ssid, subelem, data->ssid_len);
1065 		break;
1066 	case WLAN_BEACON_REQUEST_SUBELEM_INFO:
1067 		if (slen != 2) {
1068 			wpa_printf(MSG_DEBUG,
1069 				   "Invalid reporting information subelement length: %u",
1070 				   slen);
1071 			return -1;
1072 		}
1073 
1074 		report_info = subelem[0];
1075 		if (report_info != 0) {
1076 			wpa_printf(MSG_DEBUG,
1077 				   "reporting information=%u is not supported",
1078 				   report_info);
1079 			return 0;
1080 		}
1081 		break;
1082 	case WLAN_BEACON_REQUEST_SUBELEM_DETAIL:
1083 		if (slen != 1) {
1084 			wpa_printf(MSG_DEBUG,
1085 				   "Invalid reporting detail subelement length: %u",
1086 				   slen);
1087 			return -1;
1088 		}
1089 
1090 		data->report_detail = subelem[0];
1091 		if (data->report_detail >
1092 		    BEACON_REPORT_DETAIL_ALL_FIELDS_AND_ELEMENTS) {
1093 			wpa_printf(MSG_DEBUG, "Invalid reporting detail: %u",
1094 				   subelem[0]);
1095 			return -1;
1096 		}
1097 
1098 		break;
1099 	case WLAN_BEACON_REQUEST_SUBELEM_REQUEST:
1100 		if (data->report_detail !=
1101 		    BEACON_REPORT_DETAIL_REQUESTED_ONLY) {
1102 			wpa_printf(MSG_DEBUG,
1103 				   "Beacon request: request subelement is present but report detail is %u",
1104 				   data->report_detail);
1105 			return -1;
1106 		}
1107 
1108 		if (!slen) {
1109 			wpa_printf(MSG_DEBUG,
1110 				   "Invalid request subelement length: %u",
1111 				   slen);
1112 			return -1;
1113 		}
1114 
1115 		if (data->eids) {
1116 			wpa_printf(MSG_DEBUG,
1117 				   "Beacon Request: Request subelement appears more than once");
1118 			return -1;
1119 		}
1120 
1121 		data->eids = bitfield_alloc(255);
1122 		if (!data->eids) {
1123 			wpa_printf(MSG_DEBUG, "Failed to allocate EIDs bitmap");
1124 			return -1;
1125 		}
1126 
1127 		for (i = 0; i < slen; i++)
1128 			bitfield_set(data->eids, subelem[i]);
1129 		break;
1130 	case WLAN_BEACON_REQUEST_SUBELEM_AP_CHANNEL:
1131 		/* Skip - it will be processed when freqs are added */
1132 		break;
1133 	case WLAN_BEACON_REQUEST_SUBELEM_LAST_INDICATION:
1134 		if (slen != 1) {
1135 			wpa_printf(MSG_DEBUG,
1136 				   "Beacon request: Invalid last indication request subelement length: %u",
1137 				   slen);
1138 			return -1;
1139 		}
1140 
1141 		data->last_indication = subelem[0];
1142 		break;
1143 	default:
1144 		wpa_printf(MSG_DEBUG,
1145 			   "Beacon request: Unknown subelement id %u", sid);
1146 		break;
1147 	}
1148 
1149 	return 1;
1150 }
1151 
1152 
1153 /**
1154  * Returns 0 if the next element can be processed, 1 if some operation was
1155  * triggered, and -1 if processing failed (i.e., the element is in invalid
1156  * format or an internal error occurred).
1157  */
1158 static int
1159 wpas_rm_handle_beacon_req(struct wpa_supplicant *wpa_s,
1160 			  u8 elem_token, int duration_mandatory,
1161 			  const struct rrm_measurement_beacon_request *req,
1162 			  size_t len, struct wpabuf **buf)
1163 {
1164 	struct beacon_rep_data *data = &wpa_s->beacon_rep_data;
1165 	struct wpa_driver_scan_params *params = &data->scan_params;
1166 	const u8 *subelems;
1167 	size_t elems_len;
1168 	u16 rand_interval;
1169 	u32 interval_usec;
1170 	u32 _rand;
1171 	int ret = 0, res;
1172 	u8 reject_mode;
1173 
1174 	if (len < sizeof(*req))
1175 		return -1;
1176 
1177 	if (req->mode != BEACON_REPORT_MODE_PASSIVE &&
1178 	    req->mode != BEACON_REPORT_MODE_ACTIVE &&
1179 	    req->mode != BEACON_REPORT_MODE_TABLE)
1180 		return 0;
1181 
1182 	subelems = req->variable;
1183 	elems_len = len - sizeof(*req);
1184 	rand_interval = le_to_host16(req->rand_interval);
1185 
1186 	os_free(params->freqs);
1187 	os_memset(params, 0, sizeof(*params));
1188 
1189 	data->token = elem_token;
1190 
1191 	/* default reporting detail is all fixed length fields and all
1192 	 * elements */
1193 	data->report_detail = BEACON_REPORT_DETAIL_ALL_FIELDS_AND_ELEMENTS;
1194 	os_memcpy(data->bssid, req->bssid, ETH_ALEN);
1195 
1196 	while (elems_len >= 2) {
1197 		if (subelems[1] > elems_len - 2) {
1198 			wpa_printf(MSG_DEBUG,
1199 				   "Beacon Request: Truncated subelement");
1200 			ret = -1;
1201 			goto out;
1202 		}
1203 
1204 		res = wpas_rm_handle_beacon_req_subelem(
1205 			wpa_s, data, subelems[0], subelems[1], &subelems[2]);
1206 		if (res < 0) {
1207 			ret = res;
1208 			goto out;
1209 		} else if (!res) {
1210 			reject_mode = MEASUREMENT_REPORT_MODE_REJECT_INCAPABLE;
1211 			goto out_reject;
1212 		}
1213 
1214 		elems_len -= 2 + subelems[1];
1215 		subelems += 2 + subelems[1];
1216 	}
1217 
1218 	if (req->mode == BEACON_REPORT_MODE_TABLE) {
1219 		wpas_beacon_rep_table(wpa_s, buf);
1220 		goto out;
1221 	}
1222 
1223 	params->freqs = wpas_beacon_request_freqs(
1224 		wpa_s, req->oper_class, req->channel,
1225 		req->mode == BEACON_REPORT_MODE_ACTIVE,
1226 		req->variable, len - sizeof(*req));
1227 	if (!params->freqs) {
1228 		wpa_printf(MSG_DEBUG, "Beacon request: No valid channels");
1229 		reject_mode = MEASUREMENT_REPORT_MODE_REJECT_REFUSED;
1230 		goto out_reject;
1231 	}
1232 
1233 	params->duration = le_to_host16(req->duration);
1234 	params->duration_mandatory = duration_mandatory;
1235 	if (!params->duration) {
1236 		wpa_printf(MSG_DEBUG, "Beacon request: Duration is 0");
1237 		ret = -1;
1238 		goto out;
1239 	}
1240 
1241 	params->only_new_results = 1;
1242 
1243 	if (req->mode == BEACON_REPORT_MODE_ACTIVE) {
1244 		params->ssids[params->num_ssids].ssid = data->ssid;
1245 		params->ssids[params->num_ssids++].ssid_len = data->ssid_len;
1246 	}
1247 
1248 	if (os_get_random((u8 *) &_rand, sizeof(_rand)) < 0)
1249 		_rand = os_random();
1250 	interval_usec = (_rand % (rand_interval + 1)) * 1024;
1251 	eloop_register_timeout(0, interval_usec, wpas_rrm_scan_timeout, wpa_s,
1252 			       NULL);
1253 	return 1;
1254 out_reject:
1255 	if (!is_multicast_ether_addr(wpa_s->rrm.dst_addr) &&
1256 	    wpas_rrm_report_elem(buf, elem_token, reject_mode,
1257 				 MEASURE_TYPE_BEACON, NULL, 0) < 0) {
1258 		wpa_printf(MSG_DEBUG, "RRM: Failed to add report element");
1259 		ret = -1;
1260 	}
1261 out:
1262 	wpas_clear_beacon_rep_data(wpa_s);
1263 	return ret;
1264 }
1265 
1266 
1267 static int
1268 wpas_rrm_handle_msr_req_element(
1269 	struct wpa_supplicant *wpa_s,
1270 	const struct rrm_measurement_request_element *req,
1271 	struct wpabuf **buf)
1272 {
1273 	int duration_mandatory;
1274 
1275 	wpa_printf(MSG_DEBUG, "Measurement request type %d token %d",
1276 		   req->type, req->token);
1277 
1278 	if (req->mode & MEASUREMENT_REQUEST_MODE_ENABLE) {
1279 		/* Enable bit is not supported for now */
1280 		wpa_printf(MSG_DEBUG, "RRM: Enable bit not supported, ignore");
1281 		return 0;
1282 	}
1283 
1284 	if ((req->mode & MEASUREMENT_REQUEST_MODE_PARALLEL) &&
1285 	    req->type > MEASURE_TYPE_RPI_HIST) {
1286 		/* Parallel measurements are not supported for now */
1287 		wpa_printf(MSG_DEBUG,
1288 			   "RRM: Parallel measurements are not supported, reject");
1289 		goto reject;
1290 	}
1291 
1292 	duration_mandatory =
1293 		!!(req->mode & MEASUREMENT_REQUEST_MODE_DURATION_MANDATORY);
1294 
1295 	switch (req->type) {
1296 	case MEASURE_TYPE_LCI:
1297 		return wpas_rrm_build_lci_report(wpa_s, req, buf);
1298 	case MEASURE_TYPE_BEACON:
1299 		if (duration_mandatory &&
1300 		    !(wpa_s->drv_rrm_flags &
1301 		      WPA_DRIVER_FLAGS_SUPPORT_SET_SCAN_DWELL)) {
1302 			wpa_printf(MSG_DEBUG,
1303 				   "RRM: Driver does not support dwell time configuration - reject beacon report with mandatory duration");
1304 			goto reject;
1305 		}
1306 		return wpas_rm_handle_beacon_req(wpa_s, req->token,
1307 						 duration_mandatory,
1308 						 (const void *) req->variable,
1309 						 req->len - 3, buf);
1310 	default:
1311 		wpa_printf(MSG_INFO,
1312 			   "RRM: Unsupported radio measurement type %u",
1313 			   req->type);
1314 		break;
1315 	}
1316 
1317 reject:
1318 	if (!is_multicast_ether_addr(wpa_s->rrm.dst_addr) &&
1319 	    wpas_rrm_report_elem(buf, req->token,
1320 				 MEASUREMENT_REPORT_MODE_REJECT_INCAPABLE,
1321 				 req->type, NULL, 0) < 0) {
1322 		wpa_printf(MSG_DEBUG, "RRM: Failed to add report element");
1323 		return -1;
1324 	}
1325 
1326 	return 0;
1327 }
1328 
1329 
1330 static struct wpabuf *
1331 wpas_rrm_process_msr_req_elems(struct wpa_supplicant *wpa_s, const u8 *pos,
1332 			       size_t len)
1333 {
1334 	struct wpabuf *buf = NULL;
1335 
1336 	while (len) {
1337 		const struct rrm_measurement_request_element *req;
1338 		int res;
1339 
1340 		if (len < 2) {
1341 			wpa_printf(MSG_DEBUG, "RRM: Truncated element");
1342 			goto out;
1343 		}
1344 
1345 		req = (const struct rrm_measurement_request_element *) pos;
1346 		if (req->eid != WLAN_EID_MEASURE_REQUEST) {
1347 			wpa_printf(MSG_DEBUG,
1348 				   "RRM: Expected Measurement Request element, but EID is %u",
1349 				   req->eid);
1350 			goto out;
1351 		}
1352 
1353 		if (req->len < 3) {
1354 			wpa_printf(MSG_DEBUG, "RRM: Element length too short");
1355 			goto out;
1356 		}
1357 
1358 		if (req->len > len - 2) {
1359 			wpa_printf(MSG_DEBUG, "RRM: Element length too long");
1360 			goto out;
1361 		}
1362 
1363 		res = wpas_rrm_handle_msr_req_element(wpa_s, req, &buf);
1364 		if (res < 0)
1365 			goto out;
1366 
1367 		pos += req->len + 2;
1368 		len -= req->len + 2;
1369 	}
1370 
1371 	return buf;
1372 
1373 out:
1374 	wpabuf_free(buf);
1375 	return NULL;
1376 }
1377 
1378 
1379 void wpas_rrm_handle_radio_measurement_request(struct wpa_supplicant *wpa_s,
1380 					       const u8 *src, const u8 *dst,
1381 					       const u8 *frame, size_t len)
1382 {
1383 	struct wpabuf *report;
1384 
1385 	if (wpa_s->wpa_state != WPA_COMPLETED) {
1386 		wpa_printf(MSG_INFO,
1387 			   "RRM: Ignoring radio measurement request: Not associated");
1388 		return;
1389 	}
1390 
1391 	if (!wpa_s->rrm.rrm_used) {
1392 		wpa_printf(MSG_INFO,
1393 			   "RRM: Ignoring radio measurement request: Not RRM network");
1394 		return;
1395 	}
1396 
1397 	if (len < 3) {
1398 		wpa_printf(MSG_INFO,
1399 			   "RRM: Ignoring too short radio measurement request");
1400 		return;
1401 	}
1402 
1403 	wpa_s->rrm.token = *frame;
1404 	os_memcpy(wpa_s->rrm.dst_addr, dst, ETH_ALEN);
1405 
1406 	/* Number of repetitions is not supported */
1407 
1408 	report = wpas_rrm_process_msr_req_elems(wpa_s, frame + 3, len - 3);
1409 	if (!report)
1410 		return;
1411 
1412 	wpas_rrm_send_msr_report(wpa_s, report);
1413 	wpabuf_free(report);
1414 }
1415 
1416 
1417 void wpas_rrm_handle_link_measurement_request(struct wpa_supplicant *wpa_s,
1418 					      const u8 *src,
1419 					      const u8 *frame, size_t len,
1420 					      int rssi)
1421 {
1422 	struct wpabuf *buf;
1423 	const struct rrm_link_measurement_request *req;
1424 	struct rrm_link_measurement_report report;
1425 
1426 	if (wpa_s->wpa_state != WPA_COMPLETED) {
1427 		wpa_printf(MSG_INFO,
1428 			   "RRM: Ignoring link measurement request. Not associated");
1429 		return;
1430 	}
1431 
1432 	if (!wpa_s->rrm.rrm_used) {
1433 		wpa_printf(MSG_INFO,
1434 			   "RRM: Ignoring link measurement request. Not RRM network");
1435 		return;
1436 	}
1437 
1438 	if (!(wpa_s->drv_rrm_flags & WPA_DRIVER_FLAGS_TX_POWER_INSERTION)) {
1439 		wpa_printf(MSG_INFO,
1440 			   "RRM: Measurement report failed. TX power insertion not supported");
1441 		return;
1442 	}
1443 
1444 	req = (const struct rrm_link_measurement_request *) frame;
1445 	if (len < sizeof(*req)) {
1446 		wpa_printf(MSG_INFO,
1447 			   "RRM: Link measurement report failed. Request too short");
1448 		return;
1449 	}
1450 
1451 	os_memset(&report, 0, sizeof(report));
1452 	report.dialog_token = req->dialog_token;
1453 	report.tpc.eid = WLAN_EID_TPC_REPORT;
1454 	report.tpc.len = 2;
1455 	/* Note: The driver is expected to update report.tpc.tx_power and
1456 	 * report.tpc.link_margin subfields when sending out this frame.
1457 	 * Similarly, the driver would need to update report.rx_ant_id and
1458 	 * report.tx_ant_id subfields. */
1459 	report.rsni = 255; /* 255 indicates that RSNI is not available */
1460 	report.rcpi = rssi_to_rcpi(rssi);
1461 
1462 	/* action_category + action_code */
1463 	buf = wpabuf_alloc(2 + sizeof(report));
1464 	if (buf == NULL) {
1465 		wpa_printf(MSG_ERROR,
1466 			   "RRM: Link measurement report failed. Buffer allocation failed");
1467 		return;
1468 	}
1469 
1470 	wpabuf_put_u8(buf, WLAN_ACTION_RADIO_MEASUREMENT);
1471 	wpabuf_put_u8(buf, WLAN_RRM_LINK_MEASUREMENT_REPORT);
1472 	wpabuf_put_data(buf, &report, sizeof(report));
1473 	wpa_hexdump_buf(MSG_DEBUG, "RRM: Link measurement report", buf);
1474 
1475 	if (wpa_drv_send_action(wpa_s, wpa_s->assoc_freq, 0, src,
1476 				wpa_s->own_addr, wpa_s->bssid,
1477 				wpabuf_head(buf), wpabuf_len(buf), 0)) {
1478 		wpa_printf(MSG_ERROR,
1479 			   "RRM: Link measurement report failed. Send action failed");
1480 	}
1481 	wpabuf_free(buf);
1482 }
1483 
1484 
1485 int wpas_beacon_rep_scan_process(struct wpa_supplicant *wpa_s,
1486 				 struct wpa_scan_results *scan_res,
1487 				 struct scan_info *info)
1488 {
1489 	size_t i = 0;
1490 	struct wpabuf *buf = NULL;
1491 
1492 	if (!wpa_s->beacon_rep_data.token)
1493 		return 0;
1494 
1495 	if (!wpa_s->current_bss)
1496 		goto out;
1497 
1498 	/* If the measurement was aborted, don't report partial results */
1499 	if (info->aborted)
1500 		goto out;
1501 
1502 	wpa_printf(MSG_DEBUG, "RRM: TSF BSSID: " MACSTR " current BSS: " MACSTR,
1503 		   MAC2STR(info->scan_start_tsf_bssid),
1504 		   MAC2STR(wpa_s->current_bss->bssid));
1505 	if ((wpa_s->drv_rrm_flags & WPA_DRIVER_FLAGS_SUPPORT_BEACON_REPORT) &&
1506 	    os_memcmp(info->scan_start_tsf_bssid, wpa_s->current_bss->bssid,
1507 		      ETH_ALEN) != 0) {
1508 		wpa_printf(MSG_DEBUG,
1509 			   "RRM: Ignore scan results due to mismatching TSF BSSID");
1510 		goto out;
1511 	}
1512 
1513 	for (i = 0; i < scan_res->num; i++) {
1514 		struct wpa_bss *bss =
1515 			wpa_bss_get_bssid(wpa_s, scan_res->res[i]->bssid);
1516 
1517 		if (!bss)
1518 			continue;
1519 
1520 		if ((wpa_s->drv_rrm_flags &
1521 		     WPA_DRIVER_FLAGS_SUPPORT_BEACON_REPORT) &&
1522 		    os_memcmp(scan_res->res[i]->tsf_bssid,
1523 			      wpa_s->current_bss->bssid, ETH_ALEN) != 0) {
1524 			wpa_printf(MSG_DEBUG,
1525 				   "RRM: Ignore scan result for " MACSTR
1526 				   " due to mismatching TSF BSSID" MACSTR,
1527 				   MAC2STR(scan_res->res[i]->bssid),
1528 				   MAC2STR(scan_res->res[i]->tsf_bssid));
1529 			continue;
1530 		}
1531 
1532 		/*
1533 		 * Don't report results that were not received during the
1534 		 * current measurement.
1535 		 */
1536 		if (!(wpa_s->drv_rrm_flags &
1537 		      WPA_DRIVER_FLAGS_SUPPORT_BEACON_REPORT)) {
1538 			struct os_reltime update_time, diff;
1539 
1540 			/* For now, allow 8 ms older results due to some
1541 			 * unknown issue with cfg80211 BSS table updates during
1542 			 * a scan with the current BSS.
1543 			 * TODO: Fix this more properly to avoid having to have
1544 			 * this type of hacks in place. */
1545 			calculate_update_time(&scan_res->fetch_time,
1546 					      scan_res->res[i]->age,
1547 					      &update_time);
1548 			os_reltime_sub(&wpa_s->beacon_rep_scan,
1549 				       &update_time, &diff);
1550 			if (os_reltime_before(&update_time,
1551 					      &wpa_s->beacon_rep_scan) &&
1552 			    (diff.sec || diff.usec >= 8000)) {
1553 				wpa_printf(MSG_DEBUG,
1554 					   "RRM: Ignore scan result for " MACSTR
1555 					   " due to old update (age(ms) %u, calculated age %u.%06u seconds)",
1556 					   MAC2STR(scan_res->res[i]->bssid),
1557 					   scan_res->res[i]->age,
1558 					   (unsigned int) diff.sec,
1559 					   (unsigned int) diff.usec);
1560 				continue;
1561 			}
1562 		} else if (info->scan_start_tsf >
1563 			   scan_res->res[i]->parent_tsf) {
1564 			continue;
1565 		}
1566 
1567 		if (wpas_add_beacon_rep(wpa_s, &buf, bss, info->scan_start_tsf,
1568 					scan_res->res[i]->parent_tsf) < 0)
1569 			break;
1570 	}
1571 
1572 	if (!buf && wpas_beacon_rep_no_results(wpa_s, &buf))
1573 		goto out;
1574 
1575 	wpa_hexdump_buf(MSG_DEBUG, "RRM: Radio Measurement report", buf);
1576 
1577 	wpas_rrm_send_msr_report(wpa_s, buf);
1578 	wpabuf_free(buf);
1579 
1580 out:
1581 	wpas_clear_beacon_rep_data(wpa_s);
1582 	return 1;
1583 }
1584 
1585 
1586 void wpas_clear_beacon_rep_data(struct wpa_supplicant *wpa_s)
1587 {
1588 	struct beacon_rep_data *data = &wpa_s->beacon_rep_data;
1589 
1590 	eloop_cancel_timeout(wpas_rrm_scan_timeout, wpa_s, NULL);
1591 	bitfield_free(data->eids);
1592 	os_free(data->scan_params.freqs);
1593 	os_memset(data, 0, sizeof(*data));
1594 }
1595