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