d9634522643393f19aa1cce7be82d59b8e485c96
[mech_eap.git] / wpa_supplicant / scan.c
1 /*
2  * WPA Supplicant - Scanning
3  * Copyright (c) 2003-2012, 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 "utils/includes.h"
10
11 #include "utils/common.h"
12 #include "utils/eloop.h"
13 #include "common/ieee802_11_defs.h"
14 #include "common/wpa_ctrl.h"
15 #include "config.h"
16 #include "wpa_supplicant_i.h"
17 #include "driver_i.h"
18 #include "wps_supplicant.h"
19 #include "p2p_supplicant.h"
20 #include "p2p/p2p.h"
21 #include "hs20_supplicant.h"
22 #include "notify.h"
23 #include "bss.h"
24 #include "gas_query.h"
25 #include "scan.h"
26
27
28 static void wpa_supplicant_gen_assoc_event(struct wpa_supplicant *wpa_s)
29 {
30         struct wpa_ssid *ssid;
31         union wpa_event_data data;
32
33         ssid = wpa_supplicant_get_ssid(wpa_s);
34         if (ssid == NULL)
35                 return;
36
37         if (wpa_s->current_ssid == NULL) {
38                 wpa_s->current_ssid = ssid;
39                 if (wpa_s->current_ssid != NULL)
40                         wpas_notify_network_changed(wpa_s);
41         }
42         wpa_supplicant_initiate_eapol(wpa_s);
43         wpa_dbg(wpa_s, MSG_DEBUG, "Already associated with a configured "
44                 "network - generating associated event");
45         os_memset(&data, 0, sizeof(data));
46         wpa_supplicant_event(wpa_s, EVENT_ASSOC, &data);
47 }
48
49
50 #ifdef CONFIG_WPS
51 static int wpas_wps_in_use(struct wpa_supplicant *wpa_s,
52                            enum wps_request_type *req_type)
53 {
54         struct wpa_ssid *ssid;
55         int wps = 0;
56
57         for (ssid = wpa_s->conf->ssid; ssid; ssid = ssid->next) {
58                 if (!(ssid->key_mgmt & WPA_KEY_MGMT_WPS))
59                         continue;
60
61                 wps = 1;
62                 *req_type = wpas_wps_get_req_type(ssid);
63                 if (!ssid->eap.phase1)
64                         continue;
65
66                 if (os_strstr(ssid->eap.phase1, "pbc=1"))
67                         return 2;
68         }
69
70 #ifdef CONFIG_P2P
71         if (!wpa_s->global->p2p_disabled && wpa_s->global->p2p &&
72             !wpa_s->conf->p2p_disabled) {
73                 wpa_s->wps->dev.p2p = 1;
74                 if (!wps) {
75                         wps = 1;
76                         *req_type = WPS_REQ_ENROLLEE_INFO;
77                 }
78         }
79 #endif /* CONFIG_P2P */
80
81         return wps;
82 }
83 #endif /* CONFIG_WPS */
84
85
86 /**
87  * wpa_supplicant_enabled_networks - Check whether there are enabled networks
88  * @wpa_s: Pointer to wpa_supplicant data
89  * Returns: 0 if no networks are enabled, >0 if networks are enabled
90  *
91  * This function is used to figure out whether any networks (or Interworking
92  * with enabled credentials and auto_interworking) are present in the current
93  * configuration.
94  */
95 int wpa_supplicant_enabled_networks(struct wpa_supplicant *wpa_s)
96 {
97         struct wpa_ssid *ssid = wpa_s->conf->ssid;
98         int count = 0, disabled = 0;
99         while (ssid) {
100                 if (!wpas_network_disabled(wpa_s, ssid))
101                         count++;
102                 else
103                         disabled++;
104                 ssid = ssid->next;
105         }
106         if (wpa_s->conf->cred && wpa_s->conf->interworking &&
107             wpa_s->conf->auto_interworking)
108                 count++;
109         if (count == 0 && disabled > 0) {
110                 wpa_dbg(wpa_s, MSG_DEBUG, "No enabled networks (%d disabled "
111                         "networks)", disabled);
112         }
113         return count;
114 }
115
116
117 static void wpa_supplicant_assoc_try(struct wpa_supplicant *wpa_s,
118                                      struct wpa_ssid *ssid)
119 {
120         while (ssid) {
121                 if (!wpas_network_disabled(wpa_s, ssid))
122                         break;
123                 ssid = ssid->next;
124         }
125
126         /* ap_scan=2 mode - try to associate with each SSID. */
127         if (ssid == NULL) {
128                 wpa_dbg(wpa_s, MSG_DEBUG, "wpa_supplicant_assoc_try: Reached "
129                         "end of scan list - go back to beginning");
130                 wpa_s->prev_scan_ssid = WILDCARD_SSID_SCAN;
131                 wpa_supplicant_req_scan(wpa_s, 0, 0);
132                 return;
133         }
134         if (ssid->next) {
135                 /* Continue from the next SSID on the next attempt. */
136                 wpa_s->prev_scan_ssid = ssid;
137         } else {
138                 /* Start from the beginning of the SSID list. */
139                 wpa_s->prev_scan_ssid = WILDCARD_SSID_SCAN;
140         }
141         wpa_supplicant_associate(wpa_s, NULL, ssid);
142 }
143
144
145 /**
146  * wpa_supplicant_trigger_scan - Request driver to start a scan
147  * @wpa_s: Pointer to wpa_supplicant data
148  * @params: Scan parameters
149  * Returns: 0 on success, -1 on failure
150  */
151 int wpa_supplicant_trigger_scan(struct wpa_supplicant *wpa_s,
152                                 struct wpa_driver_scan_params *params)
153 {
154         int ret;
155
156         wpa_supplicant_notify_scanning(wpa_s, 1);
157
158         ret = wpa_drv_scan(wpa_s, params);
159         if (ret) {
160                 wpa_supplicant_notify_scanning(wpa_s, 0);
161                 wpas_notify_scan_done(wpa_s, 0);
162         } else {
163                 os_get_reltime(&wpa_s->scan_trigger_time);
164                 wpa_s->scan_runs++;
165                 wpa_s->normal_scans++;
166         }
167
168         return ret;
169 }
170
171
172 static void
173 wpa_supplicant_delayed_sched_scan_timeout(void *eloop_ctx, void *timeout_ctx)
174 {
175         struct wpa_supplicant *wpa_s = eloop_ctx;
176
177         wpa_dbg(wpa_s, MSG_DEBUG, "Starting delayed sched scan");
178
179         if (wpa_supplicant_req_sched_scan(wpa_s))
180                 wpa_supplicant_req_scan(wpa_s, 0, 0);
181 }
182
183
184 static void
185 wpa_supplicant_sched_scan_timeout(void *eloop_ctx, void *timeout_ctx)
186 {
187         struct wpa_supplicant *wpa_s = eloop_ctx;
188
189         wpa_dbg(wpa_s, MSG_DEBUG, "Sched scan timeout - stopping it");
190
191         wpa_s->sched_scan_timed_out = 1;
192         wpa_supplicant_cancel_sched_scan(wpa_s);
193 }
194
195
196 int wpa_supplicant_start_sched_scan(struct wpa_supplicant *wpa_s,
197                                     struct wpa_driver_scan_params *params,
198                                     int interval)
199 {
200         int ret;
201
202         wpa_supplicant_notify_scanning(wpa_s, 1);
203         ret = wpa_drv_sched_scan(wpa_s, params, interval * 1000);
204         if (ret)
205                 wpa_supplicant_notify_scanning(wpa_s, 0);
206         else
207                 wpa_s->sched_scanning = 1;
208
209         return ret;
210 }
211
212
213 int wpa_supplicant_stop_sched_scan(struct wpa_supplicant *wpa_s)
214 {
215         int ret;
216
217         ret = wpa_drv_stop_sched_scan(wpa_s);
218         if (ret) {
219                 wpa_dbg(wpa_s, MSG_DEBUG, "stopping sched_scan failed!");
220                 /* TODO: what to do if stopping fails? */
221                 return -1;
222         }
223
224         return ret;
225 }
226
227
228 static struct wpa_driver_scan_filter *
229 wpa_supplicant_build_filter_ssids(struct wpa_config *conf, size_t *num_ssids)
230 {
231         struct wpa_driver_scan_filter *ssids;
232         struct wpa_ssid *ssid;
233         size_t count;
234
235         *num_ssids = 0;
236         if (!conf->filter_ssids)
237                 return NULL;
238
239         for (count = 0, ssid = conf->ssid; ssid; ssid = ssid->next) {
240                 if (ssid->ssid && ssid->ssid_len)
241                         count++;
242         }
243         if (count == 0)
244                 return NULL;
245         ssids = os_zalloc(count * sizeof(struct wpa_driver_scan_filter));
246         if (ssids == NULL)
247                 return NULL;
248
249         for (ssid = conf->ssid; ssid; ssid = ssid->next) {
250                 if (!ssid->ssid || !ssid->ssid_len)
251                         continue;
252                 os_memcpy(ssids[*num_ssids].ssid, ssid->ssid, ssid->ssid_len);
253                 ssids[*num_ssids].ssid_len = ssid->ssid_len;
254                 (*num_ssids)++;
255         }
256
257         return ssids;
258 }
259
260
261 static void wpa_supplicant_optimize_freqs(
262         struct wpa_supplicant *wpa_s, struct wpa_driver_scan_params *params)
263 {
264 #ifdef CONFIG_P2P
265         if (params->freqs == NULL && wpa_s->p2p_in_provisioning &&
266             wpa_s->go_params) {
267                 /* Optimize provisioning state scan based on GO information */
268                 if (wpa_s->p2p_in_provisioning < 5 &&
269                     wpa_s->go_params->freq > 0) {
270                         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Scan only GO "
271                                 "preferred frequency %d MHz",
272                                 wpa_s->go_params->freq);
273                         params->freqs = os_zalloc(2 * sizeof(int));
274                         if (params->freqs)
275                                 params->freqs[0] = wpa_s->go_params->freq;
276                 } else if (wpa_s->p2p_in_provisioning < 8 &&
277                            wpa_s->go_params->freq_list[0]) {
278                         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Scan only common "
279                                 "channels");
280                         int_array_concat(&params->freqs,
281                                          wpa_s->go_params->freq_list);
282                         if (params->freqs)
283                                 int_array_sort_unique(params->freqs);
284                 }
285                 wpa_s->p2p_in_provisioning++;
286         }
287 #endif /* CONFIG_P2P */
288
289 #ifdef CONFIG_WPS
290         if (params->freqs == NULL && wpa_s->after_wps && wpa_s->wps_freq) {
291                 /*
292                  * Optimize post-provisioning scan based on channel used
293                  * during provisioning.
294                  */
295                 wpa_dbg(wpa_s, MSG_DEBUG, "WPS: Scan only frequency %u MHz "
296                         "that was used during provisioning", wpa_s->wps_freq);
297                 params->freqs = os_zalloc(2 * sizeof(int));
298                 if (params->freqs)
299                         params->freqs[0] = wpa_s->wps_freq;
300                 wpa_s->after_wps--;
301         }
302
303         if (params->freqs == NULL && wpa_s->known_wps_freq && wpa_s->wps_freq)
304         {
305                 /* Optimize provisioning scan based on already known channel */
306                 wpa_dbg(wpa_s, MSG_DEBUG, "WPS: Scan only frequency %u MHz",
307                         wpa_s->wps_freq);
308                 params->freqs = os_zalloc(2 * sizeof(int));
309                 if (params->freqs)
310                         params->freqs[0] = wpa_s->wps_freq;
311                 wpa_s->known_wps_freq = 0; /* only do this once */
312         }
313 #endif /* CONFIG_WPS */
314 }
315
316
317 #ifdef CONFIG_INTERWORKING
318 static void wpas_add_interworking_elements(struct wpa_supplicant *wpa_s,
319                                            struct wpabuf *buf)
320 {
321         if (wpa_s->conf->interworking == 0)
322                 return;
323
324         wpabuf_put_u8(buf, WLAN_EID_EXT_CAPAB);
325         wpabuf_put_u8(buf, 4);
326         wpabuf_put_u8(buf, 0x00);
327         wpabuf_put_u8(buf, 0x00);
328         wpabuf_put_u8(buf, 0x00);
329         wpabuf_put_u8(buf, 0x80); /* Bit 31 - Interworking */
330
331         wpabuf_put_u8(buf, WLAN_EID_INTERWORKING);
332         wpabuf_put_u8(buf, is_zero_ether_addr(wpa_s->conf->hessid) ? 1 :
333                       1 + ETH_ALEN);
334         wpabuf_put_u8(buf, wpa_s->conf->access_network_type);
335         /* No Venue Info */
336         if (!is_zero_ether_addr(wpa_s->conf->hessid))
337                 wpabuf_put_data(buf, wpa_s->conf->hessid, ETH_ALEN);
338 }
339 #endif /* CONFIG_INTERWORKING */
340
341
342 static struct wpabuf * wpa_supplicant_extra_ies(struct wpa_supplicant *wpa_s)
343 {
344         struct wpabuf *extra_ie = NULL;
345 #ifdef CONFIG_WPS
346         int wps = 0;
347         enum wps_request_type req_type = WPS_REQ_ENROLLEE_INFO;
348 #endif /* CONFIG_WPS */
349
350 #ifdef CONFIG_INTERWORKING
351         if (wpa_s->conf->interworking &&
352             wpabuf_resize(&extra_ie, 100) == 0)
353                 wpas_add_interworking_elements(wpa_s, extra_ie);
354 #endif /* CONFIG_INTERWORKING */
355
356 #ifdef CONFIG_WPS
357         wps = wpas_wps_in_use(wpa_s, &req_type);
358
359         if (wps) {
360                 struct wpabuf *wps_ie;
361                 wps_ie = wps_build_probe_req_ie(wps == 2 ? DEV_PW_PUSHBUTTON :
362                                                 DEV_PW_DEFAULT,
363                                                 &wpa_s->wps->dev,
364                                                 wpa_s->wps->uuid, req_type,
365                                                 0, NULL);
366                 if (wps_ie) {
367                         if (wpabuf_resize(&extra_ie, wpabuf_len(wps_ie)) == 0)
368                                 wpabuf_put_buf(extra_ie, wps_ie);
369                         wpabuf_free(wps_ie);
370                 }
371         }
372
373 #ifdef CONFIG_P2P
374         if (wps) {
375                 size_t ielen = p2p_scan_ie_buf_len(wpa_s->global->p2p);
376                 if (wpabuf_resize(&extra_ie, ielen) == 0)
377                         wpas_p2p_scan_ie(wpa_s, extra_ie);
378         }
379 #endif /* CONFIG_P2P */
380
381 #endif /* CONFIG_WPS */
382
383 #ifdef CONFIG_HS20
384         if (wpa_s->conf->hs20 && wpabuf_resize(&extra_ie, 7) == 0)
385                 wpas_hs20_add_indication(extra_ie);
386 #endif /* CONFIG_HS20 */
387
388         return extra_ie;
389 }
390
391
392 #ifdef CONFIG_P2P
393
394 /*
395  * Check whether there are any enabled networks or credentials that could be
396  * used for a non-P2P connection.
397  */
398 static int non_p2p_network_enabled(struct wpa_supplicant *wpa_s)
399 {
400         struct wpa_ssid *ssid;
401
402         for (ssid = wpa_s->conf->ssid; ssid; ssid = ssid->next) {
403                 if (wpas_network_disabled(wpa_s, ssid))
404                         continue;
405                 if (!ssid->p2p_group)
406                         return 1;
407         }
408
409         if (wpa_s->conf->cred && wpa_s->conf->interworking &&
410             wpa_s->conf->auto_interworking)
411                 return 1;
412
413         return 0;
414 }
415
416 #endif /* CONFIG_P2P */
417
418
419 static struct hostapd_hw_modes * get_mode(struct hostapd_hw_modes *modes,
420                                           u16 num_modes,
421                                           enum hostapd_hw_mode mode)
422 {
423         u16 i;
424
425         for (i = 0; i < num_modes; i++) {
426                 if (modes[i].mode == mode)
427                         return &modes[i];
428         }
429
430         return NULL;
431 }
432
433
434 static void wpa_setband_scan_freqs_list(struct wpa_supplicant *wpa_s,
435                                         enum hostapd_hw_mode band,
436                                         struct wpa_driver_scan_params *params)
437 {
438         /* Include only supported channels for the specified band */
439         struct hostapd_hw_modes *mode;
440         int count, i;
441
442         mode = get_mode(wpa_s->hw.modes, wpa_s->hw.num_modes, band);
443         if (mode == NULL) {
444                 /* No channels supported in this band - use empty list */
445                 params->freqs = os_zalloc(sizeof(int));
446                 return;
447         }
448
449         params->freqs = os_zalloc((mode->num_channels + 1) * sizeof(int));
450         if (params->freqs == NULL)
451                 return;
452         for (count = 0, i = 0; i < mode->num_channels; i++) {
453                 if (mode->channels[i].flag & HOSTAPD_CHAN_DISABLED)
454                         continue;
455                 params->freqs[count++] = mode->channels[i].freq;
456         }
457 }
458
459
460 static void wpa_setband_scan_freqs(struct wpa_supplicant *wpa_s,
461                                    struct wpa_driver_scan_params *params)
462 {
463         if (wpa_s->hw.modes == NULL)
464                 return; /* unknown what channels the driver supports */
465         if (params->freqs)
466                 return; /* already using a limited channel set */
467         if (wpa_s->setband == WPA_SETBAND_5G)
468                 wpa_setband_scan_freqs_list(wpa_s, HOSTAPD_MODE_IEEE80211A,
469                                             params);
470         else if (wpa_s->setband == WPA_SETBAND_2G)
471                 wpa_setband_scan_freqs_list(wpa_s, HOSTAPD_MODE_IEEE80211G,
472                                             params);
473 }
474
475
476 static void wpa_supplicant_scan(void *eloop_ctx, void *timeout_ctx)
477 {
478         struct wpa_supplicant *wpa_s = eloop_ctx;
479         struct wpa_ssid *ssid;
480         int ret;
481         struct wpabuf *extra_ie = NULL;
482         struct wpa_driver_scan_params params;
483         struct wpa_driver_scan_params *scan_params;
484         size_t max_ssids;
485         enum wpa_states prev_state;
486
487         if (wpa_s->wpa_state == WPA_INTERFACE_DISABLED) {
488                 wpa_dbg(wpa_s, MSG_DEBUG, "Skip scan - interface disabled");
489                 wpas_p2p_continue_after_scan(wpa_s);
490                 return;
491         }
492
493         if (wpa_s->disconnected && wpa_s->scan_req == NORMAL_SCAN_REQ) {
494                 wpa_dbg(wpa_s, MSG_DEBUG, "Disconnected - do not scan");
495                 wpa_supplicant_set_state(wpa_s, WPA_DISCONNECTED);
496                 wpas_p2p_continue_after_scan(wpa_s);
497                 return;
498         }
499
500         if (wpa_s->scanning) {
501                 /*
502                  * If we are already in scanning state, we shall reschedule the
503                  * the incoming scan request.
504                  */
505                 wpa_dbg(wpa_s, MSG_DEBUG, "Already scanning - Reschedule the incoming scan req");
506                 wpa_supplicant_req_scan(wpa_s, 1, 0);
507                 return;
508         }
509
510         if (!wpa_supplicant_enabled_networks(wpa_s) &&
511             wpa_s->scan_req == NORMAL_SCAN_REQ) {
512                 wpa_dbg(wpa_s, MSG_DEBUG, "No enabled networks - do not scan");
513                 wpa_supplicant_set_state(wpa_s, WPA_INACTIVE);
514                 wpas_p2p_continue_after_scan(wpa_s);
515                 return;
516         }
517
518         if (wpa_s->conf->ap_scan != 0 &&
519             (wpa_s->drv_flags & WPA_DRIVER_FLAGS_WIRED)) {
520                 wpa_dbg(wpa_s, MSG_DEBUG, "Using wired authentication - "
521                         "overriding ap_scan configuration");
522                 wpa_s->conf->ap_scan = 0;
523                 wpas_notify_ap_scan_changed(wpa_s);
524         }
525
526         if (wpa_s->conf->ap_scan == 0) {
527                 wpa_supplicant_gen_assoc_event(wpa_s);
528                 return;
529         }
530
531 #ifdef CONFIG_P2P
532         if (wpas_p2p_in_progress(wpa_s) || wpas_wpa_is_in_progress(wpa_s, 0)) {
533                 if (wpa_s->sta_scan_pending &&
534                     wpas_p2p_in_progress(wpa_s) == 2 &&
535                     wpa_s->global->p2p_cb_on_scan_complete) {
536                         wpa_dbg(wpa_s, MSG_DEBUG, "Process pending station "
537                                 "mode scan during P2P search");
538                 } else {
539                         wpa_dbg(wpa_s, MSG_DEBUG, "Delay station mode scan "
540                                 "while P2P operation is in progress");
541                         wpa_s->sta_scan_pending = 1;
542                         wpa_supplicant_req_scan(wpa_s, 5, 0);
543                         return;
544                 }
545         }
546 #endif /* CONFIG_P2P */
547
548 #ifdef CONFIG_GAS
549         if (gas_query_in_progress(wpa_s->gas)) {
550                 wpa_dbg(wpa_s, MSG_DEBUG, "Delay scan while GAS query is in progress");
551                 wpa_supplicant_req_scan(wpa_s, 1, 0);
552                 return;
553         }
554 #endif /* CONFIG_GAS */
555
556         if (wpa_s->conf->ap_scan == 2)
557                 max_ssids = 1;
558         else {
559                 max_ssids = wpa_s->max_scan_ssids;
560                 if (max_ssids > WPAS_MAX_SCAN_SSIDS)
561                         max_ssids = WPAS_MAX_SCAN_SSIDS;
562         }
563
564         wpa_s->last_scan_req = wpa_s->scan_req;
565         wpa_s->scan_req = NORMAL_SCAN_REQ;
566
567         os_memset(&params, 0, sizeof(params));
568
569         prev_state = wpa_s->wpa_state;
570         if (wpa_s->wpa_state == WPA_DISCONNECTED ||
571             wpa_s->wpa_state == WPA_INACTIVE)
572                 wpa_supplicant_set_state(wpa_s, WPA_SCANNING);
573
574         /*
575          * If autoscan has set its own scanning parameters
576          */
577         if (wpa_s->autoscan_params != NULL) {
578                 scan_params = wpa_s->autoscan_params;
579                 goto scan;
580         }
581
582         if (wpa_s->last_scan_req != MANUAL_SCAN_REQ &&
583             wpa_s->connect_without_scan) {
584                 for (ssid = wpa_s->conf->ssid; ssid; ssid = ssid->next) {
585                         if (ssid == wpa_s->connect_without_scan)
586                                 break;
587                 }
588                 wpa_s->connect_without_scan = NULL;
589                 if (ssid) {
590                         wpa_printf(MSG_DEBUG, "Start a pre-selected network "
591                                    "without scan step");
592                         wpa_supplicant_associate(wpa_s, NULL, ssid);
593                         return;
594                 }
595         }
596
597 #ifdef CONFIG_P2P
598         if ((wpa_s->p2p_in_provisioning || wpa_s->show_group_started) &&
599             wpa_s->go_params) {
600                 wpa_printf(MSG_DEBUG, "P2P: Use specific SSID for scan during P2P group formation (p2p_in_provisioning=%d show_group_started=%d)",
601                            wpa_s->p2p_in_provisioning,
602                            wpa_s->show_group_started);
603                 params.ssids[0].ssid = wpa_s->go_params->ssid;
604                 params.ssids[0].ssid_len = wpa_s->go_params->ssid_len;
605                 params.num_ssids = 1;
606                 goto ssid_list_set;
607         }
608 #endif /* CONFIG_P2P */
609
610         /* Find the starting point from which to continue scanning */
611         ssid = wpa_s->conf->ssid;
612         if (wpa_s->prev_scan_ssid != WILDCARD_SSID_SCAN) {
613                 while (ssid) {
614                         if (ssid == wpa_s->prev_scan_ssid) {
615                                 ssid = ssid->next;
616                                 break;
617                         }
618                         ssid = ssid->next;
619                 }
620         }
621
622         if (wpa_s->last_scan_req != MANUAL_SCAN_REQ &&
623             wpa_s->conf->ap_scan == 2) {
624                 wpa_s->connect_without_scan = NULL;
625                 wpa_s->prev_scan_wildcard = 0;
626                 wpa_supplicant_assoc_try(wpa_s, ssid);
627                 return;
628         } else if (wpa_s->conf->ap_scan == 2) {
629                 /*
630                  * User-initiated scan request in ap_scan == 2; scan with
631                  * wildcard SSID.
632                  */
633                 ssid = NULL;
634         } else {
635                 struct wpa_ssid *start = ssid, *tssid;
636                 int freqs_set = 0;
637                 if (ssid == NULL && max_ssids > 1)
638                         ssid = wpa_s->conf->ssid;
639                 while (ssid) {
640                         if (!wpas_network_disabled(wpa_s, ssid) &&
641                             ssid->scan_ssid) {
642                                 wpa_hexdump_ascii(MSG_DEBUG, "Scan SSID",
643                                                   ssid->ssid, ssid->ssid_len);
644                                 params.ssids[params.num_ssids].ssid =
645                                         ssid->ssid;
646                                 params.ssids[params.num_ssids].ssid_len =
647                                         ssid->ssid_len;
648                                 params.num_ssids++;
649                                 if (params.num_ssids + 1 >= max_ssids)
650                                         break;
651                         }
652                         ssid = ssid->next;
653                         if (ssid == start)
654                                 break;
655                         if (ssid == NULL && max_ssids > 1 &&
656                             start != wpa_s->conf->ssid)
657                                 ssid = wpa_s->conf->ssid;
658                 }
659
660                 for (tssid = wpa_s->conf->ssid; tssid; tssid = tssid->next) {
661                         if (wpas_network_disabled(wpa_s, tssid))
662                                 continue;
663                         if ((params.freqs || !freqs_set) && tssid->scan_freq) {
664                                 int_array_concat(&params.freqs,
665                                                  tssid->scan_freq);
666                         } else {
667                                 os_free(params.freqs);
668                                 params.freqs = NULL;
669                         }
670                         freqs_set = 1;
671                 }
672                 int_array_sort_unique(params.freqs);
673         }
674
675         if (ssid && max_ssids == 1) {
676                 /*
677                  * If the driver is limited to 1 SSID at a time interleave
678                  * wildcard SSID scans with specific SSID scans to avoid
679                  * waiting a long time for a wildcard scan.
680                  */
681                 if (!wpa_s->prev_scan_wildcard) {
682                         params.ssids[0].ssid = NULL;
683                         params.ssids[0].ssid_len = 0;
684                         wpa_s->prev_scan_wildcard = 1;
685                         wpa_dbg(wpa_s, MSG_DEBUG, "Starting AP scan for "
686                                 "wildcard SSID (Interleave with specific)");
687                 } else {
688                         wpa_s->prev_scan_ssid = ssid;
689                         wpa_s->prev_scan_wildcard = 0;
690                         wpa_dbg(wpa_s, MSG_DEBUG,
691                                 "Starting AP scan for specific SSID: %s",
692                                 wpa_ssid_txt(ssid->ssid, ssid->ssid_len));
693                 }
694         } else if (ssid) {
695                 /* max_ssids > 1 */
696
697                 wpa_s->prev_scan_ssid = ssid;
698                 wpa_dbg(wpa_s, MSG_DEBUG, "Include wildcard SSID in "
699                         "the scan request");
700                 params.num_ssids++;
701         } else if (wpa_s->last_scan_req == MANUAL_SCAN_REQ &&
702                    wpa_s->manual_scan_passive && params.num_ssids == 0) {
703                 wpa_dbg(wpa_s, MSG_DEBUG, "Use passive scan based on manual request");
704         } else {
705                 wpa_s->prev_scan_ssid = WILDCARD_SSID_SCAN;
706                 params.num_ssids++;
707                 wpa_dbg(wpa_s, MSG_DEBUG, "Starting AP scan for wildcard "
708                         "SSID");
709         }
710 #ifdef CONFIG_P2P
711 ssid_list_set:
712 #endif /* CONFIG_P2P */
713
714         wpa_supplicant_optimize_freqs(wpa_s, &params);
715         extra_ie = wpa_supplicant_extra_ies(wpa_s);
716
717         if (wpa_s->last_scan_req == MANUAL_SCAN_REQ && params.freqs == NULL &&
718             wpa_s->manual_scan_freqs) {
719                 wpa_dbg(wpa_s, MSG_DEBUG, "Limit manual scan to specified channels");
720                 params.freqs = wpa_s->manual_scan_freqs;
721                 wpa_s->manual_scan_freqs = NULL;
722         }
723
724         if (params.freqs == NULL && wpa_s->next_scan_freqs) {
725                 wpa_dbg(wpa_s, MSG_DEBUG, "Optimize scan based on previously "
726                         "generated frequency list");
727                 params.freqs = wpa_s->next_scan_freqs;
728         } else
729                 os_free(wpa_s->next_scan_freqs);
730         wpa_s->next_scan_freqs = NULL;
731         wpa_setband_scan_freqs(wpa_s, &params);
732
733         /* See if user specified frequencies. If so, scan only those. */
734         if (wpa_s->conf->freq_list && !params.freqs) {
735                 wpa_dbg(wpa_s, MSG_DEBUG,
736                         "Optimize scan based on conf->freq_list");
737                 int_array_concat(&params.freqs, wpa_s->conf->freq_list);
738         }
739
740         /* Use current associated channel? */
741         if (wpa_s->conf->scan_cur_freq && !params.freqs) {
742                 unsigned int num = wpa_s->num_multichan_concurrent;
743
744                 params.freqs = os_calloc(num + 1, sizeof(int));
745                 if (params.freqs) {
746                         num = get_shared_radio_freqs(wpa_s, params.freqs, num);
747                         if (num > 0) {
748                                 wpa_dbg(wpa_s, MSG_DEBUG, "Scan only the "
749                                         "current operating channels since "
750                                         "scan_cur_freq is enabled");
751                         } else {
752                                 os_free(params.freqs);
753                                 params.freqs = NULL;
754                         }
755                 }
756         }
757
758         params.filter_ssids = wpa_supplicant_build_filter_ssids(
759                 wpa_s->conf, &params.num_filter_ssids);
760         if (extra_ie) {
761                 params.extra_ies = wpabuf_head(extra_ie);
762                 params.extra_ies_len = wpabuf_len(extra_ie);
763         }
764
765 #ifdef CONFIG_P2P
766         if (wpa_s->p2p_in_provisioning ||
767             (wpa_s->show_group_started && wpa_s->go_params)) {
768                 /*
769                  * The interface may not yet be in P2P mode, so we have to
770                  * explicitly request P2P probe to disable CCK rates.
771                  */
772                 params.p2p_probe = 1;
773         }
774 #endif /* CONFIG_P2P */
775
776         scan_params = &params;
777
778 scan:
779 #ifdef CONFIG_P2P
780         /*
781          * If the driver does not support multi-channel concurrency and a
782          * virtual interface that shares the same radio with the wpa_s interface
783          * is operating there may not be need to scan other channels apart from
784          * the current operating channel on the other virtual interface. Filter
785          * out other channels in case we are trying to find a connection for a
786          * station interface when we are not configured to prefer station
787          * connection and a concurrent operation is already in process.
788          */
789         if (wpa_s->scan_for_connection &&
790             wpa_s->last_scan_req == NORMAL_SCAN_REQ &&
791             !scan_params->freqs && !params.freqs &&
792             wpas_is_p2p_prioritized(wpa_s) &&
793             wpa_s->p2p_group_interface == NOT_P2P_GROUP_INTERFACE &&
794             non_p2p_network_enabled(wpa_s)) {
795                 unsigned int num = wpa_s->num_multichan_concurrent;
796
797                 params.freqs = os_calloc(num + 1, sizeof(int));
798                 if (params.freqs) {
799                         num = get_shared_radio_freqs(wpa_s, params.freqs, num);
800                         if (num > 0 && num == wpa_s->num_multichan_concurrent) {
801                                 wpa_dbg(wpa_s, MSG_DEBUG, "Scan only the current operating channels since all channels are already used");
802                         } else {
803                                 os_free(params.freqs);
804                                 params.freqs = NULL;
805                         }
806                 }
807         }
808 #endif /* CONFIG_P2P */
809
810         ret = wpa_supplicant_trigger_scan(wpa_s, scan_params);
811
812         if (ret && wpa_s->last_scan_req == MANUAL_SCAN_REQ && params.freqs &&
813             !wpa_s->manual_scan_freqs) {
814                 /* Restore manual_scan_freqs for the next attempt */
815                 wpa_s->manual_scan_freqs = params.freqs;
816                 params.freqs = NULL;
817         }
818
819         wpabuf_free(extra_ie);
820         os_free(params.freqs);
821         os_free(params.filter_ssids);
822
823         if (ret) {
824                 wpa_msg(wpa_s, MSG_WARNING, "Failed to initiate AP scan");
825                 if (prev_state != wpa_s->wpa_state)
826                         wpa_supplicant_set_state(wpa_s, prev_state);
827                 /* Restore scan_req since we will try to scan again */
828                 wpa_s->scan_req = wpa_s->last_scan_req;
829                 wpa_supplicant_req_scan(wpa_s, 1, 0);
830         } else {
831                 wpa_s->scan_for_connection = 0;
832         }
833 }
834
835
836 void wpa_supplicant_update_scan_int(struct wpa_supplicant *wpa_s, int sec)
837 {
838         struct os_reltime remaining, new_int;
839         int cancelled;
840
841         cancelled = eloop_cancel_timeout_one(wpa_supplicant_scan, wpa_s, NULL,
842                                              &remaining);
843
844         new_int.sec = sec;
845         new_int.usec = 0;
846         if (cancelled && os_reltime_before(&remaining, &new_int)) {
847                 new_int.sec = remaining.sec;
848                 new_int.usec = remaining.usec;
849         }
850
851         if (cancelled) {
852                 eloop_register_timeout(new_int.sec, new_int.usec,
853                                        wpa_supplicant_scan, wpa_s, NULL);
854         }
855         wpa_s->scan_interval = sec;
856 }
857
858
859 /**
860  * wpa_supplicant_req_scan - Schedule a scan for neighboring access points
861  * @wpa_s: Pointer to wpa_supplicant data
862  * @sec: Number of seconds after which to scan
863  * @usec: Number of microseconds after which to scan
864  *
865  * This function is used to schedule a scan for neighboring access points after
866  * the specified time.
867  */
868 void wpa_supplicant_req_scan(struct wpa_supplicant *wpa_s, int sec, int usec)
869 {
870         if (eloop_deplete_timeout(sec, usec, wpa_supplicant_scan, wpa_s, NULL))
871         {
872                 wpa_dbg(wpa_s, MSG_DEBUG, "Rescheduling scan request: %d sec %d usec",
873                         sec, usec);
874                 return;
875         }
876
877         wpa_dbg(wpa_s, MSG_DEBUG, "Setting scan request: %d sec %d usec",
878                 sec, usec);
879         eloop_cancel_timeout(wpa_supplicant_scan, wpa_s, NULL);
880         eloop_register_timeout(sec, usec, wpa_supplicant_scan, wpa_s, NULL);
881 }
882
883
884 /**
885  * wpa_supplicant_delayed_sched_scan - Request a delayed scheduled scan
886  * @wpa_s: Pointer to wpa_supplicant data
887  * @sec: Number of seconds after which to scan
888  * @usec: Number of microseconds after which to scan
889  * Returns: 0 on success or -1 otherwise
890  *
891  * This function is used to schedule periodic scans for neighboring
892  * access points after the specified time.
893  */
894 int wpa_supplicant_delayed_sched_scan(struct wpa_supplicant *wpa_s,
895                                       int sec, int usec)
896 {
897         if (!wpa_s->sched_scan_supported)
898                 return -1;
899
900         eloop_register_timeout(sec, usec,
901                                wpa_supplicant_delayed_sched_scan_timeout,
902                                wpa_s, NULL);
903
904         return 0;
905 }
906
907
908 /**
909  * wpa_supplicant_req_sched_scan - Start a periodic scheduled scan
910  * @wpa_s: Pointer to wpa_supplicant data
911  * Returns: 0 is sched_scan was started or -1 otherwise
912  *
913  * This function is used to schedule periodic scans for neighboring
914  * access points repeating the scan continuously.
915  */
916 int wpa_supplicant_req_sched_scan(struct wpa_supplicant *wpa_s)
917 {
918         struct wpa_driver_scan_params params;
919         struct wpa_driver_scan_params *scan_params;
920         enum wpa_states prev_state;
921         struct wpa_ssid *ssid = NULL;
922         struct wpabuf *extra_ie = NULL;
923         int ret;
924         unsigned int max_sched_scan_ssids;
925         int wildcard = 0;
926         int need_ssids;
927
928         if (!wpa_s->sched_scan_supported)
929                 return -1;
930
931         if (wpa_s->max_sched_scan_ssids > WPAS_MAX_SCAN_SSIDS)
932                 max_sched_scan_ssids = WPAS_MAX_SCAN_SSIDS;
933         else
934                 max_sched_scan_ssids = wpa_s->max_sched_scan_ssids;
935         if (max_sched_scan_ssids < 1 || wpa_s->conf->disable_scan_offload)
936                 return -1;
937
938         if (wpa_s->sched_scanning) {
939                 wpa_dbg(wpa_s, MSG_DEBUG, "Already sched scanning");
940                 return 0;
941         }
942
943         need_ssids = 0;
944         for (ssid = wpa_s->conf->ssid; ssid; ssid = ssid->next) {
945                 if (!wpas_network_disabled(wpa_s, ssid) && !ssid->scan_ssid) {
946                         /* Use wildcard SSID to find this network */
947                         wildcard = 1;
948                 } else if (!wpas_network_disabled(wpa_s, ssid) &&
949                            ssid->ssid_len)
950                         need_ssids++;
951
952 #ifdef CONFIG_WPS
953                 if (!wpas_network_disabled(wpa_s, ssid) &&
954                     ssid->key_mgmt == WPA_KEY_MGMT_WPS) {
955                         /*
956                          * Normal scan is more reliable and faster for WPS
957                          * operations and since these are for short periods of
958                          * time, the benefit of trying to use sched_scan would
959                          * be limited.
960                          */
961                         wpa_dbg(wpa_s, MSG_DEBUG, "Use normal scan instead of "
962                                 "sched_scan for WPS");
963                         return -1;
964                 }
965 #endif /* CONFIG_WPS */
966         }
967         if (wildcard)
968                 need_ssids++;
969
970         if (wpa_s->normal_scans < 3 &&
971             (need_ssids <= wpa_s->max_scan_ssids ||
972              wpa_s->max_scan_ssids >= (int) max_sched_scan_ssids)) {
973                 /*
974                  * When normal scan can speed up operations, use that for the
975                  * first operations before starting the sched_scan to allow
976                  * user space sleep more. We do this only if the normal scan
977                  * has functionality that is suitable for this or if the
978                  * sched_scan does not have better support for multiple SSIDs.
979                  */
980                 wpa_dbg(wpa_s, MSG_DEBUG, "Use normal scan instead of "
981                         "sched_scan for initial scans (normal_scans=%d)",
982                         wpa_s->normal_scans);
983                 return -1;
984         }
985
986         os_memset(&params, 0, sizeof(params));
987
988         /* If we can't allocate space for the filters, we just don't filter */
989         params.filter_ssids = os_zalloc(wpa_s->max_match_sets *
990                                         sizeof(struct wpa_driver_scan_filter));
991
992         prev_state = wpa_s->wpa_state;
993         if (wpa_s->wpa_state == WPA_DISCONNECTED ||
994             wpa_s->wpa_state == WPA_INACTIVE)
995                 wpa_supplicant_set_state(wpa_s, WPA_SCANNING);
996
997         if (wpa_s->autoscan_params != NULL) {
998                 scan_params = wpa_s->autoscan_params;
999                 goto scan;
1000         }
1001
1002         /* Find the starting point from which to continue scanning */
1003         ssid = wpa_s->conf->ssid;
1004         if (wpa_s->prev_sched_ssid) {
1005                 while (ssid) {
1006                         if (ssid == wpa_s->prev_sched_ssid) {
1007                                 ssid = ssid->next;
1008                                 break;
1009                         }
1010                         ssid = ssid->next;
1011                 }
1012         }
1013
1014         if (!ssid || !wpa_s->prev_sched_ssid) {
1015                 wpa_dbg(wpa_s, MSG_DEBUG, "Beginning of SSID list");
1016                 if (wpa_s->conf->sched_scan_interval)
1017                         wpa_s->sched_scan_interval =
1018                                 wpa_s->conf->sched_scan_interval;
1019                 if (wpa_s->sched_scan_interval == 0)
1020                         wpa_s->sched_scan_interval = 10;
1021                 wpa_s->sched_scan_timeout = max_sched_scan_ssids * 2;
1022                 wpa_s->first_sched_scan = 1;
1023                 ssid = wpa_s->conf->ssid;
1024                 wpa_s->prev_sched_ssid = ssid;
1025         }
1026
1027         if (wildcard) {
1028                 wpa_dbg(wpa_s, MSG_DEBUG, "Add wildcard SSID to sched_scan");
1029                 params.num_ssids++;
1030         }
1031
1032         while (ssid) {
1033                 if (wpas_network_disabled(wpa_s, ssid))
1034                         goto next;
1035
1036                 if (params.num_filter_ssids < wpa_s->max_match_sets &&
1037                     params.filter_ssids && ssid->ssid && ssid->ssid_len) {
1038                         wpa_dbg(wpa_s, MSG_DEBUG, "add to filter ssid: %s",
1039                                 wpa_ssid_txt(ssid->ssid, ssid->ssid_len));
1040                         os_memcpy(params.filter_ssids[params.num_filter_ssids].ssid,
1041                                   ssid->ssid, ssid->ssid_len);
1042                         params.filter_ssids[params.num_filter_ssids].ssid_len =
1043                                 ssid->ssid_len;
1044                         params.num_filter_ssids++;
1045                 } else if (params.filter_ssids && ssid->ssid && ssid->ssid_len)
1046                 {
1047                         wpa_dbg(wpa_s, MSG_DEBUG, "Not enough room for SSID "
1048                                 "filter for sched_scan - drop filter");
1049                         os_free(params.filter_ssids);
1050                         params.filter_ssids = NULL;
1051                         params.num_filter_ssids = 0;
1052                 }
1053
1054                 if (ssid->scan_ssid && ssid->ssid && ssid->ssid_len) {
1055                         if (params.num_ssids == max_sched_scan_ssids)
1056                                 break; /* only room for broadcast SSID */
1057                         wpa_dbg(wpa_s, MSG_DEBUG,
1058                                 "add to active scan ssid: %s",
1059                                 wpa_ssid_txt(ssid->ssid, ssid->ssid_len));
1060                         params.ssids[params.num_ssids].ssid =
1061                                 ssid->ssid;
1062                         params.ssids[params.num_ssids].ssid_len =
1063                                 ssid->ssid_len;
1064                         params.num_ssids++;
1065                         if (params.num_ssids >= max_sched_scan_ssids) {
1066                                 wpa_s->prev_sched_ssid = ssid;
1067                                 do {
1068                                         ssid = ssid->next;
1069                                 } while (ssid &&
1070                                          (wpas_network_disabled(wpa_s, ssid) ||
1071                                           !ssid->scan_ssid));
1072                                 break;
1073                         }
1074                 }
1075
1076         next:
1077                 wpa_s->prev_sched_ssid = ssid;
1078                 ssid = ssid->next;
1079         }
1080
1081         if (params.num_filter_ssids == 0) {
1082                 os_free(params.filter_ssids);
1083                 params.filter_ssids = NULL;
1084         }
1085
1086         extra_ie = wpa_supplicant_extra_ies(wpa_s);
1087         if (extra_ie) {
1088                 params.extra_ies = wpabuf_head(extra_ie);
1089                 params.extra_ies_len = wpabuf_len(extra_ie);
1090         }
1091
1092         scan_params = &params;
1093
1094 scan:
1095         if (ssid || !wpa_s->first_sched_scan) {
1096                 wpa_dbg(wpa_s, MSG_DEBUG,
1097                         "Starting sched scan: interval %d timeout %d",
1098                         wpa_s->sched_scan_interval, wpa_s->sched_scan_timeout);
1099         } else {
1100                 wpa_dbg(wpa_s, MSG_DEBUG,
1101                         "Starting sched scan: interval %d (no timeout)",
1102                         wpa_s->sched_scan_interval);
1103         }
1104
1105         wpa_setband_scan_freqs(wpa_s, scan_params);
1106
1107         ret = wpa_supplicant_start_sched_scan(wpa_s, scan_params,
1108                                               wpa_s->sched_scan_interval);
1109         wpabuf_free(extra_ie);
1110         os_free(params.filter_ssids);
1111         if (ret) {
1112                 wpa_msg(wpa_s, MSG_WARNING, "Failed to initiate sched scan");
1113                 if (prev_state != wpa_s->wpa_state)
1114                         wpa_supplicant_set_state(wpa_s, prev_state);
1115                 return ret;
1116         }
1117
1118         /* If we have more SSIDs to scan, add a timeout so we scan them too */
1119         if (ssid || !wpa_s->first_sched_scan) {
1120                 wpa_s->sched_scan_timed_out = 0;
1121                 eloop_register_timeout(wpa_s->sched_scan_timeout, 0,
1122                                        wpa_supplicant_sched_scan_timeout,
1123                                        wpa_s, NULL);
1124                 wpa_s->first_sched_scan = 0;
1125                 wpa_s->sched_scan_timeout /= 2;
1126                 wpa_s->sched_scan_interval *= 2;
1127                 if (wpa_s->sched_scan_timeout < wpa_s->sched_scan_interval) {
1128                         wpa_s->sched_scan_interval = 10;
1129                         wpa_s->sched_scan_timeout = max_sched_scan_ssids * 2;
1130                 }
1131         }
1132
1133         /* If there is no more ssids, start next time from the beginning */
1134         if (!ssid)
1135                 wpa_s->prev_sched_ssid = NULL;
1136
1137         return 0;
1138 }
1139
1140
1141 /**
1142  * wpa_supplicant_cancel_scan - Cancel a scheduled scan request
1143  * @wpa_s: Pointer to wpa_supplicant data
1144  *
1145  * This function is used to cancel a scan request scheduled with
1146  * wpa_supplicant_req_scan().
1147  */
1148 void wpa_supplicant_cancel_scan(struct wpa_supplicant *wpa_s)
1149 {
1150         wpa_dbg(wpa_s, MSG_DEBUG, "Cancelling scan request");
1151         eloop_cancel_timeout(wpa_supplicant_scan, wpa_s, NULL);
1152         wpas_p2p_continue_after_scan(wpa_s);
1153 }
1154
1155
1156 /**
1157  * wpa_supplicant_cancel_delayed_sched_scan - Stop a delayed scheduled scan
1158  * @wpa_s: Pointer to wpa_supplicant data
1159  *
1160  * This function is used to stop a delayed scheduled scan.
1161  */
1162 void wpa_supplicant_cancel_delayed_sched_scan(struct wpa_supplicant *wpa_s)
1163 {
1164         if (!wpa_s->sched_scan_supported)
1165                 return;
1166
1167         wpa_dbg(wpa_s, MSG_DEBUG, "Cancelling delayed sched scan");
1168         eloop_cancel_timeout(wpa_supplicant_delayed_sched_scan_timeout,
1169                              wpa_s, NULL);
1170 }
1171
1172
1173 /**
1174  * wpa_supplicant_cancel_sched_scan - Stop running scheduled scans
1175  * @wpa_s: Pointer to wpa_supplicant data
1176  *
1177  * This function is used to stop a periodic scheduled scan.
1178  */
1179 void wpa_supplicant_cancel_sched_scan(struct wpa_supplicant *wpa_s)
1180 {
1181         if (!wpa_s->sched_scanning)
1182                 return;
1183
1184         wpa_dbg(wpa_s, MSG_DEBUG, "Cancelling sched scan");
1185         eloop_cancel_timeout(wpa_supplicant_sched_scan_timeout, wpa_s, NULL);
1186         wpa_supplicant_stop_sched_scan(wpa_s);
1187 }
1188
1189
1190 /**
1191  * wpa_supplicant_notify_scanning - Indicate possible scan state change
1192  * @wpa_s: Pointer to wpa_supplicant data
1193  * @scanning: Whether scanning is currently in progress
1194  *
1195  * This function is to generate scanning notifycations. It is called whenever
1196  * there may have been a change in scanning (scan started, completed, stopped).
1197  * wpas_notify_scanning() is called whenever the scanning state changed from the
1198  * previously notified state.
1199  */
1200 void wpa_supplicant_notify_scanning(struct wpa_supplicant *wpa_s,
1201                                     int scanning)
1202 {
1203         if (wpa_s->scanning != scanning) {
1204                 wpa_s->scanning = scanning;
1205                 wpas_notify_scanning(wpa_s);
1206         }
1207 }
1208
1209
1210 static int wpa_scan_get_max_rate(const struct wpa_scan_res *res)
1211 {
1212         int rate = 0;
1213         const u8 *ie;
1214         int i;
1215
1216         ie = wpa_scan_get_ie(res, WLAN_EID_SUPP_RATES);
1217         for (i = 0; ie && i < ie[1]; i++) {
1218                 if ((ie[i + 2] & 0x7f) > rate)
1219                         rate = ie[i + 2] & 0x7f;
1220         }
1221
1222         ie = wpa_scan_get_ie(res, WLAN_EID_EXT_SUPP_RATES);
1223         for (i = 0; ie && i < ie[1]; i++) {
1224                 if ((ie[i + 2] & 0x7f) > rate)
1225                         rate = ie[i + 2] & 0x7f;
1226         }
1227
1228         return rate;
1229 }
1230
1231
1232 /**
1233  * wpa_scan_get_ie - Fetch a specified information element from a scan result
1234  * @res: Scan result entry
1235  * @ie: Information element identitifier (WLAN_EID_*)
1236  * Returns: Pointer to the information element (id field) or %NULL if not found
1237  *
1238  * This function returns the first matching information element in the scan
1239  * result.
1240  */
1241 const u8 * wpa_scan_get_ie(const struct wpa_scan_res *res, u8 ie)
1242 {
1243         const u8 *end, *pos;
1244
1245         pos = (const u8 *) (res + 1);
1246         end = pos + res->ie_len;
1247
1248         while (pos + 1 < end) {
1249                 if (pos + 2 + pos[1] > end)
1250                         break;
1251                 if (pos[0] == ie)
1252                         return pos;
1253                 pos += 2 + pos[1];
1254         }
1255
1256         return NULL;
1257 }
1258
1259
1260 /**
1261  * wpa_scan_get_vendor_ie - Fetch vendor information element from a scan result
1262  * @res: Scan result entry
1263  * @vendor_type: Vendor type (four octets starting the IE payload)
1264  * Returns: Pointer to the information element (id field) or %NULL if not found
1265  *
1266  * This function returns the first matching information element in the scan
1267  * result.
1268  */
1269 const u8 * wpa_scan_get_vendor_ie(const struct wpa_scan_res *res,
1270                                   u32 vendor_type)
1271 {
1272         const u8 *end, *pos;
1273
1274         pos = (const u8 *) (res + 1);
1275         end = pos + res->ie_len;
1276
1277         while (pos + 1 < end) {
1278                 if (pos + 2 + pos[1] > end)
1279                         break;
1280                 if (pos[0] == WLAN_EID_VENDOR_SPECIFIC && pos[1] >= 4 &&
1281                     vendor_type == WPA_GET_BE32(&pos[2]))
1282                         return pos;
1283                 pos += 2 + pos[1];
1284         }
1285
1286         return NULL;
1287 }
1288
1289
1290 /**
1291  * wpa_scan_get_vendor_ie_beacon - Fetch vendor information from a scan result
1292  * @res: Scan result entry
1293  * @vendor_type: Vendor type (four octets starting the IE payload)
1294  * Returns: Pointer to the information element (id field) or %NULL if not found
1295  *
1296  * This function returns the first matching information element in the scan
1297  * result.
1298  *
1299  * This function is like wpa_scan_get_vendor_ie(), but uses IE buffer only
1300  * from Beacon frames instead of either Beacon or Probe Response frames.
1301  */
1302 const u8 * wpa_scan_get_vendor_ie_beacon(const struct wpa_scan_res *res,
1303                                          u32 vendor_type)
1304 {
1305         const u8 *end, *pos;
1306
1307         if (res->beacon_ie_len == 0)
1308                 return NULL;
1309
1310         pos = (const u8 *) (res + 1);
1311         pos += res->ie_len;
1312         end = pos + res->beacon_ie_len;
1313
1314         while (pos + 1 < end) {
1315                 if (pos + 2 + pos[1] > end)
1316                         break;
1317                 if (pos[0] == WLAN_EID_VENDOR_SPECIFIC && pos[1] >= 4 &&
1318                     vendor_type == WPA_GET_BE32(&pos[2]))
1319                         return pos;
1320                 pos += 2 + pos[1];
1321         }
1322
1323         return NULL;
1324 }
1325
1326
1327 /**
1328  * wpa_scan_get_vendor_ie_multi - Fetch vendor IE data from a scan result
1329  * @res: Scan result entry
1330  * @vendor_type: Vendor type (four octets starting the IE payload)
1331  * Returns: Pointer to the information element payload or %NULL if not found
1332  *
1333  * This function returns concatenated payload of possibly fragmented vendor
1334  * specific information elements in the scan result. The caller is responsible
1335  * for freeing the returned buffer.
1336  */
1337 struct wpabuf * wpa_scan_get_vendor_ie_multi(const struct wpa_scan_res *res,
1338                                              u32 vendor_type)
1339 {
1340         struct wpabuf *buf;
1341         const u8 *end, *pos;
1342
1343         buf = wpabuf_alloc(res->ie_len);
1344         if (buf == NULL)
1345                 return NULL;
1346
1347         pos = (const u8 *) (res + 1);
1348         end = pos + res->ie_len;
1349
1350         while (pos + 1 < end) {
1351                 if (pos + 2 + pos[1] > end)
1352                         break;
1353                 if (pos[0] == WLAN_EID_VENDOR_SPECIFIC && pos[1] >= 4 &&
1354                     vendor_type == WPA_GET_BE32(&pos[2]))
1355                         wpabuf_put_data(buf, pos + 2 + 4, pos[1] - 4);
1356                 pos += 2 + pos[1];
1357         }
1358
1359         if (wpabuf_len(buf) == 0) {
1360                 wpabuf_free(buf);
1361                 buf = NULL;
1362         }
1363
1364         return buf;
1365 }
1366
1367
1368 /*
1369  * Channels with a great SNR can operate at full rate. What is a great SNR?
1370  * This doc https://supportforums.cisco.com/docs/DOC-12954 says, "the general
1371  * rule of thumb is that any SNR above 20 is good." This one
1372  * http://www.cisco.com/en/US/tech/tk722/tk809/technologies_q_and_a_item09186a00805e9a96.shtml#qa23
1373  * recommends 25 as a minimum SNR for 54 Mbps data rate. 30 is chosen here as a
1374  * conservative value.
1375  */
1376 #define GREAT_SNR 30
1377
1378 /* Compare function for sorting scan results. Return >0 if @b is considered
1379  * better. */
1380 static int wpa_scan_result_compar(const void *a, const void *b)
1381 {
1382 #define IS_5GHZ(n) (n > 4000)
1383 #define MIN(a,b) a < b ? a : b
1384         struct wpa_scan_res **_wa = (void *) a;
1385         struct wpa_scan_res **_wb = (void *) b;
1386         struct wpa_scan_res *wa = *_wa;
1387         struct wpa_scan_res *wb = *_wb;
1388         int wpa_a, wpa_b, maxrate_a, maxrate_b;
1389         int snr_a, snr_b;
1390
1391         /* WPA/WPA2 support preferred */
1392         wpa_a = wpa_scan_get_vendor_ie(wa, WPA_IE_VENDOR_TYPE) != NULL ||
1393                 wpa_scan_get_ie(wa, WLAN_EID_RSN) != NULL;
1394         wpa_b = wpa_scan_get_vendor_ie(wb, WPA_IE_VENDOR_TYPE) != NULL ||
1395                 wpa_scan_get_ie(wb, WLAN_EID_RSN) != NULL;
1396
1397         if (wpa_b && !wpa_a)
1398                 return 1;
1399         if (!wpa_b && wpa_a)
1400                 return -1;
1401
1402         /* privacy support preferred */
1403         if ((wa->caps & IEEE80211_CAP_PRIVACY) == 0 &&
1404             (wb->caps & IEEE80211_CAP_PRIVACY))
1405                 return 1;
1406         if ((wa->caps & IEEE80211_CAP_PRIVACY) &&
1407             (wb->caps & IEEE80211_CAP_PRIVACY) == 0)
1408                 return -1;
1409
1410         if ((wa->flags & wb->flags & WPA_SCAN_LEVEL_DBM) &&
1411             !((wa->flags | wb->flags) & WPA_SCAN_NOISE_INVALID)) {
1412                 snr_a = MIN(wa->level - wa->noise, GREAT_SNR);
1413                 snr_b = MIN(wb->level - wb->noise, GREAT_SNR);
1414         } else {
1415                 /* Not suitable information to calculate SNR, so use level */
1416                 snr_a = wa->level;
1417                 snr_b = wb->level;
1418         }
1419
1420         /* best/max rate preferred if SNR close enough */
1421         if ((snr_a && snr_b && abs(snr_b - snr_a) < 5) ||
1422             (wa->qual && wb->qual && abs(wb->qual - wa->qual) < 10)) {
1423                 maxrate_a = wpa_scan_get_max_rate(wa);
1424                 maxrate_b = wpa_scan_get_max_rate(wb);
1425                 if (maxrate_a != maxrate_b)
1426                         return maxrate_b - maxrate_a;
1427                 if (IS_5GHZ(wa->freq) ^ IS_5GHZ(wb->freq))
1428                         return IS_5GHZ(wa->freq) ? -1 : 1;
1429         }
1430
1431         /* use freq for channel preference */
1432
1433         /* all things being equal, use SNR; if SNRs are
1434          * identical, use quality values since some drivers may only report
1435          * that value and leave the signal level zero */
1436         if (snr_b == snr_a)
1437                 return wb->qual - wa->qual;
1438         return snr_b - snr_a;
1439 #undef MIN
1440 #undef IS_5GHZ
1441 }
1442
1443
1444 #ifdef CONFIG_WPS
1445 /* Compare function for sorting scan results when searching a WPS AP for
1446  * provisioning. Return >0 if @b is considered better. */
1447 static int wpa_scan_result_wps_compar(const void *a, const void *b)
1448 {
1449         struct wpa_scan_res **_wa = (void *) a;
1450         struct wpa_scan_res **_wb = (void *) b;
1451         struct wpa_scan_res *wa = *_wa;
1452         struct wpa_scan_res *wb = *_wb;
1453         int uses_wps_a, uses_wps_b;
1454         struct wpabuf *wps_a, *wps_b;
1455         int res;
1456
1457         /* Optimization - check WPS IE existence before allocated memory and
1458          * doing full reassembly. */
1459         uses_wps_a = wpa_scan_get_vendor_ie(wa, WPS_IE_VENDOR_TYPE) != NULL;
1460         uses_wps_b = wpa_scan_get_vendor_ie(wb, WPS_IE_VENDOR_TYPE) != NULL;
1461         if (uses_wps_a && !uses_wps_b)
1462                 return -1;
1463         if (!uses_wps_a && uses_wps_b)
1464                 return 1;
1465
1466         if (uses_wps_a && uses_wps_b) {
1467                 wps_a = wpa_scan_get_vendor_ie_multi(wa, WPS_IE_VENDOR_TYPE);
1468                 wps_b = wpa_scan_get_vendor_ie_multi(wb, WPS_IE_VENDOR_TYPE);
1469                 res = wps_ap_priority_compar(wps_a, wps_b);
1470                 wpabuf_free(wps_a);
1471                 wpabuf_free(wps_b);
1472                 if (res)
1473                         return res;
1474         }
1475
1476         /*
1477          * Do not use current AP security policy as a sorting criteria during
1478          * WPS provisioning step since the AP may get reconfigured at the
1479          * completion of provisioning.
1480          */
1481
1482         /* all things being equal, use signal level; if signal levels are
1483          * identical, use quality values since some drivers may only report
1484          * that value and leave the signal level zero */
1485         if (wb->level == wa->level)
1486                 return wb->qual - wa->qual;
1487         return wb->level - wa->level;
1488 }
1489 #endif /* CONFIG_WPS */
1490
1491
1492 static void dump_scan_res(struct wpa_scan_results *scan_res)
1493 {
1494 #ifndef CONFIG_NO_STDOUT_DEBUG
1495         size_t i;
1496
1497         if (scan_res->res == NULL || scan_res->num == 0)
1498                 return;
1499
1500         wpa_printf(MSG_EXCESSIVE, "Sorted scan results");
1501
1502         for (i = 0; i < scan_res->num; i++) {
1503                 struct wpa_scan_res *r = scan_res->res[i];
1504                 u8 *pos;
1505                 if ((r->flags & (WPA_SCAN_LEVEL_DBM | WPA_SCAN_NOISE_INVALID))
1506                     == WPA_SCAN_LEVEL_DBM) {
1507                         int snr = r->level - r->noise;
1508                         wpa_printf(MSG_EXCESSIVE, MACSTR " freq=%d qual=%d "
1509                                    "noise=%d level=%d snr=%d%s flags=0x%x "
1510                                    "age=%u",
1511                                    MAC2STR(r->bssid), r->freq, r->qual,
1512                                    r->noise, r->level, snr,
1513                                    snr >= GREAT_SNR ? "*" : "", r->flags,
1514                                    r->age);
1515                 } else {
1516                         wpa_printf(MSG_EXCESSIVE, MACSTR " freq=%d qual=%d "
1517                                    "noise=%d level=%d flags=0x%x age=%u",
1518                                    MAC2STR(r->bssid), r->freq, r->qual,
1519                                    r->noise, r->level, r->flags, r->age);
1520                 }
1521                 pos = (u8 *) (r + 1);
1522                 if (r->ie_len)
1523                         wpa_hexdump(MSG_EXCESSIVE, "IEs", pos, r->ie_len);
1524                 pos += r->ie_len;
1525                 if (r->beacon_ie_len)
1526                         wpa_hexdump(MSG_EXCESSIVE, "Beacon IEs",
1527                                     pos, r->beacon_ie_len);
1528         }
1529 #endif /* CONFIG_NO_STDOUT_DEBUG */
1530 }
1531
1532
1533 /**
1534  * wpa_supplicant_filter_bssid_match - Is the specified BSSID allowed
1535  * @wpa_s: Pointer to wpa_supplicant data
1536  * @bssid: BSSID to check
1537  * Returns: 0 if the BSSID is filtered or 1 if not
1538  *
1539  * This function is used to filter out specific BSSIDs from scan reslts mainly
1540  * for testing purposes (SET bssid_filter ctrl_iface command).
1541  */
1542 int wpa_supplicant_filter_bssid_match(struct wpa_supplicant *wpa_s,
1543                                       const u8 *bssid)
1544 {
1545         size_t i;
1546
1547         if (wpa_s->bssid_filter == NULL)
1548                 return 1;
1549
1550         for (i = 0; i < wpa_s->bssid_filter_count; i++) {
1551                 if (os_memcmp(wpa_s->bssid_filter + i * ETH_ALEN, bssid,
1552                               ETH_ALEN) == 0)
1553                         return 1;
1554         }
1555
1556         return 0;
1557 }
1558
1559
1560 static void filter_scan_res(struct wpa_supplicant *wpa_s,
1561                             struct wpa_scan_results *res)
1562 {
1563         size_t i, j;
1564
1565         if (wpa_s->bssid_filter == NULL)
1566                 return;
1567
1568         for (i = 0, j = 0; i < res->num; i++) {
1569                 if (wpa_supplicant_filter_bssid_match(wpa_s,
1570                                                       res->res[i]->bssid)) {
1571                         res->res[j++] = res->res[i];
1572                 } else {
1573                         os_free(res->res[i]);
1574                         res->res[i] = NULL;
1575                 }
1576         }
1577
1578         if (res->num != j) {
1579                 wpa_printf(MSG_DEBUG, "Filtered out %d scan results",
1580                            (int) (res->num - j));
1581                 res->num = j;
1582         }
1583 }
1584
1585
1586 /**
1587  * wpa_supplicant_get_scan_results - Get scan results
1588  * @wpa_s: Pointer to wpa_supplicant data
1589  * @info: Information about what was scanned or %NULL if not available
1590  * @new_scan: Whether a new scan was performed
1591  * Returns: Scan results, %NULL on failure
1592  *
1593  * This function request the current scan results from the driver and updates
1594  * the local BSS list wpa_s->bss. The caller is responsible for freeing the
1595  * results with wpa_scan_results_free().
1596  */
1597 struct wpa_scan_results *
1598 wpa_supplicant_get_scan_results(struct wpa_supplicant *wpa_s,
1599                                 struct scan_info *info, int new_scan)
1600 {
1601         struct wpa_scan_results *scan_res;
1602         size_t i;
1603         int (*compar)(const void *, const void *) = wpa_scan_result_compar;
1604
1605         scan_res = wpa_drv_get_scan_results2(wpa_s);
1606         if (scan_res == NULL) {
1607                 wpa_dbg(wpa_s, MSG_DEBUG, "Failed to get scan results");
1608                 return NULL;
1609         }
1610         if (scan_res->fetch_time.sec == 0) {
1611                 /*
1612                  * Make sure we have a valid timestamp if the driver wrapper
1613                  * does not set this.
1614                  */
1615                 os_get_reltime(&scan_res->fetch_time);
1616         }
1617         filter_scan_res(wpa_s, scan_res);
1618
1619 #ifdef CONFIG_WPS
1620         if (wpas_wps_in_progress(wpa_s)) {
1621                 wpa_dbg(wpa_s, MSG_DEBUG, "WPS: Order scan results with WPS "
1622                         "provisioning rules");
1623                 compar = wpa_scan_result_wps_compar;
1624         }
1625 #endif /* CONFIG_WPS */
1626
1627         qsort(scan_res->res, scan_res->num, sizeof(struct wpa_scan_res *),
1628               compar);
1629         dump_scan_res(scan_res);
1630
1631         wpa_bss_update_start(wpa_s);
1632         for (i = 0; i < scan_res->num; i++)
1633                 wpa_bss_update_scan_res(wpa_s, scan_res->res[i],
1634                                         &scan_res->fetch_time);
1635         wpa_bss_update_end(wpa_s, info, new_scan);
1636
1637         return scan_res;
1638 }
1639
1640
1641 /**
1642  * wpa_supplicant_update_scan_results - Update scan results from the driver
1643  * @wpa_s: Pointer to wpa_supplicant data
1644  * Returns: 0 on success, -1 on failure
1645  *
1646  * This function updates the BSS table within wpa_supplicant based on the
1647  * currently available scan results from the driver without requesting a new
1648  * scan. This is used in cases where the driver indicates an association
1649  * (including roaming within ESS) and wpa_supplicant does not yet have the
1650  * needed information to complete the connection (e.g., to perform validation
1651  * steps in 4-way handshake).
1652  */
1653 int wpa_supplicant_update_scan_results(struct wpa_supplicant *wpa_s)
1654 {
1655         struct wpa_scan_results *scan_res;
1656         scan_res = wpa_supplicant_get_scan_results(wpa_s, NULL, 0);
1657         if (scan_res == NULL)
1658                 return -1;
1659         wpa_scan_results_free(scan_res);
1660
1661         return 0;
1662 }
1663
1664
1665 /**
1666  * scan_only_handler - Reports scan results
1667  */
1668 void scan_only_handler(struct wpa_supplicant *wpa_s,
1669                        struct wpa_scan_results *scan_res)
1670 {
1671         wpa_dbg(wpa_s, MSG_DEBUG, "Scan-only results received");
1672         wpa_msg_ctrl(wpa_s, MSG_INFO, WPA_EVENT_SCAN_RESULTS);
1673         wpas_notify_scan_results(wpa_s);
1674         wpas_notify_scan_done(wpa_s, 1);
1675 }
1676
1677
1678 int wpas_scan_scheduled(struct wpa_supplicant *wpa_s)
1679 {
1680         return eloop_is_timeout_registered(wpa_supplicant_scan, wpa_s, NULL);
1681 }