P2P: Do not allow scan or normal association on cfg80211 P2P Device
[mech_eap.git] / wpa_supplicant / scan.c
1 /*
2  * WPA Supplicant - Scanning
3  * Copyright (c) 2003-2014, 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 "scan.h"
25 #include "mesh.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
100         if (wpa_s->p2p_mgmt)
101                 return 0; /* no normal network profiles on p2p_mgmt interface */
102
103         while (ssid) {
104                 if (!wpas_network_disabled(wpa_s, ssid))
105                         count++;
106                 else
107                         disabled++;
108                 ssid = ssid->next;
109         }
110         if (wpa_s->conf->cred && wpa_s->conf->interworking &&
111             wpa_s->conf->auto_interworking)
112                 count++;
113         if (count == 0 && disabled > 0) {
114                 wpa_dbg(wpa_s, MSG_DEBUG, "No enabled networks (%d disabled "
115                         "networks)", disabled);
116         }
117         return count;
118 }
119
120
121 static void wpa_supplicant_assoc_try(struct wpa_supplicant *wpa_s,
122                                      struct wpa_ssid *ssid)
123 {
124         while (ssid) {
125                 if (!wpas_network_disabled(wpa_s, ssid))
126                         break;
127                 ssid = ssid->next;
128         }
129
130         /* ap_scan=2 mode - try to associate with each SSID. */
131         if (ssid == NULL) {
132                 wpa_dbg(wpa_s, MSG_DEBUG, "wpa_supplicant_assoc_try: Reached "
133                         "end of scan list - go back to beginning");
134                 wpa_s->prev_scan_ssid = WILDCARD_SSID_SCAN;
135                 wpa_supplicant_req_scan(wpa_s, 0, 0);
136                 return;
137         }
138         if (ssid->next) {
139                 /* Continue from the next SSID on the next attempt. */
140                 wpa_s->prev_scan_ssid = ssid;
141         } else {
142                 /* Start from the beginning of the SSID list. */
143                 wpa_s->prev_scan_ssid = WILDCARD_SSID_SCAN;
144         }
145         wpa_supplicant_associate(wpa_s, NULL, ssid);
146 }
147
148
149 static void wpas_trigger_scan_cb(struct wpa_radio_work *work, int deinit)
150 {
151         struct wpa_supplicant *wpa_s = work->wpa_s;
152         struct wpa_driver_scan_params *params = work->ctx;
153         int ret;
154
155         if (deinit) {
156                 if (!work->started) {
157                         wpa_scan_free_params(params);
158                         return;
159                 }
160                 wpa_supplicant_notify_scanning(wpa_s, 0);
161                 wpas_notify_scan_done(wpa_s, 0);
162                 wpa_s->scan_work = NULL;
163                 return;
164         }
165
166         if (wpas_update_random_addr_disassoc(wpa_s) < 0) {
167                 wpa_msg(wpa_s, MSG_INFO,
168                         "Failed to assign random MAC address for a scan");
169                 radio_work_done(work);
170                 return;
171         }
172
173         wpa_supplicant_notify_scanning(wpa_s, 1);
174
175         if (wpa_s->clear_driver_scan_cache) {
176                 wpa_printf(MSG_DEBUG,
177                            "Request driver to clear scan cache due to local BSS flush");
178                 params->only_new_results = 1;
179         }
180         ret = wpa_drv_scan(wpa_s, params);
181         wpa_scan_free_params(params);
182         work->ctx = NULL;
183         if (ret) {
184                 int retry = wpa_s->last_scan_req != MANUAL_SCAN_REQ;
185
186                 if (wpa_s->disconnected)
187                         retry = 0;
188
189                 wpa_supplicant_notify_scanning(wpa_s, 0);
190                 wpas_notify_scan_done(wpa_s, 0);
191                 if (wpa_s->wpa_state == WPA_SCANNING)
192                         wpa_supplicant_set_state(wpa_s,
193                                                  wpa_s->scan_prev_wpa_state);
194                 wpa_msg(wpa_s, MSG_INFO, WPA_EVENT_SCAN_FAILED "ret=%d%s",
195                         ret, retry ? " retry=1" : "");
196                 radio_work_done(work);
197
198                 if (retry) {
199                         /* Restore scan_req since we will try to scan again */
200                         wpa_s->scan_req = wpa_s->last_scan_req;
201                         wpa_supplicant_req_scan(wpa_s, 1, 0);
202                 }
203                 return;
204         }
205
206         os_get_reltime(&wpa_s->scan_trigger_time);
207         wpa_s->scan_runs++;
208         wpa_s->normal_scans++;
209         wpa_s->own_scan_requested = 1;
210         wpa_s->clear_driver_scan_cache = 0;
211         wpa_s->scan_work = work;
212 }
213
214
215 /**
216  * wpa_supplicant_trigger_scan - Request driver to start a scan
217  * @wpa_s: Pointer to wpa_supplicant data
218  * @params: Scan parameters
219  * Returns: 0 on success, -1 on failure
220  */
221 int wpa_supplicant_trigger_scan(struct wpa_supplicant *wpa_s,
222                                 struct wpa_driver_scan_params *params)
223 {
224         struct wpa_driver_scan_params *ctx;
225
226         if (wpa_s->scan_work) {
227                 wpa_dbg(wpa_s, MSG_INFO, "Reject scan trigger since one is already pending");
228                 return -1;
229         }
230
231         ctx = wpa_scan_clone_params(params);
232         if (ctx == NULL)
233                 return -1;
234
235         if (radio_add_work(wpa_s, 0, "scan", 0, wpas_trigger_scan_cb, ctx) < 0)
236         {
237                 wpa_scan_free_params(ctx);
238                 return -1;
239         }
240
241         return 0;
242 }
243
244
245 static void
246 wpa_supplicant_delayed_sched_scan_timeout(void *eloop_ctx, void *timeout_ctx)
247 {
248         struct wpa_supplicant *wpa_s = eloop_ctx;
249
250         wpa_dbg(wpa_s, MSG_DEBUG, "Starting delayed sched scan");
251
252         if (wpa_supplicant_req_sched_scan(wpa_s))
253                 wpa_supplicant_req_scan(wpa_s, 0, 0);
254 }
255
256
257 static void
258 wpa_supplicant_sched_scan_timeout(void *eloop_ctx, void *timeout_ctx)
259 {
260         struct wpa_supplicant *wpa_s = eloop_ctx;
261
262         wpa_dbg(wpa_s, MSG_DEBUG, "Sched scan timeout - stopping it");
263
264         wpa_s->sched_scan_timed_out = 1;
265         wpa_supplicant_cancel_sched_scan(wpa_s);
266 }
267
268
269 int wpa_supplicant_start_sched_scan(struct wpa_supplicant *wpa_s,
270                                     struct wpa_driver_scan_params *params,
271                                     int interval)
272 {
273         int ret;
274
275         wpa_supplicant_notify_scanning(wpa_s, 1);
276         ret = wpa_drv_sched_scan(wpa_s, params, interval * 1000);
277         if (ret)
278                 wpa_supplicant_notify_scanning(wpa_s, 0);
279         else
280                 wpa_s->sched_scanning = 1;
281
282         return ret;
283 }
284
285
286 int wpa_supplicant_stop_sched_scan(struct wpa_supplicant *wpa_s)
287 {
288         int ret;
289
290         ret = wpa_drv_stop_sched_scan(wpa_s);
291         if (ret) {
292                 wpa_dbg(wpa_s, MSG_DEBUG, "stopping sched_scan failed!");
293                 /* TODO: what to do if stopping fails? */
294                 return -1;
295         }
296
297         return ret;
298 }
299
300
301 static struct wpa_driver_scan_filter *
302 wpa_supplicant_build_filter_ssids(struct wpa_config *conf, size_t *num_ssids)
303 {
304         struct wpa_driver_scan_filter *ssids;
305         struct wpa_ssid *ssid;
306         size_t count;
307
308         *num_ssids = 0;
309         if (!conf->filter_ssids)
310                 return NULL;
311
312         for (count = 0, ssid = conf->ssid; ssid; ssid = ssid->next) {
313                 if (ssid->ssid && ssid->ssid_len)
314                         count++;
315         }
316         if (count == 0)
317                 return NULL;
318         ssids = os_calloc(count, sizeof(struct wpa_driver_scan_filter));
319         if (ssids == NULL)
320                 return NULL;
321
322         for (ssid = conf->ssid; ssid; ssid = ssid->next) {
323                 if (!ssid->ssid || !ssid->ssid_len)
324                         continue;
325                 os_memcpy(ssids[*num_ssids].ssid, ssid->ssid, ssid->ssid_len);
326                 ssids[*num_ssids].ssid_len = ssid->ssid_len;
327                 (*num_ssids)++;
328         }
329
330         return ssids;
331 }
332
333
334 static void wpa_supplicant_optimize_freqs(
335         struct wpa_supplicant *wpa_s, struct wpa_driver_scan_params *params)
336 {
337 #ifdef CONFIG_P2P
338         if (params->freqs == NULL && wpa_s->p2p_in_provisioning &&
339             wpa_s->go_params) {
340                 /* Optimize provisioning state scan based on GO information */
341                 if (wpa_s->p2p_in_provisioning < 5 &&
342                     wpa_s->go_params->freq > 0) {
343                         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Scan only GO "
344                                 "preferred frequency %d MHz",
345                                 wpa_s->go_params->freq);
346                         params->freqs = os_calloc(2, sizeof(int));
347                         if (params->freqs)
348                                 params->freqs[0] = wpa_s->go_params->freq;
349                 } else if (wpa_s->p2p_in_provisioning < 8 &&
350                            wpa_s->go_params->freq_list[0]) {
351                         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Scan only common "
352                                 "channels");
353                         int_array_concat(&params->freqs,
354                                          wpa_s->go_params->freq_list);
355                         if (params->freqs)
356                                 int_array_sort_unique(params->freqs);
357                 }
358                 wpa_s->p2p_in_provisioning++;
359         }
360
361         if (params->freqs == NULL && wpa_s->p2p_in_invitation) {
362                 /*
363                  * Optimize scan based on GO information during persistent
364                  * group reinvocation
365                  */
366                 if (wpa_s->p2p_in_invitation < 5 &&
367                     wpa_s->p2p_invite_go_freq > 0) {
368                         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Scan only GO preferred frequency %d MHz during invitation",
369                                 wpa_s->p2p_invite_go_freq);
370                         params->freqs = os_calloc(2, sizeof(int));
371                         if (params->freqs)
372                                 params->freqs[0] = wpa_s->p2p_invite_go_freq;
373                 }
374                 wpa_s->p2p_in_invitation++;
375                 if (wpa_s->p2p_in_invitation > 20) {
376                         /*
377                          * This should not really happen since the variable is
378                          * cleared on group removal, but if it does happen, make
379                          * sure we do not get stuck in special invitation scan
380                          * mode.
381                          */
382                         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Clear p2p_in_invitation");
383                         wpa_s->p2p_in_invitation = 0;
384                 }
385         }
386 #endif /* CONFIG_P2P */
387
388 #ifdef CONFIG_WPS
389         if (params->freqs == NULL && wpa_s->after_wps && wpa_s->wps_freq) {
390                 /*
391                  * Optimize post-provisioning scan based on channel used
392                  * during provisioning.
393                  */
394                 wpa_dbg(wpa_s, MSG_DEBUG, "WPS: Scan only frequency %u MHz "
395                         "that was used during provisioning", wpa_s->wps_freq);
396                 params->freqs = os_calloc(2, sizeof(int));
397                 if (params->freqs)
398                         params->freqs[0] = wpa_s->wps_freq;
399                 wpa_s->after_wps--;
400         } else if (wpa_s->after_wps)
401                 wpa_s->after_wps--;
402
403         if (params->freqs == NULL && wpa_s->known_wps_freq && wpa_s->wps_freq)
404         {
405                 /* Optimize provisioning scan based on already known channel */
406                 wpa_dbg(wpa_s, MSG_DEBUG, "WPS: Scan only frequency %u MHz",
407                         wpa_s->wps_freq);
408                 params->freqs = os_calloc(2, sizeof(int));
409                 if (params->freqs)
410                         params->freqs[0] = wpa_s->wps_freq;
411                 wpa_s->known_wps_freq = 0; /* only do this once */
412         }
413 #endif /* CONFIG_WPS */
414 }
415
416
417 #ifdef CONFIG_INTERWORKING
418 static void wpas_add_interworking_elements(struct wpa_supplicant *wpa_s,
419                                            struct wpabuf *buf)
420 {
421         if (wpa_s->conf->interworking == 0)
422                 return;
423
424         wpabuf_put_u8(buf, WLAN_EID_EXT_CAPAB);
425         wpabuf_put_u8(buf, 6);
426         wpabuf_put_u8(buf, 0x00);
427         wpabuf_put_u8(buf, 0x00);
428         wpabuf_put_u8(buf, 0x00);
429         wpabuf_put_u8(buf, 0x80); /* Bit 31 - Interworking */
430         wpabuf_put_u8(buf, 0x00);
431 #ifdef CONFIG_HS20
432         wpabuf_put_u8(buf, 0x40); /* Bit 46 - WNM-Notification */
433 #else /* CONFIG_HS20 */
434         wpabuf_put_u8(buf, 0x00);
435 #endif /* CONFIG_HS20 */
436
437         wpabuf_put_u8(buf, WLAN_EID_INTERWORKING);
438         wpabuf_put_u8(buf, is_zero_ether_addr(wpa_s->conf->hessid) ? 1 :
439                       1 + ETH_ALEN);
440         wpabuf_put_u8(buf, wpa_s->conf->access_network_type);
441         /* No Venue Info */
442         if (!is_zero_ether_addr(wpa_s->conf->hessid))
443                 wpabuf_put_data(buf, wpa_s->conf->hessid, ETH_ALEN);
444 }
445 #endif /* CONFIG_INTERWORKING */
446
447
448 static struct wpabuf * wpa_supplicant_extra_ies(struct wpa_supplicant *wpa_s)
449 {
450         struct wpabuf *extra_ie = NULL;
451 #ifdef CONFIG_WPS
452         int wps = 0;
453         enum wps_request_type req_type = WPS_REQ_ENROLLEE_INFO;
454 #endif /* CONFIG_WPS */
455
456 #ifdef CONFIG_INTERWORKING
457         if (wpa_s->conf->interworking &&
458             wpabuf_resize(&extra_ie, 100) == 0)
459                 wpas_add_interworking_elements(wpa_s, extra_ie);
460 #endif /* CONFIG_INTERWORKING */
461
462 #ifdef CONFIG_WPS
463         wps = wpas_wps_in_use(wpa_s, &req_type);
464
465         if (wps) {
466                 struct wpabuf *wps_ie;
467                 wps_ie = wps_build_probe_req_ie(wps == 2 ? DEV_PW_PUSHBUTTON :
468                                                 DEV_PW_DEFAULT,
469                                                 &wpa_s->wps->dev,
470                                                 wpa_s->wps->uuid, req_type,
471                                                 0, NULL);
472                 if (wps_ie) {
473                         if (wpabuf_resize(&extra_ie, wpabuf_len(wps_ie)) == 0)
474                                 wpabuf_put_buf(extra_ie, wps_ie);
475                         wpabuf_free(wps_ie);
476                 }
477         }
478
479 #ifdef CONFIG_P2P
480         if (wps) {
481                 size_t ielen = p2p_scan_ie_buf_len(wpa_s->global->p2p);
482                 if (wpabuf_resize(&extra_ie, ielen) == 0)
483                         wpas_p2p_scan_ie(wpa_s, extra_ie);
484         }
485 #endif /* CONFIG_P2P */
486
487         wpa_supplicant_mesh_add_scan_ie(wpa_s, &extra_ie);
488
489 #endif /* CONFIG_WPS */
490
491 #ifdef CONFIG_HS20
492         if (wpa_s->conf->hs20 && wpabuf_resize(&extra_ie, 7) == 0)
493                 wpas_hs20_add_indication(extra_ie, -1);
494 #endif /* CONFIG_HS20 */
495
496         return extra_ie;
497 }
498
499
500 #ifdef CONFIG_P2P
501
502 /*
503  * Check whether there are any enabled networks or credentials that could be
504  * used for a non-P2P connection.
505  */
506 static int non_p2p_network_enabled(struct wpa_supplicant *wpa_s)
507 {
508         struct wpa_ssid *ssid;
509
510         for (ssid = wpa_s->conf->ssid; ssid; ssid = ssid->next) {
511                 if (wpas_network_disabled(wpa_s, ssid))
512                         continue;
513                 if (!ssid->p2p_group)
514                         return 1;
515         }
516
517         if (wpa_s->conf->cred && wpa_s->conf->interworking &&
518             wpa_s->conf->auto_interworking)
519                 return 1;
520
521         return 0;
522 }
523
524 #endif /* CONFIG_P2P */
525
526
527 static struct hostapd_hw_modes * get_mode(struct hostapd_hw_modes *modes,
528                                           u16 num_modes,
529                                           enum hostapd_hw_mode mode)
530 {
531         u16 i;
532
533         for (i = 0; i < num_modes; i++) {
534                 if (modes[i].mode == mode)
535                         return &modes[i];
536         }
537
538         return NULL;
539 }
540
541
542 static void wpa_setband_scan_freqs_list(struct wpa_supplicant *wpa_s,
543                                         enum hostapd_hw_mode band,
544                                         struct wpa_driver_scan_params *params)
545 {
546         /* Include only supported channels for the specified band */
547         struct hostapd_hw_modes *mode;
548         int count, i;
549
550         mode = get_mode(wpa_s->hw.modes, wpa_s->hw.num_modes, band);
551         if (mode == NULL) {
552                 /* No channels supported in this band - use empty list */
553                 params->freqs = os_zalloc(sizeof(int));
554                 return;
555         }
556
557         params->freqs = os_calloc(mode->num_channels + 1, sizeof(int));
558         if (params->freqs == NULL)
559                 return;
560         for (count = 0, i = 0; i < mode->num_channels; i++) {
561                 if (mode->channels[i].flag & HOSTAPD_CHAN_DISABLED)
562                         continue;
563                 params->freqs[count++] = mode->channels[i].freq;
564         }
565 }
566
567
568 static void wpa_setband_scan_freqs(struct wpa_supplicant *wpa_s,
569                                    struct wpa_driver_scan_params *params)
570 {
571         if (wpa_s->hw.modes == NULL)
572                 return; /* unknown what channels the driver supports */
573         if (params->freqs)
574                 return; /* already using a limited channel set */
575         if (wpa_s->setband == WPA_SETBAND_5G)
576                 wpa_setband_scan_freqs_list(wpa_s, HOSTAPD_MODE_IEEE80211A,
577                                             params);
578         else if (wpa_s->setband == WPA_SETBAND_2G)
579                 wpa_setband_scan_freqs_list(wpa_s, HOSTAPD_MODE_IEEE80211G,
580                                             params);
581 }
582
583
584 static void wpa_set_scan_ssids(struct wpa_supplicant *wpa_s,
585                                struct wpa_driver_scan_params *params,
586                                size_t max_ssids)
587 {
588         unsigned int i;
589         struct wpa_ssid *ssid;
590
591         for (i = 0; i < wpa_s->scan_id_count; i++) {
592                 unsigned int j;
593
594                 ssid = wpa_config_get_network(wpa_s->conf, wpa_s->scan_id[i]);
595                 if (!ssid || !ssid->scan_ssid)
596                         continue;
597
598                 for (j = 0; j < params->num_ssids; j++) {
599                         if (params->ssids[j].ssid_len == ssid->ssid_len &&
600                             params->ssids[j].ssid &&
601                             os_memcmp(params->ssids[j].ssid, ssid->ssid,
602                                       ssid->ssid_len) == 0)
603                                 break;
604                 }
605                 if (j < params->num_ssids)
606                         continue; /* already in the list */
607
608                 if (params->num_ssids + 1 > max_ssids) {
609                         wpa_printf(MSG_DEBUG,
610                                    "Over max scan SSIDs for manual request");
611                         break;
612                 }
613
614                 wpa_printf(MSG_DEBUG, "Scan SSID (manual request): %s",
615                            wpa_ssid_txt(ssid->ssid, ssid->ssid_len));
616                 params->ssids[params->num_ssids].ssid = ssid->ssid;
617                 params->ssids[params->num_ssids].ssid_len = ssid->ssid_len;
618                 params->num_ssids++;
619         }
620
621         wpa_s->scan_id_count = 0;
622 }
623
624
625 static void wpa_supplicant_scan(void *eloop_ctx, void *timeout_ctx)
626 {
627         struct wpa_supplicant *wpa_s = eloop_ctx;
628         struct wpa_ssid *ssid;
629         int ret, p2p_in_prog;
630         struct wpabuf *extra_ie = NULL;
631         struct wpa_driver_scan_params params;
632         struct wpa_driver_scan_params *scan_params;
633         size_t max_ssids;
634
635         if (wpa_s->pno || wpa_s->pno_sched_pending) {
636                 wpa_dbg(wpa_s, MSG_DEBUG, "Skip scan - PNO is in progress");
637                 return;
638         }
639
640         if (wpa_s->wpa_state == WPA_INTERFACE_DISABLED) {
641                 wpa_dbg(wpa_s, MSG_DEBUG, "Skip scan - interface disabled");
642                 return;
643         }
644
645         if (wpa_s->disconnected && wpa_s->scan_req == NORMAL_SCAN_REQ) {
646                 wpa_dbg(wpa_s, MSG_DEBUG, "Disconnected - do not scan");
647                 wpa_supplicant_set_state(wpa_s, WPA_DISCONNECTED);
648                 return;
649         }
650
651         if (wpa_s->scanning) {
652                 /*
653                  * If we are already in scanning state, we shall reschedule the
654                  * the incoming scan request.
655                  */
656                 wpa_dbg(wpa_s, MSG_DEBUG, "Already scanning - Reschedule the incoming scan req");
657                 wpa_supplicant_req_scan(wpa_s, 1, 0);
658                 return;
659         }
660
661         if (!wpa_supplicant_enabled_networks(wpa_s) &&
662             wpa_s->scan_req == NORMAL_SCAN_REQ) {
663                 wpa_dbg(wpa_s, MSG_DEBUG, "No enabled networks - do not scan");
664                 wpa_supplicant_set_state(wpa_s, WPA_INACTIVE);
665                 return;
666         }
667
668         if (wpa_s->conf->ap_scan != 0 &&
669             (wpa_s->drv_flags & WPA_DRIVER_FLAGS_WIRED)) {
670                 wpa_dbg(wpa_s, MSG_DEBUG, "Using wired authentication - "
671                         "overriding ap_scan configuration");
672                 wpa_s->conf->ap_scan = 0;
673                 wpas_notify_ap_scan_changed(wpa_s);
674         }
675
676         if (wpa_s->conf->ap_scan == 0) {
677                 wpa_supplicant_gen_assoc_event(wpa_s);
678                 return;
679         }
680
681         p2p_in_prog = wpas_p2p_in_progress(wpa_s);
682         if (p2p_in_prog && p2p_in_prog != 2) {
683                 wpa_dbg(wpa_s, MSG_DEBUG, "Delay station mode scan while P2P operation is in progress");
684                 wpa_supplicant_req_scan(wpa_s, 5, 0);
685                 return;
686         }
687
688         if (wpa_s->conf->ap_scan == 2)
689                 max_ssids = 1;
690         else {
691                 max_ssids = wpa_s->max_scan_ssids;
692                 if (max_ssids > WPAS_MAX_SCAN_SSIDS)
693                         max_ssids = WPAS_MAX_SCAN_SSIDS;
694         }
695
696         wpa_s->last_scan_req = wpa_s->scan_req;
697         wpa_s->scan_req = NORMAL_SCAN_REQ;
698
699         os_memset(&params, 0, sizeof(params));
700
701         wpa_s->scan_prev_wpa_state = wpa_s->wpa_state;
702         if (wpa_s->wpa_state == WPA_DISCONNECTED ||
703             wpa_s->wpa_state == WPA_INACTIVE)
704                 wpa_supplicant_set_state(wpa_s, WPA_SCANNING);
705
706         /*
707          * If autoscan has set its own scanning parameters
708          */
709         if (wpa_s->autoscan_params != NULL) {
710                 scan_params = wpa_s->autoscan_params;
711                 goto scan;
712         }
713
714         if (wpa_s->last_scan_req != MANUAL_SCAN_REQ &&
715             wpa_s->connect_without_scan) {
716                 for (ssid = wpa_s->conf->ssid; ssid; ssid = ssid->next) {
717                         if (ssid == wpa_s->connect_without_scan)
718                                 break;
719                 }
720                 wpa_s->connect_without_scan = NULL;
721                 if (ssid) {
722                         wpa_printf(MSG_DEBUG, "Start a pre-selected network "
723                                    "without scan step");
724                         wpa_supplicant_associate(wpa_s, NULL, ssid);
725                         return;
726                 }
727         }
728
729 #ifdef CONFIG_P2P
730         if ((wpa_s->p2p_in_provisioning || wpa_s->show_group_started) &&
731             wpa_s->go_params && !wpa_s->conf->passive_scan) {
732                 wpa_printf(MSG_DEBUG, "P2P: Use specific SSID for scan during P2P group formation (p2p_in_provisioning=%d show_group_started=%d)",
733                            wpa_s->p2p_in_provisioning,
734                            wpa_s->show_group_started);
735                 params.ssids[0].ssid = wpa_s->go_params->ssid;
736                 params.ssids[0].ssid_len = wpa_s->go_params->ssid_len;
737                 params.num_ssids = 1;
738                 goto ssid_list_set;
739         }
740
741         if (wpa_s->p2p_in_invitation) {
742                 if (wpa_s->current_ssid) {
743                         wpa_printf(MSG_DEBUG, "P2P: Use specific SSID for scan during invitation");
744                         params.ssids[0].ssid = wpa_s->current_ssid->ssid;
745                         params.ssids[0].ssid_len =
746                                 wpa_s->current_ssid->ssid_len;
747                         params.num_ssids = 1;
748                 } else {
749                         wpa_printf(MSG_DEBUG, "P2P: No specific SSID known for scan during invitation");
750                 }
751                 goto ssid_list_set;
752         }
753 #endif /* CONFIG_P2P */
754
755         /* Find the starting point from which to continue scanning */
756         ssid = wpa_s->conf->ssid;
757         if (wpa_s->prev_scan_ssid != WILDCARD_SSID_SCAN) {
758                 while (ssid) {
759                         if (ssid == wpa_s->prev_scan_ssid) {
760                                 ssid = ssid->next;
761                                 break;
762                         }
763                         ssid = ssid->next;
764                 }
765         }
766
767         if (wpa_s->last_scan_req != MANUAL_SCAN_REQ &&
768             wpa_s->conf->ap_scan == 2) {
769                 wpa_s->connect_without_scan = NULL;
770                 wpa_s->prev_scan_wildcard = 0;
771                 wpa_supplicant_assoc_try(wpa_s, ssid);
772                 return;
773         } else if (wpa_s->conf->ap_scan == 2) {
774                 /*
775                  * User-initiated scan request in ap_scan == 2; scan with
776                  * wildcard SSID.
777                  */
778                 ssid = NULL;
779         } else if (wpa_s->reattach && wpa_s->current_ssid != NULL) {
780                 /*
781                  * Perform single-channel single-SSID scan for
782                  * reassociate-to-same-BSS operation.
783                  */
784                 /* Setup SSID */
785                 ssid = wpa_s->current_ssid;
786                 wpa_hexdump_ascii(MSG_DEBUG, "Scan SSID",
787                                   ssid->ssid, ssid->ssid_len);
788                 params.ssids[0].ssid = ssid->ssid;
789                 params.ssids[0].ssid_len = ssid->ssid_len;
790                 params.num_ssids = 1;
791
792                 /*
793                  * Allocate memory for frequency array, allocate one extra
794                  * slot for the zero-terminator.
795                  */
796                 params.freqs = os_malloc(sizeof(int) * 2);
797                 if (params.freqs == NULL) {
798                         wpa_dbg(wpa_s, MSG_ERROR, "Memory allocation failed");
799                         return;
800                 }
801                 params.freqs[0] = wpa_s->assoc_freq;
802                 params.freqs[1] = 0;
803
804                 /*
805                  * Reset the reattach flag so that we fall back to full scan if
806                  * this scan fails.
807                  */
808                 wpa_s->reattach = 0;
809         } else {
810                 struct wpa_ssid *start = ssid, *tssid;
811                 int freqs_set = 0;
812                 if (ssid == NULL && max_ssids > 1)
813                         ssid = wpa_s->conf->ssid;
814                 while (ssid) {
815                         if (!wpas_network_disabled(wpa_s, ssid) &&
816                             ssid->scan_ssid) {
817                                 wpa_hexdump_ascii(MSG_DEBUG, "Scan SSID",
818                                                   ssid->ssid, ssid->ssid_len);
819                                 params.ssids[params.num_ssids].ssid =
820                                         ssid->ssid;
821                                 params.ssids[params.num_ssids].ssid_len =
822                                         ssid->ssid_len;
823                                 params.num_ssids++;
824                                 if (params.num_ssids + 1 >= max_ssids)
825                                         break;
826                         }
827                         ssid = ssid->next;
828                         if (ssid == start)
829                                 break;
830                         if (ssid == NULL && max_ssids > 1 &&
831                             start != wpa_s->conf->ssid)
832                                 ssid = wpa_s->conf->ssid;
833                 }
834
835                 if (wpa_s->scan_id_count &&
836                     wpa_s->last_scan_req == MANUAL_SCAN_REQ)
837                         wpa_set_scan_ssids(wpa_s, &params, max_ssids);
838
839                 for (tssid = wpa_s->conf->ssid;
840                      wpa_s->last_scan_req != MANUAL_SCAN_REQ && tssid;
841                      tssid = tssid->next) {
842                         if (wpas_network_disabled(wpa_s, tssid))
843                                 continue;
844                         if ((params.freqs || !freqs_set) && tssid->scan_freq) {
845                                 int_array_concat(&params.freqs,
846                                                  tssid->scan_freq);
847                         } else {
848                                 os_free(params.freqs);
849                                 params.freqs = NULL;
850                         }
851                         freqs_set = 1;
852                 }
853                 int_array_sort_unique(params.freqs);
854         }
855
856         if (ssid && max_ssids == 1) {
857                 /*
858                  * If the driver is limited to 1 SSID at a time interleave
859                  * wildcard SSID scans with specific SSID scans to avoid
860                  * waiting a long time for a wildcard scan.
861                  */
862                 if (!wpa_s->prev_scan_wildcard) {
863                         params.ssids[0].ssid = NULL;
864                         params.ssids[0].ssid_len = 0;
865                         wpa_s->prev_scan_wildcard = 1;
866                         wpa_dbg(wpa_s, MSG_DEBUG, "Starting AP scan for "
867                                 "wildcard SSID (Interleave with specific)");
868                 } else {
869                         wpa_s->prev_scan_ssid = ssid;
870                         wpa_s->prev_scan_wildcard = 0;
871                         wpa_dbg(wpa_s, MSG_DEBUG,
872                                 "Starting AP scan for specific SSID: %s",
873                                 wpa_ssid_txt(ssid->ssid, ssid->ssid_len));
874                 }
875         } else if (ssid) {
876                 /* max_ssids > 1 */
877
878                 wpa_s->prev_scan_ssid = ssid;
879                 wpa_dbg(wpa_s, MSG_DEBUG, "Include wildcard SSID in "
880                         "the scan request");
881                 params.num_ssids++;
882         } else if (wpa_s->last_scan_req == MANUAL_SCAN_REQ &&
883                    wpa_s->manual_scan_passive && params.num_ssids == 0) {
884                 wpa_dbg(wpa_s, MSG_DEBUG, "Use passive scan based on manual request");
885         } else if (wpa_s->conf->passive_scan) {
886                 wpa_dbg(wpa_s, MSG_DEBUG,
887                         "Use passive scan based on configuration");
888         } else {
889                 wpa_s->prev_scan_ssid = WILDCARD_SSID_SCAN;
890                 params.num_ssids++;
891                 wpa_dbg(wpa_s, MSG_DEBUG, "Starting AP scan for wildcard "
892                         "SSID");
893         }
894 #ifdef CONFIG_P2P
895 ssid_list_set:
896 #endif /* CONFIG_P2P */
897
898         wpa_supplicant_optimize_freqs(wpa_s, &params);
899         extra_ie = wpa_supplicant_extra_ies(wpa_s);
900
901         if (wpa_s->last_scan_req == MANUAL_SCAN_REQ &&
902             wpa_s->manual_scan_only_new) {
903                 wpa_printf(MSG_DEBUG,
904                            "Request driver to clear scan cache due to manual only_new=1 scan");
905                 params.only_new_results = 1;
906         }
907
908         if (wpa_s->last_scan_req == MANUAL_SCAN_REQ && params.freqs == NULL &&
909             wpa_s->manual_scan_freqs) {
910                 wpa_dbg(wpa_s, MSG_DEBUG, "Limit manual scan to specified channels");
911                 params.freqs = wpa_s->manual_scan_freqs;
912                 wpa_s->manual_scan_freqs = NULL;
913         }
914
915         if (params.freqs == NULL && wpa_s->next_scan_freqs) {
916                 wpa_dbg(wpa_s, MSG_DEBUG, "Optimize scan based on previously "
917                         "generated frequency list");
918                 params.freqs = wpa_s->next_scan_freqs;
919         } else
920                 os_free(wpa_s->next_scan_freqs);
921         wpa_s->next_scan_freqs = NULL;
922         wpa_setband_scan_freqs(wpa_s, &params);
923
924         /* See if user specified frequencies. If so, scan only those. */
925         if (wpa_s->conf->freq_list && !params.freqs) {
926                 wpa_dbg(wpa_s, MSG_DEBUG,
927                         "Optimize scan based on conf->freq_list");
928                 int_array_concat(&params.freqs, wpa_s->conf->freq_list);
929         }
930
931         /* Use current associated channel? */
932         if (wpa_s->conf->scan_cur_freq && !params.freqs) {
933                 unsigned int num = wpa_s->num_multichan_concurrent;
934
935                 params.freqs = os_calloc(num + 1, sizeof(int));
936                 if (params.freqs) {
937                         num = get_shared_radio_freqs(wpa_s, params.freqs, num);
938                         if (num > 0) {
939                                 wpa_dbg(wpa_s, MSG_DEBUG, "Scan only the "
940                                         "current operating channels since "
941                                         "scan_cur_freq is enabled");
942                         } else {
943                                 os_free(params.freqs);
944                                 params.freqs = NULL;
945                         }
946                 }
947         }
948
949         params.filter_ssids = wpa_supplicant_build_filter_ssids(
950                 wpa_s->conf, &params.num_filter_ssids);
951         if (extra_ie) {
952                 params.extra_ies = wpabuf_head(extra_ie);
953                 params.extra_ies_len = wpabuf_len(extra_ie);
954         }
955
956 #ifdef CONFIG_P2P
957         if (wpa_s->p2p_in_provisioning || wpa_s->p2p_in_invitation ||
958             (wpa_s->show_group_started && wpa_s->go_params)) {
959                 /*
960                  * The interface may not yet be in P2P mode, so we have to
961                  * explicitly request P2P probe to disable CCK rates.
962                  */
963                 params.p2p_probe = 1;
964         }
965 #endif /* CONFIG_P2P */
966
967         if (wpa_s->mac_addr_rand_enable & MAC_ADDR_RAND_SCAN) {
968                 params.mac_addr_rand = 1;
969                 if (wpa_s->mac_addr_scan) {
970                         params.mac_addr = wpa_s->mac_addr_scan;
971                         params.mac_addr_mask = wpa_s->mac_addr_scan + ETH_ALEN;
972                 }
973         }
974
975         scan_params = &params;
976
977 scan:
978 #ifdef CONFIG_P2P
979         /*
980          * If the driver does not support multi-channel concurrency and a
981          * virtual interface that shares the same radio with the wpa_s interface
982          * is operating there may not be need to scan other channels apart from
983          * the current operating channel on the other virtual interface. Filter
984          * out other channels in case we are trying to find a connection for a
985          * station interface when we are not configured to prefer station
986          * connection and a concurrent operation is already in process.
987          */
988         if (wpa_s->scan_for_connection &&
989             wpa_s->last_scan_req == NORMAL_SCAN_REQ &&
990             !scan_params->freqs && !params.freqs &&
991             wpas_is_p2p_prioritized(wpa_s) &&
992             wpa_s->p2p_group_interface == NOT_P2P_GROUP_INTERFACE &&
993             non_p2p_network_enabled(wpa_s)) {
994                 unsigned int num = wpa_s->num_multichan_concurrent;
995
996                 params.freqs = os_calloc(num + 1, sizeof(int));
997                 if (params.freqs) {
998                         num = get_shared_radio_freqs(wpa_s, params.freqs, num);
999                         if (num > 0 && num == wpa_s->num_multichan_concurrent) {
1000                                 wpa_dbg(wpa_s, MSG_DEBUG, "Scan only the current operating channels since all channels are already used");
1001                         } else {
1002                                 os_free(params.freqs);
1003                                 params.freqs = NULL;
1004                         }
1005                 }
1006         }
1007 #endif /* CONFIG_P2P */
1008
1009         ret = wpa_supplicant_trigger_scan(wpa_s, scan_params);
1010
1011         if (ret && wpa_s->last_scan_req == MANUAL_SCAN_REQ && params.freqs &&
1012             !wpa_s->manual_scan_freqs) {
1013                 /* Restore manual_scan_freqs for the next attempt */
1014                 wpa_s->manual_scan_freqs = params.freqs;
1015                 params.freqs = NULL;
1016         }
1017
1018         wpabuf_free(extra_ie);
1019         os_free(params.freqs);
1020         os_free(params.filter_ssids);
1021
1022         if (ret) {
1023                 wpa_msg(wpa_s, MSG_WARNING, "Failed to initiate AP scan");
1024                 if (wpa_s->scan_prev_wpa_state != wpa_s->wpa_state)
1025                         wpa_supplicant_set_state(wpa_s,
1026                                                  wpa_s->scan_prev_wpa_state);
1027                 /* Restore scan_req since we will try to scan again */
1028                 wpa_s->scan_req = wpa_s->last_scan_req;
1029                 wpa_supplicant_req_scan(wpa_s, 1, 0);
1030         } else {
1031                 wpa_s->scan_for_connection = 0;
1032 #ifdef CONFIG_INTERWORKING
1033                 wpa_s->interworking_fast_assoc_tried = 0;
1034 #endif /* CONFIG_INTERWORKING */
1035         }
1036 }
1037
1038
1039 void wpa_supplicant_update_scan_int(struct wpa_supplicant *wpa_s, int sec)
1040 {
1041         struct os_reltime remaining, new_int;
1042         int cancelled;
1043
1044         cancelled = eloop_cancel_timeout_one(wpa_supplicant_scan, wpa_s, NULL,
1045                                              &remaining);
1046
1047         new_int.sec = sec;
1048         new_int.usec = 0;
1049         if (cancelled && os_reltime_before(&remaining, &new_int)) {
1050                 new_int.sec = remaining.sec;
1051                 new_int.usec = remaining.usec;
1052         }
1053
1054         if (cancelled) {
1055                 eloop_register_timeout(new_int.sec, new_int.usec,
1056                                        wpa_supplicant_scan, wpa_s, NULL);
1057         }
1058         wpa_s->scan_interval = sec;
1059 }
1060
1061
1062 /**
1063  * wpa_supplicant_req_scan - Schedule a scan for neighboring access points
1064  * @wpa_s: Pointer to wpa_supplicant data
1065  * @sec: Number of seconds after which to scan
1066  * @usec: Number of microseconds after which to scan
1067  *
1068  * This function is used to schedule a scan for neighboring access points after
1069  * the specified time.
1070  */
1071 void wpa_supplicant_req_scan(struct wpa_supplicant *wpa_s, int sec, int usec)
1072 {
1073         int res;
1074
1075         if (wpa_s->p2p_mgmt) {
1076                 wpa_dbg(wpa_s, MSG_DEBUG,
1077                         "Ignore scan request (%d.%06d sec) on p2p_mgmt interface",
1078                         sec, usec);
1079                 return;
1080         }
1081
1082         res = eloop_deplete_timeout(sec, usec, wpa_supplicant_scan, wpa_s,
1083                                     NULL);
1084         if (res == 1) {
1085                 wpa_dbg(wpa_s, MSG_DEBUG, "Rescheduling scan request: %d.%06d sec",
1086                         sec, usec);
1087         } else if (res == 0) {
1088                 wpa_dbg(wpa_s, MSG_DEBUG, "Ignore new scan request for %d.%06d sec since an earlier request is scheduled to trigger sooner",
1089                         sec, usec);
1090         } else {
1091                 wpa_dbg(wpa_s, MSG_DEBUG, "Setting scan request: %d.%06d sec",
1092                         sec, usec);
1093                 eloop_register_timeout(sec, usec, wpa_supplicant_scan, wpa_s, NULL);
1094         }
1095 }
1096
1097
1098 /**
1099  * wpa_supplicant_delayed_sched_scan - Request a delayed scheduled scan
1100  * @wpa_s: Pointer to wpa_supplicant data
1101  * @sec: Number of seconds after which to scan
1102  * @usec: Number of microseconds after which to scan
1103  * Returns: 0 on success or -1 otherwise
1104  *
1105  * This function is used to schedule periodic scans for neighboring
1106  * access points after the specified time.
1107  */
1108 int wpa_supplicant_delayed_sched_scan(struct wpa_supplicant *wpa_s,
1109                                       int sec, int usec)
1110 {
1111         if (!wpa_s->sched_scan_supported)
1112                 return -1;
1113
1114         eloop_register_timeout(sec, usec,
1115                                wpa_supplicant_delayed_sched_scan_timeout,
1116                                wpa_s, NULL);
1117
1118         return 0;
1119 }
1120
1121
1122 /**
1123  * wpa_supplicant_req_sched_scan - Start a periodic scheduled scan
1124  * @wpa_s: Pointer to wpa_supplicant data
1125  * Returns: 0 is sched_scan was started or -1 otherwise
1126  *
1127  * This function is used to schedule periodic scans for neighboring
1128  * access points repeating the scan continuously.
1129  */
1130 int wpa_supplicant_req_sched_scan(struct wpa_supplicant *wpa_s)
1131 {
1132         struct wpa_driver_scan_params params;
1133         struct wpa_driver_scan_params *scan_params;
1134         enum wpa_states prev_state;
1135         struct wpa_ssid *ssid = NULL;
1136         struct wpabuf *extra_ie = NULL;
1137         int ret;
1138         unsigned int max_sched_scan_ssids;
1139         int wildcard = 0;
1140         int need_ssids;
1141
1142         if (!wpa_s->sched_scan_supported)
1143                 return -1;
1144
1145         if (wpa_s->max_sched_scan_ssids > WPAS_MAX_SCAN_SSIDS)
1146                 max_sched_scan_ssids = WPAS_MAX_SCAN_SSIDS;
1147         else
1148                 max_sched_scan_ssids = wpa_s->max_sched_scan_ssids;
1149         if (max_sched_scan_ssids < 1 || wpa_s->conf->disable_scan_offload)
1150                 return -1;
1151
1152         if (wpa_s->sched_scanning) {
1153                 wpa_dbg(wpa_s, MSG_DEBUG, "Already sched scanning");
1154                 return 0;
1155         }
1156
1157         need_ssids = 0;
1158         for (ssid = wpa_s->conf->ssid; ssid; ssid = ssid->next) {
1159                 if (!wpas_network_disabled(wpa_s, ssid) && !ssid->scan_ssid) {
1160                         /* Use wildcard SSID to find this network */
1161                         wildcard = 1;
1162                 } else if (!wpas_network_disabled(wpa_s, ssid) &&
1163                            ssid->ssid_len)
1164                         need_ssids++;
1165
1166 #ifdef CONFIG_WPS
1167                 if (!wpas_network_disabled(wpa_s, ssid) &&
1168                     ssid->key_mgmt == WPA_KEY_MGMT_WPS) {
1169                         /*
1170                          * Normal scan is more reliable and faster for WPS
1171                          * operations and since these are for short periods of
1172                          * time, the benefit of trying to use sched_scan would
1173                          * be limited.
1174                          */
1175                         wpa_dbg(wpa_s, MSG_DEBUG, "Use normal scan instead of "
1176                                 "sched_scan for WPS");
1177                         return -1;
1178                 }
1179 #endif /* CONFIG_WPS */
1180         }
1181         if (wildcard)
1182                 need_ssids++;
1183
1184         if (wpa_s->normal_scans < 3 &&
1185             (need_ssids <= wpa_s->max_scan_ssids ||
1186              wpa_s->max_scan_ssids >= (int) max_sched_scan_ssids)) {
1187                 /*
1188                  * When normal scan can speed up operations, use that for the
1189                  * first operations before starting the sched_scan to allow
1190                  * user space sleep more. We do this only if the normal scan
1191                  * has functionality that is suitable for this or if the
1192                  * sched_scan does not have better support for multiple SSIDs.
1193                  */
1194                 wpa_dbg(wpa_s, MSG_DEBUG, "Use normal scan instead of "
1195                         "sched_scan for initial scans (normal_scans=%d)",
1196                         wpa_s->normal_scans);
1197                 return -1;
1198         }
1199
1200         os_memset(&params, 0, sizeof(params));
1201
1202         /* If we can't allocate space for the filters, we just don't filter */
1203         params.filter_ssids = os_calloc(wpa_s->max_match_sets,
1204                                         sizeof(struct wpa_driver_scan_filter));
1205
1206         prev_state = wpa_s->wpa_state;
1207         if (wpa_s->wpa_state == WPA_DISCONNECTED ||
1208             wpa_s->wpa_state == WPA_INACTIVE)
1209                 wpa_supplicant_set_state(wpa_s, WPA_SCANNING);
1210
1211         if (wpa_s->autoscan_params != NULL) {
1212                 scan_params = wpa_s->autoscan_params;
1213                 goto scan;
1214         }
1215
1216         /* Find the starting point from which to continue scanning */
1217         ssid = wpa_s->conf->ssid;
1218         if (wpa_s->prev_sched_ssid) {
1219                 while (ssid) {
1220                         if (ssid == wpa_s->prev_sched_ssid) {
1221                                 ssid = ssid->next;
1222                                 break;
1223                         }
1224                         ssid = ssid->next;
1225                 }
1226         }
1227
1228         if (!ssid || !wpa_s->prev_sched_ssid) {
1229                 wpa_dbg(wpa_s, MSG_DEBUG, "Beginning of SSID list");
1230                 if (wpa_s->conf->sched_scan_interval)
1231                         wpa_s->sched_scan_interval =
1232                                 wpa_s->conf->sched_scan_interval;
1233                 if (wpa_s->sched_scan_interval == 0)
1234                         wpa_s->sched_scan_interval = 10;
1235                 wpa_s->sched_scan_timeout = max_sched_scan_ssids * 2;
1236                 wpa_s->first_sched_scan = 1;
1237                 ssid = wpa_s->conf->ssid;
1238                 wpa_s->prev_sched_ssid = ssid;
1239         }
1240
1241         if (wildcard) {
1242                 wpa_dbg(wpa_s, MSG_DEBUG, "Add wildcard SSID to sched_scan");
1243                 params.num_ssids++;
1244         }
1245
1246         while (ssid) {
1247                 if (wpas_network_disabled(wpa_s, ssid))
1248                         goto next;
1249
1250                 if (params.num_filter_ssids < wpa_s->max_match_sets &&
1251                     params.filter_ssids && ssid->ssid && ssid->ssid_len) {
1252                         wpa_dbg(wpa_s, MSG_DEBUG, "add to filter ssid: %s",
1253                                 wpa_ssid_txt(ssid->ssid, ssid->ssid_len));
1254                         os_memcpy(params.filter_ssids[params.num_filter_ssids].ssid,
1255                                   ssid->ssid, ssid->ssid_len);
1256                         params.filter_ssids[params.num_filter_ssids].ssid_len =
1257                                 ssid->ssid_len;
1258                         params.num_filter_ssids++;
1259                 } else if (params.filter_ssids && ssid->ssid && ssid->ssid_len)
1260                 {
1261                         wpa_dbg(wpa_s, MSG_DEBUG, "Not enough room for SSID "
1262                                 "filter for sched_scan - drop filter");
1263                         os_free(params.filter_ssids);
1264                         params.filter_ssids = NULL;
1265                         params.num_filter_ssids = 0;
1266                 }
1267
1268                 if (ssid->scan_ssid && ssid->ssid && ssid->ssid_len) {
1269                         if (params.num_ssids == max_sched_scan_ssids)
1270                                 break; /* only room for broadcast SSID */
1271                         wpa_dbg(wpa_s, MSG_DEBUG,
1272                                 "add to active scan ssid: %s",
1273                                 wpa_ssid_txt(ssid->ssid, ssid->ssid_len));
1274                         params.ssids[params.num_ssids].ssid =
1275                                 ssid->ssid;
1276                         params.ssids[params.num_ssids].ssid_len =
1277                                 ssid->ssid_len;
1278                         params.num_ssids++;
1279                         if (params.num_ssids >= max_sched_scan_ssids) {
1280                                 wpa_s->prev_sched_ssid = ssid;
1281                                 do {
1282                                         ssid = ssid->next;
1283                                 } while (ssid &&
1284                                          (wpas_network_disabled(wpa_s, ssid) ||
1285                                           !ssid->scan_ssid));
1286                                 break;
1287                         }
1288                 }
1289
1290         next:
1291                 wpa_s->prev_sched_ssid = ssid;
1292                 ssid = ssid->next;
1293         }
1294
1295         if (params.num_filter_ssids == 0) {
1296                 os_free(params.filter_ssids);
1297                 params.filter_ssids = NULL;
1298         }
1299
1300         extra_ie = wpa_supplicant_extra_ies(wpa_s);
1301         if (extra_ie) {
1302                 params.extra_ies = wpabuf_head(extra_ie);
1303                 params.extra_ies_len = wpabuf_len(extra_ie);
1304         }
1305
1306         if (wpa_s->conf->filter_rssi)
1307                 params.filter_rssi = wpa_s->conf->filter_rssi;
1308
1309         /* See if user specified frequencies. If so, scan only those. */
1310         if (wpa_s->conf->freq_list && !params.freqs) {
1311                 wpa_dbg(wpa_s, MSG_DEBUG,
1312                         "Optimize scan based on conf->freq_list");
1313                 int_array_concat(&params.freqs, wpa_s->conf->freq_list);
1314         }
1315
1316         scan_params = &params;
1317
1318 scan:
1319         if (ssid || !wpa_s->first_sched_scan) {
1320                 wpa_dbg(wpa_s, MSG_DEBUG,
1321                         "Starting sched scan: interval %d timeout %d",
1322                         wpa_s->sched_scan_interval, wpa_s->sched_scan_timeout);
1323         } else {
1324                 wpa_dbg(wpa_s, MSG_DEBUG,
1325                         "Starting sched scan: interval %d (no timeout)",
1326                         wpa_s->sched_scan_interval);
1327         }
1328
1329         wpa_setband_scan_freqs(wpa_s, scan_params);
1330
1331         if (wpa_s->mac_addr_rand_enable & MAC_ADDR_RAND_SCHED_SCAN) {
1332                 params.mac_addr_rand = 1;
1333                 if (wpa_s->mac_addr_sched_scan) {
1334                         params.mac_addr = wpa_s->mac_addr_sched_scan;
1335                         params.mac_addr_mask = wpa_s->mac_addr_sched_scan +
1336                                 ETH_ALEN;
1337                 }
1338         }
1339
1340         ret = wpa_supplicant_start_sched_scan(wpa_s, scan_params,
1341                                               wpa_s->sched_scan_interval);
1342         wpabuf_free(extra_ie);
1343         os_free(params.filter_ssids);
1344         if (ret) {
1345                 wpa_msg(wpa_s, MSG_WARNING, "Failed to initiate sched scan");
1346                 if (prev_state != wpa_s->wpa_state)
1347                         wpa_supplicant_set_state(wpa_s, prev_state);
1348                 return ret;
1349         }
1350
1351         /* If we have more SSIDs to scan, add a timeout so we scan them too */
1352         if (ssid || !wpa_s->first_sched_scan) {
1353                 wpa_s->sched_scan_timed_out = 0;
1354                 eloop_register_timeout(wpa_s->sched_scan_timeout, 0,
1355                                        wpa_supplicant_sched_scan_timeout,
1356                                        wpa_s, NULL);
1357                 wpa_s->first_sched_scan = 0;
1358                 wpa_s->sched_scan_timeout /= 2;
1359                 wpa_s->sched_scan_interval *= 2;
1360                 if (wpa_s->sched_scan_timeout < wpa_s->sched_scan_interval) {
1361                         wpa_s->sched_scan_interval = 10;
1362                         wpa_s->sched_scan_timeout = max_sched_scan_ssids * 2;
1363                 }
1364         }
1365
1366         /* If there is no more ssids, start next time from the beginning */
1367         if (!ssid)
1368                 wpa_s->prev_sched_ssid = NULL;
1369
1370         return 0;
1371 }
1372
1373
1374 /**
1375  * wpa_supplicant_cancel_scan - Cancel a scheduled scan request
1376  * @wpa_s: Pointer to wpa_supplicant data
1377  *
1378  * This function is used to cancel a scan request scheduled with
1379  * wpa_supplicant_req_scan().
1380  */
1381 void wpa_supplicant_cancel_scan(struct wpa_supplicant *wpa_s)
1382 {
1383         wpa_dbg(wpa_s, MSG_DEBUG, "Cancelling scan request");
1384         eloop_cancel_timeout(wpa_supplicant_scan, wpa_s, NULL);
1385 }
1386
1387
1388 /**
1389  * wpa_supplicant_cancel_delayed_sched_scan - Stop a delayed scheduled scan
1390  * @wpa_s: Pointer to wpa_supplicant data
1391  *
1392  * This function is used to stop a delayed scheduled scan.
1393  */
1394 void wpa_supplicant_cancel_delayed_sched_scan(struct wpa_supplicant *wpa_s)
1395 {
1396         if (!wpa_s->sched_scan_supported)
1397                 return;
1398
1399         wpa_dbg(wpa_s, MSG_DEBUG, "Cancelling delayed sched scan");
1400         eloop_cancel_timeout(wpa_supplicant_delayed_sched_scan_timeout,
1401                              wpa_s, NULL);
1402 }
1403
1404
1405 /**
1406  * wpa_supplicant_cancel_sched_scan - Stop running scheduled scans
1407  * @wpa_s: Pointer to wpa_supplicant data
1408  *
1409  * This function is used to stop a periodic scheduled scan.
1410  */
1411 void wpa_supplicant_cancel_sched_scan(struct wpa_supplicant *wpa_s)
1412 {
1413         if (!wpa_s->sched_scanning)
1414                 return;
1415
1416         wpa_dbg(wpa_s, MSG_DEBUG, "Cancelling sched scan");
1417         eloop_cancel_timeout(wpa_supplicant_sched_scan_timeout, wpa_s, NULL);
1418         wpa_supplicant_stop_sched_scan(wpa_s);
1419 }
1420
1421
1422 /**
1423  * wpa_supplicant_notify_scanning - Indicate possible scan state change
1424  * @wpa_s: Pointer to wpa_supplicant data
1425  * @scanning: Whether scanning is currently in progress
1426  *
1427  * This function is to generate scanning notifycations. It is called whenever
1428  * there may have been a change in scanning (scan started, completed, stopped).
1429  * wpas_notify_scanning() is called whenever the scanning state changed from the
1430  * previously notified state.
1431  */
1432 void wpa_supplicant_notify_scanning(struct wpa_supplicant *wpa_s,
1433                                     int scanning)
1434 {
1435         if (wpa_s->scanning != scanning) {
1436                 wpa_s->scanning = scanning;
1437                 wpas_notify_scanning(wpa_s);
1438         }
1439 }
1440
1441
1442 static int wpa_scan_get_max_rate(const struct wpa_scan_res *res)
1443 {
1444         int rate = 0;
1445         const u8 *ie;
1446         int i;
1447
1448         ie = wpa_scan_get_ie(res, WLAN_EID_SUPP_RATES);
1449         for (i = 0; ie && i < ie[1]; i++) {
1450                 if ((ie[i + 2] & 0x7f) > rate)
1451                         rate = ie[i + 2] & 0x7f;
1452         }
1453
1454         ie = wpa_scan_get_ie(res, WLAN_EID_EXT_SUPP_RATES);
1455         for (i = 0; ie && i < ie[1]; i++) {
1456                 if ((ie[i + 2] & 0x7f) > rate)
1457                         rate = ie[i + 2] & 0x7f;
1458         }
1459
1460         return rate;
1461 }
1462
1463
1464 /**
1465  * wpa_scan_get_ie - Fetch a specified information element from a scan result
1466  * @res: Scan result entry
1467  * @ie: Information element identitifier (WLAN_EID_*)
1468  * Returns: Pointer to the information element (id field) or %NULL if not found
1469  *
1470  * This function returns the first matching information element in the scan
1471  * result.
1472  */
1473 const u8 * wpa_scan_get_ie(const struct wpa_scan_res *res, u8 ie)
1474 {
1475         const u8 *end, *pos;
1476
1477         pos = (const u8 *) (res + 1);
1478         end = pos + res->ie_len;
1479
1480         while (pos + 1 < end) {
1481                 if (pos + 2 + pos[1] > end)
1482                         break;
1483                 if (pos[0] == ie)
1484                         return pos;
1485                 pos += 2 + pos[1];
1486         }
1487
1488         return NULL;
1489 }
1490
1491
1492 /**
1493  * wpa_scan_get_vendor_ie - Fetch vendor information element from a scan result
1494  * @res: Scan result entry
1495  * @vendor_type: Vendor type (four octets starting the IE payload)
1496  * Returns: Pointer to the information element (id field) or %NULL if not found
1497  *
1498  * This function returns the first matching information element in the scan
1499  * result.
1500  */
1501 const u8 * wpa_scan_get_vendor_ie(const struct wpa_scan_res *res,
1502                                   u32 vendor_type)
1503 {
1504         const u8 *end, *pos;
1505
1506         pos = (const u8 *) (res + 1);
1507         end = pos + res->ie_len;
1508
1509         while (pos + 1 < end) {
1510                 if (pos + 2 + pos[1] > end)
1511                         break;
1512                 if (pos[0] == WLAN_EID_VENDOR_SPECIFIC && pos[1] >= 4 &&
1513                     vendor_type == WPA_GET_BE32(&pos[2]))
1514                         return pos;
1515                 pos += 2 + pos[1];
1516         }
1517
1518         return NULL;
1519 }
1520
1521
1522 /**
1523  * wpa_scan_get_vendor_ie_beacon - Fetch vendor information from a scan result
1524  * @res: Scan result entry
1525  * @vendor_type: Vendor type (four octets starting the IE payload)
1526  * Returns: Pointer to the information element (id field) or %NULL if not found
1527  *
1528  * This function returns the first matching information element in the scan
1529  * result.
1530  *
1531  * This function is like wpa_scan_get_vendor_ie(), but uses IE buffer only
1532  * from Beacon frames instead of either Beacon or Probe Response frames.
1533  */
1534 const u8 * wpa_scan_get_vendor_ie_beacon(const struct wpa_scan_res *res,
1535                                          u32 vendor_type)
1536 {
1537         const u8 *end, *pos;
1538
1539         if (res->beacon_ie_len == 0)
1540                 return NULL;
1541
1542         pos = (const u8 *) (res + 1);
1543         pos += res->ie_len;
1544         end = pos + res->beacon_ie_len;
1545
1546         while (pos + 1 < end) {
1547                 if (pos + 2 + pos[1] > end)
1548                         break;
1549                 if (pos[0] == WLAN_EID_VENDOR_SPECIFIC && pos[1] >= 4 &&
1550                     vendor_type == WPA_GET_BE32(&pos[2]))
1551                         return pos;
1552                 pos += 2 + pos[1];
1553         }
1554
1555         return NULL;
1556 }
1557
1558
1559 /**
1560  * wpa_scan_get_vendor_ie_multi - Fetch vendor IE data from a scan result
1561  * @res: Scan result entry
1562  * @vendor_type: Vendor type (four octets starting the IE payload)
1563  * Returns: Pointer to the information element payload or %NULL if not found
1564  *
1565  * This function returns concatenated payload of possibly fragmented vendor
1566  * specific information elements in the scan result. The caller is responsible
1567  * for freeing the returned buffer.
1568  */
1569 struct wpabuf * wpa_scan_get_vendor_ie_multi(const struct wpa_scan_res *res,
1570                                              u32 vendor_type)
1571 {
1572         struct wpabuf *buf;
1573         const u8 *end, *pos;
1574
1575         buf = wpabuf_alloc(res->ie_len);
1576         if (buf == NULL)
1577                 return NULL;
1578
1579         pos = (const u8 *) (res + 1);
1580         end = pos + res->ie_len;
1581
1582         while (pos + 1 < end) {
1583                 if (pos + 2 + pos[1] > end)
1584                         break;
1585                 if (pos[0] == WLAN_EID_VENDOR_SPECIFIC && pos[1] >= 4 &&
1586                     vendor_type == WPA_GET_BE32(&pos[2]))
1587                         wpabuf_put_data(buf, pos + 2 + 4, pos[1] - 4);
1588                 pos += 2 + pos[1];
1589         }
1590
1591         if (wpabuf_len(buf) == 0) {
1592                 wpabuf_free(buf);
1593                 buf = NULL;
1594         }
1595
1596         return buf;
1597 }
1598
1599
1600 /*
1601  * Channels with a great SNR can operate at full rate. What is a great SNR?
1602  * This doc https://supportforums.cisco.com/docs/DOC-12954 says, "the general
1603  * rule of thumb is that any SNR above 20 is good." This one
1604  * http://www.cisco.com/en/US/tech/tk722/tk809/technologies_q_and_a_item09186a00805e9a96.shtml#qa23
1605  * recommends 25 as a minimum SNR for 54 Mbps data rate. 30 is chosen here as a
1606  * conservative value.
1607  */
1608 #define GREAT_SNR 30
1609
1610 #define IS_5GHZ(n) (n > 4000)
1611
1612 /* Compare function for sorting scan results. Return >0 if @b is considered
1613  * better. */
1614 static int wpa_scan_result_compar(const void *a, const void *b)
1615 {
1616 #define MIN(a,b) a < b ? a : b
1617         struct wpa_scan_res **_wa = (void *) a;
1618         struct wpa_scan_res **_wb = (void *) b;
1619         struct wpa_scan_res *wa = *_wa;
1620         struct wpa_scan_res *wb = *_wb;
1621         int wpa_a, wpa_b;
1622         int snr_a, snr_b, snr_a_full, snr_b_full;
1623
1624         /* WPA/WPA2 support preferred */
1625         wpa_a = wpa_scan_get_vendor_ie(wa, WPA_IE_VENDOR_TYPE) != NULL ||
1626                 wpa_scan_get_ie(wa, WLAN_EID_RSN) != NULL;
1627         wpa_b = wpa_scan_get_vendor_ie(wb, WPA_IE_VENDOR_TYPE) != NULL ||
1628                 wpa_scan_get_ie(wb, WLAN_EID_RSN) != NULL;
1629
1630         if (wpa_b && !wpa_a)
1631                 return 1;
1632         if (!wpa_b && wpa_a)
1633                 return -1;
1634
1635         /* privacy support preferred */
1636         if ((wa->caps & IEEE80211_CAP_PRIVACY) == 0 &&
1637             (wb->caps & IEEE80211_CAP_PRIVACY))
1638                 return 1;
1639         if ((wa->caps & IEEE80211_CAP_PRIVACY) &&
1640             (wb->caps & IEEE80211_CAP_PRIVACY) == 0)
1641                 return -1;
1642
1643         if (wa->flags & wb->flags & WPA_SCAN_LEVEL_DBM) {
1644                 snr_a_full = wa->snr;
1645                 snr_a = MIN(wa->snr, GREAT_SNR);
1646                 snr_b_full = wb->snr;
1647                 snr_b = MIN(wa->snr, GREAT_SNR);
1648         } else {
1649                 /* Level is not in dBm, so we can't calculate
1650                  * SNR. Just use raw level (units unknown). */
1651                 snr_a = snr_a_full = wa->level;
1652                 snr_b = snr_b_full = wb->level;
1653         }
1654
1655         /* if SNR is close, decide by max rate or frequency band */
1656         if ((snr_a && snr_b && abs(snr_b - snr_a) < 5) ||
1657             (wa->qual && wb->qual && abs(wb->qual - wa->qual) < 10)) {
1658                 if (wa->est_throughput != wb->est_throughput)
1659                         return wb->est_throughput - wa->est_throughput;
1660                 if (IS_5GHZ(wa->freq) ^ IS_5GHZ(wb->freq))
1661                         return IS_5GHZ(wa->freq) ? -1 : 1;
1662         }
1663
1664         /* all things being equal, use SNR; if SNRs are
1665          * identical, use quality values since some drivers may only report
1666          * that value and leave the signal level zero */
1667         if (snr_b_full == snr_a_full)
1668                 return wb->qual - wa->qual;
1669         return snr_b_full - snr_a_full;
1670 #undef MIN
1671 }
1672
1673
1674 #ifdef CONFIG_WPS
1675 /* Compare function for sorting scan results when searching a WPS AP for
1676  * provisioning. Return >0 if @b is considered better. */
1677 static int wpa_scan_result_wps_compar(const void *a, const void *b)
1678 {
1679         struct wpa_scan_res **_wa = (void *) a;
1680         struct wpa_scan_res **_wb = (void *) b;
1681         struct wpa_scan_res *wa = *_wa;
1682         struct wpa_scan_res *wb = *_wb;
1683         int uses_wps_a, uses_wps_b;
1684         struct wpabuf *wps_a, *wps_b;
1685         int res;
1686
1687         /* Optimization - check WPS IE existence before allocated memory and
1688          * doing full reassembly. */
1689         uses_wps_a = wpa_scan_get_vendor_ie(wa, WPS_IE_VENDOR_TYPE) != NULL;
1690         uses_wps_b = wpa_scan_get_vendor_ie(wb, WPS_IE_VENDOR_TYPE) != NULL;
1691         if (uses_wps_a && !uses_wps_b)
1692                 return -1;
1693         if (!uses_wps_a && uses_wps_b)
1694                 return 1;
1695
1696         if (uses_wps_a && uses_wps_b) {
1697                 wps_a = wpa_scan_get_vendor_ie_multi(wa, WPS_IE_VENDOR_TYPE);
1698                 wps_b = wpa_scan_get_vendor_ie_multi(wb, WPS_IE_VENDOR_TYPE);
1699                 res = wps_ap_priority_compar(wps_a, wps_b);
1700                 wpabuf_free(wps_a);
1701                 wpabuf_free(wps_b);
1702                 if (res)
1703                         return res;
1704         }
1705
1706         /*
1707          * Do not use current AP security policy as a sorting criteria during
1708          * WPS provisioning step since the AP may get reconfigured at the
1709          * completion of provisioning.
1710          */
1711
1712         /* all things being equal, use signal level; if signal levels are
1713          * identical, use quality values since some drivers may only report
1714          * that value and leave the signal level zero */
1715         if (wb->level == wa->level)
1716                 return wb->qual - wa->qual;
1717         return wb->level - wa->level;
1718 }
1719 #endif /* CONFIG_WPS */
1720
1721
1722 static void dump_scan_res(struct wpa_scan_results *scan_res)
1723 {
1724 #ifndef CONFIG_NO_STDOUT_DEBUG
1725         size_t i;
1726
1727         if (scan_res->res == NULL || scan_res->num == 0)
1728                 return;
1729
1730         wpa_printf(MSG_EXCESSIVE, "Sorted scan results");
1731
1732         for (i = 0; i < scan_res->num; i++) {
1733                 struct wpa_scan_res *r = scan_res->res[i];
1734                 u8 *pos;
1735                 if (r->flags & WPA_SCAN_LEVEL_DBM) {
1736                         int noise_valid = !(r->flags & WPA_SCAN_NOISE_INVALID);
1737
1738                         wpa_printf(MSG_EXCESSIVE, MACSTR " freq=%d qual=%d "
1739                                    "noise=%d%s level=%d snr=%d%s flags=0x%x age=%u est=%u",
1740                                    MAC2STR(r->bssid), r->freq, r->qual,
1741                                    r->noise, noise_valid ? "" : "~", r->level,
1742                                    r->snr, r->snr >= GREAT_SNR ? "*" : "",
1743                                    r->flags,
1744                                    r->age, r->est_throughput);
1745                 } else {
1746                         wpa_printf(MSG_EXCESSIVE, MACSTR " freq=%d qual=%d "
1747                                    "noise=%d level=%d flags=0x%x age=%u est=%u",
1748                                    MAC2STR(r->bssid), r->freq, r->qual,
1749                                    r->noise, r->level, r->flags, r->age,
1750                                    r->est_throughput);
1751                 }
1752                 pos = (u8 *) (r + 1);
1753                 if (r->ie_len)
1754                         wpa_hexdump(MSG_EXCESSIVE, "IEs", pos, r->ie_len);
1755                 pos += r->ie_len;
1756                 if (r->beacon_ie_len)
1757                         wpa_hexdump(MSG_EXCESSIVE, "Beacon IEs",
1758                                     pos, r->beacon_ie_len);
1759         }
1760 #endif /* CONFIG_NO_STDOUT_DEBUG */
1761 }
1762
1763
1764 /**
1765  * wpa_supplicant_filter_bssid_match - Is the specified BSSID allowed
1766  * @wpa_s: Pointer to wpa_supplicant data
1767  * @bssid: BSSID to check
1768  * Returns: 0 if the BSSID is filtered or 1 if not
1769  *
1770  * This function is used to filter out specific BSSIDs from scan reslts mainly
1771  * for testing purposes (SET bssid_filter ctrl_iface command).
1772  */
1773 int wpa_supplicant_filter_bssid_match(struct wpa_supplicant *wpa_s,
1774                                       const u8 *bssid)
1775 {
1776         size_t i;
1777
1778         if (wpa_s->bssid_filter == NULL)
1779                 return 1;
1780
1781         for (i = 0; i < wpa_s->bssid_filter_count; i++) {
1782                 if (os_memcmp(wpa_s->bssid_filter + i * ETH_ALEN, bssid,
1783                               ETH_ALEN) == 0)
1784                         return 1;
1785         }
1786
1787         return 0;
1788 }
1789
1790
1791 static void filter_scan_res(struct wpa_supplicant *wpa_s,
1792                             struct wpa_scan_results *res)
1793 {
1794         size_t i, j;
1795
1796         if (wpa_s->bssid_filter == NULL)
1797                 return;
1798
1799         for (i = 0, j = 0; i < res->num; i++) {
1800                 if (wpa_supplicant_filter_bssid_match(wpa_s,
1801                                                       res->res[i]->bssid)) {
1802                         res->res[j++] = res->res[i];
1803                 } else {
1804                         os_free(res->res[i]);
1805                         res->res[i] = NULL;
1806                 }
1807         }
1808
1809         if (res->num != j) {
1810                 wpa_printf(MSG_DEBUG, "Filtered out %d scan results",
1811                            (int) (res->num - j));
1812                 res->num = j;
1813         }
1814 }
1815
1816
1817 /*
1818  * Noise floor values to use when we have signal strength
1819  * measurements, but no noise floor measurments. These values were
1820  * measured in an office environment with many APs.
1821  */
1822 #define DEFAULT_NOISE_FLOOR_2GHZ (-89)
1823 #define DEFAULT_NOISE_FLOOR_5GHZ (-92)
1824
1825 static void scan_snr(struct wpa_scan_res *res)
1826 {
1827         if (res->flags & WPA_SCAN_NOISE_INVALID) {
1828                 res->noise = IS_5GHZ(res->freq) ?
1829                         DEFAULT_NOISE_FLOOR_5GHZ :
1830                         DEFAULT_NOISE_FLOOR_2GHZ;
1831         }
1832
1833         if (res->flags & WPA_SCAN_LEVEL_DBM) {
1834                 res->snr = res->level - res->noise;
1835         } else {
1836                 /* Level is not in dBm, so we can't calculate
1837                  * SNR. Just use raw level (units unknown). */
1838                 res->snr = res->level;
1839         }
1840 }
1841
1842
1843 static unsigned int max_ht20_rate(int snr)
1844 {
1845         if (snr < 6)
1846                 return 6500; /* HT20 MCS0 */
1847         if (snr < 8)
1848                 return 13000; /* HT20 MCS1 */
1849         if (snr < 13)
1850                 return 19500; /* HT20 MCS2 */
1851         if (snr < 17)
1852                 return 26000; /* HT20 MCS3 */
1853         if (snr < 20)
1854                 return 39000; /* HT20 MCS4 */
1855         if (snr < 23)
1856                 return 52000; /* HT20 MCS5 */
1857         if (snr < 24)
1858                 return 58500; /* HT20 MCS6 */
1859         return 65000; /* HT20 MCS7 */
1860 }
1861
1862
1863 static unsigned int max_ht40_rate(int snr)
1864 {
1865         if (snr < 3)
1866                 return 13500; /* HT40 MCS0 */
1867         if (snr < 6)
1868                 return 27000; /* HT40 MCS1 */
1869         if (snr < 10)
1870                 return 40500; /* HT40 MCS2 */
1871         if (snr < 15)
1872                 return 54000; /* HT40 MCS3 */
1873         if (snr < 17)
1874                 return 81000; /* HT40 MCS4 */
1875         if (snr < 22)
1876                 return 108000; /* HT40 MCS5 */
1877         if (snr < 24)
1878                 return 121500; /* HT40 MCS6 */
1879         return 135000; /* HT40 MCS7 */
1880 }
1881
1882
1883 static unsigned int max_vht80_rate(int snr)
1884 {
1885         if (snr < 1)
1886                 return 0;
1887         if (snr < 2)
1888                 return 29300; /* VHT80 MCS0 */
1889         if (snr < 5)
1890                 return 58500; /* VHT80 MCS1 */
1891         if (snr < 9)
1892                 return 87800; /* VHT80 MCS2 */
1893         if (snr < 11)
1894                 return 117000; /* VHT80 MCS3 */
1895         if (snr < 15)
1896                 return 175500; /* VHT80 MCS4 */
1897         if (snr < 16)
1898                 return 234000; /* VHT80 MCS5 */
1899         if (snr < 18)
1900                 return 263300; /* VHT80 MCS6 */
1901         if (snr < 20)
1902                 return 292500; /* VHT80 MCS7 */
1903         if (snr < 22)
1904                 return 351000; /* VHT80 MCS8 */
1905         return 390000; /* VHT80 MCS9 */
1906 }
1907
1908
1909 static void scan_est_throughput(struct wpa_supplicant *wpa_s,
1910                                 struct wpa_scan_res *res)
1911 {
1912         enum local_hw_capab capab = wpa_s->hw_capab;
1913         int rate; /* max legacy rate in 500 kb/s units */
1914         const u8 *ie;
1915         unsigned int est, tmp;
1916         int snr = res->snr;
1917
1918         if (res->est_throughput)
1919                 return;
1920
1921         /* Get maximum legacy rate */
1922         rate = wpa_scan_get_max_rate(res);
1923
1924         /* Limit based on estimated SNR */
1925         if (rate > 1 * 2 && snr < 1)
1926                 rate = 1 * 2;
1927         else if (rate > 2 * 2 && snr < 4)
1928                 rate = 2 * 2;
1929         else if (rate > 6 * 2 && snr < 5)
1930                 rate = 6 * 2;
1931         else if (rate > 9 * 2 && snr < 6)
1932                 rate = 9 * 2;
1933         else if (rate > 12 * 2 && snr < 7)
1934                 rate = 12 * 2;
1935         else if (rate > 18 * 2 && snr < 10)
1936                 rate = 18 * 2;
1937         else if (rate > 24 * 2 && snr < 11)
1938                 rate = 24 * 2;
1939         else if (rate > 36 * 2 && snr < 15)
1940                 rate = 36 * 2;
1941         else if (rate > 48 * 2 && snr < 19)
1942                 rate = 48 * 2;
1943         else if (rate > 54 * 2 && snr < 21)
1944                 rate = 54 * 2;
1945         est = rate * 500;
1946
1947         if (capab == CAPAB_HT || capab == CAPAB_HT40 || capab == CAPAB_VHT) {
1948                 ie = wpa_scan_get_ie(res, WLAN_EID_HT_CAP);
1949                 if (ie) {
1950                         tmp = max_ht20_rate(snr);
1951                         if (tmp > est)
1952                                 est = tmp;
1953                 }
1954         }
1955
1956         if (capab == CAPAB_HT40 || capab == CAPAB_VHT) {
1957                 ie = wpa_scan_get_ie(res, WLAN_EID_HT_OPERATION);
1958                 if (ie && ie[1] >= 2 &&
1959                     (ie[3] & HT_INFO_HT_PARAM_SECONDARY_CHNL_OFF_MASK)) {
1960                         tmp = max_ht40_rate(snr);
1961                         if (tmp > est)
1962                                 est = tmp;
1963                 }
1964         }
1965
1966         if (capab == CAPAB_VHT) {
1967                 /* Use +1 to assume VHT is always faster than HT */
1968                 ie = wpa_scan_get_ie(res, WLAN_EID_VHT_CAP);
1969                 if (ie) {
1970                         tmp = max_ht20_rate(snr) + 1;
1971                         if (tmp > est)
1972                                 est = tmp;
1973
1974                         ie = wpa_scan_get_ie(res, WLAN_EID_HT_OPERATION);
1975                         if (ie && ie[1] >= 2 &&
1976                             (ie[3] &
1977                              HT_INFO_HT_PARAM_SECONDARY_CHNL_OFF_MASK)) {
1978                                 tmp = max_ht40_rate(snr) + 1;
1979                                 if (tmp > est)
1980                                         est = tmp;
1981                         }
1982
1983                         ie = wpa_scan_get_ie(res, WLAN_EID_VHT_OPERATION);
1984                         if (ie && ie[1] >= 1 &&
1985                             (ie[2] & VHT_OPMODE_CHANNEL_WIDTH_MASK)) {
1986                                 tmp = max_vht80_rate(snr) + 1;
1987                                 if (tmp > est)
1988                                         est = tmp;
1989                         }
1990                 }
1991         }
1992
1993         /* TODO: channel utilization and AP load (e.g., from AP Beacon) */
1994
1995         res->est_throughput = est;
1996 }
1997
1998
1999 /**
2000  * wpa_supplicant_get_scan_results - Get scan results
2001  * @wpa_s: Pointer to wpa_supplicant data
2002  * @info: Information about what was scanned or %NULL if not available
2003  * @new_scan: Whether a new scan was performed
2004  * Returns: Scan results, %NULL on failure
2005  *
2006  * This function request the current scan results from the driver and updates
2007  * the local BSS list wpa_s->bss. The caller is responsible for freeing the
2008  * results with wpa_scan_results_free().
2009  */
2010 struct wpa_scan_results *
2011 wpa_supplicant_get_scan_results(struct wpa_supplicant *wpa_s,
2012                                 struct scan_info *info, int new_scan)
2013 {
2014         struct wpa_scan_results *scan_res;
2015         size_t i;
2016         int (*compar)(const void *, const void *) = wpa_scan_result_compar;
2017
2018         scan_res = wpa_drv_get_scan_results2(wpa_s);
2019         if (scan_res == NULL) {
2020                 wpa_dbg(wpa_s, MSG_DEBUG, "Failed to get scan results");
2021                 return NULL;
2022         }
2023         if (scan_res->fetch_time.sec == 0) {
2024                 /*
2025                  * Make sure we have a valid timestamp if the driver wrapper
2026                  * does not set this.
2027                  */
2028                 os_get_reltime(&scan_res->fetch_time);
2029         }
2030         filter_scan_res(wpa_s, scan_res);
2031
2032         for (i = 0; i < scan_res->num; i++) {
2033                 struct wpa_scan_res *scan_res_item = scan_res->res[i];
2034
2035                 scan_snr(scan_res_item);
2036                 scan_est_throughput(wpa_s, scan_res_item);
2037         }
2038
2039 #ifdef CONFIG_WPS
2040         if (wpas_wps_searching(wpa_s)) {
2041                 wpa_dbg(wpa_s, MSG_DEBUG, "WPS: Order scan results with WPS "
2042                         "provisioning rules");
2043                 compar = wpa_scan_result_wps_compar;
2044         }
2045 #endif /* CONFIG_WPS */
2046
2047         qsort(scan_res->res, scan_res->num, sizeof(struct wpa_scan_res *),
2048               compar);
2049         dump_scan_res(scan_res);
2050
2051         wpa_bss_update_start(wpa_s);
2052         for (i = 0; i < scan_res->num; i++)
2053                 wpa_bss_update_scan_res(wpa_s, scan_res->res[i],
2054                                         &scan_res->fetch_time);
2055         wpa_bss_update_end(wpa_s, info, new_scan);
2056
2057         return scan_res;
2058 }
2059
2060
2061 /**
2062  * wpa_supplicant_update_scan_results - Update scan results from the driver
2063  * @wpa_s: Pointer to wpa_supplicant data
2064  * Returns: 0 on success, -1 on failure
2065  *
2066  * This function updates the BSS table within wpa_supplicant based on the
2067  * currently available scan results from the driver without requesting a new
2068  * scan. This is used in cases where the driver indicates an association
2069  * (including roaming within ESS) and wpa_supplicant does not yet have the
2070  * needed information to complete the connection (e.g., to perform validation
2071  * steps in 4-way handshake).
2072  */
2073 int wpa_supplicant_update_scan_results(struct wpa_supplicant *wpa_s)
2074 {
2075         struct wpa_scan_results *scan_res;
2076         scan_res = wpa_supplicant_get_scan_results(wpa_s, NULL, 0);
2077         if (scan_res == NULL)
2078                 return -1;
2079         wpa_scan_results_free(scan_res);
2080
2081         return 0;
2082 }
2083
2084
2085 /**
2086  * scan_only_handler - Reports scan results
2087  */
2088 void scan_only_handler(struct wpa_supplicant *wpa_s,
2089                        struct wpa_scan_results *scan_res)
2090 {
2091         wpa_dbg(wpa_s, MSG_DEBUG, "Scan-only results received");
2092         if (wpa_s->last_scan_req == MANUAL_SCAN_REQ &&
2093             wpa_s->manual_scan_use_id && wpa_s->own_scan_running) {
2094                 wpa_msg_ctrl(wpa_s, MSG_INFO, WPA_EVENT_SCAN_RESULTS "id=%u",
2095                              wpa_s->manual_scan_id);
2096                 wpa_s->manual_scan_use_id = 0;
2097         } else {
2098                 wpa_msg_ctrl(wpa_s, MSG_INFO, WPA_EVENT_SCAN_RESULTS);
2099         }
2100         wpas_notify_scan_results(wpa_s);
2101         wpas_notify_scan_done(wpa_s, 1);
2102         if (wpa_s->scan_work) {
2103                 struct wpa_radio_work *work = wpa_s->scan_work;
2104                 wpa_s->scan_work = NULL;
2105                 radio_work_done(work);
2106         }
2107 }
2108
2109
2110 int wpas_scan_scheduled(struct wpa_supplicant *wpa_s)
2111 {
2112         return eloop_is_timeout_registered(wpa_supplicant_scan, wpa_s, NULL);
2113 }
2114
2115
2116 struct wpa_driver_scan_params *
2117 wpa_scan_clone_params(const struct wpa_driver_scan_params *src)
2118 {
2119         struct wpa_driver_scan_params *params;
2120         size_t i;
2121         u8 *n;
2122
2123         params = os_zalloc(sizeof(*params));
2124         if (params == NULL)
2125                 return NULL;
2126
2127         for (i = 0; i < src->num_ssids; i++) {
2128                 if (src->ssids[i].ssid) {
2129                         n = os_malloc(src->ssids[i].ssid_len);
2130                         if (n == NULL)
2131                                 goto failed;
2132                         os_memcpy(n, src->ssids[i].ssid,
2133                                   src->ssids[i].ssid_len);
2134                         params->ssids[i].ssid = n;
2135                         params->ssids[i].ssid_len = src->ssids[i].ssid_len;
2136                 }
2137         }
2138         params->num_ssids = src->num_ssids;
2139
2140         if (src->extra_ies) {
2141                 n = os_malloc(src->extra_ies_len);
2142                 if (n == NULL)
2143                         goto failed;
2144                 os_memcpy(n, src->extra_ies, src->extra_ies_len);
2145                 params->extra_ies = n;
2146                 params->extra_ies_len = src->extra_ies_len;
2147         }
2148
2149         if (src->freqs) {
2150                 int len = int_array_len(src->freqs);
2151                 params->freqs = os_malloc((len + 1) * sizeof(int));
2152                 if (params->freqs == NULL)
2153                         goto failed;
2154                 os_memcpy(params->freqs, src->freqs, (len + 1) * sizeof(int));
2155         }
2156
2157         if (src->filter_ssids) {
2158                 params->filter_ssids = os_malloc(sizeof(*params->filter_ssids) *
2159                                                  src->num_filter_ssids);
2160                 if (params->filter_ssids == NULL)
2161                         goto failed;
2162                 os_memcpy(params->filter_ssids, src->filter_ssids,
2163                           sizeof(*params->filter_ssids) *
2164                           src->num_filter_ssids);
2165                 params->num_filter_ssids = src->num_filter_ssids;
2166         }
2167
2168         params->filter_rssi = src->filter_rssi;
2169         params->p2p_probe = src->p2p_probe;
2170         params->only_new_results = src->only_new_results;
2171         params->low_priority = src->low_priority;
2172
2173         if (src->mac_addr_rand) {
2174                 params->mac_addr_rand = src->mac_addr_rand;
2175
2176                 if (src->mac_addr && src->mac_addr_mask) {
2177                         u8 *mac_addr;
2178
2179                         mac_addr = os_malloc(2 * ETH_ALEN);
2180                         if (!mac_addr)
2181                                 goto failed;
2182
2183                         os_memcpy(mac_addr, src->mac_addr, ETH_ALEN);
2184                         os_memcpy(mac_addr + ETH_ALEN, src->mac_addr_mask,
2185                                   ETH_ALEN);
2186                         params->mac_addr = mac_addr;
2187                         params->mac_addr_mask = mac_addr + ETH_ALEN;
2188                 }
2189         }
2190         return params;
2191
2192 failed:
2193         wpa_scan_free_params(params);
2194         return NULL;
2195 }
2196
2197
2198 void wpa_scan_free_params(struct wpa_driver_scan_params *params)
2199 {
2200         size_t i;
2201
2202         if (params == NULL)
2203                 return;
2204
2205         for (i = 0; i < params->num_ssids; i++)
2206                 os_free((u8 *) params->ssids[i].ssid);
2207         os_free((u8 *) params->extra_ies);
2208         os_free(params->freqs);
2209         os_free(params->filter_ssids);
2210
2211         /*
2212          * Note: params->mac_addr_mask points to same memory allocation and
2213          * must not be freed separately.
2214          */
2215         os_free((u8 *) params->mac_addr);
2216
2217         os_free(params);
2218 }
2219
2220
2221 int wpas_start_pno(struct wpa_supplicant *wpa_s)
2222 {
2223         int ret, interval, prio;
2224         size_t i, num_ssid, num_match_ssid;
2225         struct wpa_ssid *ssid;
2226         struct wpa_driver_scan_params params;
2227
2228         if (!wpa_s->sched_scan_supported)
2229                 return -1;
2230
2231         if (wpa_s->pno || wpa_s->pno_sched_pending)
2232                 return 0;
2233
2234         if ((wpa_s->wpa_state > WPA_SCANNING) &&
2235             (wpa_s->wpa_state <= WPA_COMPLETED)) {
2236                 wpa_printf(MSG_ERROR, "PNO: In assoc process");
2237                 return -EAGAIN;
2238         }
2239
2240         if (wpa_s->wpa_state == WPA_SCANNING) {
2241                 wpa_supplicant_cancel_scan(wpa_s);
2242                 if (wpa_s->sched_scanning) {
2243                         wpa_printf(MSG_DEBUG, "Schedule PNO on completion of "
2244                                    "ongoing sched scan");
2245                         wpa_supplicant_cancel_sched_scan(wpa_s);
2246                         wpa_s->pno_sched_pending = 1;
2247                         return 0;
2248                 }
2249         }
2250
2251         os_memset(&params, 0, sizeof(params));
2252
2253         num_ssid = num_match_ssid = 0;
2254         ssid = wpa_s->conf->ssid;
2255         while (ssid) {
2256                 if (!wpas_network_disabled(wpa_s, ssid)) {
2257                         num_match_ssid++;
2258                         if (ssid->scan_ssid)
2259                                 num_ssid++;
2260                 }
2261                 ssid = ssid->next;
2262         }
2263
2264         if (num_match_ssid == 0) {
2265                 wpa_printf(MSG_DEBUG, "PNO: No configured SSIDs");
2266                 return -1;
2267         }
2268
2269         if (num_match_ssid > num_ssid) {
2270                 params.num_ssids++; /* wildcard */
2271                 num_ssid++;
2272         }
2273
2274         if (num_ssid > WPAS_MAX_SCAN_SSIDS) {
2275                 wpa_printf(MSG_DEBUG, "PNO: Use only the first %u SSIDs from "
2276                            "%u", WPAS_MAX_SCAN_SSIDS, (unsigned int) num_ssid);
2277                 num_ssid = WPAS_MAX_SCAN_SSIDS;
2278         }
2279
2280         if (num_match_ssid > wpa_s->max_match_sets) {
2281                 num_match_ssid = wpa_s->max_match_sets;
2282                 wpa_dbg(wpa_s, MSG_DEBUG, "PNO: Too many SSIDs to match");
2283         }
2284         params.filter_ssids = os_calloc(num_match_ssid,
2285                                         sizeof(struct wpa_driver_scan_filter));
2286         if (params.filter_ssids == NULL)
2287                 return -1;
2288
2289         i = 0;
2290         prio = 0;
2291         ssid = wpa_s->conf->pssid[prio];
2292         while (ssid) {
2293                 if (!wpas_network_disabled(wpa_s, ssid)) {
2294                         if (ssid->scan_ssid && params.num_ssids < num_ssid) {
2295                                 params.ssids[params.num_ssids].ssid =
2296                                         ssid->ssid;
2297                                 params.ssids[params.num_ssids].ssid_len =
2298                                          ssid->ssid_len;
2299                                 params.num_ssids++;
2300                         }
2301                         os_memcpy(params.filter_ssids[i].ssid, ssid->ssid,
2302                                   ssid->ssid_len);
2303                         params.filter_ssids[i].ssid_len = ssid->ssid_len;
2304                         params.num_filter_ssids++;
2305                         i++;
2306                         if (i == num_match_ssid)
2307                                 break;
2308                 }
2309                 if (ssid->pnext)
2310                         ssid = ssid->pnext;
2311                 else if (prio + 1 == wpa_s->conf->num_prio)
2312                         break;
2313                 else
2314                         ssid = wpa_s->conf->pssid[++prio];
2315         }
2316
2317         if (wpa_s->conf->filter_rssi)
2318                 params.filter_rssi = wpa_s->conf->filter_rssi;
2319
2320         interval = wpa_s->conf->sched_scan_interval ?
2321                 wpa_s->conf->sched_scan_interval : 10;
2322
2323         if (params.freqs == NULL && wpa_s->manual_sched_scan_freqs) {
2324                 wpa_dbg(wpa_s, MSG_DEBUG, "Limit sched scan to specified channels");
2325                 params.freqs = wpa_s->manual_sched_scan_freqs;
2326         }
2327
2328         if (wpa_s->mac_addr_rand_enable & MAC_ADDR_RAND_PNO) {
2329                 params.mac_addr_rand = 1;
2330                 if (wpa_s->mac_addr_pno) {
2331                         params.mac_addr = wpa_s->mac_addr_pno;
2332                         params.mac_addr_mask = wpa_s->mac_addr_pno + ETH_ALEN;
2333                 }
2334         }
2335
2336         ret = wpa_supplicant_start_sched_scan(wpa_s, &params, interval);
2337         os_free(params.filter_ssids);
2338         if (ret == 0)
2339                 wpa_s->pno = 1;
2340         else
2341                 wpa_msg(wpa_s, MSG_ERROR, "Failed to schedule PNO");
2342         return ret;
2343 }
2344
2345
2346 int wpas_stop_pno(struct wpa_supplicant *wpa_s)
2347 {
2348         int ret = 0;
2349
2350         if (!wpa_s->pno)
2351                 return 0;
2352
2353         ret = wpa_supplicant_stop_sched_scan(wpa_s);
2354
2355         wpa_s->pno = 0;
2356         wpa_s->pno_sched_pending = 0;
2357
2358         if (wpa_s->wpa_state == WPA_SCANNING)
2359                 wpa_supplicant_req_scan(wpa_s, 0, 0);
2360
2361         return ret;
2362 }
2363
2364
2365 void wpas_mac_addr_rand_scan_clear(struct wpa_supplicant *wpa_s,
2366                                     unsigned int type)
2367 {
2368         type &= MAC_ADDR_RAND_ALL;
2369         wpa_s->mac_addr_rand_enable &= ~type;
2370
2371         if (type & MAC_ADDR_RAND_SCAN) {
2372                 os_free(wpa_s->mac_addr_scan);
2373                 wpa_s->mac_addr_scan = NULL;
2374         }
2375
2376         if (type & MAC_ADDR_RAND_SCHED_SCAN) {
2377                 os_free(wpa_s->mac_addr_sched_scan);
2378                 wpa_s->mac_addr_sched_scan = NULL;
2379         }
2380
2381         if (type & MAC_ADDR_RAND_PNO) {
2382                 os_free(wpa_s->mac_addr_pno);
2383                 wpa_s->mac_addr_pno = NULL;
2384         }
2385 }
2386
2387
2388 int wpas_mac_addr_rand_scan_set(struct wpa_supplicant *wpa_s,
2389                                 unsigned int type, const u8 *addr,
2390                                 const u8 *mask)
2391 {
2392         u8 *tmp = NULL;
2393
2394         wpas_mac_addr_rand_scan_clear(wpa_s, type);
2395
2396         if (addr) {
2397                 tmp = os_malloc(2 * ETH_ALEN);
2398                 if (!tmp)
2399                         return -1;
2400                 os_memcpy(tmp, addr, ETH_ALEN);
2401                 os_memcpy(tmp + ETH_ALEN, mask, ETH_ALEN);
2402         }
2403
2404         if (type == MAC_ADDR_RAND_SCAN) {
2405                 wpa_s->mac_addr_scan = tmp;
2406         } else if (type == MAC_ADDR_RAND_SCHED_SCAN) {
2407                 wpa_s->mac_addr_sched_scan = tmp;
2408         } else if (type == MAC_ADDR_RAND_PNO) {
2409                 wpa_s->mac_addr_pno = tmp;
2410         } else {
2411                 wpa_printf(MSG_INFO,
2412                            "scan: Invalid MAC randomization type=0x%x",
2413                            type);
2414                 os_free(tmp);
2415                 return -1;
2416         }
2417
2418         wpa_s->mac_addr_rand_enable |= type;
2419         return 0;
2420 }