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