wpa_supplicant: Fix AP mode frequency initialization
[mech_eap.git] / wpa_supplicant / p2p_supplicant.c
1 /*
2  * wpa_supplicant - P2P
3  * Copyright (c) 2009-2010, Atheros Communications
4  *
5  * This software may be distributed under the terms of the BSD license.
6  * See README for more details.
7  */
8
9 #include "includes.h"
10
11 #include "common.h"
12 #include "eloop.h"
13 #include "common/ieee802_11_common.h"
14 #include "common/ieee802_11_defs.h"
15 #include "common/wpa_ctrl.h"
16 #include "wps/wps_i.h"
17 #include "p2p/p2p.h"
18 #include "ap/hostapd.h"
19 #include "ap/ap_config.h"
20 #include "ap/p2p_hostapd.h"
21 #include "eapol_supp/eapol_supp_sm.h"
22 #include "rsn_supp/wpa.h"
23 #include "wpa_supplicant_i.h"
24 #include "driver_i.h"
25 #include "ap.h"
26 #include "config_ssid.h"
27 #include "config.h"
28 #include "notify.h"
29 #include "scan.h"
30 #include "bss.h"
31 #include "offchannel.h"
32 #include "wps_supplicant.h"
33 #include "p2p_supplicant.h"
34
35
36 /*
37  * How many times to try to scan to find the GO before giving up on join
38  * request.
39  */
40 #define P2P_MAX_JOIN_SCAN_ATTEMPTS 10
41
42 #define P2P_AUTO_PD_SCAN_ATTEMPTS 5
43
44 #ifndef P2P_MAX_CLIENT_IDLE
45 /*
46  * How many seconds to try to reconnect to the GO when connection in P2P client
47  * role has been lost.
48  */
49 #define P2P_MAX_CLIENT_IDLE 10
50 #endif /* P2P_MAX_CLIENT_IDLE */
51
52 #ifndef P2P_MAX_INITIAL_CONN_WAIT
53 /*
54  * How many seconds to wait for initial 4-way handshake to get completed after
55  * WPS provisioning step.
56  */
57 #define P2P_MAX_INITIAL_CONN_WAIT 10
58 #endif /* P2P_MAX_INITIAL_CONN_WAIT */
59
60 #ifndef P2P_CONCURRENT_SEARCH_DELAY
61 #define P2P_CONCURRENT_SEARCH_DELAY 500
62 #endif /* P2P_CONCURRENT_SEARCH_DELAY */
63
64 #define P2P_MGMT_DEVICE_PREFIX          "p2p-dev-"
65
66 enum p2p_group_removal_reason {
67         P2P_GROUP_REMOVAL_UNKNOWN,
68         P2P_GROUP_REMOVAL_SILENT,
69         P2P_GROUP_REMOVAL_FORMATION_FAILED,
70         P2P_GROUP_REMOVAL_REQUESTED,
71         P2P_GROUP_REMOVAL_IDLE_TIMEOUT,
72         P2P_GROUP_REMOVAL_UNAVAILABLE,
73         P2P_GROUP_REMOVAL_GO_ENDING_SESSION
74 };
75
76
77 static void wpas_p2p_long_listen_timeout(void *eloop_ctx, void *timeout_ctx);
78 static struct wpa_supplicant *
79 wpas_p2p_get_group_iface(struct wpa_supplicant *wpa_s, int addr_allocated,
80                          int go);
81 static int wpas_p2p_join_start(struct wpa_supplicant *wpa_s);
82 static void wpas_p2p_join_scan_req(struct wpa_supplicant *wpa_s, int freq);
83 static void wpas_p2p_join_scan(void *eloop_ctx, void *timeout_ctx);
84 static int wpas_p2p_join(struct wpa_supplicant *wpa_s, const u8 *iface_addr,
85                          const u8 *dev_addr, enum p2p_wps_method wps_method,
86                          int auto_join);
87 static int wpas_p2p_create_iface(struct wpa_supplicant *wpa_s);
88 static void wpas_p2p_cross_connect_setup(struct wpa_supplicant *wpa_s);
89 static void wpas_p2p_group_idle_timeout(void *eloop_ctx, void *timeout_ctx);
90 static void wpas_p2p_set_group_idle_timeout(struct wpa_supplicant *wpa_s);
91 static void wpas_p2p_group_formation_timeout(void *eloop_ctx,
92                                              void *timeout_ctx);
93 static void wpas_p2p_fallback_to_go_neg(struct wpa_supplicant *wpa_s,
94                                         int group_added);
95 static int wpas_p2p_stop_find_oper(struct wpa_supplicant *wpa_s);
96
97
98 /*
99  * Get the number of concurrent channels that the HW can operate, but that are
100  * currently not in use by any of the wpa_supplicant interfaces.
101  */
102 static int wpas_p2p_num_unused_channels(struct wpa_supplicant *wpa_s)
103 {
104         int *freqs;
105         int num;
106
107         freqs = os_calloc(wpa_s->num_multichan_concurrent, sizeof(int));
108         if (!freqs)
109                 return -1;
110
111         num = get_shared_radio_freqs(wpa_s, freqs,
112                                      wpa_s->num_multichan_concurrent);
113         os_free(freqs);
114
115         return wpa_s->num_multichan_concurrent - num;
116 }
117
118
119 /*
120  * Get the frequencies that are currently in use by one or more of the virtual
121  * interfaces, and that are also valid for P2P operation.
122  */
123 static int wpas_p2p_valid_oper_freqs(struct wpa_supplicant *wpa_s,
124                                      int *p2p_freqs, unsigned int len)
125 {
126         int *freqs;
127         unsigned int num, i, j;
128
129         freqs = os_calloc(wpa_s->num_multichan_concurrent, sizeof(int));
130         if (!freqs)
131                 return -1;
132
133         num = get_shared_radio_freqs(wpa_s, freqs,
134                                      wpa_s->num_multichan_concurrent);
135
136         os_memset(p2p_freqs, 0, sizeof(int) * len);
137
138         for (i = 0, j = 0; i < num && j < len; i++) {
139                 if (p2p_supported_freq(wpa_s->global->p2p, freqs[i]))
140                         p2p_freqs[j++] = freqs[i];
141         }
142
143         os_free(freqs);
144
145         return j;
146 }
147
148
149 static void wpas_p2p_set_own_freq_preference(struct wpa_supplicant *wpa_s,
150                                              int freq)
151 {
152         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
153                 return;
154         if (freq > 0 && wpa_s->num_multichan_concurrent > 1 &&
155             wpas_p2p_num_unused_channels(wpa_s) > 0 &&
156             wpa_s->parent->conf->p2p_ignore_shared_freq)
157                 freq = 0;
158         p2p_set_own_freq_preference(wpa_s->global->p2p, freq);
159 }
160
161
162 static void wpas_p2p_scan_res_handler(struct wpa_supplicant *wpa_s,
163                                       struct wpa_scan_results *scan_res)
164 {
165         size_t i;
166
167         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
168                 return;
169
170         wpa_printf(MSG_DEBUG, "P2P: Scan results received (%d BSS)",
171                    (int) scan_res->num);
172
173         for (i = 0; i < scan_res->num; i++) {
174                 struct wpa_scan_res *bss = scan_res->res[i];
175                 struct os_time time_tmp_age, entry_ts;
176                 time_tmp_age.sec = bss->age / 1000;
177                 time_tmp_age.usec = (bss->age % 1000) * 1000;
178                 os_time_sub(&scan_res->fetch_time, &time_tmp_age, &entry_ts);
179                 if (p2p_scan_res_handler(wpa_s->global->p2p, bss->bssid,
180                                          bss->freq, &entry_ts, bss->level,
181                                          (const u8 *) (bss + 1),
182                                          bss->ie_len) > 0)
183                         break;
184         }
185
186         p2p_scan_res_handled(wpa_s->global->p2p);
187 }
188
189
190 static int wpas_p2p_scan(void *ctx, enum p2p_scan_type type, int freq,
191                          unsigned int num_req_dev_types,
192                          const u8 *req_dev_types, const u8 *dev_id, u16 pw_id)
193 {
194         struct wpa_supplicant *wpa_s = ctx;
195         struct wpa_supplicant *ifs;
196         struct wpa_driver_scan_params params;
197         int ret;
198         struct wpabuf *wps_ie, *ies;
199         int social_channels[] = { 2412, 2437, 2462, 0, 0 };
200         size_t ielen;
201
202         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
203                 return -1;
204
205         for (ifs = wpa_s->global->ifaces; ifs; ifs = ifs->next) {
206                 if (ifs->sta_scan_pending &&
207                     (wpas_scan_scheduled(ifs) || ifs->scanning) &&
208                     wpas_p2p_in_progress(wpa_s) == 2) {
209                         wpa_printf(MSG_DEBUG, "Delaying P2P scan to allow "
210                                    "pending station mode scan to be "
211                                    "completed on interface %s", ifs->ifname);
212                         wpa_s->global->p2p_cb_on_scan_complete = 1;
213                         wpa_supplicant_req_scan(ifs, 0, 0);
214                         return 1;
215                 }
216         }
217
218         os_memset(&params, 0, sizeof(params));
219
220         /* P2P Wildcard SSID */
221         params.num_ssids = 1;
222         params.ssids[0].ssid = (u8 *) P2P_WILDCARD_SSID;
223         params.ssids[0].ssid_len = P2P_WILDCARD_SSID_LEN;
224
225         wpa_s->wps->dev.p2p = 1;
226         wps_ie = wps_build_probe_req_ie(pw_id, &wpa_s->wps->dev,
227                                         wpa_s->wps->uuid, WPS_REQ_ENROLLEE,
228                                         num_req_dev_types, req_dev_types);
229         if (wps_ie == NULL)
230                 return -1;
231
232         ielen = p2p_scan_ie_buf_len(wpa_s->global->p2p);
233         ies = wpabuf_alloc(wpabuf_len(wps_ie) + ielen);
234         if (ies == NULL) {
235                 wpabuf_free(wps_ie);
236                 return -1;
237         }
238         wpabuf_put_buf(ies, wps_ie);
239         wpabuf_free(wps_ie);
240
241         p2p_scan_ie(wpa_s->global->p2p, ies, dev_id);
242
243         params.p2p_probe = 1;
244         params.extra_ies = wpabuf_head(ies);
245         params.extra_ies_len = wpabuf_len(ies);
246
247         switch (type) {
248         case P2P_SCAN_SOCIAL:
249                 params.freqs = social_channels;
250                 break;
251         case P2P_SCAN_FULL:
252                 break;
253         case P2P_SCAN_SOCIAL_PLUS_ONE:
254                 social_channels[3] = freq;
255                 params.freqs = social_channels;
256                 break;
257         }
258
259         ret = wpa_drv_scan(wpa_s, &params);
260
261         wpabuf_free(ies);
262
263         if (ret) {
264                 for (ifs = wpa_s->global->ifaces; ifs; ifs = ifs->next) {
265                         if (ifs->scanning ||
266                             ifs->scan_res_handler == wpas_p2p_scan_res_handler) {
267                                 wpa_s->global->p2p_cb_on_scan_complete = 1;
268                                 ret = 1;
269                                 break;
270                         }
271                 }
272         } else {
273                 os_get_time(&wpa_s->scan_trigger_time);
274                 wpa_s->scan_res_handler = wpas_p2p_scan_res_handler;
275         }
276
277         return ret;
278 }
279
280
281 static enum wpa_driver_if_type wpas_p2p_if_type(int p2p_group_interface)
282 {
283         switch (p2p_group_interface) {
284         case P2P_GROUP_INTERFACE_PENDING:
285                 return WPA_IF_P2P_GROUP;
286         case P2P_GROUP_INTERFACE_GO:
287                 return WPA_IF_P2P_GO;
288         case P2P_GROUP_INTERFACE_CLIENT:
289                 return WPA_IF_P2P_CLIENT;
290         }
291
292         return WPA_IF_P2P_GROUP;
293 }
294
295
296 static struct wpa_supplicant * wpas_get_p2p_group(struct wpa_supplicant *wpa_s,
297                                                   const u8 *ssid,
298                                                   size_t ssid_len, int *go)
299 {
300         struct wpa_ssid *s;
301
302         for (wpa_s = wpa_s->global->ifaces; wpa_s; wpa_s = wpa_s->next) {
303                 for (s = wpa_s->conf->ssid; s; s = s->next) {
304                         if (s->disabled != 0 || !s->p2p_group ||
305                             s->ssid_len != ssid_len ||
306                             os_memcmp(ssid, s->ssid, ssid_len) != 0)
307                                 continue;
308                         if (s->mode == WPAS_MODE_P2P_GO &&
309                             s != wpa_s->current_ssid)
310                                 continue;
311                         if (go)
312                                 *go = s->mode == WPAS_MODE_P2P_GO;
313                         return wpa_s;
314                 }
315         }
316
317         return NULL;
318 }
319
320
321 static int wpas_p2p_group_delete(struct wpa_supplicant *wpa_s,
322                                  enum p2p_group_removal_reason removal_reason)
323 {
324         struct wpa_ssid *ssid;
325         char *gtype;
326         const char *reason;
327
328         ssid = wpa_s->current_ssid;
329         if (ssid == NULL) {
330                 /*
331                  * The current SSID was not known, but there may still be a
332                  * pending P2P group interface waiting for provisioning or a
333                  * P2P group that is trying to reconnect.
334                  */
335                 ssid = wpa_s->conf->ssid;
336                 while (ssid) {
337                         if (ssid->p2p_group && ssid->disabled != 2)
338                                 break;
339                         ssid = ssid->next;
340                 }
341                 if (ssid == NULL &&
342                         wpa_s->p2p_group_interface == NOT_P2P_GROUP_INTERFACE)
343                 {
344                         wpa_printf(MSG_ERROR, "P2P: P2P group interface "
345                                    "not found");
346                         return -1;
347                 }
348         }
349         if (wpa_s->p2p_group_interface == P2P_GROUP_INTERFACE_GO)
350                 gtype = "GO";
351         else if (wpa_s->p2p_group_interface == P2P_GROUP_INTERFACE_CLIENT ||
352                  (ssid && ssid->mode == WPAS_MODE_INFRA)) {
353                 wpa_s->reassociate = 0;
354                 wpa_s->disconnected = 1;
355                 wpa_supplicant_deauthenticate(wpa_s,
356                                               WLAN_REASON_DEAUTH_LEAVING);
357                 gtype = "client";
358         } else
359                 gtype = "GO";
360         if (wpa_s->cross_connect_in_use) {
361                 wpa_s->cross_connect_in_use = 0;
362                 wpa_msg_global(wpa_s->parent, MSG_INFO,
363                                P2P_EVENT_CROSS_CONNECT_DISABLE "%s %s",
364                                wpa_s->ifname, wpa_s->cross_connect_uplink);
365         }
366         switch (removal_reason) {
367         case P2P_GROUP_REMOVAL_REQUESTED:
368                 reason = " reason=REQUESTED";
369                 break;
370         case P2P_GROUP_REMOVAL_FORMATION_FAILED:
371                 reason = " reason=FORMATION_FAILED";
372                 break;
373         case P2P_GROUP_REMOVAL_IDLE_TIMEOUT:
374                 reason = " reason=IDLE";
375                 break;
376         case P2P_GROUP_REMOVAL_UNAVAILABLE:
377                 reason = " reason=UNAVAILABLE";
378                 break;
379         case P2P_GROUP_REMOVAL_GO_ENDING_SESSION:
380                 reason = " reason=GO_ENDING_SESSION";
381                 break;
382         default:
383                 reason = "";
384                 break;
385         }
386         if (removal_reason != P2P_GROUP_REMOVAL_SILENT) {
387                 wpa_msg_global(wpa_s->parent, MSG_INFO,
388                                P2P_EVENT_GROUP_REMOVED "%s %s%s",
389                                wpa_s->ifname, gtype, reason);
390         }
391
392         if (eloop_cancel_timeout(wpas_p2p_group_idle_timeout, wpa_s, NULL) > 0)
393                 wpa_printf(MSG_DEBUG, "P2P: Cancelled P2P group idle timeout");
394         if (eloop_cancel_timeout(wpas_p2p_group_formation_timeout,
395                                  wpa_s->parent, NULL) > 0) {
396                 wpa_printf(MSG_DEBUG, "P2P: Cancelled P2P group formation "
397                            "timeout");
398                 wpa_s->p2p_in_provisioning = 0;
399         }
400
401         if (removal_reason != P2P_GROUP_REMOVAL_SILENT && ssid)
402                 wpas_notify_p2p_group_removed(wpa_s, ssid, gtype);
403
404         if (wpa_s->p2p_group_interface != NOT_P2P_GROUP_INTERFACE) {
405                 struct wpa_global *global;
406                 char *ifname;
407                 enum wpa_driver_if_type type;
408                 wpa_printf(MSG_DEBUG, "P2P: Remove group interface %s",
409                         wpa_s->ifname);
410                 global = wpa_s->global;
411                 ifname = os_strdup(wpa_s->ifname);
412                 type = wpas_p2p_if_type(wpa_s->p2p_group_interface);
413                 wpa_supplicant_remove_iface(wpa_s->global, wpa_s, 0);
414                 wpa_s = global->ifaces;
415                 if (wpa_s && ifname)
416                         wpa_drv_if_remove(wpa_s, type, ifname);
417                 os_free(ifname);
418                 return 1;
419         }
420
421         wpa_printf(MSG_DEBUG, "P2P: Remove temporary group network");
422         if (ssid && (ssid->p2p_group ||
423                      ssid->mode == WPAS_MODE_P2P_GROUP_FORMATION ||
424                      (ssid->key_mgmt & WPA_KEY_MGMT_WPS))) {
425                 int id = ssid->id;
426                 if (ssid == wpa_s->current_ssid) {
427                         wpa_sm_set_config(wpa_s->wpa, NULL);
428                         eapol_sm_notify_config(wpa_s->eapol, NULL, NULL);
429                         wpa_s->current_ssid = NULL;
430                 }
431                 /*
432                  * Networks objects created during any P2P activities are not
433                  * exposed out as they might/will confuse certain non-P2P aware
434                  * applications since these network objects won't behave like
435                  * regular ones.
436                  *
437                  * Likewise, we don't send out network removed signals for such
438                  * network objects.
439                  */
440                 wpa_config_remove_network(wpa_s->conf, id);
441                 wpa_supplicant_clear_status(wpa_s);
442                 wpa_supplicant_cancel_sched_scan(wpa_s);
443                 wpa_s->sta_scan_pending = 0;
444         } else {
445                 wpa_printf(MSG_DEBUG, "P2P: Temporary group network not "
446                            "found");
447         }
448         if (wpa_s->ap_iface)
449                 wpa_supplicant_ap_deinit(wpa_s);
450         else
451                 wpa_drv_deinit_p2p_cli(wpa_s);
452
453         return 0;
454 }
455
456
457 static int wpas_p2p_persistent_group(struct wpa_supplicant *wpa_s,
458                                      u8 *go_dev_addr,
459                                      const u8 *ssid, size_t ssid_len)
460 {
461         struct wpa_bss *bss;
462         const u8 *bssid;
463         struct wpabuf *p2p;
464         u8 group_capab;
465         const u8 *addr;
466
467         if (wpa_s->go_params)
468                 bssid = wpa_s->go_params->peer_interface_addr;
469         else
470                 bssid = wpa_s->bssid;
471
472         bss = wpa_bss_get(wpa_s, bssid, ssid, ssid_len);
473         if (bss == NULL) {
474                 u8 iface_addr[ETH_ALEN];
475                 if (p2p_get_interface_addr(wpa_s->global->p2p, bssid,
476                                            iface_addr) == 0)
477                         bss = wpa_bss_get(wpa_s, iface_addr, ssid, ssid_len);
478         }
479         if (bss == NULL) {
480                 wpa_printf(MSG_DEBUG, "P2P: Could not figure out whether "
481                            "group is persistent - BSS " MACSTR " not found",
482                            MAC2STR(bssid));
483                 return 0;
484         }
485
486         p2p = wpa_bss_get_vendor_ie_multi(bss, P2P_IE_VENDOR_TYPE);
487         if (p2p == NULL) {
488                 wpa_printf(MSG_DEBUG, "P2P: Could not figure out whether "
489                            "group is persistent - BSS " MACSTR
490                            " did not include P2P IE", MAC2STR(bssid));
491                 wpa_hexdump(MSG_DEBUG, "P2P: Probe Response IEs",
492                             (u8 *) (bss + 1), bss->ie_len);
493                 wpa_hexdump(MSG_DEBUG, "P2P: Beacon IEs",
494                             ((u8 *) bss + 1) + bss->ie_len,
495                             bss->beacon_ie_len);
496                 return 0;
497         }
498
499         group_capab = p2p_get_group_capab(p2p);
500         addr = p2p_get_go_dev_addr(p2p);
501         wpa_printf(MSG_DEBUG, "P2P: Checking whether group is persistent: "
502                    "group_capab=0x%x", group_capab);
503         if (addr) {
504                 os_memcpy(go_dev_addr, addr, ETH_ALEN);
505                 wpa_printf(MSG_DEBUG, "P2P: GO Device Address " MACSTR,
506                            MAC2STR(addr));
507         } else
508                 os_memset(go_dev_addr, 0, ETH_ALEN);
509         wpabuf_free(p2p);
510
511         wpa_printf(MSG_DEBUG, "P2P: BSS " MACSTR " group_capab=0x%x "
512                    "go_dev_addr=" MACSTR,
513                    MAC2STR(bssid), group_capab, MAC2STR(go_dev_addr));
514
515         return group_capab & P2P_GROUP_CAPAB_PERSISTENT_GROUP;
516 }
517
518
519 static int wpas_p2p_store_persistent_group(struct wpa_supplicant *wpa_s,
520                                            struct wpa_ssid *ssid,
521                                            const u8 *go_dev_addr)
522 {
523         struct wpa_ssid *s;
524         int changed = 0;
525
526         wpa_printf(MSG_DEBUG, "P2P: Storing credentials for a persistent "
527                    "group (GO Dev Addr " MACSTR ")", MAC2STR(go_dev_addr));
528         for (s = wpa_s->conf->ssid; s; s = s->next) {
529                 if (s->disabled == 2 &&
530                     os_memcmp(go_dev_addr, s->bssid, ETH_ALEN) == 0 &&
531                     s->ssid_len == ssid->ssid_len &&
532                     os_memcmp(ssid->ssid, s->ssid, ssid->ssid_len) == 0)
533                         break;
534         }
535
536         if (s) {
537                 wpa_printf(MSG_DEBUG, "P2P: Update existing persistent group "
538                            "entry");
539                 if (ssid->passphrase && !s->passphrase)
540                         changed = 1;
541                 else if (ssid->passphrase && s->passphrase &&
542                          os_strcmp(ssid->passphrase, s->passphrase) != 0)
543                         changed = 1;
544         } else {
545                 wpa_printf(MSG_DEBUG, "P2P: Create a new persistent group "
546                            "entry");
547                 changed = 1;
548                 s = wpa_config_add_network(wpa_s->conf);
549                 if (s == NULL)
550                         return -1;
551
552                 /*
553                  * Instead of network_added we emit persistent_group_added
554                  * notification. Also to keep the defense checks in
555                  * persistent_group obj registration method, we set the
556                  * relevant flags in s to designate it as a persistent group.
557                  */
558                 s->p2p_group = 1;
559                 s->p2p_persistent_group = 1;
560                 wpas_notify_persistent_group_added(wpa_s, s);
561                 wpa_config_set_network_defaults(s);
562         }
563
564         s->p2p_group = 1;
565         s->p2p_persistent_group = 1;
566         s->disabled = 2;
567         s->bssid_set = 1;
568         os_memcpy(s->bssid, go_dev_addr, ETH_ALEN);
569         s->mode = ssid->mode;
570         s->auth_alg = WPA_AUTH_ALG_OPEN;
571         s->key_mgmt = WPA_KEY_MGMT_PSK;
572         s->proto = WPA_PROTO_RSN;
573         s->pairwise_cipher = WPA_CIPHER_CCMP;
574         s->export_keys = 1;
575         if (ssid->passphrase) {
576                 os_free(s->passphrase);
577                 s->passphrase = os_strdup(ssid->passphrase);
578         }
579         if (ssid->psk_set) {
580                 s->psk_set = 1;
581                 os_memcpy(s->psk, ssid->psk, 32);
582         }
583         if (s->passphrase && !s->psk_set)
584                 wpa_config_update_psk(s);
585         if (s->ssid == NULL || s->ssid_len < ssid->ssid_len) {
586                 os_free(s->ssid);
587                 s->ssid = os_malloc(ssid->ssid_len);
588         }
589         if (s->ssid) {
590                 s->ssid_len = ssid->ssid_len;
591                 os_memcpy(s->ssid, ssid->ssid, s->ssid_len);
592         }
593
594 #ifndef CONFIG_NO_CONFIG_WRITE
595         if (changed && wpa_s->conf->update_config &&
596             wpa_config_write(wpa_s->confname, wpa_s->conf)) {
597                 wpa_printf(MSG_DEBUG, "P2P: Failed to update configuration");
598         }
599 #endif /* CONFIG_NO_CONFIG_WRITE */
600
601         return s->id;
602 }
603
604
605 static void wpas_p2p_add_persistent_group_client(struct wpa_supplicant *wpa_s,
606                                                  const u8 *addr)
607 {
608         struct wpa_ssid *ssid, *s;
609         u8 *n;
610         size_t i;
611         int found = 0;
612
613         ssid = wpa_s->current_ssid;
614         if (ssid == NULL || ssid->mode != WPAS_MODE_P2P_GO ||
615             !ssid->p2p_persistent_group)
616                 return;
617
618         for (s = wpa_s->parent->conf->ssid; s; s = s->next) {
619                 if (s->disabled != 2 || s->mode != WPAS_MODE_P2P_GO)
620                         continue;
621
622                 if (s->ssid_len == ssid->ssid_len &&
623                     os_memcmp(s->ssid, ssid->ssid, s->ssid_len) == 0)
624                         break;
625         }
626
627         if (s == NULL)
628                 return;
629
630         for (i = 0; s->p2p_client_list && i < s->num_p2p_clients; i++) {
631                 if (os_memcmp(s->p2p_client_list + i * ETH_ALEN, addr,
632                               ETH_ALEN) != 0)
633                         continue;
634
635                 if (i == s->num_p2p_clients - 1)
636                         return; /* already the most recent entry */
637
638                 /* move the entry to mark it most recent */
639                 os_memmove(s->p2p_client_list + i * ETH_ALEN,
640                            s->p2p_client_list + (i + 1) * ETH_ALEN,
641                            (s->num_p2p_clients - i - 1) * ETH_ALEN);
642                 os_memcpy(s->p2p_client_list +
643                           (s->num_p2p_clients - 1) * ETH_ALEN, addr, ETH_ALEN);
644                 found = 1;
645                 break;
646         }
647
648         if (!found && s->num_p2p_clients < P2P_MAX_STORED_CLIENTS) {
649                 n = os_realloc_array(s->p2p_client_list,
650                                      s->num_p2p_clients + 1, ETH_ALEN);
651                 if (n == NULL)
652                         return;
653                 os_memcpy(n + s->num_p2p_clients * ETH_ALEN, addr, ETH_ALEN);
654                 s->p2p_client_list = n;
655                 s->num_p2p_clients++;
656         } else if (!found) {
657                 /* Not enough room for an additional entry - drop the oldest
658                  * entry */
659                 os_memmove(s->p2p_client_list,
660                            s->p2p_client_list + ETH_ALEN,
661                            (s->num_p2p_clients - 1) * ETH_ALEN);
662                 os_memcpy(s->p2p_client_list +
663                           (s->num_p2p_clients - 1) * ETH_ALEN,
664                           addr, ETH_ALEN);
665         }
666
667 #ifndef CONFIG_NO_CONFIG_WRITE
668         if (wpa_s->parent->conf->update_config &&
669             wpa_config_write(wpa_s->parent->confname, wpa_s->parent->conf))
670                 wpa_printf(MSG_DEBUG, "P2P: Failed to update configuration");
671 #endif /* CONFIG_NO_CONFIG_WRITE */
672 }
673
674
675 static void wpas_group_formation_completed(struct wpa_supplicant *wpa_s,
676                                            int success)
677 {
678         struct wpa_ssid *ssid;
679         const char *ssid_txt;
680         int client;
681         int persistent;
682         u8 go_dev_addr[ETH_ALEN];
683         int network_id = -1;
684
685         /*
686          * This callback is likely called for the main interface. Update wpa_s
687          * to use the group interface if a new interface was created for the
688          * group.
689          */
690         if (wpa_s->global->p2p_group_formation)
691                 wpa_s = wpa_s->global->p2p_group_formation;
692         wpa_s->global->p2p_group_formation = NULL;
693         wpa_s->p2p_in_provisioning = 0;
694
695         if (!success) {
696                 wpa_msg_global(wpa_s->parent, MSG_INFO,
697                                P2P_EVENT_GROUP_FORMATION_FAILURE);
698                 wpas_p2p_group_delete(wpa_s,
699                                       P2P_GROUP_REMOVAL_FORMATION_FAILED);
700                 return;
701         }
702
703         wpa_msg_global(wpa_s->parent, MSG_INFO,
704                        P2P_EVENT_GROUP_FORMATION_SUCCESS);
705
706         ssid = wpa_s->current_ssid;
707         if (ssid && ssid->mode == WPAS_MODE_P2P_GROUP_FORMATION) {
708                 ssid->mode = WPAS_MODE_P2P_GO;
709                 p2p_group_notif_formation_done(wpa_s->p2p_group);
710                 wpa_supplicant_ap_mac_addr_filter(wpa_s, NULL);
711         }
712
713         persistent = 0;
714         if (ssid) {
715                 ssid_txt = wpa_ssid_txt(ssid->ssid, ssid->ssid_len);
716                 client = ssid->mode == WPAS_MODE_INFRA;
717                 if (ssid->mode == WPAS_MODE_P2P_GO) {
718                         persistent = ssid->p2p_persistent_group;
719                         os_memcpy(go_dev_addr, wpa_s->global->p2p_dev_addr,
720                                   ETH_ALEN);
721                 } else
722                         persistent = wpas_p2p_persistent_group(wpa_s,
723                                                                go_dev_addr,
724                                                                ssid->ssid,
725                                                                ssid->ssid_len);
726         } else {
727                 ssid_txt = "";
728                 client = wpa_s->p2p_group_interface ==
729                         P2P_GROUP_INTERFACE_CLIENT;
730                 os_memset(go_dev_addr, 0, ETH_ALEN);
731         }
732
733         wpa_s->show_group_started = 0;
734         if (client) {
735                 /*
736                  * Indicate event only after successfully completed 4-way
737                  * handshake, i.e., when the interface is ready for data
738                  * packets.
739                  */
740                 wpa_s->show_group_started = 1;
741         } else if (ssid && ssid->passphrase == NULL && ssid->psk_set) {
742                 char psk[65];
743                 wpa_snprintf_hex(psk, sizeof(psk), ssid->psk, 32);
744                 wpa_msg_global(wpa_s->parent, MSG_INFO, P2P_EVENT_GROUP_STARTED
745                                "%s GO ssid=\"%s\" freq=%d psk=%s go_dev_addr="
746                                MACSTR "%s",
747                                wpa_s->ifname, ssid_txt, ssid->frequency, psk,
748                                MAC2STR(go_dev_addr),
749                                persistent ? " [PERSISTENT]" : "");
750                 wpas_p2p_cross_connect_setup(wpa_s);
751                 wpas_p2p_set_group_idle_timeout(wpa_s);
752         } else {
753                 wpa_msg_global(wpa_s->parent, MSG_INFO, P2P_EVENT_GROUP_STARTED
754                                "%s GO ssid=\"%s\" freq=%d passphrase=\"%s\" "
755                                "go_dev_addr=" MACSTR "%s",
756                                wpa_s->ifname, ssid_txt,
757                                ssid ? ssid->frequency : 0,
758                                ssid && ssid->passphrase ? ssid->passphrase : "",
759                                MAC2STR(go_dev_addr),
760                                persistent ? " [PERSISTENT]" : "");
761                 wpas_p2p_cross_connect_setup(wpa_s);
762                 wpas_p2p_set_group_idle_timeout(wpa_s);
763         }
764
765         if (persistent)
766                 network_id = wpas_p2p_store_persistent_group(wpa_s->parent,
767                                                              ssid, go_dev_addr);
768         if (network_id < 0 && ssid)
769                 network_id = ssid->id;
770         if (!client)
771                 wpas_notify_p2p_group_started(wpa_s, ssid, network_id, 0);
772 }
773
774
775 static void wpas_p2p_send_action_tx_status(struct wpa_supplicant *wpa_s,
776                                            unsigned int freq,
777                                            const u8 *dst, const u8 *src,
778                                            const u8 *bssid,
779                                            const u8 *data, size_t data_len,
780                                            enum offchannel_send_action_result
781                                            result)
782 {
783         enum p2p_send_action_result res = P2P_SEND_ACTION_SUCCESS;
784
785         if (wpa_s->global->p2p == NULL || wpa_s->global->p2p_disabled)
786                 return;
787         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT)
788                 return;
789
790         switch (result) {
791         case OFFCHANNEL_SEND_ACTION_SUCCESS:
792                 res = P2P_SEND_ACTION_SUCCESS;
793                 break;
794         case OFFCHANNEL_SEND_ACTION_NO_ACK:
795                 res = P2P_SEND_ACTION_NO_ACK;
796                 break;
797         case OFFCHANNEL_SEND_ACTION_FAILED:
798                 res = P2P_SEND_ACTION_FAILED;
799                 break;
800         }
801
802         p2p_send_action_cb(wpa_s->global->p2p, freq, dst, src, bssid, res);
803
804         if (result != OFFCHANNEL_SEND_ACTION_SUCCESS &&
805             wpa_s->pending_pd_before_join &&
806             (os_memcmp(dst, wpa_s->pending_join_dev_addr, ETH_ALEN) == 0 ||
807              os_memcmp(dst, wpa_s->pending_join_iface_addr, ETH_ALEN) == 0) &&
808             wpa_s->p2p_fallback_to_go_neg) {
809                 wpa_s->pending_pd_before_join = 0;
810                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: No ACK for PD Req "
811                         "during p2p_connect-auto");
812                 wpas_p2p_fallback_to_go_neg(wpa_s, 0);
813                 return;
814         }
815 }
816
817
818 static int wpas_send_action(void *ctx, unsigned int freq, const u8 *dst,
819                             const u8 *src, const u8 *bssid, const u8 *buf,
820                             size_t len, unsigned int wait_time)
821 {
822         struct wpa_supplicant *wpa_s = ctx;
823         return offchannel_send_action(wpa_s, freq, dst, src, bssid, buf, len,
824                                       wait_time,
825                                       wpas_p2p_send_action_tx_status, 1);
826 }
827
828
829 static void wpas_send_action_done(void *ctx)
830 {
831         struct wpa_supplicant *wpa_s = ctx;
832         offchannel_send_action_done(wpa_s);
833 }
834
835
836 static int wpas_copy_go_neg_results(struct wpa_supplicant *wpa_s,
837                                     struct p2p_go_neg_results *params)
838 {
839         if (wpa_s->go_params == NULL) {
840                 wpa_s->go_params = os_malloc(sizeof(*params));
841                 if (wpa_s->go_params == NULL)
842                         return -1;
843         }
844         os_memcpy(wpa_s->go_params, params, sizeof(*params));
845         return 0;
846 }
847
848
849 static void wpas_start_wps_enrollee(struct wpa_supplicant *wpa_s,
850                                     struct p2p_go_neg_results *res)
851 {
852         wpa_printf(MSG_DEBUG, "P2P: Start WPS Enrollee for peer " MACSTR,
853                    MAC2STR(res->peer_interface_addr));
854         wpa_hexdump_ascii(MSG_DEBUG, "P2P: Start WPS Enrollee for SSID",
855                           res->ssid, res->ssid_len);
856         wpa_supplicant_ap_deinit(wpa_s);
857         wpas_copy_go_neg_results(wpa_s, res);
858         if (res->wps_method == WPS_PBC)
859                 wpas_wps_start_pbc(wpa_s, res->peer_interface_addr, 1);
860         else {
861                 u16 dev_pw_id = DEV_PW_DEFAULT;
862                 if (wpa_s->p2p_wps_method == WPS_PIN_KEYPAD)
863                         dev_pw_id = DEV_PW_REGISTRAR_SPECIFIED;
864                 wpas_wps_start_pin(wpa_s, res->peer_interface_addr,
865                                    wpa_s->p2p_pin, 1, dev_pw_id);
866         }
867 }
868
869
870 static void p2p_go_configured(void *ctx, void *data)
871 {
872         struct wpa_supplicant *wpa_s = ctx;
873         struct p2p_go_neg_results *params = data;
874         struct wpa_ssid *ssid;
875         int network_id = -1;
876
877         ssid = wpa_s->current_ssid;
878         if (ssid && ssid->mode == WPAS_MODE_P2P_GO) {
879                 wpa_printf(MSG_DEBUG, "P2P: Group setup without provisioning");
880                 if (wpa_s->global->p2p_group_formation == wpa_s)
881                         wpa_s->global->p2p_group_formation = NULL;
882                 if (os_strlen(params->passphrase) > 0) {
883                         wpa_msg_global(wpa_s->parent, MSG_INFO,
884                                        P2P_EVENT_GROUP_STARTED
885                                        "%s GO ssid=\"%s\" freq=%d "
886                                        "passphrase=\"%s\" go_dev_addr=" MACSTR
887                                        "%s", wpa_s->ifname,
888                                        wpa_ssid_txt(ssid->ssid, ssid->ssid_len),
889                                        ssid->frequency, params->passphrase,
890                                        MAC2STR(wpa_s->global->p2p_dev_addr),
891                                        params->persistent_group ?
892                                        " [PERSISTENT]" : "");
893                 } else {
894                         char psk[65];
895                         wpa_snprintf_hex(psk, sizeof(psk), params->psk,
896                                          sizeof(params->psk));
897                         wpa_msg_global(wpa_s->parent, MSG_INFO,
898                                        P2P_EVENT_GROUP_STARTED
899                                        "%s GO ssid=\"%s\" freq=%d psk=%s "
900                                        "go_dev_addr=" MACSTR "%s",
901                                        wpa_s->ifname,
902                                        wpa_ssid_txt(ssid->ssid, ssid->ssid_len),
903                                        ssid->frequency, psk,
904                                        MAC2STR(wpa_s->global->p2p_dev_addr),
905                                        params->persistent_group ?
906                                        " [PERSISTENT]" : "");
907                 }
908
909                 if (params->persistent_group)
910                         network_id = wpas_p2p_store_persistent_group(
911                                 wpa_s->parent, ssid,
912                                 wpa_s->global->p2p_dev_addr);
913                 if (network_id < 0)
914                         network_id = ssid->id;
915                 wpas_notify_p2p_group_started(wpa_s, ssid, network_id, 0);
916                 wpas_p2p_cross_connect_setup(wpa_s);
917                 wpas_p2p_set_group_idle_timeout(wpa_s);
918                 return;
919         }
920
921         wpa_printf(MSG_DEBUG, "P2P: Setting up WPS for GO provisioning");
922         if (wpa_supplicant_ap_mac_addr_filter(wpa_s,
923                                               params->peer_interface_addr)) {
924                 wpa_printf(MSG_DEBUG, "P2P: Failed to setup MAC address "
925                            "filtering");
926                 return;
927         }
928         if (params->wps_method == WPS_PBC)
929                 wpa_supplicant_ap_wps_pbc(wpa_s, params->peer_interface_addr,
930                                           params->peer_device_addr);
931         else if (wpa_s->p2p_pin[0])
932                 wpa_supplicant_ap_wps_pin(wpa_s, params->peer_interface_addr,
933                                           wpa_s->p2p_pin, NULL, 0, 0);
934         os_free(wpa_s->go_params);
935         wpa_s->go_params = NULL;
936 }
937
938
939 static void wpas_start_wps_go(struct wpa_supplicant *wpa_s,
940                               struct p2p_go_neg_results *params,
941                               int group_formation)
942 {
943         struct wpa_ssid *ssid;
944
945         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Starting GO");
946         if (wpas_copy_go_neg_results(wpa_s, params) < 0) {
947                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Could not copy GO Negotiation "
948                         "results");
949                 return;
950         }
951
952         ssid = wpa_config_add_network(wpa_s->conf);
953         if (ssid == NULL) {
954                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Could not add network for GO");
955                 return;
956         }
957
958         wpa_s->show_group_started = 0;
959
960         wpa_config_set_network_defaults(ssid);
961         ssid->temporary = 1;
962         ssid->p2p_group = 1;
963         ssid->p2p_persistent_group = params->persistent_group;
964         ssid->mode = group_formation ? WPAS_MODE_P2P_GROUP_FORMATION :
965                 WPAS_MODE_P2P_GO;
966         ssid->frequency = params->freq;
967         ssid->ht40 = params->ht40;
968         ssid->ssid = os_zalloc(params->ssid_len + 1);
969         if (ssid->ssid) {
970                 os_memcpy(ssid->ssid, params->ssid, params->ssid_len);
971                 ssid->ssid_len = params->ssid_len;
972         }
973         ssid->auth_alg = WPA_AUTH_ALG_OPEN;
974         ssid->key_mgmt = WPA_KEY_MGMT_PSK;
975         ssid->proto = WPA_PROTO_RSN;
976         ssid->pairwise_cipher = WPA_CIPHER_CCMP;
977         if (os_strlen(params->passphrase) > 0) {
978                 ssid->passphrase = os_strdup(params->passphrase);
979                 if (ssid->passphrase == NULL) {
980                         wpa_msg_global(wpa_s, MSG_ERROR,
981                                        "P2P: Failed to copy passphrase for GO");
982                         wpa_config_remove_network(wpa_s->conf, ssid->id);
983                         return;
984                 }
985         } else
986                 ssid->passphrase = NULL;
987         ssid->psk_set = params->psk_set;
988         if (ssid->psk_set)
989                 os_memcpy(ssid->psk, params->psk, sizeof(ssid->psk));
990         else if (ssid->passphrase)
991                 wpa_config_update_psk(ssid);
992         ssid->ap_max_inactivity = wpa_s->parent->conf->p2p_go_max_inactivity;
993
994         wpa_s->ap_configured_cb = p2p_go_configured;
995         wpa_s->ap_configured_cb_ctx = wpa_s;
996         wpa_s->ap_configured_cb_data = wpa_s->go_params;
997         wpa_s->connect_without_scan = ssid;
998         wpa_s->reassociate = 1;
999         wpa_s->disconnected = 0;
1000         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Request scan (that will be skipped) to "
1001                 "start GO)");
1002         wpa_supplicant_req_scan(wpa_s, 0, 0);
1003 }
1004
1005
1006 static void wpas_p2p_clone_config(struct wpa_supplicant *dst,
1007                                   const struct wpa_supplicant *src)
1008 {
1009         struct wpa_config *d;
1010         const struct wpa_config *s;
1011
1012         d = dst->conf;
1013         s = src->conf;
1014
1015 #define C(n) if (s->n) d->n = os_strdup(s->n)
1016         C(device_name);
1017         C(manufacturer);
1018         C(model_name);
1019         C(model_number);
1020         C(serial_number);
1021         C(config_methods);
1022 #undef C
1023
1024         os_memcpy(d->device_type, s->device_type, WPS_DEV_TYPE_LEN);
1025         os_memcpy(d->sec_device_type, s->sec_device_type,
1026                   sizeof(d->sec_device_type));
1027         d->num_sec_device_types = s->num_sec_device_types;
1028
1029         d->p2p_group_idle = s->p2p_group_idle;
1030         d->p2p_intra_bss = s->p2p_intra_bss;
1031         d->persistent_reconnect = s->persistent_reconnect;
1032         d->max_num_sta = s->max_num_sta;
1033         d->pbc_in_m1 = s->pbc_in_m1;
1034         d->ignore_old_scan_res = s->ignore_old_scan_res;
1035         d->beacon_int = s->beacon_int;
1036         d->disassoc_low_ack = s->disassoc_low_ack;
1037 }
1038
1039
1040 static void wpas_p2p_get_group_ifname(struct wpa_supplicant *wpa_s,
1041                                       char *ifname, size_t len)
1042 {
1043         char *ifname_ptr = wpa_s->ifname;
1044
1045         if (os_strncmp(wpa_s->ifname, P2P_MGMT_DEVICE_PREFIX,
1046                        os_strlen(P2P_MGMT_DEVICE_PREFIX)) == 0) {
1047                 ifname_ptr = os_strrchr(wpa_s->ifname, '-') + 1;
1048         }
1049
1050         os_snprintf(ifname, len, "p2p-%s-%d", ifname_ptr, wpa_s->p2p_group_idx);
1051         if (os_strlen(ifname) >= IFNAMSIZ &&
1052             os_strlen(wpa_s->ifname) < IFNAMSIZ) {
1053                 /* Try to avoid going over the IFNAMSIZ length limit */
1054                 os_snprintf(ifname, sizeof(ifname), "p2p-%d",
1055                             wpa_s->p2p_group_idx);
1056         }
1057 }
1058
1059
1060 static int wpas_p2p_add_group_interface(struct wpa_supplicant *wpa_s,
1061                                         enum wpa_driver_if_type type)
1062 {
1063         char ifname[120], force_ifname[120];
1064
1065         if (wpa_s->pending_interface_name[0]) {
1066                 wpa_printf(MSG_DEBUG, "P2P: Pending virtual interface exists "
1067                            "- skip creation of a new one");
1068                 if (is_zero_ether_addr(wpa_s->pending_interface_addr)) {
1069                         wpa_printf(MSG_DEBUG, "P2P: Pending virtual address "
1070                                    "unknown?! ifname='%s'",
1071                                    wpa_s->pending_interface_name);
1072                         return -1;
1073                 }
1074                 return 0;
1075         }
1076
1077         wpas_p2p_get_group_ifname(wpa_s, ifname, sizeof(ifname));
1078         force_ifname[0] = '\0';
1079
1080         wpa_printf(MSG_DEBUG, "P2P: Create a new interface %s for the group",
1081                    ifname);
1082         wpa_s->p2p_group_idx++;
1083
1084         wpa_s->pending_interface_type = type;
1085         if (wpa_drv_if_add(wpa_s, type, ifname, NULL, NULL, force_ifname,
1086                            wpa_s->pending_interface_addr, NULL) < 0) {
1087                 wpa_printf(MSG_ERROR, "P2P: Failed to create new group "
1088                            "interface");
1089                 return -1;
1090         }
1091
1092         if (force_ifname[0]) {
1093                 wpa_printf(MSG_DEBUG, "P2P: Driver forced interface name %s",
1094                            force_ifname);
1095                 os_strlcpy(wpa_s->pending_interface_name, force_ifname,
1096                            sizeof(wpa_s->pending_interface_name));
1097         } else
1098                 os_strlcpy(wpa_s->pending_interface_name, ifname,
1099                            sizeof(wpa_s->pending_interface_name));
1100         wpa_printf(MSG_DEBUG, "P2P: Created pending virtual interface %s addr "
1101                    MACSTR, wpa_s->pending_interface_name,
1102                    MAC2STR(wpa_s->pending_interface_addr));
1103
1104         return 0;
1105 }
1106
1107
1108 static void wpas_p2p_remove_pending_group_interface(
1109         struct wpa_supplicant *wpa_s)
1110 {
1111         if (!wpa_s->pending_interface_name[0] ||
1112             is_zero_ether_addr(wpa_s->pending_interface_addr))
1113                 return; /* No pending virtual interface */
1114
1115         wpa_printf(MSG_DEBUG, "P2P: Removing pending group interface %s",
1116                    wpa_s->pending_interface_name);
1117         wpa_drv_if_remove(wpa_s, wpa_s->pending_interface_type,
1118                           wpa_s->pending_interface_name);
1119         os_memset(wpa_s->pending_interface_addr, 0, ETH_ALEN);
1120         wpa_s->pending_interface_name[0] = '\0';
1121 }
1122
1123
1124 static struct wpa_supplicant *
1125 wpas_p2p_init_group_interface(struct wpa_supplicant *wpa_s, int go)
1126 {
1127         struct wpa_interface iface;
1128         struct wpa_supplicant *group_wpa_s;
1129
1130         if (!wpa_s->pending_interface_name[0]) {
1131                 wpa_printf(MSG_ERROR, "P2P: No pending group interface");
1132                 if (!wpas_p2p_create_iface(wpa_s))
1133                         return NULL;
1134                 /*
1135                  * Something has forced us to remove the pending interface; try
1136                  * to create a new one and hope for the best that we will get
1137                  * the same local address.
1138                  */
1139                 if (wpas_p2p_add_group_interface(wpa_s, go ? WPA_IF_P2P_GO :
1140                                                  WPA_IF_P2P_CLIENT) < 0)
1141                         return NULL;
1142         }
1143
1144         os_memset(&iface, 0, sizeof(iface));
1145         iface.ifname = wpa_s->pending_interface_name;
1146         iface.driver = wpa_s->driver->name;
1147         if (wpa_s->conf->ctrl_interface == NULL &&
1148             wpa_s->parent != wpa_s &&
1149             wpa_s->p2p_mgmt &&
1150             (wpa_s->drv_flags & WPA_DRIVER_FLAGS_DEDICATED_P2P_DEVICE))
1151                 iface.ctrl_interface = wpa_s->parent->conf->ctrl_interface;
1152         else
1153                 iface.ctrl_interface = wpa_s->conf->ctrl_interface;
1154         iface.driver_param = wpa_s->conf->driver_param;
1155         group_wpa_s = wpa_supplicant_add_iface(wpa_s->global, &iface);
1156         if (group_wpa_s == NULL) {
1157                 wpa_printf(MSG_ERROR, "P2P: Failed to create new "
1158                            "wpa_supplicant interface");
1159                 return NULL;
1160         }
1161         wpa_s->pending_interface_name[0] = '\0';
1162         group_wpa_s->parent = wpa_s;
1163         group_wpa_s->p2p_group_interface = go ? P2P_GROUP_INTERFACE_GO :
1164                 P2P_GROUP_INTERFACE_CLIENT;
1165         wpa_s->global->p2p_group_formation = group_wpa_s;
1166
1167         wpas_p2p_clone_config(group_wpa_s, wpa_s);
1168
1169         return group_wpa_s;
1170 }
1171
1172
1173 static void wpas_p2p_group_formation_timeout(void *eloop_ctx,
1174                                              void *timeout_ctx)
1175 {
1176         struct wpa_supplicant *wpa_s = eloop_ctx;
1177         wpa_printf(MSG_DEBUG, "P2P: Group Formation timed out");
1178         wpas_p2p_group_formation_failed(wpa_s);
1179 }
1180
1181
1182 void wpas_p2p_group_formation_failed(struct wpa_supplicant *wpa_s)
1183 {
1184         eloop_cancel_timeout(wpas_p2p_group_formation_timeout,
1185                              wpa_s->parent, NULL);
1186         if (wpa_s->global->p2p)
1187                 p2p_group_formation_failed(wpa_s->global->p2p);
1188         else if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT)
1189                 wpa_drv_p2p_group_formation_failed(wpa_s);
1190         wpas_group_formation_completed(wpa_s, 0);
1191 }
1192
1193
1194 void wpas_go_neg_completed(void *ctx, struct p2p_go_neg_results *res)
1195 {
1196         struct wpa_supplicant *wpa_s = ctx;
1197
1198         if (wpa_s->off_channel_freq || wpa_s->roc_waiting_drv_freq) {
1199                 wpa_drv_cancel_remain_on_channel(wpa_s);
1200                 wpa_s->off_channel_freq = 0;
1201                 wpa_s->roc_waiting_drv_freq = 0;
1202         }
1203
1204         if (res->status) {
1205                 wpa_msg_global(wpa_s, MSG_INFO,
1206                                P2P_EVENT_GO_NEG_FAILURE "status=%d",
1207                                res->status);
1208                 wpas_notify_p2p_go_neg_completed(wpa_s, res);
1209                 wpas_p2p_remove_pending_group_interface(wpa_s);
1210                 return;
1211         }
1212
1213         if (wpa_s->p2p_go_ht40)
1214                 res->ht40 = 1;
1215
1216         wpa_msg_global(wpa_s, MSG_INFO, P2P_EVENT_GO_NEG_SUCCESS);
1217         wpas_notify_p2p_go_neg_completed(wpa_s, res);
1218
1219         if (res->role_go && wpa_s->p2p_persistent_id >= 0) {
1220                 struct wpa_ssid *ssid;
1221                 ssid = wpa_config_get_network(wpa_s->conf,
1222                                               wpa_s->p2p_persistent_id);
1223                 if (ssid && ssid->disabled == 2 &&
1224                     ssid->mode == WPAS_MODE_P2P_GO && ssid->passphrase) {
1225                         size_t len = os_strlen(ssid->passphrase);
1226                         wpa_printf(MSG_DEBUG, "P2P: Override passphrase based "
1227                                    "on requested persistent group");
1228                         os_memcpy(res->passphrase, ssid->passphrase, len);
1229                         res->passphrase[len] = '\0';
1230                 }
1231         }
1232
1233         if (wpa_s->create_p2p_iface) {
1234                 struct wpa_supplicant *group_wpa_s =
1235                         wpas_p2p_init_group_interface(wpa_s, res->role_go);
1236                 if (group_wpa_s == NULL) {
1237                         wpas_p2p_remove_pending_group_interface(wpa_s);
1238                         return;
1239                 }
1240                 if (group_wpa_s != wpa_s) {
1241                         os_memcpy(group_wpa_s->p2p_pin, wpa_s->p2p_pin,
1242                                   sizeof(group_wpa_s->p2p_pin));
1243                         group_wpa_s->p2p_wps_method = wpa_s->p2p_wps_method;
1244                 }
1245                 os_memset(wpa_s->pending_interface_addr, 0, ETH_ALEN);
1246                 wpa_s->pending_interface_name[0] = '\0';
1247                 group_wpa_s->p2p_in_provisioning = 1;
1248
1249                 if (res->role_go)
1250                         wpas_start_wps_go(group_wpa_s, res, 1);
1251                 else
1252                         wpas_start_wps_enrollee(group_wpa_s, res);
1253         } else {
1254                 wpa_s->p2p_in_provisioning = 1;
1255                 wpa_s->global->p2p_group_formation = wpa_s;
1256
1257                 if (res->role_go)
1258                         wpas_start_wps_go(wpa_s, res, 1);
1259                 else
1260                         wpas_start_wps_enrollee(ctx, res);
1261         }
1262
1263         wpa_s->p2p_long_listen = 0;
1264         eloop_cancel_timeout(wpas_p2p_long_listen_timeout, wpa_s, NULL);
1265
1266         eloop_cancel_timeout(wpas_p2p_group_formation_timeout, wpa_s, NULL);
1267         eloop_register_timeout(15 + res->peer_config_timeout / 100,
1268                                (res->peer_config_timeout % 100) * 10000,
1269                                wpas_p2p_group_formation_timeout, wpa_s, NULL);
1270 }
1271
1272
1273 void wpas_go_neg_req_rx(void *ctx, const u8 *src, u16 dev_passwd_id)
1274 {
1275         struct wpa_supplicant *wpa_s = ctx;
1276         wpa_msg_global(wpa_s, MSG_INFO, P2P_EVENT_GO_NEG_REQUEST MACSTR
1277                        " dev_passwd_id=%u", MAC2STR(src), dev_passwd_id);
1278
1279         wpas_notify_p2p_go_neg_req(wpa_s, src, dev_passwd_id);
1280 }
1281
1282
1283 void wpas_dev_found(void *ctx, const u8 *addr,
1284                     const struct p2p_peer_info *info,
1285                     int new_device)
1286 {
1287 #ifndef CONFIG_NO_STDOUT_DEBUG
1288         struct wpa_supplicant *wpa_s = ctx;
1289         char devtype[WPS_DEV_TYPE_BUFSIZE];
1290
1291         wpa_msg_global(wpa_s, MSG_INFO, P2P_EVENT_DEVICE_FOUND MACSTR
1292                        " p2p_dev_addr=" MACSTR
1293                        " pri_dev_type=%s name='%s' config_methods=0x%x "
1294                        "dev_capab=0x%x group_capab=0x%x",
1295                        MAC2STR(addr), MAC2STR(info->p2p_device_addr),
1296                        wps_dev_type_bin2str(info->pri_dev_type, devtype,
1297                                             sizeof(devtype)),
1298                 info->device_name, info->config_methods,
1299                 info->dev_capab, info->group_capab);
1300 #endif /* CONFIG_NO_STDOUT_DEBUG */
1301
1302         wpas_notify_p2p_device_found(ctx, info->p2p_device_addr, new_device);
1303 }
1304
1305
1306 static void wpas_dev_lost(void *ctx, const u8 *dev_addr)
1307 {
1308         struct wpa_supplicant *wpa_s = ctx;
1309
1310         wpa_msg_global(wpa_s, MSG_INFO, P2P_EVENT_DEVICE_LOST
1311                        "p2p_dev_addr=" MACSTR, MAC2STR(dev_addr));
1312
1313         wpas_notify_p2p_device_lost(wpa_s, dev_addr);
1314 }
1315
1316
1317 static void wpas_find_stopped(void *ctx)
1318 {
1319         struct wpa_supplicant *wpa_s = ctx;
1320         wpa_msg_global(wpa_s, MSG_INFO, P2P_EVENT_FIND_STOPPED);
1321 }
1322
1323
1324 static int wpas_start_listen(void *ctx, unsigned int freq,
1325                              unsigned int duration,
1326                              const struct wpabuf *probe_resp_ie)
1327 {
1328         struct wpa_supplicant *wpa_s = ctx;
1329
1330         wpa_drv_set_ap_wps_ie(wpa_s, NULL, probe_resp_ie, NULL);
1331
1332         if (wpa_drv_probe_req_report(wpa_s, 1) < 0) {
1333                 wpa_printf(MSG_DEBUG, "P2P: Failed to request the driver to "
1334                            "report received Probe Request frames");
1335                 return -1;
1336         }
1337
1338         wpa_s->pending_listen_freq = freq;
1339         wpa_s->pending_listen_duration = duration;
1340
1341         if (wpa_drv_remain_on_channel(wpa_s, freq, duration) < 0) {
1342                 wpa_printf(MSG_DEBUG, "P2P: Failed to request the driver "
1343                            "to remain on channel (%u MHz) for Listen "
1344                            "state", freq);
1345                 wpa_s->pending_listen_freq = 0;
1346                 return -1;
1347         }
1348         wpa_s->off_channel_freq = 0;
1349         wpa_s->roc_waiting_drv_freq = freq;
1350
1351         return 0;
1352 }
1353
1354
1355 static void wpas_stop_listen(void *ctx)
1356 {
1357         struct wpa_supplicant *wpa_s = ctx;
1358         if (wpa_s->off_channel_freq || wpa_s->roc_waiting_drv_freq) {
1359                 wpa_drv_cancel_remain_on_channel(wpa_s);
1360                 wpa_s->off_channel_freq = 0;
1361                 wpa_s->roc_waiting_drv_freq = 0;
1362         }
1363         wpa_drv_set_ap_wps_ie(wpa_s, NULL, NULL, NULL);
1364         wpa_drv_probe_req_report(wpa_s, 0);
1365 }
1366
1367
1368 static int wpas_send_probe_resp(void *ctx, const struct wpabuf *buf)
1369 {
1370         struct wpa_supplicant *wpa_s = ctx;
1371         return wpa_drv_send_mlme(wpa_s, wpabuf_head(buf), wpabuf_len(buf), 1);
1372 }
1373
1374
1375 /*
1376  * DNS Header section is used only to calculate compression pointers, so the
1377  * contents of this data does not matter, but the length needs to be reserved
1378  * in the virtual packet.
1379  */
1380 #define DNS_HEADER_LEN 12
1381
1382 /*
1383  * 27-octet in-memory packet from P2P specification containing two implied
1384  * queries for _tcp.lcoal. PTR IN and _udp.local. PTR IN
1385  */
1386 #define P2P_SD_IN_MEMORY_LEN 27
1387
1388 static int p2p_sd_dns_uncompress_label(char **upos, char *uend, u8 *start,
1389                                        u8 **spos, const u8 *end)
1390 {
1391         while (*spos < end) {
1392                 u8 val = ((*spos)[0] & 0xc0) >> 6;
1393                 int len;
1394
1395                 if (val == 1 || val == 2) {
1396                         /* These are reserved values in RFC 1035 */
1397                         wpa_printf(MSG_DEBUG, "P2P: Invalid domain name "
1398                                    "sequence starting with 0x%x", val);
1399                         return -1;
1400                 }
1401
1402                 if (val == 3) {
1403                         u16 offset;
1404                         u8 *spos_tmp;
1405
1406                         /* Offset */
1407                         if (*spos + 2 > end) {
1408                                 wpa_printf(MSG_DEBUG, "P2P: No room for full "
1409                                            "DNS offset field");
1410                                 return -1;
1411                         }
1412
1413                         offset = (((*spos)[0] & 0x3f) << 8) | (*spos)[1];
1414                         if (offset >= *spos - start) {
1415                                 wpa_printf(MSG_DEBUG, "P2P: Invalid DNS "
1416                                            "pointer offset %u", offset);
1417                                 return -1;
1418                         }
1419
1420                         (*spos) += 2;
1421                         spos_tmp = start + offset;
1422                         return p2p_sd_dns_uncompress_label(upos, uend, start,
1423                                                            &spos_tmp,
1424                                                            *spos - 2);
1425                 }
1426
1427                 /* Label */
1428                 len = (*spos)[0] & 0x3f;
1429                 if (len == 0)
1430                         return 0;
1431
1432                 (*spos)++;
1433                 if (*spos + len > end) {
1434                         wpa_printf(MSG_DEBUG, "P2P: Invalid domain name "
1435                                    "sequence - no room for label with length "
1436                                    "%u", len);
1437                         return -1;
1438                 }
1439
1440                 if (*upos + len + 2 > uend)
1441                         return -2;
1442
1443                 os_memcpy(*upos, *spos, len);
1444                 *spos += len;
1445                 *upos += len;
1446                 (*upos)[0] = '.';
1447                 (*upos)++;
1448                 (*upos)[0] = '\0';
1449         }
1450
1451         return 0;
1452 }
1453
1454
1455 /* Uncompress domain names per RFC 1035 using the P2P SD in-memory packet.
1456  * Returns -1 on parsing error (invalid input sequence), -2 if output buffer is
1457  * not large enough */
1458 static int p2p_sd_dns_uncompress(char *buf, size_t buf_len, const u8 *msg,
1459                                  size_t msg_len, size_t offset)
1460 {
1461         /* 27-octet in-memory packet from P2P specification */
1462         const char *prefix = "\x04_tcp\x05local\x00\x00\x0C\x00\x01"
1463                 "\x04_udp\xC0\x11\x00\x0C\x00\x01";
1464         u8 *tmp, *end, *spos;
1465         char *upos, *uend;
1466         int ret = 0;
1467
1468         if (buf_len < 2)
1469                 return -1;
1470         if (offset > msg_len)
1471                 return -1;
1472
1473         tmp = os_malloc(DNS_HEADER_LEN + P2P_SD_IN_MEMORY_LEN + msg_len);
1474         if (tmp == NULL)
1475                 return -1;
1476         spos = tmp + DNS_HEADER_LEN + P2P_SD_IN_MEMORY_LEN;
1477         end = spos + msg_len;
1478         spos += offset;
1479
1480         os_memset(tmp, 0, DNS_HEADER_LEN);
1481         os_memcpy(tmp + DNS_HEADER_LEN, prefix, P2P_SD_IN_MEMORY_LEN);
1482         os_memcpy(tmp + DNS_HEADER_LEN + P2P_SD_IN_MEMORY_LEN, msg, msg_len);
1483
1484         upos = buf;
1485         uend = buf + buf_len;
1486
1487         ret = p2p_sd_dns_uncompress_label(&upos, uend, tmp, &spos, end);
1488         if (ret) {
1489                 os_free(tmp);
1490                 return ret;
1491         }
1492
1493         if (upos == buf) {
1494                 upos[0] = '.';
1495                 upos[1] = '\0';
1496         } else if (upos[-1] == '.')
1497                 upos[-1] = '\0';
1498
1499         os_free(tmp);
1500         return 0;
1501 }
1502
1503
1504 static struct p2p_srv_bonjour *
1505 wpas_p2p_service_get_bonjour(struct wpa_supplicant *wpa_s,
1506                              const struct wpabuf *query)
1507 {
1508         struct p2p_srv_bonjour *bsrv;
1509         size_t len;
1510
1511         len = wpabuf_len(query);
1512         dl_list_for_each(bsrv, &wpa_s->global->p2p_srv_bonjour,
1513                          struct p2p_srv_bonjour, list) {
1514                 if (len == wpabuf_len(bsrv->query) &&
1515                     os_memcmp(wpabuf_head(query), wpabuf_head(bsrv->query),
1516                               len) == 0)
1517                         return bsrv;
1518         }
1519         return NULL;
1520 }
1521
1522
1523 static struct p2p_srv_upnp *
1524 wpas_p2p_service_get_upnp(struct wpa_supplicant *wpa_s, u8 version,
1525                           const char *service)
1526 {
1527         struct p2p_srv_upnp *usrv;
1528
1529         dl_list_for_each(usrv, &wpa_s->global->p2p_srv_upnp,
1530                          struct p2p_srv_upnp, list) {
1531                 if (version == usrv->version &&
1532                     os_strcmp(service, usrv->service) == 0)
1533                         return usrv;
1534         }
1535         return NULL;
1536 }
1537
1538
1539 static void wpas_sd_add_proto_not_avail(struct wpabuf *resp, u8 srv_proto,
1540                                         u8 srv_trans_id)
1541 {
1542         u8 *len_pos;
1543
1544         if (wpabuf_tailroom(resp) < 5)
1545                 return;
1546
1547         /* Length (to be filled) */
1548         len_pos = wpabuf_put(resp, 2);
1549         wpabuf_put_u8(resp, srv_proto);
1550         wpabuf_put_u8(resp, srv_trans_id);
1551         /* Status Code */
1552         wpabuf_put_u8(resp, P2P_SD_PROTO_NOT_AVAILABLE);
1553         /* Response Data: empty */
1554         WPA_PUT_LE16(len_pos, (u8 *) wpabuf_put(resp, 0) - len_pos - 2);
1555 }
1556
1557
1558 static void wpas_sd_all_bonjour(struct wpa_supplicant *wpa_s,
1559                                 struct wpabuf *resp, u8 srv_trans_id)
1560 {
1561         struct p2p_srv_bonjour *bsrv;
1562         u8 *len_pos;
1563
1564         wpa_printf(MSG_DEBUG, "P2P: SD Request for all Bonjour services");
1565
1566         if (dl_list_empty(&wpa_s->global->p2p_srv_bonjour)) {
1567                 wpa_printf(MSG_DEBUG, "P2P: Bonjour protocol not available");
1568                 return;
1569         }
1570
1571         dl_list_for_each(bsrv, &wpa_s->global->p2p_srv_bonjour,
1572                          struct p2p_srv_bonjour, list) {
1573                 if (wpabuf_tailroom(resp) <
1574                     5 + wpabuf_len(bsrv->query) + wpabuf_len(bsrv->resp))
1575                         return;
1576                 /* Length (to be filled) */
1577                 len_pos = wpabuf_put(resp, 2);
1578                 wpabuf_put_u8(resp, P2P_SERV_BONJOUR);
1579                 wpabuf_put_u8(resp, srv_trans_id);
1580                 /* Status Code */
1581                 wpabuf_put_u8(resp, P2P_SD_SUCCESS);
1582                 wpa_hexdump_ascii(MSG_DEBUG, "P2P: Matching Bonjour service",
1583                                   wpabuf_head(bsrv->resp),
1584                                   wpabuf_len(bsrv->resp));
1585                 /* Response Data */
1586                 wpabuf_put_buf(resp, bsrv->query); /* Key */
1587                 wpabuf_put_buf(resp, bsrv->resp); /* Value */
1588                 WPA_PUT_LE16(len_pos, (u8 *) wpabuf_put(resp, 0) - len_pos -
1589                              2);
1590         }
1591 }
1592
1593
1594 static int match_bonjour_query(struct p2p_srv_bonjour *bsrv, const u8 *query,
1595                                size_t query_len)
1596 {
1597         char str_rx[256], str_srv[256];
1598
1599         if (query_len < 3 || wpabuf_len(bsrv->query) < 3)
1600                 return 0; /* Too short to include DNS Type and Version */
1601         if (os_memcmp(query + query_len - 3,
1602                       wpabuf_head_u8(bsrv->query) + wpabuf_len(bsrv->query) - 3,
1603                       3) != 0)
1604                 return 0; /* Mismatch in DNS Type or Version */
1605         if (query_len == wpabuf_len(bsrv->query) &&
1606             os_memcmp(query, wpabuf_head(bsrv->query), query_len - 3) == 0)
1607                 return 1; /* Binary match */
1608
1609         if (p2p_sd_dns_uncompress(str_rx, sizeof(str_rx), query, query_len - 3,
1610                                   0))
1611                 return 0; /* Failed to uncompress query */
1612         if (p2p_sd_dns_uncompress(str_srv, sizeof(str_srv),
1613                                   wpabuf_head(bsrv->query),
1614                                   wpabuf_len(bsrv->query) - 3, 0))
1615                 return 0; /* Failed to uncompress service */
1616
1617         return os_strcmp(str_rx, str_srv) == 0;
1618 }
1619
1620
1621 static void wpas_sd_req_bonjour(struct wpa_supplicant *wpa_s,
1622                                 struct wpabuf *resp, u8 srv_trans_id,
1623                                 const u8 *query, size_t query_len)
1624 {
1625         struct p2p_srv_bonjour *bsrv;
1626         u8 *len_pos;
1627         int matches = 0;
1628
1629         wpa_hexdump_ascii(MSG_DEBUG, "P2P: SD Request for Bonjour",
1630                           query, query_len);
1631         if (dl_list_empty(&wpa_s->global->p2p_srv_bonjour)) {
1632                 wpa_printf(MSG_DEBUG, "P2P: Bonjour protocol not available");
1633                 wpas_sd_add_proto_not_avail(resp, P2P_SERV_BONJOUR,
1634                                             srv_trans_id);
1635                 return;
1636         }
1637
1638         if (query_len == 0) {
1639                 wpas_sd_all_bonjour(wpa_s, resp, srv_trans_id);
1640                 return;
1641         }
1642
1643         dl_list_for_each(bsrv, &wpa_s->global->p2p_srv_bonjour,
1644                          struct p2p_srv_bonjour, list) {
1645                 if (!match_bonjour_query(bsrv, query, query_len))
1646                         continue;
1647
1648                 if (wpabuf_tailroom(resp) <
1649                     5 + query_len + wpabuf_len(bsrv->resp))
1650                         return;
1651
1652                 matches++;
1653
1654                 /* Length (to be filled) */
1655                 len_pos = wpabuf_put(resp, 2);
1656                 wpabuf_put_u8(resp, P2P_SERV_BONJOUR);
1657                 wpabuf_put_u8(resp, srv_trans_id);
1658
1659                 /* Status Code */
1660                 wpabuf_put_u8(resp, P2P_SD_SUCCESS);
1661                 wpa_hexdump_ascii(MSG_DEBUG, "P2P: Matching Bonjour service",
1662                                   wpabuf_head(bsrv->resp),
1663                                   wpabuf_len(bsrv->resp));
1664
1665                 /* Response Data */
1666                 wpabuf_put_data(resp, query, query_len); /* Key */
1667                 wpabuf_put_buf(resp, bsrv->resp); /* Value */
1668
1669                 WPA_PUT_LE16(len_pos, (u8 *) wpabuf_put(resp, 0) - len_pos - 2);
1670         }
1671
1672         if (matches == 0) {
1673                 wpa_printf(MSG_DEBUG, "P2P: Requested Bonjour service not "
1674                            "available");
1675                 if (wpabuf_tailroom(resp) < 5)
1676                         return;
1677
1678                 /* Length (to be filled) */
1679                 len_pos = wpabuf_put(resp, 2);
1680                 wpabuf_put_u8(resp, P2P_SERV_BONJOUR);
1681                 wpabuf_put_u8(resp, srv_trans_id);
1682
1683                 /* Status Code */
1684                 wpabuf_put_u8(resp, P2P_SD_REQUESTED_INFO_NOT_AVAILABLE);
1685                 /* Response Data: empty */
1686                 WPA_PUT_LE16(len_pos, (u8 *) wpabuf_put(resp, 0) - len_pos -
1687                              2);
1688         }
1689 }
1690
1691
1692 static void wpas_sd_all_upnp(struct wpa_supplicant *wpa_s,
1693                              struct wpabuf *resp, u8 srv_trans_id)
1694 {
1695         struct p2p_srv_upnp *usrv;
1696         u8 *len_pos;
1697
1698         wpa_printf(MSG_DEBUG, "P2P: SD Request for all UPnP services");
1699
1700         if (dl_list_empty(&wpa_s->global->p2p_srv_upnp)) {
1701                 wpa_printf(MSG_DEBUG, "P2P: UPnP protocol not available");
1702                 return;
1703         }
1704
1705         dl_list_for_each(usrv, &wpa_s->global->p2p_srv_upnp,
1706                          struct p2p_srv_upnp, list) {
1707                 if (wpabuf_tailroom(resp) < 5 + 1 + os_strlen(usrv->service))
1708                         return;
1709
1710                 /* Length (to be filled) */
1711                 len_pos = wpabuf_put(resp, 2);
1712                 wpabuf_put_u8(resp, P2P_SERV_UPNP);
1713                 wpabuf_put_u8(resp, srv_trans_id);
1714
1715                 /* Status Code */
1716                 wpabuf_put_u8(resp, P2P_SD_SUCCESS);
1717                 /* Response Data */
1718                 wpabuf_put_u8(resp, usrv->version);
1719                 wpa_printf(MSG_DEBUG, "P2P: Matching UPnP Service: %s",
1720                            usrv->service);
1721                 wpabuf_put_str(resp, usrv->service);
1722                 WPA_PUT_LE16(len_pos, (u8 *) wpabuf_put(resp, 0) - len_pos -
1723                              2);
1724         }
1725 }
1726
1727
1728 static void wpas_sd_req_upnp(struct wpa_supplicant *wpa_s,
1729                              struct wpabuf *resp, u8 srv_trans_id,
1730                              const u8 *query, size_t query_len)
1731 {
1732         struct p2p_srv_upnp *usrv;
1733         u8 *len_pos;
1734         u8 version;
1735         char *str;
1736         int count = 0;
1737
1738         wpa_hexdump_ascii(MSG_DEBUG, "P2P: SD Request for UPnP",
1739                           query, query_len);
1740
1741         if (dl_list_empty(&wpa_s->global->p2p_srv_upnp)) {
1742                 wpa_printf(MSG_DEBUG, "P2P: UPnP protocol not available");
1743                 wpas_sd_add_proto_not_avail(resp, P2P_SERV_UPNP,
1744                                             srv_trans_id);
1745                 return;
1746         }
1747
1748         if (query_len == 0) {
1749                 wpas_sd_all_upnp(wpa_s, resp, srv_trans_id);
1750                 return;
1751         }
1752
1753         if (wpabuf_tailroom(resp) < 5)
1754                 return;
1755
1756         /* Length (to be filled) */
1757         len_pos = wpabuf_put(resp, 2);
1758         wpabuf_put_u8(resp, P2P_SERV_UPNP);
1759         wpabuf_put_u8(resp, srv_trans_id);
1760
1761         version = query[0];
1762         str = os_malloc(query_len);
1763         if (str == NULL)
1764                 return;
1765         os_memcpy(str, query + 1, query_len - 1);
1766         str[query_len - 1] = '\0';
1767
1768         dl_list_for_each(usrv, &wpa_s->global->p2p_srv_upnp,
1769                          struct p2p_srv_upnp, list) {
1770                 if (version != usrv->version)
1771                         continue;
1772
1773                 if (os_strcmp(str, "ssdp:all") != 0 &&
1774                     os_strstr(usrv->service, str) == NULL)
1775                         continue;
1776
1777                 if (wpabuf_tailroom(resp) < 2)
1778                         break;
1779                 if (count == 0) {
1780                         /* Status Code */
1781                         wpabuf_put_u8(resp, P2P_SD_SUCCESS);
1782                         /* Response Data */
1783                         wpabuf_put_u8(resp, version);
1784                 } else
1785                         wpabuf_put_u8(resp, ',');
1786
1787                 count++;
1788
1789                 wpa_printf(MSG_DEBUG, "P2P: Matching UPnP Service: %s",
1790                            usrv->service);
1791                 if (wpabuf_tailroom(resp) < os_strlen(usrv->service))
1792                         break;
1793                 wpabuf_put_str(resp, usrv->service);
1794         }
1795         os_free(str);
1796
1797         if (count == 0) {
1798                 wpa_printf(MSG_DEBUG, "P2P: Requested UPnP service not "
1799                            "available");
1800                 /* Status Code */
1801                 wpabuf_put_u8(resp, P2P_SD_REQUESTED_INFO_NOT_AVAILABLE);
1802                 /* Response Data: empty */
1803         }
1804
1805         WPA_PUT_LE16(len_pos, (u8 *) wpabuf_put(resp, 0) - len_pos - 2);
1806 }
1807
1808
1809 #ifdef CONFIG_WIFI_DISPLAY
1810 static void wpas_sd_req_wfd(struct wpa_supplicant *wpa_s,
1811                             struct wpabuf *resp, u8 srv_trans_id,
1812                             const u8 *query, size_t query_len)
1813 {
1814         const u8 *pos;
1815         u8 role;
1816         u8 *len_pos;
1817
1818         wpa_hexdump(MSG_DEBUG, "P2P: SD Request for WFD", query, query_len);
1819
1820         if (!wpa_s->global->wifi_display) {
1821                 wpa_printf(MSG_DEBUG, "P2P: WFD protocol not available");
1822                 wpas_sd_add_proto_not_avail(resp, P2P_SERV_WIFI_DISPLAY,
1823                                             srv_trans_id);
1824                 return;
1825         }
1826
1827         if (query_len < 1) {
1828                 wpa_printf(MSG_DEBUG, "P2P: Missing WFD Requested Device "
1829                            "Role");
1830                 return;
1831         }
1832
1833         if (wpabuf_tailroom(resp) < 5)
1834                 return;
1835
1836         pos = query;
1837         role = *pos++;
1838         wpa_printf(MSG_DEBUG, "P2P: WSD for device role 0x%x", role);
1839
1840         /* TODO: role specific handling */
1841
1842         /* Length (to be filled) */
1843         len_pos = wpabuf_put(resp, 2);
1844         wpabuf_put_u8(resp, P2P_SERV_WIFI_DISPLAY);
1845         wpabuf_put_u8(resp, srv_trans_id);
1846         wpabuf_put_u8(resp, P2P_SD_SUCCESS); /* Status Code */
1847
1848         while (pos < query + query_len) {
1849                 if (*pos < MAX_WFD_SUBELEMS &&
1850                     wpa_s->global->wfd_subelem[*pos] &&
1851                     wpabuf_tailroom(resp) >=
1852                     wpabuf_len(wpa_s->global->wfd_subelem[*pos])) {
1853                         wpa_printf(MSG_DEBUG, "P2P: Add WSD response "
1854                                    "subelement %u", *pos);
1855                         wpabuf_put_buf(resp, wpa_s->global->wfd_subelem[*pos]);
1856                 }
1857                 pos++;
1858         }
1859
1860         WPA_PUT_LE16(len_pos, (u8 *) wpabuf_put(resp, 0) - len_pos - 2);
1861 }
1862 #endif /* CONFIG_WIFI_DISPLAY */
1863
1864
1865 void wpas_sd_request(void *ctx, int freq, const u8 *sa, u8 dialog_token,
1866                      u16 update_indic, const u8 *tlvs, size_t tlvs_len)
1867 {
1868         struct wpa_supplicant *wpa_s = ctx;
1869         const u8 *pos = tlvs;
1870         const u8 *end = tlvs + tlvs_len;
1871         const u8 *tlv_end;
1872         u16 slen;
1873         struct wpabuf *resp;
1874         u8 srv_proto, srv_trans_id;
1875         size_t buf_len;
1876         char *buf;
1877
1878         wpa_hexdump(MSG_MSGDUMP, "P2P: Service Discovery Request TLVs",
1879                     tlvs, tlvs_len);
1880         buf_len = 2 * tlvs_len + 1;
1881         buf = os_malloc(buf_len);
1882         if (buf) {
1883                 wpa_snprintf_hex(buf, buf_len, tlvs, tlvs_len);
1884                 wpa_msg_ctrl(wpa_s, MSG_INFO, P2P_EVENT_SERV_DISC_REQ "%d "
1885                              MACSTR " %u %u %s",
1886                              freq, MAC2STR(sa), dialog_token, update_indic,
1887                              buf);
1888                 os_free(buf);
1889         }
1890
1891         if (wpa_s->p2p_sd_over_ctrl_iface) {
1892                 wpas_notify_p2p_sd_request(wpa_s, freq, sa, dialog_token,
1893                                            update_indic, tlvs, tlvs_len);
1894                 return; /* to be processed by an external program */
1895         }
1896
1897         resp = wpabuf_alloc(10000);
1898         if (resp == NULL)
1899                 return;
1900
1901         while (pos + 1 < end) {
1902                 wpa_printf(MSG_DEBUG, "P2P: Service Request TLV");
1903                 slen = WPA_GET_LE16(pos);
1904                 pos += 2;
1905                 if (pos + slen > end || slen < 2) {
1906                         wpa_printf(MSG_DEBUG, "P2P: Unexpected Query Data "
1907                                    "length");
1908                         wpabuf_free(resp);
1909                         return;
1910                 }
1911                 tlv_end = pos + slen;
1912
1913                 srv_proto = *pos++;
1914                 wpa_printf(MSG_DEBUG, "P2P: Service Protocol Type %u",
1915                            srv_proto);
1916                 srv_trans_id = *pos++;
1917                 wpa_printf(MSG_DEBUG, "P2P: Service Transaction ID %u",
1918                            srv_trans_id);
1919
1920                 wpa_hexdump(MSG_MSGDUMP, "P2P: Query Data",
1921                             pos, tlv_end - pos);
1922
1923
1924                 if (wpa_s->force_long_sd) {
1925                         wpa_printf(MSG_DEBUG, "P2P: SD test - force long "
1926                                    "response");
1927                         wpas_sd_all_bonjour(wpa_s, resp, srv_trans_id);
1928                         wpas_sd_all_upnp(wpa_s, resp, srv_trans_id);
1929                         goto done;
1930                 }
1931
1932                 switch (srv_proto) {
1933                 case P2P_SERV_ALL_SERVICES:
1934                         wpa_printf(MSG_DEBUG, "P2P: Service Discovery Request "
1935                                    "for all services");
1936                         if (dl_list_empty(&wpa_s->global->p2p_srv_upnp) &&
1937                             dl_list_empty(&wpa_s->global->p2p_srv_bonjour)) {
1938                                 wpa_printf(MSG_DEBUG, "P2P: No service "
1939                                            "discovery protocols available");
1940                                 wpas_sd_add_proto_not_avail(
1941                                         resp, P2P_SERV_ALL_SERVICES,
1942                                         srv_trans_id);
1943                                 break;
1944                         }
1945                         wpas_sd_all_bonjour(wpa_s, resp, srv_trans_id);
1946                         wpas_sd_all_upnp(wpa_s, resp, srv_trans_id);
1947                         break;
1948                 case P2P_SERV_BONJOUR:
1949                         wpas_sd_req_bonjour(wpa_s, resp, srv_trans_id,
1950                                             pos, tlv_end - pos);
1951                         break;
1952                 case P2P_SERV_UPNP:
1953                         wpas_sd_req_upnp(wpa_s, resp, srv_trans_id,
1954                                          pos, tlv_end - pos);
1955                         break;
1956 #ifdef CONFIG_WIFI_DISPLAY
1957                 case P2P_SERV_WIFI_DISPLAY:
1958                         wpas_sd_req_wfd(wpa_s, resp, srv_trans_id,
1959                                         pos, tlv_end - pos);
1960                         break;
1961 #endif /* CONFIG_WIFI_DISPLAY */
1962                 default:
1963                         wpa_printf(MSG_DEBUG, "P2P: Unavailable service "
1964                                    "protocol %u", srv_proto);
1965                         wpas_sd_add_proto_not_avail(resp, srv_proto,
1966                                                     srv_trans_id);
1967                         break;
1968                 }
1969
1970                 pos = tlv_end;
1971         }
1972
1973 done:
1974         wpas_notify_p2p_sd_request(wpa_s, freq, sa, dialog_token,
1975                                    update_indic, tlvs, tlvs_len);
1976
1977         wpas_p2p_sd_response(wpa_s, freq, sa, dialog_token, resp);
1978
1979         wpabuf_free(resp);
1980 }
1981
1982
1983 void wpas_sd_response(void *ctx, const u8 *sa, u16 update_indic,
1984                       const u8 *tlvs, size_t tlvs_len)
1985 {
1986         struct wpa_supplicant *wpa_s = ctx;
1987         const u8 *pos = tlvs;
1988         const u8 *end = tlvs + tlvs_len;
1989         const u8 *tlv_end;
1990         u16 slen;
1991         size_t buf_len;
1992         char *buf;
1993
1994         wpa_hexdump(MSG_MSGDUMP, "P2P: Service Discovery Response TLVs",
1995                     tlvs, tlvs_len);
1996         if (tlvs_len > 1500) {
1997                 /* TODO: better way for handling this */
1998                 wpa_msg_ctrl(wpa_s, MSG_INFO,
1999                              P2P_EVENT_SERV_DISC_RESP MACSTR
2000                              " %u <long response: %u bytes>",
2001                              MAC2STR(sa), update_indic,
2002                              (unsigned int) tlvs_len);
2003         } else {
2004                 buf_len = 2 * tlvs_len + 1;
2005                 buf = os_malloc(buf_len);
2006                 if (buf) {
2007                         wpa_snprintf_hex(buf, buf_len, tlvs, tlvs_len);
2008                         wpa_msg_ctrl(wpa_s, MSG_INFO,
2009                                      P2P_EVENT_SERV_DISC_RESP MACSTR " %u %s",
2010                                      MAC2STR(sa), update_indic, buf);
2011                         os_free(buf);
2012                 }
2013         }
2014
2015         while (pos < end) {
2016                 u8 srv_proto, srv_trans_id, status;
2017
2018                 wpa_printf(MSG_DEBUG, "P2P: Service Response TLV");
2019                 slen = WPA_GET_LE16(pos);
2020                 pos += 2;
2021                 if (pos + slen > end || slen < 3) {
2022                         wpa_printf(MSG_DEBUG, "P2P: Unexpected Response Data "
2023                                    "length");
2024                         return;
2025                 }
2026                 tlv_end = pos + slen;
2027
2028                 srv_proto = *pos++;
2029                 wpa_printf(MSG_DEBUG, "P2P: Service Protocol Type %u",
2030                            srv_proto);
2031                 srv_trans_id = *pos++;
2032                 wpa_printf(MSG_DEBUG, "P2P: Service Transaction ID %u",
2033                            srv_trans_id);
2034                 status = *pos++;
2035                 wpa_printf(MSG_DEBUG, "P2P: Status Code ID %u",
2036                            status);
2037
2038                 wpa_hexdump(MSG_MSGDUMP, "P2P: Response Data",
2039                             pos, tlv_end - pos);
2040
2041                 pos = tlv_end;
2042         }
2043
2044         wpas_notify_p2p_sd_response(wpa_s, sa, update_indic, tlvs, tlvs_len);
2045 }
2046
2047
2048 u64 wpas_p2p_sd_request(struct wpa_supplicant *wpa_s, const u8 *dst,
2049                         const struct wpabuf *tlvs)
2050 {
2051         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT)
2052                 return wpa_drv_p2p_sd_request(wpa_s, dst, tlvs);
2053         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
2054                 return 0;
2055         return (uintptr_t) p2p_sd_request(wpa_s->global->p2p, dst, tlvs);
2056 }
2057
2058
2059 u64 wpas_p2p_sd_request_upnp(struct wpa_supplicant *wpa_s, const u8 *dst,
2060                              u8 version, const char *query)
2061 {
2062         struct wpabuf *tlvs;
2063         u64 ret;
2064
2065         tlvs = wpabuf_alloc(2 + 1 + 1 + 1 + os_strlen(query));
2066         if (tlvs == NULL)
2067                 return 0;
2068         wpabuf_put_le16(tlvs, 1 + 1 + 1 + os_strlen(query));
2069         wpabuf_put_u8(tlvs, P2P_SERV_UPNP); /* Service Protocol Type */
2070         wpabuf_put_u8(tlvs, 1); /* Service Transaction ID */
2071         wpabuf_put_u8(tlvs, version);
2072         wpabuf_put_str(tlvs, query);
2073         ret = wpas_p2p_sd_request(wpa_s, dst, tlvs);
2074         wpabuf_free(tlvs);
2075         return ret;
2076 }
2077
2078
2079 #ifdef CONFIG_WIFI_DISPLAY
2080
2081 static u64 wpas_p2p_sd_request_wfd(struct wpa_supplicant *wpa_s, const u8 *dst,
2082                                    const struct wpabuf *tlvs)
2083 {
2084         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT)
2085                 return 0;
2086         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
2087                 return 0;
2088         return (uintptr_t) p2p_sd_request_wfd(wpa_s->global->p2p, dst, tlvs);
2089 }
2090
2091
2092 #define MAX_WFD_SD_SUBELEMS 20
2093
2094 static void wfd_add_sd_req_role(struct wpabuf *tlvs, u8 id, u8 role,
2095                                 const char *subelems)
2096 {
2097         u8 *len;
2098         const char *pos;
2099         int val;
2100         int count = 0;
2101
2102         len = wpabuf_put(tlvs, 2);
2103         wpabuf_put_u8(tlvs, P2P_SERV_WIFI_DISPLAY); /* Service Protocol Type */
2104         wpabuf_put_u8(tlvs, id); /* Service Transaction ID */
2105
2106         wpabuf_put_u8(tlvs, role);
2107
2108         pos = subelems;
2109         while (*pos) {
2110                 val = atoi(pos);
2111                 if (val >= 0 && val < 256) {
2112                         wpabuf_put_u8(tlvs, val);
2113                         count++;
2114                         if (count == MAX_WFD_SD_SUBELEMS)
2115                                 break;
2116                 }
2117                 pos = os_strchr(pos + 1, ',');
2118                 if (pos == NULL)
2119                         break;
2120                 pos++;
2121         }
2122
2123         WPA_PUT_LE16(len, (u8 *) wpabuf_put(tlvs, 0) - len - 2);
2124 }
2125
2126
2127 u64 wpas_p2p_sd_request_wifi_display(struct wpa_supplicant *wpa_s,
2128                                      const u8 *dst, const char *role)
2129 {
2130         struct wpabuf *tlvs;
2131         u64 ret;
2132         const char *subelems;
2133         u8 id = 1;
2134
2135         subelems = os_strchr(role, ' ');
2136         if (subelems == NULL)
2137                 return 0;
2138         subelems++;
2139
2140         tlvs = wpabuf_alloc(4 * (2 + 1 + 1 + 1 + MAX_WFD_SD_SUBELEMS));
2141         if (tlvs == NULL)
2142                 return 0;
2143
2144         if (os_strstr(role, "[source]"))
2145                 wfd_add_sd_req_role(tlvs, id++, 0x00, subelems);
2146         if (os_strstr(role, "[pri-sink]"))
2147                 wfd_add_sd_req_role(tlvs, id++, 0x01, subelems);
2148         if (os_strstr(role, "[sec-sink]"))
2149                 wfd_add_sd_req_role(tlvs, id++, 0x02, subelems);
2150         if (os_strstr(role, "[source+sink]"))
2151                 wfd_add_sd_req_role(tlvs, id++, 0x03, subelems);
2152
2153         ret = wpas_p2p_sd_request_wfd(wpa_s, dst, tlvs);
2154         wpabuf_free(tlvs);
2155         return ret;
2156 }
2157
2158 #endif /* CONFIG_WIFI_DISPLAY */
2159
2160
2161 int wpas_p2p_sd_cancel_request(struct wpa_supplicant *wpa_s, u64 req)
2162 {
2163         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT)
2164                 return wpa_drv_p2p_sd_cancel_request(wpa_s, req);
2165         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
2166                 return -1;
2167         return p2p_sd_cancel_request(wpa_s->global->p2p,
2168                                      (void *) (uintptr_t) req);
2169 }
2170
2171
2172 void wpas_p2p_sd_response(struct wpa_supplicant *wpa_s, int freq,
2173                           const u8 *dst, u8 dialog_token,
2174                           const struct wpabuf *resp_tlvs)
2175 {
2176         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT) {
2177                 wpa_drv_p2p_sd_response(wpa_s, freq, dst, dialog_token,
2178                                         resp_tlvs);
2179                 return;
2180         }
2181         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
2182                 return;
2183         p2p_sd_response(wpa_s->global->p2p, freq, dst, dialog_token,
2184                         resp_tlvs);
2185 }
2186
2187
2188 void wpas_p2p_sd_service_update(struct wpa_supplicant *wpa_s)
2189 {
2190         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT) {
2191                 wpa_drv_p2p_service_update(wpa_s);
2192                 return;
2193         }
2194         if (wpa_s->global->p2p)
2195                 p2p_sd_service_update(wpa_s->global->p2p);
2196 }
2197
2198
2199 static void wpas_p2p_srv_bonjour_free(struct p2p_srv_bonjour *bsrv)
2200 {
2201         dl_list_del(&bsrv->list);
2202         wpabuf_free(bsrv->query);
2203         wpabuf_free(bsrv->resp);
2204         os_free(bsrv);
2205 }
2206
2207
2208 static void wpas_p2p_srv_upnp_free(struct p2p_srv_upnp *usrv)
2209 {
2210         dl_list_del(&usrv->list);
2211         os_free(usrv->service);
2212         os_free(usrv);
2213 }
2214
2215
2216 void wpas_p2p_service_flush(struct wpa_supplicant *wpa_s)
2217 {
2218         struct p2p_srv_bonjour *bsrv, *bn;
2219         struct p2p_srv_upnp *usrv, *un;
2220
2221         dl_list_for_each_safe(bsrv, bn, &wpa_s->global->p2p_srv_bonjour,
2222                               struct p2p_srv_bonjour, list)
2223                 wpas_p2p_srv_bonjour_free(bsrv);
2224
2225         dl_list_for_each_safe(usrv, un, &wpa_s->global->p2p_srv_upnp,
2226                               struct p2p_srv_upnp, list)
2227                 wpas_p2p_srv_upnp_free(usrv);
2228
2229         wpas_p2p_sd_service_update(wpa_s);
2230 }
2231
2232
2233 int wpas_p2p_service_add_bonjour(struct wpa_supplicant *wpa_s,
2234                                  struct wpabuf *query, struct wpabuf *resp)
2235 {
2236         struct p2p_srv_bonjour *bsrv;
2237
2238         bsrv = os_zalloc(sizeof(*bsrv));
2239         if (bsrv == NULL)
2240                 return -1;
2241         bsrv->query = query;
2242         bsrv->resp = resp;
2243         dl_list_add(&wpa_s->global->p2p_srv_bonjour, &bsrv->list);
2244
2245         wpas_p2p_sd_service_update(wpa_s);
2246         return 0;
2247 }
2248
2249
2250 int wpas_p2p_service_del_bonjour(struct wpa_supplicant *wpa_s,
2251                                  const struct wpabuf *query)
2252 {
2253         struct p2p_srv_bonjour *bsrv;
2254
2255         bsrv = wpas_p2p_service_get_bonjour(wpa_s, query);
2256         if (bsrv == NULL)
2257                 return -1;
2258         wpas_p2p_srv_bonjour_free(bsrv);
2259         wpas_p2p_sd_service_update(wpa_s);
2260         return 0;
2261 }
2262
2263
2264 int wpas_p2p_service_add_upnp(struct wpa_supplicant *wpa_s, u8 version,
2265                               const char *service)
2266 {
2267         struct p2p_srv_upnp *usrv;
2268
2269         if (wpas_p2p_service_get_upnp(wpa_s, version, service))
2270                 return 0; /* Already listed */
2271         usrv = os_zalloc(sizeof(*usrv));
2272         if (usrv == NULL)
2273                 return -1;
2274         usrv->version = version;
2275         usrv->service = os_strdup(service);
2276         if (usrv->service == NULL) {
2277                 os_free(usrv);
2278                 return -1;
2279         }
2280         dl_list_add(&wpa_s->global->p2p_srv_upnp, &usrv->list);
2281
2282         wpas_p2p_sd_service_update(wpa_s);
2283         return 0;
2284 }
2285
2286
2287 int wpas_p2p_service_del_upnp(struct wpa_supplicant *wpa_s, u8 version,
2288                               const char *service)
2289 {
2290         struct p2p_srv_upnp *usrv;
2291
2292         usrv = wpas_p2p_service_get_upnp(wpa_s, version, service);
2293         if (usrv == NULL)
2294                 return -1;
2295         wpas_p2p_srv_upnp_free(usrv);
2296         wpas_p2p_sd_service_update(wpa_s);
2297         return 0;
2298 }
2299
2300
2301 static void wpas_prov_disc_local_display(struct wpa_supplicant *wpa_s,
2302                                          const u8 *peer, const char *params,
2303                                          unsigned int generated_pin)
2304 {
2305         wpa_msg_global(wpa_s, MSG_INFO, P2P_EVENT_PROV_DISC_SHOW_PIN MACSTR
2306                        " %08d%s", MAC2STR(peer), generated_pin, params);
2307 }
2308
2309
2310 static void wpas_prov_disc_local_keypad(struct wpa_supplicant *wpa_s,
2311                                         const u8 *peer, const char *params)
2312 {
2313         wpa_msg_global(wpa_s, MSG_INFO, P2P_EVENT_PROV_DISC_ENTER_PIN MACSTR
2314                        "%s", MAC2STR(peer), params);
2315 }
2316
2317
2318 void wpas_prov_disc_req(void *ctx, const u8 *peer, u16 config_methods,
2319                         const u8 *dev_addr, const u8 *pri_dev_type,
2320                         const char *dev_name, u16 supp_config_methods,
2321                         u8 dev_capab, u8 group_capab, const u8 *group_id,
2322                         size_t group_id_len)
2323 {
2324         struct wpa_supplicant *wpa_s = ctx;
2325         char devtype[WPS_DEV_TYPE_BUFSIZE];
2326         char params[300];
2327         u8 empty_dev_type[8];
2328         unsigned int generated_pin = 0;
2329         struct wpa_supplicant *group = NULL;
2330
2331         if (group_id) {
2332                 for (group = wpa_s->global->ifaces; group; group = group->next)
2333                 {
2334                         struct wpa_ssid *s = group->current_ssid;
2335                         if (s != NULL &&
2336                             s->mode == WPAS_MODE_P2P_GO &&
2337                             group_id_len - ETH_ALEN == s->ssid_len &&
2338                             os_memcmp(group_id + ETH_ALEN, s->ssid,
2339                                       s->ssid_len) == 0)
2340                                 break;
2341                 }
2342         }
2343
2344         if (pri_dev_type == NULL) {
2345                 os_memset(empty_dev_type, 0, sizeof(empty_dev_type));
2346                 pri_dev_type = empty_dev_type;
2347         }
2348         os_snprintf(params, sizeof(params), " p2p_dev_addr=" MACSTR
2349                     " pri_dev_type=%s name='%s' config_methods=0x%x "
2350                     "dev_capab=0x%x group_capab=0x%x%s%s",
2351                     MAC2STR(dev_addr),
2352                     wps_dev_type_bin2str(pri_dev_type, devtype,
2353                                          sizeof(devtype)),
2354                     dev_name, supp_config_methods, dev_capab, group_capab,
2355                     group ? " group=" : "",
2356                     group ? group->ifname : "");
2357         params[sizeof(params) - 1] = '\0';
2358
2359         if (config_methods & WPS_CONFIG_DISPLAY) {
2360                 generated_pin = wps_generate_pin();
2361                 wpas_prov_disc_local_display(wpa_s, peer, params,
2362                                              generated_pin);
2363         } else if (config_methods & WPS_CONFIG_KEYPAD)
2364                 wpas_prov_disc_local_keypad(wpa_s, peer, params);
2365         else if (config_methods & WPS_CONFIG_PUSHBUTTON)
2366                 wpa_msg_global(wpa_s, MSG_INFO, P2P_EVENT_PROV_DISC_PBC_REQ
2367                                MACSTR "%s", MAC2STR(peer), params);
2368
2369         wpas_notify_p2p_provision_discovery(wpa_s, peer, 1 /* request */,
2370                                             P2P_PROV_DISC_SUCCESS,
2371                                             config_methods, generated_pin);
2372 }
2373
2374
2375 void wpas_prov_disc_resp(void *ctx, const u8 *peer, u16 config_methods)
2376 {
2377         struct wpa_supplicant *wpa_s = ctx;
2378         unsigned int generated_pin = 0;
2379         char params[20];
2380
2381         if (wpa_s->pending_pd_before_join &&
2382             (os_memcmp(peer, wpa_s->pending_join_dev_addr, ETH_ALEN) == 0 ||
2383              os_memcmp(peer, wpa_s->pending_join_iface_addr, ETH_ALEN) == 0)) {
2384                 wpa_s->pending_pd_before_join = 0;
2385                 wpa_printf(MSG_DEBUG, "P2P: Starting pending "
2386                            "join-existing-group operation");
2387                 wpas_p2p_join_start(wpa_s);
2388                 return;
2389         }
2390
2391         if (wpa_s->pending_pd_use == AUTO_PD_JOIN ||
2392             wpa_s->pending_pd_use == AUTO_PD_GO_NEG)
2393                 os_snprintf(params, sizeof(params), " peer_go=%d",
2394                             wpa_s->pending_pd_use == AUTO_PD_JOIN);
2395         else
2396                 params[0] = '\0';
2397
2398         if (config_methods & WPS_CONFIG_DISPLAY)
2399                 wpas_prov_disc_local_keypad(wpa_s, peer, params);
2400         else if (config_methods & WPS_CONFIG_KEYPAD) {
2401                 generated_pin = wps_generate_pin();
2402                 wpas_prov_disc_local_display(wpa_s, peer, params,
2403                                              generated_pin);
2404         } else if (config_methods & WPS_CONFIG_PUSHBUTTON)
2405                 wpa_msg_global(wpa_s, MSG_INFO, P2P_EVENT_PROV_DISC_PBC_RESP
2406                                MACSTR "%s", MAC2STR(peer), params);
2407
2408         wpas_notify_p2p_provision_discovery(wpa_s, peer, 0 /* response */,
2409                                             P2P_PROV_DISC_SUCCESS,
2410                                             config_methods, generated_pin);
2411 }
2412
2413
2414 static void wpas_prov_disc_fail(void *ctx, const u8 *peer,
2415                                 enum p2p_prov_disc_status status)
2416 {
2417         struct wpa_supplicant *wpa_s = ctx;
2418
2419         if (wpa_s->p2p_fallback_to_go_neg) {
2420                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: PD for p2p_connect-auto "
2421                         "failed - fall back to GO Negotiation");
2422                 wpas_p2p_fallback_to_go_neg(wpa_s, 0);
2423                 return;
2424         }
2425
2426         if (status == P2P_PROV_DISC_TIMEOUT_JOIN) {
2427                 wpa_s->pending_pd_before_join = 0;
2428                 wpa_printf(MSG_DEBUG, "P2P: Starting pending "
2429                            "join-existing-group operation (no ACK for PD "
2430                            "Req attempts)");
2431                 wpas_p2p_join_start(wpa_s);
2432                 return;
2433         }
2434
2435         wpa_msg_global(wpa_s, MSG_INFO, P2P_EVENT_PROV_DISC_FAILURE
2436                        " p2p_dev_addr=" MACSTR " status=%d",
2437                        MAC2STR(peer), status);
2438
2439         wpas_notify_p2p_provision_discovery(wpa_s, peer, 0 /* response */,
2440                                             status, 0, 0);
2441 }
2442
2443
2444 static int freq_included(const struct p2p_channels *channels, unsigned int freq)
2445 {
2446         if (channels == NULL)
2447                 return 1; /* Assume no restrictions */
2448         return p2p_channels_includes_freq(channels, freq);
2449
2450 }
2451
2452
2453 static u8 wpas_invitation_process(void *ctx, const u8 *sa, const u8 *bssid,
2454                                   const u8 *go_dev_addr, const u8 *ssid,
2455                                   size_t ssid_len, int *go, u8 *group_bssid,
2456                                   int *force_freq, int persistent_group,
2457                                   const struct p2p_channels *channels)
2458 {
2459         struct wpa_supplicant *wpa_s = ctx;
2460         struct wpa_ssid *s;
2461         int res;
2462         struct wpa_supplicant *grp;
2463
2464         if (!persistent_group) {
2465                 wpa_printf(MSG_DEBUG, "P2P: Invitation from " MACSTR
2466                            " to join an active group", MAC2STR(sa));
2467                 if (!is_zero_ether_addr(wpa_s->p2p_auth_invite) &&
2468                     (os_memcmp(go_dev_addr, wpa_s->p2p_auth_invite, ETH_ALEN)
2469                      == 0 ||
2470                      os_memcmp(sa, wpa_s->p2p_auth_invite, ETH_ALEN) == 0)) {
2471                         wpa_printf(MSG_DEBUG, "P2P: Accept previously "
2472                                    "authorized invitation");
2473                         goto accept_inv;
2474                 }
2475                 /*
2476                  * Do not accept the invitation automatically; notify user and
2477                  * request approval.
2478                  */
2479                 return P2P_SC_FAIL_INFO_CURRENTLY_UNAVAILABLE;
2480         }
2481
2482         grp = wpas_get_p2p_group(wpa_s, ssid, ssid_len, go);
2483         if (grp) {
2484                 wpa_printf(MSG_DEBUG, "P2P: Accept invitation to already "
2485                            "running persistent group");
2486                 if (*go)
2487                         os_memcpy(group_bssid, grp->own_addr, ETH_ALEN);
2488                 goto accept_inv;
2489         }
2490
2491         if (!is_zero_ether_addr(wpa_s->p2p_auth_invite) &&
2492             os_memcmp(sa, wpa_s->p2p_auth_invite, ETH_ALEN) == 0) {
2493                 wpa_printf(MSG_DEBUG, "P2P: Accept previously initiated "
2494                            "invitation to re-invoke a persistent group");
2495         } else if (!wpa_s->conf->persistent_reconnect)
2496                 return P2P_SC_FAIL_INFO_CURRENTLY_UNAVAILABLE;
2497
2498         for (s = wpa_s->conf->ssid; s; s = s->next) {
2499                 if (s->disabled == 2 &&
2500                     os_memcmp(s->bssid, go_dev_addr, ETH_ALEN) == 0 &&
2501                     s->ssid_len == ssid_len &&
2502                     os_memcmp(ssid, s->ssid, ssid_len) == 0)
2503                         break;
2504         }
2505
2506         if (!s) {
2507                 wpa_printf(MSG_DEBUG, "P2P: Invitation from " MACSTR
2508                            " requested reinvocation of an unknown group",
2509                            MAC2STR(sa));
2510                 return P2P_SC_FAIL_UNKNOWN_GROUP;
2511         }
2512
2513         if (s->mode == WPAS_MODE_P2P_GO && !wpas_p2p_create_iface(wpa_s)) {
2514                 *go = 1;
2515                 if (wpa_s->wpa_state >= WPA_AUTHENTICATING) {
2516                         wpa_printf(MSG_DEBUG, "P2P: The only available "
2517                                    "interface is already in use - reject "
2518                                    "invitation");
2519                         return P2P_SC_FAIL_UNABLE_TO_ACCOMMODATE;
2520                 }
2521                 os_memcpy(group_bssid, wpa_s->own_addr, ETH_ALEN);
2522         } else if (s->mode == WPAS_MODE_P2P_GO) {
2523                 *go = 1;
2524                 if (wpas_p2p_add_group_interface(wpa_s, WPA_IF_P2P_GO) < 0)
2525                 {
2526                         wpa_printf(MSG_ERROR, "P2P: Failed to allocate a new "
2527                                    "interface address for the group");
2528                         return P2P_SC_FAIL_UNABLE_TO_ACCOMMODATE;
2529                 }
2530                 os_memcpy(group_bssid, wpa_s->pending_interface_addr,
2531                           ETH_ALEN);
2532         }
2533
2534 accept_inv:
2535         wpas_p2p_set_own_freq_preference(wpa_s, 0);
2536
2537         /* Get one of the frequencies currently in use */
2538         if (wpas_p2p_valid_oper_freqs(wpa_s, &res, 1) > 0) {
2539                 wpa_printf(MSG_DEBUG, "P2P: Trying to force channel to match a channel already used by one of the interfaces");
2540                 *force_freq = res;
2541                 wpas_p2p_set_own_freq_preference(wpa_s, res);
2542         }
2543
2544         if (*force_freq > 0 && wpa_s->num_multichan_concurrent > 1 &&
2545             wpas_p2p_num_unused_channels(wpa_s) > 0) {
2546                 if (*go == 0) {
2547                         /* We are the client */
2548                         wpa_printf(MSG_DEBUG, "P2P: Peer was found to be "
2549                                    "running a GO but we are capable of MCC, "
2550                                    "figure out the best channel to use");
2551                         *force_freq = 0;
2552                 } else if (!freq_included(channels, *force_freq)) {
2553                         /* We are the GO, and *force_freq is not in the
2554                          * intersection */
2555                         wpa_printf(MSG_DEBUG, "P2P: Forced GO freq %d MHz not "
2556                                    "in intersection but we are capable of MCC, "
2557                                    "figure out the best channel to use",
2558                                    *force_freq);
2559                         *force_freq = 0;
2560                 }
2561         }
2562
2563         return P2P_SC_SUCCESS;
2564 }
2565
2566
2567 static void wpas_invitation_received(void *ctx, const u8 *sa, const u8 *bssid,
2568                                      const u8 *ssid, size_t ssid_len,
2569                                      const u8 *go_dev_addr, u8 status,
2570                                      int op_freq)
2571 {
2572         struct wpa_supplicant *wpa_s = ctx;
2573         struct wpa_ssid *s;
2574
2575         for (s = wpa_s->conf->ssid; s; s = s->next) {
2576                 if (s->disabled == 2 &&
2577                     s->ssid_len == ssid_len &&
2578                     os_memcmp(ssid, s->ssid, ssid_len) == 0)
2579                         break;
2580         }
2581
2582         if (status == P2P_SC_SUCCESS) {
2583                 wpa_printf(MSG_DEBUG, "P2P: Invitation from peer " MACSTR
2584                            " was accepted; op_freq=%d MHz",
2585                            MAC2STR(sa), op_freq);
2586                 if (s) {
2587                         int go = s->mode == WPAS_MODE_P2P_GO;
2588                         wpas_p2p_group_add_persistent(
2589                                 wpa_s, s, go, go ? op_freq : 0, 0, NULL);
2590                 } else if (bssid) {
2591                         wpa_s->user_initiated_pd = 0;
2592                         wpas_p2p_join(wpa_s, bssid, go_dev_addr,
2593                                       wpa_s->p2p_wps_method, 0);
2594                 }
2595                 return;
2596         }
2597
2598         if (status != P2P_SC_FAIL_INFO_CURRENTLY_UNAVAILABLE) {
2599                 wpa_printf(MSG_DEBUG, "P2P: Invitation from peer " MACSTR
2600                            " was rejected (status %u)", MAC2STR(sa), status);
2601                 return;
2602         }
2603
2604         if (!s) {
2605                 if (bssid) {
2606                         wpa_msg_global(wpa_s, MSG_INFO,
2607                                        P2P_EVENT_INVITATION_RECEIVED
2608                                        "sa=" MACSTR " go_dev_addr=" MACSTR
2609                                        " bssid=" MACSTR " unknown-network",
2610                                        MAC2STR(sa), MAC2STR(go_dev_addr),
2611                                        MAC2STR(bssid));
2612                 } else {
2613                         wpa_msg_global(wpa_s, MSG_INFO,
2614                                        P2P_EVENT_INVITATION_RECEIVED
2615                                        "sa=" MACSTR " go_dev_addr=" MACSTR
2616                                        " unknown-network",
2617                                        MAC2STR(sa), MAC2STR(go_dev_addr));
2618                 }
2619                 return;
2620         }
2621
2622         if (s->mode == WPAS_MODE_P2P_GO && op_freq) {
2623                 wpa_msg_global(wpa_s, MSG_INFO, P2P_EVENT_INVITATION_RECEIVED
2624                                "sa=" MACSTR " persistent=%d freq=%d",
2625                                MAC2STR(sa), s->id, op_freq);
2626         } else {
2627                 wpa_msg_global(wpa_s, MSG_INFO, P2P_EVENT_INVITATION_RECEIVED
2628                                "sa=" MACSTR " persistent=%d",
2629                                MAC2STR(sa), s->id);
2630         }
2631 }
2632
2633
2634 static void wpas_remove_persistent_peer(struct wpa_supplicant *wpa_s,
2635                                         struct wpa_ssid *ssid,
2636                                         const u8 *peer)
2637 {
2638         size_t i;
2639
2640         if (ssid == NULL)
2641                 return;
2642
2643         for (i = 0; ssid->p2p_client_list && i < ssid->num_p2p_clients; i++) {
2644                 if (os_memcmp(ssid->p2p_client_list + i * ETH_ALEN, peer,
2645                               ETH_ALEN) == 0)
2646                         break;
2647         }
2648         if (i >= ssid->num_p2p_clients) {
2649                 if (ssid->mode != WPAS_MODE_P2P_GO &&
2650                     os_memcmp(ssid->bssid, peer, ETH_ALEN) == 0) {
2651                         wpa_printf(MSG_DEBUG, "P2P: Remove persistent group %d "
2652                                    "due to invitation result", ssid->id);
2653                         wpas_notify_network_removed(wpa_s, ssid);
2654                         wpa_config_remove_network(wpa_s->conf, ssid->id);
2655                         return;
2656                 }
2657                 return; /* Peer not found in client list */
2658         }
2659
2660         wpa_printf(MSG_DEBUG, "P2P: Remove peer " MACSTR " from persistent "
2661                    "group %d client list due to invitation result",
2662                    MAC2STR(peer), ssid->id);
2663         os_memmove(ssid->p2p_client_list + i * ETH_ALEN,
2664                    ssid->p2p_client_list + (i + 1) * ETH_ALEN,
2665                    (ssid->num_p2p_clients - i - 1) * ETH_ALEN);
2666         ssid->num_p2p_clients--;
2667 #ifndef CONFIG_NO_CONFIG_WRITE
2668         if (wpa_s->parent->conf->update_config &&
2669             wpa_config_write(wpa_s->parent->confname, wpa_s->parent->conf))
2670                 wpa_printf(MSG_DEBUG, "P2P: Failed to update configuration");
2671 #endif /* CONFIG_NO_CONFIG_WRITE */
2672 }
2673
2674
2675 static void wpas_remove_persistent_client(struct wpa_supplicant *wpa_s,
2676                                           const u8 *peer)
2677 {
2678         struct wpa_ssid *ssid;
2679
2680         wpa_s = wpa_s->global->p2p_invite_group;
2681         if (wpa_s == NULL)
2682                 return; /* No known invitation group */
2683         ssid = wpa_s->current_ssid;
2684         if (ssid == NULL || ssid->mode != WPAS_MODE_P2P_GO ||
2685             !ssid->p2p_persistent_group)
2686                 return; /* Not operating as a GO in persistent group */
2687         ssid = wpas_p2p_get_persistent(wpa_s->parent, peer,
2688                                        ssid->ssid, ssid->ssid_len);
2689         wpas_remove_persistent_peer(wpa_s, ssid, peer);
2690 }
2691
2692
2693 static void wpas_invitation_result(void *ctx, int status, const u8 *bssid,
2694                                    const struct p2p_channels *channels,
2695                                    const u8 *peer)
2696 {
2697         struct wpa_supplicant *wpa_s = ctx;
2698         struct wpa_ssid *ssid;
2699
2700         if (bssid) {
2701                 wpa_msg_global(wpa_s, MSG_INFO, P2P_EVENT_INVITATION_RESULT
2702                                "status=%d " MACSTR,
2703                                status, MAC2STR(bssid));
2704         } else {
2705                 wpa_msg_global(wpa_s, MSG_INFO, P2P_EVENT_INVITATION_RESULT
2706                                "status=%d ", status);
2707         }
2708         wpas_notify_p2p_invitation_result(wpa_s, status, bssid);
2709
2710         wpa_printf(MSG_DEBUG, "P2P: Invitation result - status=%d peer=" MACSTR,
2711                    status, MAC2STR(peer));
2712         if (wpa_s->pending_invite_ssid_id == -1) {
2713                 if (status == P2P_SC_FAIL_UNKNOWN_GROUP)
2714                         wpas_remove_persistent_client(wpa_s, peer);
2715                 return; /* Invitation to active group */
2716         }
2717
2718         if (status == P2P_SC_FAIL_INFO_CURRENTLY_UNAVAILABLE) {
2719                 wpa_printf(MSG_DEBUG, "P2P: Waiting for peer to start another "
2720                            "invitation exchange to indicate readiness for "
2721                            "re-invocation");
2722         }
2723
2724         if (status != P2P_SC_SUCCESS) {
2725                 if (status == P2P_SC_FAIL_UNKNOWN_GROUP) {
2726                         ssid = wpa_config_get_network(
2727                                 wpa_s->conf, wpa_s->pending_invite_ssid_id);
2728                         wpas_remove_persistent_peer(wpa_s, ssid, peer);
2729                 }
2730                 wpas_p2p_remove_pending_group_interface(wpa_s);
2731                 return;
2732         }
2733
2734         ssid = wpa_config_get_network(wpa_s->conf,
2735                                       wpa_s->pending_invite_ssid_id);
2736         if (ssid == NULL) {
2737                 wpa_printf(MSG_ERROR, "P2P: Could not find persistent group "
2738                            "data matching with invitation");
2739                 return;
2740         }
2741
2742         /*
2743          * The peer could have missed our ctrl::ack frame for Invitation
2744          * Response and continue retransmitting the frame. To reduce the
2745          * likelihood of the peer not getting successful TX status for the
2746          * Invitation Response frame, wait a short time here before starting
2747          * the persistent group so that we will remain on the current channel to
2748          * acknowledge any possible retransmission from the peer.
2749          */
2750         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: 50 ms wait on current channel before "
2751                 "starting persistent group");
2752         os_sleep(0, 50000);
2753
2754         wpas_p2p_group_add_persistent(wpa_s, ssid,
2755                                       ssid->mode == WPAS_MODE_P2P_GO,
2756                                       wpa_s->p2p_persistent_go_freq,
2757                                       wpa_s->p2p_go_ht40, channels);
2758 }
2759
2760
2761 static int wpas_p2p_disallowed_freq(struct wpa_global *global,
2762                                     unsigned int freq)
2763 {
2764         unsigned int i;
2765
2766         if (global->p2p_disallow_freq == NULL)
2767                 return 0;
2768
2769         for (i = 0; i < global->num_p2p_disallow_freq; i++) {
2770                 if (freq >= global->p2p_disallow_freq[i].min &&
2771                     freq <= global->p2p_disallow_freq[i].max)
2772                         return 1;
2773         }
2774
2775         return 0;
2776 }
2777
2778
2779 static void wpas_p2p_add_chan(struct p2p_reg_class *reg, u8 chan)
2780 {
2781         reg->channel[reg->channels] = chan;
2782         reg->channels++;
2783 }
2784
2785
2786 static int wpas_p2p_default_channels(struct wpa_supplicant *wpa_s,
2787                                      struct p2p_channels *chan)
2788 {
2789         int i, cla = 0;
2790
2791         wpa_printf(MSG_DEBUG, "P2P: Enable operating classes for 2.4 GHz "
2792                    "band");
2793
2794         /* Operating class 81 - 2.4 GHz band channels 1..13 */
2795         chan->reg_class[cla].reg_class = 81;
2796         chan->reg_class[cla].channels = 0;
2797         for (i = 0; i < 11; i++) {
2798                 if (!wpas_p2p_disallowed_freq(wpa_s->global, 2412 + i * 5))
2799                         wpas_p2p_add_chan(&chan->reg_class[cla], i + 1);
2800         }
2801         if (chan->reg_class[cla].channels)
2802                 cla++;
2803
2804         wpa_printf(MSG_DEBUG, "P2P: Enable operating classes for lower 5 GHz "
2805                    "band");
2806
2807         /* Operating class 115 - 5 GHz, channels 36-48 */
2808         chan->reg_class[cla].reg_class = 115;
2809         chan->reg_class[cla].channels = 0;
2810         if (!wpas_p2p_disallowed_freq(wpa_s->global, 5000 + 36 * 5))
2811                 wpas_p2p_add_chan(&chan->reg_class[cla], 36);
2812         if (!wpas_p2p_disallowed_freq(wpa_s->global, 5000 + 40 * 5))
2813                 wpas_p2p_add_chan(&chan->reg_class[cla], 40);
2814         if (!wpas_p2p_disallowed_freq(wpa_s->global, 5000 + 44 * 5))
2815                 wpas_p2p_add_chan(&chan->reg_class[cla], 44);
2816         if (!wpas_p2p_disallowed_freq(wpa_s->global, 5000 + 48 * 5))
2817                 wpas_p2p_add_chan(&chan->reg_class[cla], 48);
2818         if (chan->reg_class[cla].channels)
2819                 cla++;
2820
2821         wpa_printf(MSG_DEBUG, "P2P: Enable operating classes for higher 5 GHz "
2822                    "band");
2823
2824         /* Operating class 124 - 5 GHz, channels 149,153,157,161 */
2825         chan->reg_class[cla].reg_class = 124;
2826         chan->reg_class[cla].channels = 0;
2827         if (!wpas_p2p_disallowed_freq(wpa_s->global, 5000 + 149 * 5))
2828                 wpas_p2p_add_chan(&chan->reg_class[cla], 149);
2829         if (!wpas_p2p_disallowed_freq(wpa_s->global, 5000 + 153 * 5))
2830                 wpas_p2p_add_chan(&chan->reg_class[cla], 153);
2831         if (!wpas_p2p_disallowed_freq(wpa_s->global, 5000 + 156 * 5))
2832                 wpas_p2p_add_chan(&chan->reg_class[cla], 157);
2833         if (!wpas_p2p_disallowed_freq(wpa_s->global, 5000 + 161 * 5))
2834                 wpas_p2p_add_chan(&chan->reg_class[cla], 161);
2835         if (chan->reg_class[cla].channels)
2836                 cla++;
2837
2838         chan->reg_classes = cla;
2839         return 0;
2840 }
2841
2842
2843 static struct hostapd_hw_modes * get_mode(struct hostapd_hw_modes *modes,
2844                                           u16 num_modes,
2845                                           enum hostapd_hw_mode mode)
2846 {
2847         u16 i;
2848
2849         for (i = 0; i < num_modes; i++) {
2850                 if (modes[i].mode == mode)
2851                         return &modes[i];
2852         }
2853
2854         return NULL;
2855 }
2856
2857
2858 static int has_channel(struct wpa_global *global,
2859                        struct hostapd_hw_modes *mode, u8 chan, int *flags)
2860 {
2861         int i;
2862         unsigned int freq;
2863
2864         freq = (mode->mode == HOSTAPD_MODE_IEEE80211A ? 5000 : 2407) +
2865                 chan * 5;
2866         if (wpas_p2p_disallowed_freq(global, freq))
2867                 return 0;
2868
2869         for (i = 0; i < mode->num_channels; i++) {
2870                 if (mode->channels[i].chan == chan) {
2871                         if (flags)
2872                                 *flags = mode->channels[i].flag;
2873                         return !(mode->channels[i].flag &
2874                                  (HOSTAPD_CHAN_DISABLED |
2875                                   HOSTAPD_CHAN_PASSIVE_SCAN |
2876                                   HOSTAPD_CHAN_NO_IBSS |
2877                                   HOSTAPD_CHAN_RADAR));
2878                 }
2879         }
2880
2881         return 0;
2882 }
2883
2884
2885 struct p2p_oper_class_map {
2886         enum hostapd_hw_mode mode;
2887         u8 op_class;
2888         u8 min_chan;
2889         u8 max_chan;
2890         u8 inc;
2891         enum { BW20, BW40PLUS, BW40MINUS } bw;
2892 };
2893
2894 static struct p2p_oper_class_map op_class[] = {
2895         { HOSTAPD_MODE_IEEE80211G, 81, 1, 13, 1, BW20 },
2896 #if 0 /* Do not enable HT40 on 2 GHz for now */
2897         { HOSTAPD_MODE_IEEE80211G, 83, 1, 9, 1, BW40PLUS },
2898         { HOSTAPD_MODE_IEEE80211G, 84, 5, 13, 1, BW40MINUS },
2899 #endif
2900         { HOSTAPD_MODE_IEEE80211A, 115, 36, 48, 4, BW20 },
2901         { HOSTAPD_MODE_IEEE80211A, 124, 149, 161, 4, BW20 },
2902         { HOSTAPD_MODE_IEEE80211A, 116, 36, 44, 8, BW40PLUS },
2903         { HOSTAPD_MODE_IEEE80211A, 117, 40, 48, 8, BW40MINUS },
2904         { HOSTAPD_MODE_IEEE80211A, 126, 149, 157, 8, BW40PLUS },
2905         { HOSTAPD_MODE_IEEE80211A, 127, 153, 161, 8, BW40MINUS },
2906         { -1, 0, 0, 0, 0, BW20 }
2907 };
2908
2909
2910 static int wpas_p2p_verify_channel(struct wpa_supplicant *wpa_s,
2911                                    struct hostapd_hw_modes *mode,
2912                                    u8 channel, u8 bw)
2913 {
2914         int flag;
2915
2916         if (!has_channel(wpa_s->global, mode, channel, &flag))
2917                 return -1;
2918         if (bw == BW40MINUS &&
2919             (!(flag & HOSTAPD_CHAN_HT40MINUS) ||
2920              !has_channel(wpa_s->global, mode, channel - 4, NULL)))
2921                 return 0;
2922         if (bw == BW40PLUS &&
2923             (!(flag & HOSTAPD_CHAN_HT40PLUS) ||
2924              !has_channel(wpa_s->global, mode, channel + 4, NULL)))
2925                 return 0;
2926         return 1;
2927 }
2928
2929
2930 static int wpas_p2p_setup_channels(struct wpa_supplicant *wpa_s,
2931                                    struct p2p_channels *chan)
2932 {
2933         struct hostapd_hw_modes *mode;
2934         int cla, op;
2935
2936         if (wpa_s->hw.modes == NULL) {
2937                 wpa_printf(MSG_DEBUG, "P2P: Driver did not support fetching "
2938                            "of all supported channels; assume dualband "
2939                            "support");
2940                 return wpas_p2p_default_channels(wpa_s, chan);
2941         }
2942
2943         cla = 0;
2944
2945         for (op = 0; op_class[op].op_class; op++) {
2946                 struct p2p_oper_class_map *o = &op_class[op];
2947                 u8 ch;
2948                 struct p2p_reg_class *reg = NULL;
2949
2950                 mode = get_mode(wpa_s->hw.modes, wpa_s->hw.num_modes, o->mode);
2951                 if (mode == NULL)
2952                         continue;
2953                 for (ch = o->min_chan; ch <= o->max_chan; ch += o->inc) {
2954                         if (wpas_p2p_verify_channel(wpa_s, mode, ch, o->bw) < 1)
2955                                 continue;
2956                         if (reg == NULL) {
2957                                 wpa_printf(MSG_DEBUG, "P2P: Add operating "
2958                                            "class %u", o->op_class);
2959                                 reg = &chan->reg_class[cla];
2960                                 cla++;
2961                                 reg->reg_class = o->op_class;
2962                         }
2963                         reg->channel[reg->channels] = ch;
2964                         reg->channels++;
2965                 }
2966                 if (reg) {
2967                         wpa_hexdump(MSG_DEBUG, "P2P: Channels",
2968                                     reg->channel, reg->channels);
2969                 }
2970         }
2971
2972         chan->reg_classes = cla;
2973
2974         return 0;
2975 }
2976
2977
2978 int wpas_p2p_get_ht40_mode(struct wpa_supplicant *wpa_s,
2979                            struct hostapd_hw_modes *mode, u8 channel)
2980 {
2981         int op, ret;
2982
2983         for (op = 0; op_class[op].op_class; op++) {
2984                 struct p2p_oper_class_map *o = &op_class[op];
2985                 u8 ch;
2986
2987                 for (ch = o->min_chan; ch <= o->max_chan; ch += o->inc) {
2988                         if (o->mode != HOSTAPD_MODE_IEEE80211A ||
2989                             o->bw == BW20 || ch != channel)
2990                                 continue;
2991                         ret = wpas_p2p_verify_channel(wpa_s, mode, ch, o->bw);
2992                         if (ret < 0)
2993                                 continue;
2994                         else if (ret > 0)
2995                                 return (o->bw == BW40MINUS) ? -1 : 1;
2996                         else
2997                                 return 0;
2998                 }
2999         }
3000         return 0;
3001 }
3002
3003
3004 static int wpas_get_noa(void *ctx, const u8 *interface_addr, u8 *buf,
3005                         size_t buf_len)
3006 {
3007         struct wpa_supplicant *wpa_s = ctx;
3008
3009         for (wpa_s = wpa_s->global->ifaces; wpa_s; wpa_s = wpa_s->next) {
3010                 if (os_memcmp(wpa_s->own_addr, interface_addr, ETH_ALEN) == 0)
3011                         break;
3012         }
3013         if (wpa_s == NULL)
3014                 return -1;
3015
3016         return wpa_drv_get_noa(wpa_s, buf, buf_len);
3017 }
3018
3019
3020 static int wpas_go_connected(void *ctx, const u8 *dev_addr)
3021 {
3022         struct wpa_supplicant *wpa_s = ctx;
3023
3024         for (wpa_s = wpa_s->global->ifaces; wpa_s; wpa_s = wpa_s->next) {
3025                 struct wpa_ssid *ssid = wpa_s->current_ssid;
3026                 if (ssid == NULL)
3027                         continue;
3028                 if (ssid->mode != WPAS_MODE_INFRA)
3029                         continue;
3030                 if (wpa_s->wpa_state != WPA_COMPLETED &&
3031                     wpa_s->wpa_state != WPA_GROUP_HANDSHAKE)
3032                         continue;
3033                 if (os_memcmp(wpa_s->go_dev_addr, dev_addr, ETH_ALEN) == 0)
3034                         return 1;
3035         }
3036
3037         return 0;
3038 }
3039
3040
3041 static void wpas_p2p_debug_print(void *ctx, int level, const char *msg)
3042 {
3043         struct wpa_supplicant *wpa_s = ctx;
3044         wpa_msg_global(wpa_s, level, "P2P: %s", msg);
3045 }
3046
3047
3048 int wpas_p2p_add_p2pdev_interface(struct wpa_supplicant *wpa_s)
3049 {
3050         struct wpa_interface iface;
3051         struct wpa_supplicant *p2pdev_wpa_s;
3052         char ifname[100];
3053         char force_name[100];
3054         int ret;
3055
3056         os_snprintf(ifname, sizeof(ifname), P2P_MGMT_DEVICE_PREFIX "%s",
3057                     wpa_s->ifname);
3058         force_name[0] = '\0';
3059         wpa_s->pending_interface_type = WPA_IF_P2P_DEVICE;
3060         ret = wpa_drv_if_add(wpa_s, WPA_IF_P2P_DEVICE, ifname, NULL, NULL,
3061                              force_name, wpa_s->pending_interface_addr, NULL);
3062         if (ret < 0) {
3063                 wpa_printf(MSG_DEBUG, "P2P: Failed to create P2P Device interface");
3064                 return ret;
3065         }
3066         os_strlcpy(wpa_s->pending_interface_name, ifname,
3067                    sizeof(wpa_s->pending_interface_name));
3068
3069         os_memset(&iface, 0, sizeof(iface));
3070         iface.p2p_mgmt = 1;
3071         iface.ifname = wpa_s->pending_interface_name;
3072         iface.driver = wpa_s->driver->name;
3073         iface.driver_param = wpa_s->conf->driver_param;
3074         iface.confname = wpa_s->confname;
3075         p2pdev_wpa_s = wpa_supplicant_add_iface(wpa_s->global, &iface);
3076         if (!p2pdev_wpa_s) {
3077                 wpa_printf(MSG_DEBUG, "P2P: Failed to add P2P Device interface");
3078                 return -1;
3079         }
3080         p2pdev_wpa_s->parent = wpa_s;
3081
3082         wpa_s->pending_interface_name[0] = '\0';
3083         return 0;
3084 }
3085
3086
3087 /**
3088  * wpas_p2p_init - Initialize P2P module for %wpa_supplicant
3089  * @global: Pointer to global data from wpa_supplicant_init()
3090  * @wpa_s: Pointer to wpa_supplicant data from wpa_supplicant_add_iface()
3091  * Returns: 0 on success, -1 on failure
3092  */
3093 int wpas_p2p_init(struct wpa_global *global, struct wpa_supplicant *wpa_s)
3094 {
3095         struct p2p_config p2p;
3096         unsigned int r;
3097         int i;
3098
3099         if (!(wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_CAPABLE))
3100                 return 0;
3101
3102         if (global->p2p)
3103                 return 0;
3104
3105         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT) {
3106                 struct p2p_params params;
3107
3108                 wpa_printf(MSG_DEBUG, "P2P: Use driver-based P2P management");
3109                 os_memset(&params, 0, sizeof(params));
3110                 params.dev_name = wpa_s->conf->device_name;
3111                 os_memcpy(params.pri_dev_type, wpa_s->conf->device_type,
3112                           WPS_DEV_TYPE_LEN);
3113                 params.num_sec_dev_types = wpa_s->conf->num_sec_device_types;
3114                 os_memcpy(params.sec_dev_type,
3115                           wpa_s->conf->sec_device_type,
3116                           params.num_sec_dev_types * WPS_DEV_TYPE_LEN);
3117
3118                 if (wpa_drv_p2p_set_params(wpa_s, &params) < 0)
3119                         return -1;
3120
3121                 return 0;
3122         }
3123
3124         os_memset(&p2p, 0, sizeof(p2p));
3125         p2p.cb_ctx = wpa_s;
3126         p2p.debug_print = wpas_p2p_debug_print;
3127         p2p.p2p_scan = wpas_p2p_scan;
3128         p2p.send_action = wpas_send_action;
3129         p2p.send_action_done = wpas_send_action_done;
3130         p2p.go_neg_completed = wpas_go_neg_completed;
3131         p2p.go_neg_req_rx = wpas_go_neg_req_rx;
3132         p2p.dev_found = wpas_dev_found;
3133         p2p.dev_lost = wpas_dev_lost;
3134         p2p.find_stopped = wpas_find_stopped;
3135         p2p.start_listen = wpas_start_listen;
3136         p2p.stop_listen = wpas_stop_listen;
3137         p2p.send_probe_resp = wpas_send_probe_resp;
3138         p2p.sd_request = wpas_sd_request;
3139         p2p.sd_response = wpas_sd_response;
3140         p2p.prov_disc_req = wpas_prov_disc_req;
3141         p2p.prov_disc_resp = wpas_prov_disc_resp;
3142         p2p.prov_disc_fail = wpas_prov_disc_fail;
3143         p2p.invitation_process = wpas_invitation_process;
3144         p2p.invitation_received = wpas_invitation_received;
3145         p2p.invitation_result = wpas_invitation_result;
3146         p2p.get_noa = wpas_get_noa;
3147         p2p.go_connected = wpas_go_connected;
3148
3149         os_memcpy(wpa_s->global->p2p_dev_addr, wpa_s->own_addr, ETH_ALEN);
3150         os_memcpy(p2p.dev_addr, wpa_s->global->p2p_dev_addr, ETH_ALEN);
3151         p2p.dev_name = wpa_s->conf->device_name;
3152         p2p.manufacturer = wpa_s->conf->manufacturer;
3153         p2p.model_name = wpa_s->conf->model_name;
3154         p2p.model_number = wpa_s->conf->model_number;
3155         p2p.serial_number = wpa_s->conf->serial_number;
3156         if (wpa_s->wps) {
3157                 os_memcpy(p2p.uuid, wpa_s->wps->uuid, 16);
3158                 p2p.config_methods = wpa_s->wps->config_methods;
3159         }
3160
3161         if (wpa_s->conf->p2p_listen_reg_class &&
3162             wpa_s->conf->p2p_listen_channel) {
3163                 p2p.reg_class = wpa_s->conf->p2p_listen_reg_class;
3164                 p2p.channel = wpa_s->conf->p2p_listen_channel;
3165         } else {
3166                 p2p.reg_class = 81;
3167                 /*
3168                  * Pick one of the social channels randomly as the listen
3169                  * channel.
3170                  */
3171                 os_get_random((u8 *) &r, sizeof(r));
3172                 p2p.channel = 1 + (r % 3) * 5;
3173         }
3174         wpa_printf(MSG_DEBUG, "P2P: Own listen channel: %d", p2p.channel);
3175
3176         if (wpa_s->conf->p2p_oper_reg_class &&
3177             wpa_s->conf->p2p_oper_channel) {
3178                 p2p.op_reg_class = wpa_s->conf->p2p_oper_reg_class;
3179                 p2p.op_channel = wpa_s->conf->p2p_oper_channel;
3180                 p2p.cfg_op_channel = 1;
3181                 wpa_printf(MSG_DEBUG, "P2P: Configured operating channel: "
3182                            "%d:%d", p2p.op_reg_class, p2p.op_channel);
3183
3184         } else {
3185                 p2p.op_reg_class = 81;
3186                 /*
3187                  * Use random operation channel from (1, 6, 11) if no other
3188                  * preference is indicated.
3189                  */
3190                 os_get_random((u8 *) &r, sizeof(r));
3191                 p2p.op_channel = 1 + (r % 3) * 5;
3192                 p2p.cfg_op_channel = 0;
3193                 wpa_printf(MSG_DEBUG, "P2P: Random operating channel: "
3194                            "%d:%d", p2p.op_reg_class, p2p.op_channel);
3195         }
3196
3197         if (wpa_s->conf->p2p_pref_chan && wpa_s->conf->num_p2p_pref_chan) {
3198                 p2p.pref_chan = wpa_s->conf->p2p_pref_chan;
3199                 p2p.num_pref_chan = wpa_s->conf->num_p2p_pref_chan;
3200         }
3201
3202         if (wpa_s->conf->country[0] && wpa_s->conf->country[1]) {
3203                 os_memcpy(p2p.country, wpa_s->conf->country, 2);
3204                 p2p.country[2] = 0x04;
3205         } else
3206                 os_memcpy(p2p.country, "XX\x04", 3);
3207
3208         if (wpas_p2p_setup_channels(wpa_s, &p2p.channels)) {
3209                 wpa_printf(MSG_ERROR, "P2P: Failed to configure supported "
3210                            "channel list");
3211                 return -1;
3212         }
3213
3214         os_memcpy(p2p.pri_dev_type, wpa_s->conf->device_type,
3215                   WPS_DEV_TYPE_LEN);
3216
3217         p2p.num_sec_dev_types = wpa_s->conf->num_sec_device_types;
3218         os_memcpy(p2p.sec_dev_type, wpa_s->conf->sec_device_type,
3219                   p2p.num_sec_dev_types * WPS_DEV_TYPE_LEN);
3220
3221         p2p.concurrent_operations = !!(wpa_s->drv_flags &
3222                                        WPA_DRIVER_FLAGS_P2P_CONCURRENT);
3223
3224         p2p.max_peers = 100;
3225
3226         if (wpa_s->conf->p2p_ssid_postfix) {
3227                 p2p.ssid_postfix_len =
3228                         os_strlen(wpa_s->conf->p2p_ssid_postfix);
3229                 if (p2p.ssid_postfix_len > sizeof(p2p.ssid_postfix))
3230                         p2p.ssid_postfix_len = sizeof(p2p.ssid_postfix);
3231                 os_memcpy(p2p.ssid_postfix, wpa_s->conf->p2p_ssid_postfix,
3232                           p2p.ssid_postfix_len);
3233         }
3234
3235         p2p.p2p_intra_bss = wpa_s->conf->p2p_intra_bss;
3236
3237         p2p.max_listen = wpa_s->max_remain_on_chan;
3238
3239         global->p2p = p2p_init(&p2p);
3240         if (global->p2p == NULL)
3241                 return -1;
3242         global->p2p_init_wpa_s = wpa_s;
3243
3244         for (i = 0; i < MAX_WPS_VENDOR_EXT; i++) {
3245                 if (wpa_s->conf->wps_vendor_ext[i] == NULL)
3246                         continue;
3247                 p2p_add_wps_vendor_extension(
3248                         global->p2p, wpa_s->conf->wps_vendor_ext[i]);
3249         }
3250
3251         return 0;
3252 }
3253
3254
3255 /**
3256  * wpas_p2p_deinit - Deinitialize per-interface P2P data
3257  * @wpa_s: Pointer to wpa_supplicant data from wpa_supplicant_add_iface()
3258  *
3259  * This function deinitialize per-interface P2P data.
3260  */
3261 void wpas_p2p_deinit(struct wpa_supplicant *wpa_s)
3262 {
3263         if (wpa_s->driver && wpa_s->drv_priv)
3264                 wpa_drv_probe_req_report(wpa_s, 0);
3265
3266         if (wpa_s->go_params) {
3267                 /* Clear any stored provisioning info */
3268                 p2p_clear_provisioning_info(
3269                         wpa_s->global->p2p,
3270                         wpa_s->go_params->peer_device_addr);
3271         }
3272
3273         os_free(wpa_s->go_params);
3274         wpa_s->go_params = NULL;
3275         eloop_cancel_timeout(wpas_p2p_group_formation_timeout, wpa_s, NULL);
3276         eloop_cancel_timeout(wpas_p2p_join_scan, wpa_s, NULL);
3277         wpa_s->p2p_long_listen = 0;
3278         eloop_cancel_timeout(wpas_p2p_long_listen_timeout, wpa_s, NULL);
3279         eloop_cancel_timeout(wpas_p2p_group_idle_timeout, wpa_s, NULL);
3280         wpas_p2p_remove_pending_group_interface(wpa_s);
3281
3282         /* TODO: remove group interface from the driver if this wpa_s instance
3283          * is on top of a P2P group interface */
3284 }
3285
3286
3287 /**
3288  * wpas_p2p_deinit_global - Deinitialize global P2P module
3289  * @global: Pointer to global data from wpa_supplicant_init()
3290  *
3291  * This function deinitializes the global (per device) P2P module.
3292  */
3293 void wpas_p2p_deinit_global(struct wpa_global *global)
3294 {
3295         struct wpa_supplicant *wpa_s, *tmp;
3296
3297         wpa_s = global->ifaces;
3298         if (wpa_s)
3299                 wpas_p2p_service_flush(wpa_s);
3300
3301         if (global->p2p == NULL)
3302                 return;
3303
3304         /* Remove remaining P2P group interfaces */
3305         while (wpa_s && wpa_s->p2p_group_interface != NOT_P2P_GROUP_INTERFACE)
3306                 wpa_s = wpa_s->next;
3307         while (wpa_s) {
3308                 tmp = global->ifaces;
3309                 while (tmp &&
3310                        (tmp == wpa_s ||
3311                         tmp->p2p_group_interface == NOT_P2P_GROUP_INTERFACE)) {
3312                         tmp = tmp->next;
3313                 }
3314                 if (tmp == NULL)
3315                         break;
3316                 /* Disconnect from the P2P group and deinit the interface */
3317                 wpas_p2p_disconnect(tmp);
3318         }
3319
3320         /*
3321          * Deinit GO data on any possibly remaining interface (if main
3322          * interface is used as GO).
3323          */
3324         for (wpa_s = global->ifaces; wpa_s; wpa_s = wpa_s->next) {
3325                 if (wpa_s->ap_iface)
3326                         wpas_p2p_group_deinit(wpa_s);
3327         }
3328
3329         p2p_deinit(global->p2p);
3330         global->p2p = NULL;
3331         global->p2p_init_wpa_s = NULL;
3332 }
3333
3334
3335 static int wpas_p2p_create_iface(struct wpa_supplicant *wpa_s)
3336 {
3337         if (!(wpa_s->drv_flags & WPA_DRIVER_FLAGS_DEDICATED_P2P_DEVICE) &&
3338             wpa_s->conf->p2p_no_group_iface)
3339                 return 0; /* separate interface disabled per configuration */
3340         if (wpa_s->drv_flags &
3341             (WPA_DRIVER_FLAGS_P2P_DEDICATED_INTERFACE |
3342              WPA_DRIVER_FLAGS_P2P_MGMT_AND_NON_P2P))
3343                 return 1; /* P2P group requires a new interface in every case
3344                            */
3345         if (!(wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_CONCURRENT))
3346                 return 0; /* driver does not support concurrent operations */
3347         if (wpa_s->global->ifaces->next)
3348                 return 1; /* more that one interface already in use */
3349         if (wpa_s->wpa_state >= WPA_AUTHENTICATING)
3350                 return 1; /* this interface is already in use */
3351         return 0;
3352 }
3353
3354
3355 static int wpas_p2p_start_go_neg(struct wpa_supplicant *wpa_s,
3356                                  const u8 *peer_addr,
3357                                  enum p2p_wps_method wps_method,
3358                                  int go_intent, const u8 *own_interface_addr,
3359                                  unsigned int force_freq, int persistent_group,
3360                                  struct wpa_ssid *ssid, unsigned int pref_freq)
3361 {
3362         if (persistent_group && wpa_s->conf->persistent_reconnect)
3363                 persistent_group = 2;
3364
3365         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT) {
3366                 return wpa_drv_p2p_connect(wpa_s, peer_addr, wps_method,
3367                                            go_intent, own_interface_addr,
3368                                            force_freq, persistent_group);
3369         }
3370
3371         /*
3372          * Increase GO config timeout if HT40 is used since it takes some time
3373          * to scan channels for coex purposes before the BSS can be started.
3374          */
3375         p2p_set_config_timeout(wpa_s->global->p2p,
3376                                wpa_s->p2p_go_ht40 ? 255 : 100, 20);
3377
3378         return p2p_connect(wpa_s->global->p2p, peer_addr, wps_method,
3379                            go_intent, own_interface_addr, force_freq,
3380                            persistent_group, ssid ? ssid->ssid : NULL,
3381                            ssid ? ssid->ssid_len : 0,
3382                            wpa_s->p2p_pd_before_go_neg, pref_freq);
3383 }
3384
3385
3386 static int wpas_p2p_auth_go_neg(struct wpa_supplicant *wpa_s,
3387                                 const u8 *peer_addr,
3388                                 enum p2p_wps_method wps_method,
3389                                 int go_intent, const u8 *own_interface_addr,
3390                                 unsigned int force_freq, int persistent_group,
3391                                 struct wpa_ssid *ssid, unsigned int pref_freq)
3392 {
3393         if (persistent_group && wpa_s->conf->persistent_reconnect)
3394                 persistent_group = 2;
3395
3396         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT)
3397                 return -1;
3398
3399         return p2p_authorize(wpa_s->global->p2p, peer_addr, wps_method,
3400                              go_intent, own_interface_addr, force_freq,
3401                              persistent_group, ssid ? ssid->ssid : NULL,
3402                              ssid ? ssid->ssid_len : 0, pref_freq);
3403 }
3404
3405
3406 static void wpas_p2p_check_join_scan_limit(struct wpa_supplicant *wpa_s)
3407 {
3408         wpa_s->p2p_join_scan_count++;
3409         wpa_printf(MSG_DEBUG, "P2P: Join scan attempt %d",
3410                    wpa_s->p2p_join_scan_count);
3411         if (wpa_s->p2p_join_scan_count > P2P_MAX_JOIN_SCAN_ATTEMPTS) {
3412                 wpa_printf(MSG_DEBUG, "P2P: Failed to find GO " MACSTR
3413                            " for join operationg - stop join attempt",
3414                            MAC2STR(wpa_s->pending_join_iface_addr));
3415                 eloop_cancel_timeout(wpas_p2p_join_scan, wpa_s, NULL);
3416                 if (wpa_s->p2p_auto_pd) {
3417                         wpa_s->p2p_auto_pd = 0;
3418                         wpa_msg_global(wpa_s, MSG_INFO,
3419                                        P2P_EVENT_PROV_DISC_FAILURE
3420                                        " p2p_dev_addr=" MACSTR " status=N/A",
3421                                        MAC2STR(wpa_s->pending_join_dev_addr));
3422                         return;
3423                 }
3424                 wpa_msg_global(wpa_s->parent, MSG_INFO,
3425                                P2P_EVENT_GROUP_FORMATION_FAILURE);
3426         }
3427 }
3428
3429
3430 static int wpas_check_freq_conflict(struct wpa_supplicant *wpa_s, int freq)
3431 {
3432         int *freqs, res, num, i;
3433
3434         if (wpas_p2p_num_unused_channels(wpa_s) > 0) {
3435                 /* Multiple channels are supported and not all are in use */
3436                 return 0;
3437         }
3438
3439         freqs = os_calloc(wpa_s->num_multichan_concurrent, sizeof(int));
3440         if (!freqs)
3441                 return 1;
3442
3443         num = wpas_p2p_valid_oper_freqs(wpa_s, freqs,
3444                                         wpa_s->num_multichan_concurrent);
3445         if (num < 0) {
3446                 res = 1;
3447                 goto exit_free;
3448         }
3449
3450         for (i = 0; i < num; i++) {
3451                 if (freqs[i] == freq) {
3452                         wpa_printf(MSG_DEBUG, "P2P: Frequency %d MHz in use by another virtual interface and can be used",
3453                                    freq);
3454                         res = 0;
3455                         goto exit_free;
3456                 }
3457         }
3458
3459         res = 1;
3460
3461 exit_free:
3462         os_free(freqs);
3463         return res;
3464 }
3465
3466
3467 static int wpas_p2p_peer_go(struct wpa_supplicant *wpa_s,
3468                             const u8 *peer_dev_addr)
3469 {
3470         struct wpa_bss *bss;
3471         int updated;
3472
3473         bss = wpa_bss_get_p2p_dev_addr(wpa_s, peer_dev_addr);
3474         if (bss == NULL)
3475                 return -1;
3476         if (bss->last_update_idx < wpa_s->bss_update_idx) {
3477                 wpa_printf(MSG_DEBUG, "P2P: Peer BSS entry not updated in the "
3478                            "last scan");
3479                 return 0;
3480         }
3481
3482         updated = os_time_before(&wpa_s->p2p_auto_started, &bss->last_update);
3483         wpa_printf(MSG_DEBUG, "P2P: Current BSS entry for peer updated at "
3484                    "%ld.%06ld (%supdated in last scan)",
3485                    bss->last_update.sec, bss->last_update.usec,
3486                    updated ? "": "not ");
3487
3488         return updated;
3489 }
3490
3491
3492 static void wpas_p2p_scan_res_join(struct wpa_supplicant *wpa_s,
3493                                    struct wpa_scan_results *scan_res)
3494 {
3495         struct wpa_bss *bss;
3496         int freq;
3497         u8 iface_addr[ETH_ALEN];
3498
3499         eloop_cancel_timeout(wpas_p2p_join_scan, wpa_s, NULL);
3500
3501         if (wpa_s->global->p2p_disabled)
3502                 return;
3503
3504         wpa_printf(MSG_DEBUG, "P2P: Scan results received (%d BSS) for %sjoin",
3505                    scan_res ? (int) scan_res->num : -1,
3506                    wpa_s->p2p_auto_join ? "auto_" : "");
3507
3508         if (scan_res)
3509                 wpas_p2p_scan_res_handler(wpa_s, scan_res);
3510
3511         if (wpa_s->p2p_auto_pd) {
3512                 int join = wpas_p2p_peer_go(wpa_s,
3513                                             wpa_s->pending_join_dev_addr);
3514                 if (join == 0 &&
3515                     wpa_s->auto_pd_scan_retry < P2P_AUTO_PD_SCAN_ATTEMPTS) {
3516                         wpa_s->auto_pd_scan_retry++;
3517                         bss = wpa_bss_get_bssid_latest(
3518                                 wpa_s, wpa_s->pending_join_dev_addr);
3519                         if (bss) {
3520                                 freq = bss->freq;
3521                                 wpa_printf(MSG_DEBUG, "P2P: Scan retry %d for "
3522                                            "the peer " MACSTR " at %d MHz",
3523                                            wpa_s->auto_pd_scan_retry,
3524                                            MAC2STR(wpa_s->
3525                                                    pending_join_dev_addr),
3526                                            freq);
3527                                 wpas_p2p_join_scan_req(wpa_s, freq);
3528                                 return;
3529                         }
3530                 }
3531
3532                 if (join < 0)
3533                         join = 0;
3534
3535                 wpa_s->p2p_auto_pd = 0;
3536                 wpa_s->pending_pd_use = join ? AUTO_PD_JOIN : AUTO_PD_GO_NEG;
3537                 wpa_printf(MSG_DEBUG, "P2P: Auto PD with " MACSTR " join=%d",
3538                            MAC2STR(wpa_s->pending_join_dev_addr), join);
3539                 if (p2p_prov_disc_req(wpa_s->global->p2p,
3540                                       wpa_s->pending_join_dev_addr,
3541                                       wpa_s->pending_pd_config_methods, join,
3542                                       0, wpa_s->user_initiated_pd) < 0) {
3543                         wpa_s->p2p_auto_pd = 0;
3544                         wpa_msg_global(wpa_s, MSG_INFO,
3545                                        P2P_EVENT_PROV_DISC_FAILURE
3546                                        " p2p_dev_addr=" MACSTR " status=N/A",
3547                                        MAC2STR(wpa_s->pending_join_dev_addr));
3548                 }
3549                 return;
3550         }
3551
3552         if (wpa_s->p2p_auto_join) {
3553                 int join = wpas_p2p_peer_go(wpa_s,
3554                                             wpa_s->pending_join_dev_addr);
3555                 if (join < 0) {
3556                         wpa_printf(MSG_DEBUG, "P2P: Peer was not found to be "
3557                                    "running a GO -> use GO Negotiation");
3558                         wpas_p2p_connect(wpa_s, wpa_s->pending_join_dev_addr,
3559                                          wpa_s->p2p_pin, wpa_s->p2p_wps_method,
3560                                          wpa_s->p2p_persistent_group, 0, 0, 0,
3561                                          wpa_s->p2p_go_intent,
3562                                          wpa_s->p2p_connect_freq,
3563                                          wpa_s->p2p_persistent_id,
3564                                          wpa_s->p2p_pd_before_go_neg,
3565                                          wpa_s->p2p_go_ht40);
3566                         return;
3567                 }
3568
3569                 wpa_printf(MSG_DEBUG, "P2P: Peer was found running GO%s -> "
3570                            "try to join the group", join ? "" :
3571                            " in older scan");
3572                 if (!join)
3573                         wpa_s->p2p_fallback_to_go_neg = 1;
3574         }
3575
3576         freq = p2p_get_oper_freq(wpa_s->global->p2p,
3577                                  wpa_s->pending_join_iface_addr);
3578         if (freq < 0 &&
3579             p2p_get_interface_addr(wpa_s->global->p2p,
3580                                    wpa_s->pending_join_dev_addr,
3581                                    iface_addr) == 0 &&
3582             os_memcmp(iface_addr, wpa_s->pending_join_dev_addr, ETH_ALEN) != 0)
3583         {
3584                 wpa_printf(MSG_DEBUG, "P2P: Overwrite pending interface "
3585                            "address for join from " MACSTR " to " MACSTR
3586                            " based on newly discovered P2P peer entry",
3587                            MAC2STR(wpa_s->pending_join_iface_addr),
3588                            MAC2STR(iface_addr));
3589                 os_memcpy(wpa_s->pending_join_iface_addr, iface_addr,
3590                           ETH_ALEN);
3591
3592                 freq = p2p_get_oper_freq(wpa_s->global->p2p,
3593                                          wpa_s->pending_join_iface_addr);
3594         }
3595         if (freq >= 0) {
3596                 wpa_printf(MSG_DEBUG, "P2P: Target GO operating frequency "
3597                            "from P2P peer table: %d MHz", freq);
3598         }
3599         bss = wpa_bss_get_bssid_latest(wpa_s, wpa_s->pending_join_iface_addr);
3600         if (bss) {
3601                 freq = bss->freq;
3602                 wpa_printf(MSG_DEBUG, "P2P: Target GO operating frequency "
3603                            "from BSS table: %d MHz", freq);
3604         }
3605         if (freq > 0) {
3606                 u16 method;
3607
3608                 if (wpas_check_freq_conflict(wpa_s, freq) > 0) {
3609                         wpa_msg_global(wpa_s->parent, MSG_INFO,
3610                                        P2P_EVENT_GROUP_FORMATION_FAILURE
3611                                        "reason=FREQ_CONFLICT");
3612                         return;
3613                 }
3614
3615                 wpa_printf(MSG_DEBUG, "P2P: Send Provision Discovery Request "
3616                            "prior to joining an existing group (GO " MACSTR
3617                            " freq=%u MHz)",
3618                            MAC2STR(wpa_s->pending_join_dev_addr), freq);
3619                 wpa_s->pending_pd_before_join = 1;
3620
3621                 switch (wpa_s->pending_join_wps_method) {
3622                 case WPS_PIN_DISPLAY:
3623                         method = WPS_CONFIG_KEYPAD;
3624                         break;
3625                 case WPS_PIN_KEYPAD:
3626                         method = WPS_CONFIG_DISPLAY;
3627                         break;
3628                 case WPS_PBC:
3629                         method = WPS_CONFIG_PUSHBUTTON;
3630                         break;
3631                 default:
3632                         method = 0;
3633                         break;
3634                 }
3635
3636                 if ((p2p_get_provisioning_info(wpa_s->global->p2p,
3637                                                wpa_s->pending_join_dev_addr) ==
3638                      method)) {
3639                         /*
3640                          * We have already performed provision discovery for
3641                          * joining the group. Proceed directly to join
3642                          * operation without duplicated provision discovery. */
3643                         wpa_printf(MSG_DEBUG, "P2P: Provision discovery "
3644                                    "with " MACSTR " already done - proceed to "
3645                                    "join",
3646                                    MAC2STR(wpa_s->pending_join_dev_addr));
3647                         wpa_s->pending_pd_before_join = 0;
3648                         goto start;
3649                 }
3650
3651                 if (p2p_prov_disc_req(wpa_s->global->p2p,
3652                                       wpa_s->pending_join_dev_addr, method, 1,
3653                                       freq, wpa_s->user_initiated_pd) < 0) {
3654                         wpa_printf(MSG_DEBUG, "P2P: Failed to send Provision "
3655                                    "Discovery Request before joining an "
3656                                    "existing group");
3657                         wpa_s->pending_pd_before_join = 0;
3658                         goto start;
3659                 }
3660                 return;
3661         }
3662
3663         wpa_printf(MSG_DEBUG, "P2P: Failed to find BSS/GO - try again later");
3664         eloop_cancel_timeout(wpas_p2p_join_scan, wpa_s, NULL);
3665         eloop_register_timeout(1, 0, wpas_p2p_join_scan, wpa_s, NULL);
3666         wpas_p2p_check_join_scan_limit(wpa_s);
3667         return;
3668
3669 start:
3670         /* Start join operation immediately */
3671         wpas_p2p_join_start(wpa_s);
3672 }
3673
3674
3675 static void wpas_p2p_join_scan_req(struct wpa_supplicant *wpa_s, int freq)
3676 {
3677         int ret;
3678         struct wpa_driver_scan_params params;
3679         struct wpabuf *wps_ie, *ies;
3680         size_t ielen;
3681         int freqs[2] = { 0, 0 };
3682
3683         os_memset(&params, 0, sizeof(params));
3684
3685         /* P2P Wildcard SSID */
3686         params.num_ssids = 1;
3687         params.ssids[0].ssid = (u8 *) P2P_WILDCARD_SSID;
3688         params.ssids[0].ssid_len = P2P_WILDCARD_SSID_LEN;
3689
3690         wpa_s->wps->dev.p2p = 1;
3691         wps_ie = wps_build_probe_req_ie(DEV_PW_DEFAULT, &wpa_s->wps->dev,
3692                                         wpa_s->wps->uuid, WPS_REQ_ENROLLEE, 0,
3693                                         NULL);
3694         if (wps_ie == NULL) {
3695                 wpas_p2p_scan_res_join(wpa_s, NULL);
3696                 return;
3697         }
3698
3699         ielen = p2p_scan_ie_buf_len(wpa_s->global->p2p);
3700         ies = wpabuf_alloc(wpabuf_len(wps_ie) + ielen);
3701         if (ies == NULL) {
3702                 wpabuf_free(wps_ie);
3703                 wpas_p2p_scan_res_join(wpa_s, NULL);
3704                 return;
3705         }
3706         wpabuf_put_buf(ies, wps_ie);
3707         wpabuf_free(wps_ie);
3708
3709         p2p_scan_ie(wpa_s->global->p2p, ies, NULL);
3710
3711         params.p2p_probe = 1;
3712         params.extra_ies = wpabuf_head(ies);
3713         params.extra_ies_len = wpabuf_len(ies);
3714         if (freq > 0) {
3715                 freqs[0] = freq;
3716                 params.freqs = freqs;
3717         }
3718
3719         /*
3720          * Run a scan to update BSS table and start Provision Discovery once
3721          * the new scan results become available.
3722          */
3723         ret = wpa_drv_scan(wpa_s, &params);
3724         if (!ret) {
3725                 os_get_time(&wpa_s->scan_trigger_time);
3726                 wpa_s->scan_res_handler = wpas_p2p_scan_res_join;
3727         }
3728
3729         wpabuf_free(ies);
3730
3731         if (ret) {
3732                 wpa_printf(MSG_DEBUG, "P2P: Failed to start scan for join - "
3733                            "try again later");
3734                 eloop_cancel_timeout(wpas_p2p_join_scan, wpa_s, NULL);
3735                 eloop_register_timeout(1, 0, wpas_p2p_join_scan, wpa_s, NULL);
3736                 wpas_p2p_check_join_scan_limit(wpa_s);
3737         }
3738 }
3739
3740
3741 static void wpas_p2p_join_scan(void *eloop_ctx, void *timeout_ctx)
3742 {
3743         struct wpa_supplicant *wpa_s = eloop_ctx;
3744         wpas_p2p_join_scan_req(wpa_s, 0);
3745 }
3746
3747
3748 static int wpas_p2p_join(struct wpa_supplicant *wpa_s, const u8 *iface_addr,
3749                          const u8 *dev_addr, enum p2p_wps_method wps_method,
3750                          int auto_join)
3751 {
3752         wpa_printf(MSG_DEBUG, "P2P: Request to join existing group (iface "
3753                    MACSTR " dev " MACSTR ")%s",
3754                    MAC2STR(iface_addr), MAC2STR(dev_addr),
3755                    auto_join ? " (auto_join)" : "");
3756
3757         wpa_s->p2p_auto_pd = 0;
3758         wpa_s->p2p_auto_join = !!auto_join;
3759         os_memcpy(wpa_s->pending_join_iface_addr, iface_addr, ETH_ALEN);
3760         os_memcpy(wpa_s->pending_join_dev_addr, dev_addr, ETH_ALEN);
3761         wpa_s->pending_join_wps_method = wps_method;
3762
3763         /* Make sure we are not running find during connection establishment */
3764         wpas_p2p_stop_find(wpa_s);
3765
3766         wpa_s->p2p_join_scan_count = 0;
3767         wpas_p2p_join_scan(wpa_s, NULL);
3768         return 0;
3769 }
3770
3771
3772 static int wpas_p2p_join_start(struct wpa_supplicant *wpa_s)
3773 {
3774         struct wpa_supplicant *group;
3775         struct p2p_go_neg_results res;
3776         struct wpa_bss *bss;
3777
3778         group = wpas_p2p_get_group_iface(wpa_s, 0, 0);
3779         if (group == NULL)
3780                 return -1;
3781         if (group != wpa_s) {
3782                 os_memcpy(group->p2p_pin, wpa_s->p2p_pin,
3783                           sizeof(group->p2p_pin));
3784                 group->p2p_wps_method = wpa_s->p2p_wps_method;
3785         } else {
3786                 /*
3787                  * Need to mark the current interface for p2p_group_formation
3788                  * when a separate group interface is not used. This is needed
3789                  * to allow p2p_cancel stop a pending p2p_connect-join.
3790                  * wpas_p2p_init_group_interface() addresses this for the case
3791                  * where a separate group interface is used.
3792                  */
3793                 wpa_s->global->p2p_group_formation = wpa_s;
3794         }
3795
3796         group->p2p_in_provisioning = 1;
3797         group->p2p_fallback_to_go_neg = wpa_s->p2p_fallback_to_go_neg;
3798
3799         os_memset(&res, 0, sizeof(res));
3800         os_memcpy(res.peer_interface_addr, wpa_s->pending_join_iface_addr,
3801                   ETH_ALEN);
3802         res.wps_method = wpa_s->pending_join_wps_method;
3803         bss = wpa_bss_get_bssid_latest(wpa_s, wpa_s->pending_join_iface_addr);
3804         if (bss) {
3805                 res.freq = bss->freq;
3806                 res.ssid_len = bss->ssid_len;
3807                 os_memcpy(res.ssid, bss->ssid, bss->ssid_len);
3808         }
3809
3810         if (wpa_s->off_channel_freq || wpa_s->roc_waiting_drv_freq) {
3811                 wpa_printf(MSG_DEBUG, "P2P: Cancel remain-on-channel prior to "
3812                            "starting client");
3813                 wpa_drv_cancel_remain_on_channel(wpa_s);
3814                 wpa_s->off_channel_freq = 0;
3815                 wpa_s->roc_waiting_drv_freq = 0;
3816         }
3817         wpas_start_wps_enrollee(group, &res);
3818
3819         /*
3820          * Allow a longer timeout for join-a-running-group than normal 15
3821          * second group formation timeout since the GO may not have authorized
3822          * our connection yet.
3823          */
3824         eloop_cancel_timeout(wpas_p2p_group_formation_timeout, wpa_s, NULL);
3825         eloop_register_timeout(60, 0, wpas_p2p_group_formation_timeout,
3826                                wpa_s, NULL);
3827
3828         return 0;
3829 }
3830
3831
3832 static int wpas_p2p_setup_freqs(struct wpa_supplicant *wpa_s, int freq,
3833                                 int *force_freq, int *pref_freq)
3834 {
3835         int *freqs, res;
3836         unsigned int freq_in_use = 0, num, i;
3837
3838         freqs = os_calloc(wpa_s->num_multichan_concurrent, sizeof(int));
3839         if (!freqs)
3840                 return -1;
3841
3842         num = get_shared_radio_freqs(wpa_s, freqs,
3843                                      wpa_s->num_multichan_concurrent);
3844
3845         if (freq > 0) {
3846                 if (!p2p_supported_freq(wpa_s->global->p2p, freq)) {
3847                         wpa_printf(MSG_DEBUG, "P2P: The forced channel "
3848                                    "(%u MHz) is not supported for P2P uses",
3849                                    freq);
3850                         res = -3;
3851                         goto exit_free;
3852                 }
3853
3854                 for (i = 0; i < num; i++) {
3855                         if (freqs[i] == freq)
3856                                 freq_in_use = 1;
3857                 }
3858
3859                 if (num == wpa_s->num_multichan_concurrent && !freq_in_use) {
3860                         wpa_printf(MSG_DEBUG, "P2P: Cannot start P2P group on %u MHz as there are no available channels",
3861                                    freq);
3862                         res = -2;
3863                         goto exit_free;
3864                 }
3865                 wpa_printf(MSG_DEBUG, "P2P: Trying to force us to use the "
3866                            "requested channel (%u MHz)", freq);
3867                 *force_freq = freq;
3868                 goto exit_ok;
3869         }
3870
3871         for (i = 0; i < num; i++) {
3872                 if (!p2p_supported_freq(wpa_s->global->p2p, freqs[i]))
3873                         continue;
3874
3875                 wpa_printf(MSG_DEBUG, "P2P: Try to force us to use frequency (%u MHz) which is already in use",
3876                            *force_freq);
3877                 *force_freq = freqs[i];
3878
3879                 if (*pref_freq == 0 && num < wpa_s->num_multichan_concurrent) {
3880                         wpa_printf(MSG_DEBUG, "P2P: Try to prefer a frequency we are already using");
3881                         *pref_freq = *force_freq;
3882                 }
3883                 break;
3884         }
3885
3886         if (i == num) {
3887                 if (num < wpa_s->num_multichan_concurrent) {
3888                         wpa_printf(MSG_DEBUG, "P2P: Current operating channels are not available for P2P. Try to use another channel");
3889                         *force_freq = 0;
3890                 } else {
3891                         wpa_printf(MSG_DEBUG, "P2P: All channels are in use and none of them are P2P enabled. Cannot start P2P group");
3892                         res = -2;
3893                         goto exit_free;
3894                 }
3895         }
3896
3897 exit_ok:
3898         res = 0;
3899 exit_free:
3900         os_free(freqs);
3901         return res;
3902 }
3903
3904
3905 /**
3906  * wpas_p2p_connect - Request P2P Group Formation to be started
3907  * @wpa_s: Pointer to wpa_supplicant data from wpa_supplicant_add_iface()
3908  * @peer_addr: Address of the peer P2P Device
3909  * @pin: PIN to use during provisioning or %NULL to indicate PBC mode
3910  * @persistent_group: Whether to create a persistent group
3911  * @auto_join: Whether to select join vs. GO Negotiation automatically
3912  * @join: Whether to join an existing group (as a client) instead of starting
3913  *      Group Owner negotiation; @peer_addr is BSSID in that case
3914  * @auth: Whether to only authorize the connection instead of doing that and
3915  *      initiating Group Owner negotiation
3916  * @go_intent: GO Intent or -1 to use default
3917  * @freq: Frequency for the group or 0 for auto-selection
3918  * @persistent_id: Persistent group credentials to use for forcing GO
3919  *      parameters or -1 to generate new values (SSID/passphrase)
3920  * @pd: Whether to send Provision Discovery prior to GO Negotiation as an
3921  *      interoperability workaround when initiating group formation
3922  * @ht40: Start GO with 40 MHz channel width
3923  * Returns: 0 or new PIN (if pin was %NULL) on success, -1 on unspecified
3924  *      failure, -2 on failure due to channel not currently available,
3925  *      -3 if forced channel is not supported
3926  */
3927 int wpas_p2p_connect(struct wpa_supplicant *wpa_s, const u8 *peer_addr,
3928                      const char *pin, enum p2p_wps_method wps_method,
3929                      int persistent_group, int auto_join, int join, int auth,
3930                      int go_intent, int freq, int persistent_id, int pd,
3931                      int ht40)
3932 {
3933         int force_freq = 0, pref_freq = 0;
3934         int ret = 0, res;
3935         enum wpa_driver_if_type iftype;
3936         const u8 *if_addr;
3937         struct wpa_ssid *ssid = NULL;
3938
3939         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
3940                 return -1;
3941
3942         if (persistent_id >= 0) {
3943                 ssid = wpa_config_get_network(wpa_s->conf, persistent_id);
3944                 if (ssid == NULL || ssid->disabled != 2 ||
3945                     ssid->mode != WPAS_MODE_P2P_GO)
3946                         return -1;
3947         }
3948
3949         if (go_intent < 0)
3950                 go_intent = wpa_s->conf->p2p_go_intent;
3951
3952         if (!auth)
3953                 wpa_s->p2p_long_listen = 0;
3954
3955         wpa_s->p2p_wps_method = wps_method;
3956         wpa_s->p2p_persistent_group = !!persistent_group;
3957         wpa_s->p2p_persistent_id = persistent_id;
3958         wpa_s->p2p_go_intent = go_intent;
3959         wpa_s->p2p_connect_freq = freq;
3960         wpa_s->p2p_fallback_to_go_neg = 0;
3961         wpa_s->p2p_pd_before_go_neg = !!pd;
3962         wpa_s->p2p_go_ht40 = !!ht40;
3963
3964         if (pin)
3965                 os_strlcpy(wpa_s->p2p_pin, pin, sizeof(wpa_s->p2p_pin));
3966         else if (wps_method == WPS_PIN_DISPLAY) {
3967                 ret = wps_generate_pin();
3968                 os_snprintf(wpa_s->p2p_pin, sizeof(wpa_s->p2p_pin), "%08d",
3969                             ret);
3970                 wpa_printf(MSG_DEBUG, "P2P: Randomly generated PIN: %s",
3971                            wpa_s->p2p_pin);
3972         } else
3973                 wpa_s->p2p_pin[0] = '\0';
3974
3975         if (join || auto_join) {
3976                 u8 iface_addr[ETH_ALEN], dev_addr[ETH_ALEN];
3977                 if (auth) {
3978                         wpa_printf(MSG_DEBUG, "P2P: Authorize invitation to "
3979                                    "connect a running group from " MACSTR,
3980                                    MAC2STR(peer_addr));
3981                         os_memcpy(wpa_s->p2p_auth_invite, peer_addr, ETH_ALEN);
3982                         return ret;
3983                 }
3984                 os_memcpy(dev_addr, peer_addr, ETH_ALEN);
3985                 if (p2p_get_interface_addr(wpa_s->global->p2p, peer_addr,
3986                                            iface_addr) < 0) {
3987                         os_memcpy(iface_addr, peer_addr, ETH_ALEN);
3988                         p2p_get_dev_addr(wpa_s->global->p2p, peer_addr,
3989                                          dev_addr);
3990                 }
3991                 if (auto_join) {
3992                         os_get_time(&wpa_s->p2p_auto_started);
3993                         wpa_printf(MSG_DEBUG, "P2P: Auto join started at "
3994                                    "%ld.%06ld",
3995                                    wpa_s->p2p_auto_started.sec,
3996                                    wpa_s->p2p_auto_started.usec);
3997                 }
3998                 wpa_s->user_initiated_pd = 1;
3999                 if (wpas_p2p_join(wpa_s, iface_addr, dev_addr, wps_method,
4000                                   auto_join) < 0)
4001                         return -1;
4002                 return ret;
4003         }
4004
4005         res = wpas_p2p_setup_freqs(wpa_s, freq, &force_freq, &pref_freq);
4006         if (res)
4007                 return res;
4008         wpas_p2p_set_own_freq_preference(wpa_s, force_freq);
4009
4010         wpa_s->create_p2p_iface = wpas_p2p_create_iface(wpa_s);
4011
4012         if (wpa_s->create_p2p_iface) {
4013                 /* Prepare to add a new interface for the group */
4014                 iftype = WPA_IF_P2P_GROUP;
4015                 if (go_intent == 15)
4016                         iftype = WPA_IF_P2P_GO;
4017                 if (wpas_p2p_add_group_interface(wpa_s, iftype) < 0) {
4018                         wpa_printf(MSG_ERROR, "P2P: Failed to allocate a new "
4019                                    "interface for the group");
4020                         return -1;
4021                 }
4022
4023                 if_addr = wpa_s->pending_interface_addr;
4024         } else
4025                 if_addr = wpa_s->own_addr;
4026
4027         if (auth) {
4028                 if (wpas_p2p_auth_go_neg(wpa_s, peer_addr, wps_method,
4029                                          go_intent, if_addr,
4030                                          force_freq, persistent_group, ssid,
4031                                          pref_freq) < 0)
4032                         return -1;
4033                 return ret;
4034         }
4035
4036         if (wpas_p2p_start_go_neg(wpa_s, peer_addr, wps_method,
4037                                   go_intent, if_addr, force_freq,
4038                                   persistent_group, ssid, pref_freq) < 0) {
4039                 if (wpa_s->create_p2p_iface)
4040                         wpas_p2p_remove_pending_group_interface(wpa_s);
4041                 return -1;
4042         }
4043         return ret;
4044 }
4045
4046
4047 /**
4048  * wpas_p2p_remain_on_channel_cb - Indication of remain-on-channel start
4049  * @wpa_s: Pointer to wpa_supplicant data from wpa_supplicant_add_iface()
4050  * @freq: Frequency of the channel in MHz
4051  * @duration: Duration of the stay on the channel in milliseconds
4052  *
4053  * This callback is called when the driver indicates that it has started the
4054  * requested remain-on-channel duration.
4055  */
4056 void wpas_p2p_remain_on_channel_cb(struct wpa_supplicant *wpa_s,
4057                                    unsigned int freq, unsigned int duration)
4058 {
4059         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
4060                 return;
4061         if (wpa_s->off_channel_freq == wpa_s->pending_listen_freq) {
4062                 p2p_listen_cb(wpa_s->global->p2p, wpa_s->pending_listen_freq,
4063                               wpa_s->pending_listen_duration);
4064                 wpa_s->pending_listen_freq = 0;
4065         }
4066 }
4067
4068
4069 static int wpas_p2p_listen_start(struct wpa_supplicant *wpa_s,
4070                                  unsigned int timeout)
4071 {
4072         /* Limit maximum Listen state time based on driver limitation. */
4073         if (timeout > wpa_s->max_remain_on_chan)
4074                 timeout = wpa_s->max_remain_on_chan;
4075
4076         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT)
4077                 return wpa_drv_p2p_listen(wpa_s, timeout);
4078
4079         return p2p_listen(wpa_s->global->p2p, timeout);
4080 }
4081
4082
4083 /**
4084  * wpas_p2p_cancel_remain_on_channel_cb - Remain-on-channel timeout
4085  * @wpa_s: Pointer to wpa_supplicant data from wpa_supplicant_add_iface()
4086  * @freq: Frequency of the channel in MHz
4087  *
4088  * This callback is called when the driver indicates that a remain-on-channel
4089  * operation has been completed, i.e., the duration on the requested channel
4090  * has timed out.
4091  */
4092 void wpas_p2p_cancel_remain_on_channel_cb(struct wpa_supplicant *wpa_s,
4093                                           unsigned int freq)
4094 {
4095         wpa_printf(MSG_DEBUG, "P2P: Cancel remain-on-channel callback "
4096                    "(p2p_long_listen=%d ms pending_action_tx=%p)",
4097                    wpa_s->p2p_long_listen, offchannel_pending_action_tx(wpa_s));
4098         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
4099                 return;
4100         if (p2p_listen_end(wpa_s->global->p2p, freq) > 0)
4101                 return; /* P2P module started a new operation */
4102         if (offchannel_pending_action_tx(wpa_s))
4103                 return;
4104         if (wpa_s->p2p_long_listen > 0)
4105                 wpa_s->p2p_long_listen -= wpa_s->max_remain_on_chan;
4106         if (wpa_s->p2p_long_listen > 0) {
4107                 wpa_printf(MSG_DEBUG, "P2P: Continuing long Listen state");
4108                 wpas_p2p_listen_start(wpa_s, wpa_s->p2p_long_listen);
4109         }
4110 }
4111
4112
4113 /**
4114  * wpas_p2p_group_remove - Remove a P2P group
4115  * @wpa_s: Pointer to wpa_supplicant data from wpa_supplicant_add_iface()
4116  * @ifname: Network interface name of the group interface or "*" to remove all
4117  *      groups
4118  * Returns: 0 on success, -1 on failure
4119  *
4120  * This function is used to remove a P2P group. This can be used to disconnect
4121  * from a group in which the local end is a P2P Client or to end a P2P Group in
4122  * case the local end is the Group Owner. If a virtual network interface was
4123  * created for this group, that interface will be removed. Otherwise, only the
4124  * configured P2P group network will be removed from the interface.
4125  */
4126 int wpas_p2p_group_remove(struct wpa_supplicant *wpa_s, const char *ifname)
4127 {
4128         struct wpa_global *global = wpa_s->global;
4129
4130         if (os_strcmp(ifname, "*") == 0) {
4131                 struct wpa_supplicant *prev;
4132                 wpa_s = global->ifaces;
4133                 while (wpa_s) {
4134                         prev = wpa_s;
4135                         wpa_s = wpa_s->next;
4136                         if (prev->p2p_group_interface !=
4137                             NOT_P2P_GROUP_INTERFACE ||
4138                             (prev->current_ssid &&
4139                              prev->current_ssid->p2p_group))
4140                                 wpas_p2p_disconnect(prev);
4141                 }
4142                 return 0;
4143         }
4144
4145         for (wpa_s = global->ifaces; wpa_s; wpa_s = wpa_s->next) {
4146                 if (os_strcmp(wpa_s->ifname, ifname) == 0)
4147                         break;
4148         }
4149
4150         return wpas_p2p_disconnect(wpa_s);
4151 }
4152
4153
4154 static int wpas_p2p_select_go_freq(struct wpa_supplicant *wpa_s, int freq)
4155 {
4156         unsigned int r;
4157
4158         if (freq == 2) {
4159                 wpa_printf(MSG_DEBUG, "P2P: Request to start GO on 2.4 GHz "
4160                            "band");
4161                 if (wpa_s->best_24_freq > 0 &&
4162                     p2p_supported_freq(wpa_s->global->p2p,
4163                                        wpa_s->best_24_freq)) {
4164                         freq = wpa_s->best_24_freq;
4165                         wpa_printf(MSG_DEBUG, "P2P: Use best 2.4 GHz band "
4166                                    "channel: %d MHz", freq);
4167                 } else {
4168                         os_get_random((u8 *) &r, sizeof(r));
4169                         freq = 2412 + (r % 3) * 25;
4170                         wpa_printf(MSG_DEBUG, "P2P: Use random 2.4 GHz band "
4171                                    "channel: %d MHz", freq);
4172                 }
4173         }
4174
4175         if (freq == 5) {
4176                 wpa_printf(MSG_DEBUG, "P2P: Request to start GO on 5 GHz "
4177                            "band");
4178                 if (wpa_s->best_5_freq > 0 &&
4179                     p2p_supported_freq(wpa_s->global->p2p,
4180                                        wpa_s->best_5_freq)) {
4181                         freq = wpa_s->best_5_freq;
4182                         wpa_printf(MSG_DEBUG, "P2P: Use best 5 GHz band "
4183                                    "channel: %d MHz", freq);
4184                 } else {
4185                         os_get_random((u8 *) &r, sizeof(r));
4186                         freq = 5180 + (r % 4) * 20;
4187                         if (!p2p_supported_freq(wpa_s->global->p2p, freq)) {
4188                                 wpa_printf(MSG_DEBUG, "P2P: Could not select "
4189                                            "5 GHz channel for P2P group");
4190                                 return -1;
4191                         }
4192                         wpa_printf(MSG_DEBUG, "P2P: Use random 5 GHz band "
4193                                    "channel: %d MHz", freq);
4194                 }
4195         }
4196
4197         if (freq > 0 && !p2p_supported_freq(wpa_s->global->p2p, freq)) {
4198                 wpa_printf(MSG_DEBUG, "P2P: The forced channel for GO "
4199                            "(%u MHz) is not supported for P2P uses",
4200                            freq);
4201                 return -1;
4202         }
4203
4204         return freq;
4205 }
4206
4207
4208 static int wpas_p2p_init_go_params(struct wpa_supplicant *wpa_s,
4209                                    struct p2p_go_neg_results *params,
4210                                    int freq, int ht40,
4211                                    const struct p2p_channels *channels)
4212 {
4213         int res, *freqs;
4214         unsigned int pref_freq;
4215         unsigned int num, i;
4216
4217         os_memset(params, 0, sizeof(*params));
4218         params->role_go = 1;
4219         params->ht40 = ht40;
4220         if (freq) {
4221                 if (!freq_included(channels, freq)) {
4222                         wpa_printf(MSG_DEBUG, "P2P: Forced GO freq %d MHz not "
4223                                    "accepted", freq);
4224                         return -1;
4225                 }
4226                 wpa_printf(MSG_DEBUG, "P2P: Set GO freq based on forced "
4227                            "frequency %d MHz", freq);
4228                 params->freq = freq;
4229         } else if (wpa_s->conf->p2p_oper_reg_class == 81 &&
4230                    wpa_s->conf->p2p_oper_channel >= 1 &&
4231                    wpa_s->conf->p2p_oper_channel <= 11 &&
4232                    freq_included(channels,
4233                                  2407 + 5 * wpa_s->conf->p2p_oper_channel)) {
4234                 params->freq = 2407 + 5 * wpa_s->conf->p2p_oper_channel;
4235                 wpa_printf(MSG_DEBUG, "P2P: Set GO freq based on configured "
4236                            "frequency %d MHz", params->freq);
4237         } else if ((wpa_s->conf->p2p_oper_reg_class == 115 ||
4238                     wpa_s->conf->p2p_oper_reg_class == 116 ||
4239                     wpa_s->conf->p2p_oper_reg_class == 117 ||
4240                     wpa_s->conf->p2p_oper_reg_class == 124 ||
4241                     wpa_s->conf->p2p_oper_reg_class == 126 ||
4242                     wpa_s->conf->p2p_oper_reg_class == 127) &&
4243                    freq_included(channels,
4244                                  5000 + 5 * wpa_s->conf->p2p_oper_channel)) {
4245                 params->freq = 5000 + 5 * wpa_s->conf->p2p_oper_channel;
4246                 wpa_printf(MSG_DEBUG, "P2P: Set GO freq based on configured "
4247                            "frequency %d MHz", params->freq);
4248         } else if (wpa_s->conf->p2p_oper_channel == 0 &&
4249                    wpa_s->best_overall_freq > 0 &&
4250                    p2p_supported_freq(wpa_s->global->p2p,
4251                                       wpa_s->best_overall_freq) &&
4252                    freq_included(channels, wpa_s->best_overall_freq)) {
4253                 params->freq = wpa_s->best_overall_freq;
4254                 wpa_printf(MSG_DEBUG, "P2P: Set GO freq based on best overall "
4255                            "channel %d MHz", params->freq);
4256         } else if (wpa_s->conf->p2p_oper_channel == 0 &&
4257                    wpa_s->best_24_freq > 0 &&
4258                    p2p_supported_freq(wpa_s->global->p2p,
4259                                       wpa_s->best_24_freq) &&
4260                    freq_included(channels, wpa_s->best_24_freq)) {
4261                 params->freq = wpa_s->best_24_freq;
4262                 wpa_printf(MSG_DEBUG, "P2P: Set GO freq based on best 2.4 GHz "
4263                            "channel %d MHz", params->freq);
4264         } else if (wpa_s->conf->p2p_oper_channel == 0 &&
4265                    wpa_s->best_5_freq > 0 &&
4266                    p2p_supported_freq(wpa_s->global->p2p,
4267                                       wpa_s->best_5_freq) &&
4268                    freq_included(channels, wpa_s->best_5_freq)) {
4269                 params->freq = wpa_s->best_5_freq;
4270                 wpa_printf(MSG_DEBUG, "P2P: Set GO freq based on best 5 GHz "
4271                            "channel %d MHz", params->freq);
4272         } else if ((pref_freq = p2p_get_pref_freq(wpa_s->global->p2p,
4273                                                   channels))) {
4274                 params->freq = pref_freq;
4275                 wpa_printf(MSG_DEBUG, "P2P: Set GO freq %d MHz from preferred "
4276                            "channels", params->freq);
4277         } else {
4278                 int chan;
4279                 for (chan = 0; chan < 11; chan++) {
4280                         params->freq = 2412 + chan * 5;
4281                         if (!wpas_p2p_disallowed_freq(wpa_s->global,
4282                                                       params->freq) &&
4283                             freq_included(channels, params->freq))
4284                                 break;
4285                 }
4286                 if (chan == 11) {
4287                         wpa_printf(MSG_DEBUG, "P2P: No 2.4 GHz channel "
4288                                    "allowed");
4289                         return -1;
4290                 }
4291                 wpa_printf(MSG_DEBUG, "P2P: Set GO freq %d MHz (no preference "
4292                            "known)", params->freq);
4293         }
4294
4295         freqs = os_calloc(wpa_s->num_multichan_concurrent, sizeof(int));
4296         if (!freqs)
4297                 return -1;
4298
4299         res = wpas_p2p_valid_oper_freqs(wpa_s, freqs,
4300                                         wpa_s->num_multichan_concurrent);
4301         if (res < 0) {
4302                 os_free(freqs);
4303                 return -1;
4304         }
4305         num = res;
4306
4307         if (!freq) {
4308                 for (i = 0; i < num; i++) {
4309                         if (freq_included(channels, freqs[i])) {
4310                                 wpa_printf(MSG_DEBUG, "P2P: Force GO on a channel we are already using (%u MHz)",
4311                                            freqs[i]);
4312                                 params->freq = freqs[i];
4313                                 break;
4314                         }
4315                 }
4316
4317                 if (i == num) {
4318                         if (num == wpa_s->num_multichan_concurrent) {
4319                                 wpa_printf(MSG_DEBUG, "P2P: Cannot force GO on any of the channels we are already using");
4320                                 os_free(freqs);
4321                                 return -1;
4322                         } else {
4323                                 wpa_printf(MSG_DEBUG, "P2P: Cannot force GO on any of the channels we are already using. Use one of the free channels");
4324                         }
4325                 }
4326         } else {
4327                 for (i = 0; i < num; i++) {
4328                         if (freqs[i] == freq)
4329                                 break;
4330                 }
4331
4332                 if (i == num) {
4333                         if (num == wpa_s->num_multichan_concurrent) {
4334                                 wpa_printf(MSG_DEBUG, "P2P: Cannot force GO on freq (%u MHz) as all the channels are in use", freq);
4335                                 os_free(freqs);
4336                                 return -1;
4337                         } else {
4338                                 wpa_printf(MSG_DEBUG, "P2P: Cannot force GO on any of the channels we are already using. Use one of the free channels");
4339                         }
4340                 }
4341         }
4342         os_free(freqs);
4343         return 0;
4344 }
4345
4346
4347 static struct wpa_supplicant *
4348 wpas_p2p_get_group_iface(struct wpa_supplicant *wpa_s, int addr_allocated,
4349                          int go)
4350 {
4351         struct wpa_supplicant *group_wpa_s;
4352
4353         if (!wpas_p2p_create_iface(wpa_s)) {
4354                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Use same interface for group "
4355                         "operations");
4356                 return wpa_s;
4357         }
4358
4359         if (wpas_p2p_add_group_interface(wpa_s, go ? WPA_IF_P2P_GO :
4360                                          WPA_IF_P2P_CLIENT) < 0) {
4361                 wpa_msg_global(wpa_s, MSG_ERROR,
4362                                "P2P: Failed to add group interface");
4363                 return NULL;
4364         }
4365         group_wpa_s = wpas_p2p_init_group_interface(wpa_s, go);
4366         if (group_wpa_s == NULL) {
4367                 wpa_msg_global(wpa_s, MSG_ERROR,
4368                                "P2P: Failed to initialize group interface");
4369                 wpas_p2p_remove_pending_group_interface(wpa_s);
4370                 return NULL;
4371         }
4372
4373         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Use separate group interface %s",
4374                 group_wpa_s->ifname);
4375         return group_wpa_s;
4376 }
4377
4378
4379 /**
4380  * wpas_p2p_group_add - Add a new P2P group with local end as Group Owner
4381  * @wpa_s: Pointer to wpa_supplicant data from wpa_supplicant_add_iface()
4382  * @persistent_group: Whether to create a persistent group
4383  * @freq: Frequency for the group or 0 to indicate no hardcoding
4384  * Returns: 0 on success, -1 on failure
4385  *
4386  * This function creates a new P2P group with the local end as the Group Owner,
4387  * i.e., without using Group Owner Negotiation.
4388  */
4389 int wpas_p2p_group_add(struct wpa_supplicant *wpa_s, int persistent_group,
4390                        int freq, int ht40)
4391 {
4392         struct p2p_go_neg_results params;
4393
4394         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
4395                 return -1;
4396
4397         /* Make sure we are not running find during connection establishment */
4398         wpa_printf(MSG_DEBUG, "P2P: Stop any on-going P2P FIND");
4399         wpas_p2p_stop_find_oper(wpa_s);
4400
4401         freq = wpas_p2p_select_go_freq(wpa_s, freq);
4402         if (freq < 0)
4403                 return -1;
4404
4405         if (wpas_p2p_init_go_params(wpa_s, &params, freq, ht40, NULL))
4406                 return -1;
4407         if (params.freq &&
4408             !p2p_supported_freq(wpa_s->global->p2p, params.freq)) {
4409                 wpa_printf(MSG_DEBUG, "P2P: The selected channel for GO "
4410                            "(%u MHz) is not supported for P2P uses",
4411                            params.freq);
4412                 return -1;
4413         }
4414         p2p_go_params(wpa_s->global->p2p, &params);
4415         params.persistent_group = persistent_group;
4416
4417         wpa_s = wpas_p2p_get_group_iface(wpa_s, 0, 1);
4418         if (wpa_s == NULL)
4419                 return -1;
4420         wpas_start_wps_go(wpa_s, &params, 0);
4421
4422         return 0;
4423 }
4424
4425
4426 static int wpas_start_p2p_client(struct wpa_supplicant *wpa_s,
4427                                  struct wpa_ssid *params, int addr_allocated)
4428 {
4429         struct wpa_ssid *ssid;
4430
4431         wpa_s = wpas_p2p_get_group_iface(wpa_s, addr_allocated, 0);
4432         if (wpa_s == NULL)
4433                 return -1;
4434
4435         wpa_supplicant_ap_deinit(wpa_s);
4436
4437         ssid = wpa_config_add_network(wpa_s->conf);
4438         if (ssid == NULL)
4439                 return -1;
4440         wpa_config_set_network_defaults(ssid);
4441         ssid->temporary = 1;
4442         ssid->proto = WPA_PROTO_RSN;
4443         ssid->pairwise_cipher = WPA_CIPHER_CCMP;
4444         ssid->group_cipher = WPA_CIPHER_CCMP;
4445         ssid->key_mgmt = WPA_KEY_MGMT_PSK;
4446         ssid->ssid = os_malloc(params->ssid_len);
4447         if (ssid->ssid == NULL) {
4448                 wpa_config_remove_network(wpa_s->conf, ssid->id);
4449                 return -1;
4450         }
4451         os_memcpy(ssid->ssid, params->ssid, params->ssid_len);
4452         ssid->ssid_len = params->ssid_len;
4453         ssid->p2p_group = 1;
4454         ssid->export_keys = 1;
4455         if (params->psk_set) {
4456                 os_memcpy(ssid->psk, params->psk, 32);
4457                 ssid->psk_set = 1;
4458         }
4459         if (params->passphrase)
4460                 ssid->passphrase = os_strdup(params->passphrase);
4461
4462         wpa_supplicant_select_network(wpa_s, ssid);
4463
4464         wpa_s->show_group_started = 1;
4465
4466         return 0;
4467 }
4468
4469
4470 int wpas_p2p_group_add_persistent(struct wpa_supplicant *wpa_s,
4471                                   struct wpa_ssid *ssid, int addr_allocated,
4472                                   int freq, int ht40,
4473                                   const struct p2p_channels *channels)
4474 {
4475         struct p2p_go_neg_results params;
4476         int go = 0;
4477
4478         if (ssid->disabled != 2 || ssid->ssid == NULL)
4479                 return -1;
4480
4481         if (wpas_get_p2p_group(wpa_s, ssid->ssid, ssid->ssid_len, &go) &&
4482             go == (ssid->mode == WPAS_MODE_P2P_GO)) {
4483                 wpa_printf(MSG_DEBUG, "P2P: Requested persistent group is "
4484                            "already running");
4485                 return 0;
4486         }
4487
4488         /* Make sure we are not running find during connection establishment */
4489         wpas_p2p_stop_find_oper(wpa_s);
4490
4491         wpa_s->p2p_fallback_to_go_neg = 0;
4492
4493         if (ssid->mode == WPAS_MODE_INFRA)
4494                 return wpas_start_p2p_client(wpa_s, ssid, addr_allocated);
4495
4496         if (ssid->mode != WPAS_MODE_P2P_GO)
4497                 return -1;
4498
4499         freq = wpas_p2p_select_go_freq(wpa_s, freq);
4500         if (freq < 0)
4501                 return -1;
4502
4503         if (wpas_p2p_init_go_params(wpa_s, &params, freq, ht40, channels))
4504                 return -1;
4505
4506         params.role_go = 1;
4507         params.psk_set = ssid->psk_set;
4508         if (params.psk_set)
4509                 os_memcpy(params.psk, ssid->psk, sizeof(params.psk));
4510         if (ssid->passphrase) {
4511                 if (os_strlen(ssid->passphrase) >= sizeof(params.passphrase)) {
4512                         wpa_printf(MSG_ERROR, "P2P: Invalid passphrase in "
4513                                    "persistent group");
4514                         return -1;
4515                 }
4516                 os_strlcpy(params.passphrase, ssid->passphrase,
4517                            sizeof(params.passphrase));
4518         }
4519         os_memcpy(params.ssid, ssid->ssid, ssid->ssid_len);
4520         params.ssid_len = ssid->ssid_len;
4521         params.persistent_group = 1;
4522
4523         wpa_s = wpas_p2p_get_group_iface(wpa_s, addr_allocated, 1);
4524         if (wpa_s == NULL)
4525                 return -1;
4526
4527         wpas_start_wps_go(wpa_s, &params, 0);
4528
4529         return 0;
4530 }
4531
4532
4533 static void wpas_p2p_ie_update(void *ctx, struct wpabuf *beacon_ies,
4534                                struct wpabuf *proberesp_ies)
4535 {
4536         struct wpa_supplicant *wpa_s = ctx;
4537         if (wpa_s->ap_iface) {
4538                 struct hostapd_data *hapd = wpa_s->ap_iface->bss[0];
4539                 if (!(hapd->conf->p2p & P2P_GROUP_OWNER)) {
4540                         wpabuf_free(beacon_ies);
4541                         wpabuf_free(proberesp_ies);
4542                         return;
4543                 }
4544                 if (beacon_ies) {
4545                         wpabuf_free(hapd->p2p_beacon_ie);
4546                         hapd->p2p_beacon_ie = beacon_ies;
4547                 }
4548                 wpabuf_free(hapd->p2p_probe_resp_ie);
4549                 hapd->p2p_probe_resp_ie = proberesp_ies;
4550         } else {
4551                 wpabuf_free(beacon_ies);
4552                 wpabuf_free(proberesp_ies);
4553         }
4554         wpa_supplicant_ap_update_beacon(wpa_s);
4555 }
4556
4557
4558 static void wpas_p2p_idle_update(void *ctx, int idle)
4559 {
4560         struct wpa_supplicant *wpa_s = ctx;
4561         if (!wpa_s->ap_iface)
4562                 return;
4563         wpa_printf(MSG_DEBUG, "P2P: GO - group %sidle", idle ? "" : "not ");
4564         if (idle)
4565                 wpas_p2p_set_group_idle_timeout(wpa_s);
4566         else
4567                 eloop_cancel_timeout(wpas_p2p_group_idle_timeout, wpa_s, NULL);
4568 }
4569
4570
4571 struct p2p_group * wpas_p2p_group_init(struct wpa_supplicant *wpa_s,
4572                                        struct wpa_ssid *ssid)
4573 {
4574         struct p2p_group *group;
4575         struct p2p_group_config *cfg;
4576
4577         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT)
4578                 return NULL;
4579         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
4580                 return NULL;
4581
4582         cfg = os_zalloc(sizeof(*cfg));
4583         if (cfg == NULL)
4584                 return NULL;
4585
4586         if (ssid->p2p_persistent_group && wpa_s->conf->persistent_reconnect)
4587                 cfg->persistent_group = 2;
4588         else if (ssid->p2p_persistent_group)
4589                 cfg->persistent_group = 1;
4590         os_memcpy(cfg->interface_addr, wpa_s->own_addr, ETH_ALEN);
4591         if (wpa_s->max_stations &&
4592             wpa_s->max_stations < wpa_s->conf->max_num_sta)
4593                 cfg->max_clients = wpa_s->max_stations;
4594         else
4595                 cfg->max_clients = wpa_s->conf->max_num_sta;
4596         os_memcpy(cfg->ssid, ssid->ssid, ssid->ssid_len);
4597         cfg->ssid_len = ssid->ssid_len;
4598         cfg->cb_ctx = wpa_s;
4599         cfg->ie_update = wpas_p2p_ie_update;
4600         cfg->idle_update = wpas_p2p_idle_update;
4601
4602         group = p2p_group_init(wpa_s->global->p2p, cfg);
4603         if (group == NULL)
4604                 os_free(cfg);
4605         if (ssid->mode != WPAS_MODE_P2P_GROUP_FORMATION)
4606                 p2p_group_notif_formation_done(group);
4607         wpa_s->p2p_group = group;
4608         return group;
4609 }
4610
4611
4612 void wpas_p2p_wps_success(struct wpa_supplicant *wpa_s, const u8 *peer_addr,
4613                           int registrar)
4614 {
4615         struct wpa_ssid *ssid = wpa_s->current_ssid;
4616
4617         if (!wpa_s->p2p_in_provisioning) {
4618                 wpa_printf(MSG_DEBUG, "P2P: Ignore WPS success event - P2P "
4619                            "provisioning not in progress");
4620                 return;
4621         }
4622
4623         if (ssid && ssid->mode == WPAS_MODE_INFRA) {
4624                 u8 go_dev_addr[ETH_ALEN];
4625                 os_memcpy(go_dev_addr, wpa_s->bssid, ETH_ALEN);
4626                 wpas_p2p_persistent_group(wpa_s, go_dev_addr, ssid->ssid,
4627                                           ssid->ssid_len);
4628                 /* Clear any stored provisioning info */
4629                 p2p_clear_provisioning_info(wpa_s->global->p2p, go_dev_addr);
4630         }
4631
4632         eloop_cancel_timeout(wpas_p2p_group_formation_timeout, wpa_s->parent,
4633                              NULL);
4634         if (ssid && ssid->mode == WPAS_MODE_INFRA) {
4635                 /*
4636                  * Use a separate timeout for initial data connection to
4637                  * complete to allow the group to be removed automatically if
4638                  * something goes wrong in this step before the P2P group idle
4639                  * timeout mechanism is taken into use.
4640                  */
4641                 eloop_register_timeout(P2P_MAX_INITIAL_CONN_WAIT, 0,
4642                                        wpas_p2p_group_formation_timeout,
4643                                        wpa_s->parent, NULL);
4644         }
4645         if (wpa_s->global->p2p)
4646                 p2p_wps_success_cb(wpa_s->global->p2p, peer_addr);
4647         else if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT)
4648                 wpa_drv_wps_success_cb(wpa_s, peer_addr);
4649         wpas_group_formation_completed(wpa_s, 1);
4650 }
4651
4652
4653 void wpas_p2p_wps_failed(struct wpa_supplicant *wpa_s,
4654                          struct wps_event_fail *fail)
4655 {
4656         if (!wpa_s->p2p_in_provisioning) {
4657                 wpa_printf(MSG_DEBUG, "P2P: Ignore WPS fail event - P2P "
4658                            "provisioning not in progress");
4659                 return;
4660         }
4661
4662         if (wpa_s->go_params) {
4663                 p2p_clear_provisioning_info(
4664                         wpa_s->global->p2p,
4665                         wpa_s->go_params->peer_device_addr);
4666         }
4667
4668         wpas_notify_p2p_wps_failed(wpa_s, fail);
4669 }
4670
4671
4672 int wpas_p2p_prov_disc(struct wpa_supplicant *wpa_s, const u8 *peer_addr,
4673                        const char *config_method,
4674                        enum wpas_p2p_prov_disc_use use)
4675 {
4676         u16 config_methods;
4677
4678         wpa_s->p2p_fallback_to_go_neg = 0;
4679         wpa_s->pending_pd_use = NORMAL_PD;
4680         if (os_strncmp(config_method, "display", 7) == 0)
4681                 config_methods = WPS_CONFIG_DISPLAY;
4682         else if (os_strncmp(config_method, "keypad", 6) == 0)
4683                 config_methods = WPS_CONFIG_KEYPAD;
4684         else if (os_strncmp(config_method, "pbc", 3) == 0 ||
4685                  os_strncmp(config_method, "pushbutton", 10) == 0)
4686                 config_methods = WPS_CONFIG_PUSHBUTTON;
4687         else {
4688                 wpa_printf(MSG_DEBUG, "P2P: Unknown config method");
4689                 return -1;
4690         }
4691
4692         if (use == WPAS_P2P_PD_AUTO) {
4693                 os_memcpy(wpa_s->pending_join_dev_addr, peer_addr, ETH_ALEN);
4694                 wpa_s->pending_pd_config_methods = config_methods;
4695                 wpa_s->p2p_auto_pd = 1;
4696                 wpa_s->p2p_auto_join = 0;
4697                 wpa_s->pending_pd_before_join = 0;
4698                 wpa_s->auto_pd_scan_retry = 0;
4699                 wpas_p2p_stop_find(wpa_s);
4700                 wpa_s->p2p_join_scan_count = 0;
4701                 os_get_time(&wpa_s->p2p_auto_started);
4702                 wpa_printf(MSG_DEBUG, "P2P: Auto PD started at %ld.%06ld",
4703                            wpa_s->p2p_auto_started.sec,
4704                            wpa_s->p2p_auto_started.usec);
4705                 wpas_p2p_join_scan(wpa_s, NULL);
4706                 return 0;
4707         }
4708
4709         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT) {
4710                 return wpa_drv_p2p_prov_disc_req(wpa_s, peer_addr,
4711                                                  config_methods,
4712                                                  use == WPAS_P2P_PD_FOR_JOIN);
4713         }
4714
4715         if (wpa_s->global->p2p == NULL || wpa_s->global->p2p_disabled)
4716                 return -1;
4717
4718         return p2p_prov_disc_req(wpa_s->global->p2p, peer_addr,
4719                                  config_methods, use == WPAS_P2P_PD_FOR_JOIN,
4720                                  0, 1);
4721 }
4722
4723
4724 int wpas_p2p_scan_result_text(const u8 *ies, size_t ies_len, char *buf,
4725                               char *end)
4726 {
4727         return p2p_scan_result_text(ies, ies_len, buf, end);
4728 }
4729
4730
4731 static void wpas_p2p_clear_pending_action_tx(struct wpa_supplicant *wpa_s)
4732 {
4733         if (!offchannel_pending_action_tx(wpa_s))
4734                 return;
4735
4736         wpa_printf(MSG_DEBUG, "P2P: Drop pending Action TX due to new "
4737                    "operation request");
4738         offchannel_clear_pending_action_tx(wpa_s);
4739 }
4740
4741
4742 int wpas_p2p_find(struct wpa_supplicant *wpa_s, unsigned int timeout,
4743                   enum p2p_discovery_type type,
4744                   unsigned int num_req_dev_types, const u8 *req_dev_types,
4745                   const u8 *dev_id, unsigned int search_delay)
4746 {
4747         wpas_p2p_clear_pending_action_tx(wpa_s);
4748         wpa_s->p2p_long_listen = 0;
4749
4750         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT)
4751                 return wpa_drv_p2p_find(wpa_s, timeout, type);
4752
4753         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL ||
4754             wpa_s->p2p_in_provisioning)
4755                 return -1;
4756
4757         wpa_supplicant_cancel_sched_scan(wpa_s);
4758
4759         return p2p_find(wpa_s->global->p2p, timeout, type,
4760                         num_req_dev_types, req_dev_types, dev_id,
4761                         search_delay);
4762 }
4763
4764
4765 static int wpas_p2p_stop_find_oper(struct wpa_supplicant *wpa_s)
4766 {
4767         wpas_p2p_clear_pending_action_tx(wpa_s);
4768         wpa_s->p2p_long_listen = 0;
4769         eloop_cancel_timeout(wpas_p2p_long_listen_timeout, wpa_s, NULL);
4770         eloop_cancel_timeout(wpas_p2p_join_scan, wpa_s, NULL);
4771         wpa_s->global->p2p_cb_on_scan_complete = 0;
4772
4773         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT) {
4774                 wpa_drv_p2p_stop_find(wpa_s);
4775                 return 1;
4776         }
4777
4778         if (wpa_s->global->p2p)
4779                 p2p_stop_find(wpa_s->global->p2p);
4780
4781         return 0;
4782 }
4783
4784
4785 void wpas_p2p_stop_find(struct wpa_supplicant *wpa_s)
4786 {
4787         if (wpas_p2p_stop_find_oper(wpa_s) > 0)
4788                 return;
4789         wpas_p2p_remove_pending_group_interface(wpa_s);
4790 }
4791
4792
4793 static void wpas_p2p_long_listen_timeout(void *eloop_ctx, void *timeout_ctx)
4794 {
4795         struct wpa_supplicant *wpa_s = eloop_ctx;
4796         wpa_s->p2p_long_listen = 0;
4797 }
4798
4799
4800 int wpas_p2p_listen(struct wpa_supplicant *wpa_s, unsigned int timeout)
4801 {
4802         int res;
4803
4804         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
4805                 return -1;
4806
4807         wpa_supplicant_cancel_sched_scan(wpa_s);
4808         wpas_p2p_clear_pending_action_tx(wpa_s);
4809
4810         if (timeout == 0) {
4811                 /*
4812                  * This is a request for unlimited Listen state. However, at
4813                  * least for now, this is mapped to a Listen state for one
4814                  * hour.
4815                  */
4816                 timeout = 3600;
4817         }
4818         eloop_cancel_timeout(wpas_p2p_long_listen_timeout, wpa_s, NULL);
4819         wpa_s->p2p_long_listen = 0;
4820
4821         /*
4822          * Stop previous find/listen operation to avoid trying to request a new
4823          * remain-on-channel operation while the driver is still running the
4824          * previous one.
4825          */
4826         if (wpa_s->global->p2p)
4827                 p2p_stop_find(wpa_s->global->p2p);
4828
4829         res = wpas_p2p_listen_start(wpa_s, timeout * 1000);
4830         if (res == 0 && timeout * 1000 > wpa_s->max_remain_on_chan) {
4831                 wpa_s->p2p_long_listen = timeout * 1000;
4832                 eloop_register_timeout(timeout, 0,
4833                                        wpas_p2p_long_listen_timeout,
4834                                        wpa_s, NULL);
4835         }
4836
4837         return res;
4838 }
4839
4840
4841 int wpas_p2p_assoc_req_ie(struct wpa_supplicant *wpa_s, struct wpa_bss *bss,
4842                           u8 *buf, size_t len, int p2p_group)
4843 {
4844         struct wpabuf *p2p_ie;
4845         int ret;
4846
4847         if (wpa_s->global->p2p_disabled)
4848                 return -1;
4849         if (wpa_s->global->p2p == NULL)
4850                 return -1;
4851         if (bss == NULL)
4852                 return -1;
4853
4854         p2p_ie = wpa_bss_get_vendor_ie_multi(bss, P2P_IE_VENDOR_TYPE);
4855         ret = p2p_assoc_req_ie(wpa_s->global->p2p, bss->bssid, buf, len,
4856                                p2p_group, p2p_ie);
4857         wpabuf_free(p2p_ie);
4858
4859         return ret;
4860 }
4861
4862
4863 int wpas_p2p_probe_req_rx(struct wpa_supplicant *wpa_s, const u8 *addr,
4864                           const u8 *dst, const u8 *bssid,
4865                           const u8 *ie, size_t ie_len, int ssi_signal)
4866 {
4867         if (wpa_s->global->p2p_disabled)
4868                 return 0;
4869         if (wpa_s->global->p2p == NULL)
4870                 return 0;
4871
4872         switch (p2p_probe_req_rx(wpa_s->global->p2p, addr, dst, bssid,
4873                                  ie, ie_len)) {
4874         case P2P_PREQ_NOT_P2P:
4875                 wpas_notify_preq(wpa_s, addr, dst, bssid, ie, ie_len,
4876                                  ssi_signal);
4877                 /* fall through */
4878         case P2P_PREQ_MALFORMED:
4879         case P2P_PREQ_NOT_LISTEN:
4880         case P2P_PREQ_NOT_PROCESSED:
4881         default: /* make gcc happy */
4882                 return 0;
4883         case P2P_PREQ_PROCESSED:
4884                 return 1;
4885         }
4886 }
4887
4888
4889 void wpas_p2p_rx_action(struct wpa_supplicant *wpa_s, const u8 *da,
4890                         const u8 *sa, const u8 *bssid,
4891                         u8 category, const u8 *data, size_t len, int freq)
4892 {
4893         if (wpa_s->global->p2p_disabled)
4894                 return;
4895         if (wpa_s->global->p2p == NULL)
4896                 return;
4897
4898         p2p_rx_action(wpa_s->global->p2p, da, sa, bssid, category, data, len,
4899                       freq);
4900 }
4901
4902
4903 void wpas_p2p_scan_ie(struct wpa_supplicant *wpa_s, struct wpabuf *ies)
4904 {
4905         if (wpa_s->global->p2p_disabled)
4906                 return;
4907         if (wpa_s->global->p2p == NULL)
4908                 return;
4909
4910         p2p_scan_ie(wpa_s->global->p2p, ies, NULL);
4911 }
4912
4913
4914 void wpas_p2p_group_deinit(struct wpa_supplicant *wpa_s)
4915 {
4916         p2p_group_deinit(wpa_s->p2p_group);
4917         wpa_s->p2p_group = NULL;
4918
4919         wpa_s->ap_configured_cb = NULL;
4920         wpa_s->ap_configured_cb_ctx = NULL;
4921         wpa_s->ap_configured_cb_data = NULL;
4922         wpa_s->connect_without_scan = NULL;
4923 }
4924
4925
4926 int wpas_p2p_reject(struct wpa_supplicant *wpa_s, const u8 *addr)
4927 {
4928         wpa_s->p2p_long_listen = 0;
4929
4930         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT)
4931                 return wpa_drv_p2p_reject(wpa_s, addr);
4932
4933         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
4934                 return -1;
4935
4936         return p2p_reject(wpa_s->global->p2p, addr);
4937 }
4938
4939
4940 /* Invite to reinvoke a persistent group */
4941 int wpas_p2p_invite(struct wpa_supplicant *wpa_s, const u8 *peer_addr,
4942                     struct wpa_ssid *ssid, const u8 *go_dev_addr, int freq,
4943                     int ht40, int pref_freq)
4944 {
4945         enum p2p_invite_role role;
4946         u8 *bssid = NULL;
4947         int force_freq = 0;
4948         int res;
4949
4950         wpa_s->global->p2p_invite_group = NULL;
4951         if (peer_addr)
4952                 os_memcpy(wpa_s->p2p_auth_invite, peer_addr, ETH_ALEN);
4953         else
4954                 os_memset(wpa_s->p2p_auth_invite, 0, ETH_ALEN);
4955
4956         wpa_s->p2p_persistent_go_freq = freq;
4957         wpa_s->p2p_go_ht40 = !!ht40;
4958         if (ssid->mode == WPAS_MODE_P2P_GO) {
4959                 role = P2P_INVITE_ROLE_GO;
4960                 if (peer_addr == NULL) {
4961                         wpa_printf(MSG_DEBUG, "P2P: Missing peer "
4962                                    "address in invitation command");
4963                         return -1;
4964                 }
4965                 if (wpas_p2p_create_iface(wpa_s)) {
4966                         if (wpas_p2p_add_group_interface(wpa_s,
4967                                                          WPA_IF_P2P_GO) < 0) {
4968                                 wpa_printf(MSG_ERROR, "P2P: Failed to "
4969                                            "allocate a new interface for the "
4970                                            "group");
4971                                 return -1;
4972                         }
4973                         bssid = wpa_s->pending_interface_addr;
4974                 } else
4975                         bssid = wpa_s->own_addr;
4976         } else {
4977                 role = P2P_INVITE_ROLE_CLIENT;
4978                 peer_addr = ssid->bssid;
4979         }
4980         wpa_s->pending_invite_ssid_id = ssid->id;
4981
4982         res = wpas_p2p_setup_freqs(wpa_s, freq, &force_freq, &pref_freq);
4983         if (res)
4984                 return res;
4985
4986         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT)
4987                 return wpa_drv_p2p_invite(wpa_s, peer_addr, role, bssid,
4988                                           ssid->ssid, ssid->ssid_len,
4989                                           go_dev_addr, 1);
4990
4991         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
4992                 return -1;
4993
4994         return p2p_invite(wpa_s->global->p2p, peer_addr, role, bssid,
4995                           ssid->ssid, ssid->ssid_len, force_freq, go_dev_addr,
4996                           1, pref_freq);
4997 }
4998
4999
5000 /* Invite to join an active group */
5001 int wpas_p2p_invite_group(struct wpa_supplicant *wpa_s, const char *ifname,
5002                           const u8 *peer_addr, const u8 *go_dev_addr)
5003 {
5004         struct wpa_global *global = wpa_s->global;
5005         enum p2p_invite_role role;
5006         u8 *bssid = NULL;
5007         struct wpa_ssid *ssid;
5008         int persistent;
5009         int force_freq = 0, pref_freq = 0;
5010         int res;
5011
5012         wpa_s->p2p_persistent_go_freq = 0;
5013         wpa_s->p2p_go_ht40 = 0;
5014
5015         for (wpa_s = global->ifaces; wpa_s; wpa_s = wpa_s->next) {
5016                 if (os_strcmp(wpa_s->ifname, ifname) == 0)
5017                         break;
5018         }
5019         if (wpa_s == NULL) {
5020                 wpa_printf(MSG_DEBUG, "P2P: Interface '%s' not found", ifname);
5021                 return -1;
5022         }
5023
5024         ssid = wpa_s->current_ssid;
5025         if (ssid == NULL) {
5026                 wpa_printf(MSG_DEBUG, "P2P: No current SSID to use for "
5027                            "invitation");
5028                 return -1;
5029         }
5030
5031         wpa_s->global->p2p_invite_group = wpa_s;
5032         persistent = ssid->p2p_persistent_group &&
5033                 wpas_p2p_get_persistent(wpa_s->parent, peer_addr,
5034                                         ssid->ssid, ssid->ssid_len);
5035
5036         if (ssid->mode == WPAS_MODE_P2P_GO) {
5037                 role = P2P_INVITE_ROLE_ACTIVE_GO;
5038                 bssid = wpa_s->own_addr;
5039                 if (go_dev_addr == NULL)
5040                         go_dev_addr = wpa_s->global->p2p_dev_addr;
5041         } else {
5042                 role = P2P_INVITE_ROLE_CLIENT;
5043                 if (wpa_s->wpa_state < WPA_ASSOCIATED) {
5044                         wpa_printf(MSG_DEBUG, "P2P: Not associated - cannot "
5045                                    "invite to current group");
5046                         return -1;
5047                 }
5048                 bssid = wpa_s->bssid;
5049                 if (go_dev_addr == NULL &&
5050                     !is_zero_ether_addr(wpa_s->go_dev_addr))
5051                         go_dev_addr = wpa_s->go_dev_addr;
5052         }
5053         wpa_s->parent->pending_invite_ssid_id = -1;
5054
5055         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT)
5056                 return wpa_drv_p2p_invite(wpa_s, peer_addr, role, bssid,
5057                                           ssid->ssid, ssid->ssid_len,
5058                                           go_dev_addr, persistent);
5059
5060         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
5061                 return -1;
5062
5063         res = wpas_p2p_setup_freqs(wpa_s, 0, &force_freq, &pref_freq);
5064         if (res)
5065                 return res;
5066         wpas_p2p_set_own_freq_preference(wpa_s, force_freq);
5067
5068         return p2p_invite(wpa_s->global->p2p, peer_addr, role, bssid,
5069                           ssid->ssid, ssid->ssid_len, force_freq,
5070                           go_dev_addr, persistent, pref_freq);
5071 }
5072
5073
5074 void wpas_p2p_completed(struct wpa_supplicant *wpa_s)
5075 {
5076         struct wpa_ssid *ssid = wpa_s->current_ssid;
5077         const char *ssid_txt;
5078         u8 go_dev_addr[ETH_ALEN];
5079         int network_id = -1;
5080         int persistent;
5081         int freq;
5082
5083         if (ssid == NULL || ssid->mode != WPAS_MODE_P2P_GROUP_FORMATION) {
5084                 eloop_cancel_timeout(wpas_p2p_group_formation_timeout,
5085                                      wpa_s->parent, NULL);
5086         }
5087
5088         if (!wpa_s->show_group_started || !ssid)
5089                 goto done;
5090
5091         wpa_s->show_group_started = 0;
5092
5093         ssid_txt = wpa_ssid_txt(ssid->ssid, ssid->ssid_len);
5094         os_memset(go_dev_addr, 0, ETH_ALEN);
5095         if (ssid->bssid_set)
5096                 os_memcpy(go_dev_addr, ssid->bssid, ETH_ALEN);
5097         persistent = wpas_p2p_persistent_group(wpa_s, go_dev_addr, ssid->ssid,
5098                                                ssid->ssid_len);
5099         os_memcpy(wpa_s->go_dev_addr, go_dev_addr, ETH_ALEN);
5100
5101         if (wpa_s->global->p2p_group_formation == wpa_s)
5102                 wpa_s->global->p2p_group_formation = NULL;
5103
5104         freq = wpa_s->current_bss ? wpa_s->current_bss->freq :
5105                 (int) wpa_s->assoc_freq;
5106         if (ssid->passphrase == NULL && ssid->psk_set) {
5107                 char psk[65];
5108                 wpa_snprintf_hex(psk, sizeof(psk), ssid->psk, 32);
5109                 wpa_msg_global(wpa_s->parent, MSG_INFO, P2P_EVENT_GROUP_STARTED
5110                                "%s client ssid=\"%s\" freq=%d psk=%s "
5111                                "go_dev_addr=" MACSTR "%s",
5112                                wpa_s->ifname, ssid_txt, freq, psk,
5113                                MAC2STR(go_dev_addr),
5114                                persistent ? " [PERSISTENT]" : "");
5115         } else {
5116                 wpa_msg_global(wpa_s->parent, MSG_INFO, P2P_EVENT_GROUP_STARTED
5117                                "%s client ssid=\"%s\" freq=%d "
5118                                "passphrase=\"%s\" go_dev_addr=" MACSTR "%s",
5119                                wpa_s->ifname, ssid_txt, freq,
5120                                ssid->passphrase ? ssid->passphrase : "",
5121                                MAC2STR(go_dev_addr),
5122                                persistent ? " [PERSISTENT]" : "");
5123         }
5124
5125         if (persistent)
5126                 network_id = wpas_p2p_store_persistent_group(wpa_s->parent,
5127                                                              ssid, go_dev_addr);
5128         if (network_id < 0)
5129                 network_id = ssid->id;
5130         wpas_notify_p2p_group_started(wpa_s, ssid, network_id, 1);
5131
5132 done:
5133         wpas_p2p_continue_after_scan(wpa_s);
5134 }
5135
5136
5137 int wpas_p2p_presence_req(struct wpa_supplicant *wpa_s, u32 duration1,
5138                           u32 interval1, u32 duration2, u32 interval2)
5139 {
5140         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT)
5141                 return -1;
5142         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
5143                 return -1;
5144
5145         if (wpa_s->wpa_state < WPA_ASSOCIATED ||
5146             wpa_s->current_ssid == NULL ||
5147             wpa_s->current_ssid->mode != WPAS_MODE_INFRA)
5148                 return -1;
5149
5150         return p2p_presence_req(wpa_s->global->p2p, wpa_s->bssid,
5151                                 wpa_s->own_addr, wpa_s->assoc_freq,
5152                                 duration1, interval1, duration2, interval2);
5153 }
5154
5155
5156 int wpas_p2p_ext_listen(struct wpa_supplicant *wpa_s, unsigned int period,
5157                         unsigned int interval)
5158 {
5159         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT)
5160                 return -1;
5161
5162         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
5163                 return -1;
5164
5165         return p2p_ext_listen(wpa_s->global->p2p, period, interval);
5166 }
5167
5168
5169 static int wpas_p2p_is_client(struct wpa_supplicant *wpa_s)
5170 {
5171         if (wpa_s->current_ssid == NULL) {
5172                 /*
5173                  * current_ssid can be cleared when P2P client interface gets
5174                  * disconnected, so assume this interface was used as P2P
5175                  * client.
5176                  */
5177                 return 1;
5178         }
5179         return wpa_s->current_ssid->p2p_group &&
5180                 wpa_s->current_ssid->mode == WPAS_MODE_INFRA;
5181 }
5182
5183
5184 static void wpas_p2p_group_idle_timeout(void *eloop_ctx, void *timeout_ctx)
5185 {
5186         struct wpa_supplicant *wpa_s = eloop_ctx;
5187
5188         if (wpa_s->conf->p2p_group_idle == 0 && !wpas_p2p_is_client(wpa_s)) {
5189                 wpa_printf(MSG_DEBUG, "P2P: Ignore group idle timeout - "
5190                            "disabled");
5191                 return;
5192         }
5193
5194         wpa_printf(MSG_DEBUG, "P2P: Group idle timeout reached - terminate "
5195                    "group");
5196         wpas_p2p_group_delete(wpa_s, P2P_GROUP_REMOVAL_IDLE_TIMEOUT);
5197 }
5198
5199
5200 static void wpas_p2p_set_group_idle_timeout(struct wpa_supplicant *wpa_s)
5201 {
5202         int timeout;
5203
5204         if (eloop_cancel_timeout(wpas_p2p_group_idle_timeout, wpa_s, NULL) > 0)
5205                 wpa_printf(MSG_DEBUG, "P2P: Cancelled P2P group idle timeout");
5206
5207         if (wpa_s->current_ssid == NULL || !wpa_s->current_ssid->p2p_group)
5208                 return;
5209
5210         timeout = wpa_s->conf->p2p_group_idle;
5211         if (wpa_s->current_ssid->mode == WPAS_MODE_INFRA &&
5212             (timeout == 0 || timeout > P2P_MAX_CLIENT_IDLE))
5213             timeout = P2P_MAX_CLIENT_IDLE;
5214
5215         if (timeout == 0)
5216                 return;
5217
5218         if (timeout < 0) {
5219                 if (wpa_s->current_ssid->mode == WPAS_MODE_INFRA)
5220                         timeout = 0; /* special client mode no-timeout */
5221                 else
5222                         return;
5223         }
5224
5225         if (wpa_s->p2p_in_provisioning) {
5226                 /*
5227                  * Use the normal group formation timeout during the
5228                  * provisioning phase to avoid terminating this process too
5229                  * early due to group idle timeout.
5230                  */
5231                 wpa_printf(MSG_DEBUG, "P2P: Do not use P2P group idle timeout "
5232                            "during provisioning");
5233                 return;
5234         }
5235
5236         if (wpa_s->show_group_started) {
5237                 /*
5238                  * Use the normal group formation timeout between the end of
5239                  * the provisioning phase and completion of 4-way handshake to
5240                  * avoid terminating this process too early due to group idle
5241                  * timeout.
5242                  */
5243                 wpa_printf(MSG_DEBUG, "P2P: Do not use P2P group idle timeout "
5244                            "while waiting for initial 4-way handshake to "
5245                            "complete");
5246                 return;
5247         }
5248
5249         wpa_printf(MSG_DEBUG, "P2P: Set P2P group idle timeout to %u seconds",
5250                    timeout);
5251         eloop_register_timeout(timeout, 0, wpas_p2p_group_idle_timeout,
5252                                wpa_s, NULL);
5253 }
5254
5255
5256 /* Returns 1 if the interface was removed */
5257 int wpas_p2p_deauth_notif(struct wpa_supplicant *wpa_s, const u8 *bssid,
5258                           u16 reason_code, const u8 *ie, size_t ie_len,
5259                           int locally_generated)
5260 {
5261         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
5262                 return 0;
5263         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT)
5264                 return 0;
5265
5266         if (!locally_generated)
5267                 p2p_deauth_notif(wpa_s->global->p2p, bssid, reason_code, ie,
5268                                  ie_len);
5269
5270         if (reason_code == WLAN_REASON_DEAUTH_LEAVING && !locally_generated &&
5271             wpa_s->current_ssid &&
5272             wpa_s->current_ssid->p2p_group &&
5273             wpa_s->current_ssid->mode == WPAS_MODE_INFRA) {
5274                 wpa_printf(MSG_DEBUG, "P2P: GO indicated that the P2P Group "
5275                            "session is ending");
5276                 if (wpas_p2p_group_delete(wpa_s,
5277                                           P2P_GROUP_REMOVAL_GO_ENDING_SESSION)
5278                     > 0)
5279                         return 1;
5280         }
5281
5282         return 0;
5283 }
5284
5285
5286 void wpas_p2p_disassoc_notif(struct wpa_supplicant *wpa_s, const u8 *bssid,
5287                              u16 reason_code, const u8 *ie, size_t ie_len,
5288                              int locally_generated)
5289 {
5290         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
5291                 return;
5292         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT)
5293                 return;
5294
5295         if (!locally_generated)
5296                 p2p_disassoc_notif(wpa_s->global->p2p, bssid, reason_code, ie,
5297                                    ie_len);
5298 }
5299
5300
5301 void wpas_p2p_update_config(struct wpa_supplicant *wpa_s)
5302 {
5303         struct p2p_data *p2p = wpa_s->global->p2p;
5304
5305         if (p2p == NULL)
5306                 return;
5307
5308         if (!(wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_CAPABLE))
5309                 return;
5310
5311         if (wpa_s->conf->changed_parameters & CFG_CHANGED_DEVICE_NAME)
5312                 p2p_set_dev_name(p2p, wpa_s->conf->device_name);
5313
5314         if (wpa_s->conf->changed_parameters & CFG_CHANGED_DEVICE_TYPE)
5315                 p2p_set_pri_dev_type(p2p, wpa_s->conf->device_type);
5316
5317         if (wpa_s->wps &&
5318             (wpa_s->conf->changed_parameters & CFG_CHANGED_CONFIG_METHODS))
5319                 p2p_set_config_methods(p2p, wpa_s->wps->config_methods);
5320
5321         if (wpa_s->wps && (wpa_s->conf->changed_parameters & CFG_CHANGED_UUID))
5322                 p2p_set_uuid(p2p, wpa_s->wps->uuid);
5323
5324         if (wpa_s->conf->changed_parameters & CFG_CHANGED_WPS_STRING) {
5325                 p2p_set_manufacturer(p2p, wpa_s->conf->manufacturer);
5326                 p2p_set_model_name(p2p, wpa_s->conf->model_name);
5327                 p2p_set_model_number(p2p, wpa_s->conf->model_number);
5328                 p2p_set_serial_number(p2p, wpa_s->conf->serial_number);
5329         }
5330
5331         if (wpa_s->conf->changed_parameters & CFG_CHANGED_SEC_DEVICE_TYPE)
5332                 p2p_set_sec_dev_types(p2p,
5333                                       (void *) wpa_s->conf->sec_device_type,
5334                                       wpa_s->conf->num_sec_device_types);
5335
5336         if (wpa_s->conf->changed_parameters & CFG_CHANGED_VENDOR_EXTENSION) {
5337                 int i;
5338                 p2p_remove_wps_vendor_extensions(p2p);
5339                 for (i = 0; i < MAX_WPS_VENDOR_EXT; i++) {
5340                         if (wpa_s->conf->wps_vendor_ext[i] == NULL)
5341                                 continue;
5342                         p2p_add_wps_vendor_extension(
5343                                 p2p, wpa_s->conf->wps_vendor_ext[i]);
5344                 }
5345         }
5346
5347         if ((wpa_s->conf->changed_parameters & CFG_CHANGED_COUNTRY) &&
5348             wpa_s->conf->country[0] && wpa_s->conf->country[1]) {
5349                 char country[3];
5350                 country[0] = wpa_s->conf->country[0];
5351                 country[1] = wpa_s->conf->country[1];
5352                 country[2] = 0x04;
5353                 p2p_set_country(p2p, country);
5354         }
5355
5356         if (wpa_s->conf->changed_parameters & CFG_CHANGED_P2P_SSID_POSTFIX) {
5357                 p2p_set_ssid_postfix(p2p, (u8 *) wpa_s->conf->p2p_ssid_postfix,
5358                                      wpa_s->conf->p2p_ssid_postfix ?
5359                                      os_strlen(wpa_s->conf->p2p_ssid_postfix) :
5360                                      0);
5361         }
5362
5363         if (wpa_s->conf->changed_parameters & CFG_CHANGED_P2P_INTRA_BSS)
5364                 p2p_set_intra_bss_dist(p2p, wpa_s->conf->p2p_intra_bss);
5365
5366         if (wpa_s->conf->changed_parameters & CFG_CHANGED_P2P_LISTEN_CHANNEL) {
5367                 u8 reg_class, channel;
5368                 int ret;
5369                 unsigned int r;
5370                 if (wpa_s->conf->p2p_listen_reg_class &&
5371                     wpa_s->conf->p2p_listen_channel) {
5372                         reg_class = wpa_s->conf->p2p_listen_reg_class;
5373                         channel = wpa_s->conf->p2p_listen_channel;
5374                 } else {
5375                         reg_class = 81;
5376                         /*
5377                          * Pick one of the social channels randomly as the
5378                          * listen channel.
5379                          */
5380                         os_get_random((u8 *) &r, sizeof(r));
5381                         channel = 1 + (r % 3) * 5;
5382                 }
5383                 ret = p2p_set_listen_channel(p2p, reg_class, channel);
5384                 if (ret)
5385                         wpa_printf(MSG_ERROR, "P2P: Own listen channel update "
5386                                    "failed: %d", ret);
5387         }
5388         if (wpa_s->conf->changed_parameters & CFG_CHANGED_P2P_OPER_CHANNEL) {
5389                 u8 op_reg_class, op_channel, cfg_op_channel;
5390                 int ret = 0;
5391                 unsigned int r;
5392                 if (wpa_s->conf->p2p_oper_reg_class &&
5393                     wpa_s->conf->p2p_oper_channel) {
5394                         op_reg_class = wpa_s->conf->p2p_oper_reg_class;
5395                         op_channel = wpa_s->conf->p2p_oper_channel;
5396                         cfg_op_channel = 1;
5397                 } else {
5398                         op_reg_class = 81;
5399                         /*
5400                          * Use random operation channel from (1, 6, 11)
5401                          *if no other preference is indicated.
5402                          */
5403                         os_get_random((u8 *) &r, sizeof(r));
5404                         op_channel = 1 + (r % 3) * 5;
5405                         cfg_op_channel = 0;
5406                 }
5407                 ret = p2p_set_oper_channel(p2p, op_reg_class, op_channel,
5408                                            cfg_op_channel);
5409                 if (ret)
5410                         wpa_printf(MSG_ERROR, "P2P: Own oper channel update "
5411                                    "failed: %d", ret);
5412         }
5413
5414         if (wpa_s->conf->changed_parameters & CFG_CHANGED_P2P_PREF_CHAN) {
5415                 if (p2p_set_pref_chan(p2p, wpa_s->conf->num_p2p_pref_chan,
5416                                       wpa_s->conf->p2p_pref_chan) < 0) {
5417                         wpa_printf(MSG_ERROR, "P2P: Preferred channel list "
5418                                    "update failed");
5419                 }
5420         }
5421 }
5422
5423
5424 int wpas_p2p_set_noa(struct wpa_supplicant *wpa_s, u8 count, int start,
5425                      int duration)
5426 {
5427         if (!wpa_s->ap_iface)
5428                 return -1;
5429         return hostapd_p2p_set_noa(wpa_s->ap_iface->bss[0], count, start,
5430                                    duration);
5431 }
5432
5433
5434 int wpas_p2p_set_cross_connect(struct wpa_supplicant *wpa_s, int enabled)
5435 {
5436         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
5437                 return -1;
5438         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT)
5439                 return -1;
5440
5441         wpa_s->global->cross_connection = enabled;
5442         p2p_set_cross_connect(wpa_s->global->p2p, enabled);
5443
5444         if (!enabled) {
5445                 struct wpa_supplicant *iface;
5446
5447                 for (iface = wpa_s->global->ifaces; iface; iface = iface->next)
5448                 {
5449                         if (iface->cross_connect_enabled == 0)
5450                                 continue;
5451
5452                         iface->cross_connect_enabled = 0;
5453                         iface->cross_connect_in_use = 0;
5454                         wpa_msg_global(iface->parent, MSG_INFO,
5455                                        P2P_EVENT_CROSS_CONNECT_DISABLE "%s %s",
5456                                        iface->ifname,
5457                                        iface->cross_connect_uplink);
5458                 }
5459         }
5460
5461         return 0;
5462 }
5463
5464
5465 static void wpas_p2p_enable_cross_connect(struct wpa_supplicant *uplink)
5466 {
5467         struct wpa_supplicant *iface;
5468
5469         if (!uplink->global->cross_connection)
5470                 return;
5471
5472         for (iface = uplink->global->ifaces; iface; iface = iface->next) {
5473                 if (!iface->cross_connect_enabled)
5474                         continue;
5475                 if (os_strcmp(uplink->ifname, iface->cross_connect_uplink) !=
5476                     0)
5477                         continue;
5478                 if (iface->ap_iface == NULL)
5479                         continue;
5480                 if (iface->cross_connect_in_use)
5481                         continue;
5482
5483                 iface->cross_connect_in_use = 1;
5484                 wpa_msg_global(iface->parent, MSG_INFO,
5485                                P2P_EVENT_CROSS_CONNECT_ENABLE "%s %s",
5486                                iface->ifname, iface->cross_connect_uplink);
5487         }
5488 }
5489
5490
5491 static void wpas_p2p_disable_cross_connect(struct wpa_supplicant *uplink)
5492 {
5493         struct wpa_supplicant *iface;
5494
5495         for (iface = uplink->global->ifaces; iface; iface = iface->next) {
5496                 if (!iface->cross_connect_enabled)
5497                         continue;
5498                 if (os_strcmp(uplink->ifname, iface->cross_connect_uplink) !=
5499                     0)
5500                         continue;
5501                 if (!iface->cross_connect_in_use)
5502                         continue;
5503
5504                 wpa_msg_global(iface->parent, MSG_INFO,
5505                                P2P_EVENT_CROSS_CONNECT_DISABLE "%s %s",
5506                                iface->ifname, iface->cross_connect_uplink);
5507                 iface->cross_connect_in_use = 0;
5508         }
5509 }
5510
5511
5512 void wpas_p2p_notif_connected(struct wpa_supplicant *wpa_s)
5513 {
5514         if (wpa_s->ap_iface || wpa_s->current_ssid == NULL ||
5515             wpa_s->current_ssid->mode != WPAS_MODE_INFRA ||
5516             wpa_s->cross_connect_disallowed)
5517                 wpas_p2p_disable_cross_connect(wpa_s);
5518         else
5519                 wpas_p2p_enable_cross_connect(wpa_s);
5520         if (!wpa_s->ap_iface &&
5521             eloop_cancel_timeout(wpas_p2p_group_idle_timeout, wpa_s, NULL) > 0)
5522                 wpa_printf(MSG_DEBUG, "P2P: Cancelled P2P group idle timeout");
5523 }
5524
5525
5526 void wpas_p2p_notif_disconnected(struct wpa_supplicant *wpa_s)
5527 {
5528         wpas_p2p_disable_cross_connect(wpa_s);
5529         if (!wpa_s->ap_iface &&
5530             !eloop_is_timeout_registered(wpas_p2p_group_idle_timeout,
5531                                          wpa_s, NULL))
5532                 wpas_p2p_set_group_idle_timeout(wpa_s);
5533 }
5534
5535
5536 static void wpas_p2p_cross_connect_setup(struct wpa_supplicant *wpa_s)
5537 {
5538         struct wpa_supplicant *iface;
5539
5540         if (!wpa_s->global->cross_connection)
5541                 return;
5542
5543         for (iface = wpa_s->global->ifaces; iface; iface = iface->next) {
5544                 if (iface == wpa_s)
5545                         continue;
5546                 if (iface->drv_flags &
5547                     WPA_DRIVER_FLAGS_P2P_DEDICATED_INTERFACE)
5548                         continue;
5549                 if (iface->drv_flags & WPA_DRIVER_FLAGS_P2P_CAPABLE)
5550                         continue;
5551
5552                 wpa_s->cross_connect_enabled = 1;
5553                 os_strlcpy(wpa_s->cross_connect_uplink, iface->ifname,
5554                            sizeof(wpa_s->cross_connect_uplink));
5555                 wpa_printf(MSG_DEBUG, "P2P: Enable cross connection from "
5556                            "%s to %s whenever uplink is available",
5557                            wpa_s->ifname, wpa_s->cross_connect_uplink);
5558
5559                 if (iface->ap_iface || iface->current_ssid == NULL ||
5560                     iface->current_ssid->mode != WPAS_MODE_INFRA ||
5561                     iface->cross_connect_disallowed ||
5562                     iface->wpa_state != WPA_COMPLETED)
5563                         break;
5564
5565                 wpa_s->cross_connect_in_use = 1;
5566                 wpa_msg_global(wpa_s->parent, MSG_INFO,
5567                                P2P_EVENT_CROSS_CONNECT_ENABLE "%s %s",
5568                                wpa_s->ifname, wpa_s->cross_connect_uplink);
5569                 break;
5570         }
5571 }
5572
5573
5574 int wpas_p2p_notif_pbc_overlap(struct wpa_supplicant *wpa_s)
5575 {
5576         if (wpa_s->p2p_group_interface != P2P_GROUP_INTERFACE_CLIENT &&
5577             !wpa_s->p2p_in_provisioning)
5578                 return 0; /* not P2P client operation */
5579
5580         wpa_printf(MSG_DEBUG, "P2P: Terminate connection due to WPS PBC "
5581                    "session overlap");
5582         if (wpa_s != wpa_s->parent)
5583                 wpa_msg_ctrl(wpa_s->parent, MSG_INFO, WPS_EVENT_OVERLAP);
5584         wpas_p2p_group_formation_failed(wpa_s);
5585         return 1;
5586 }
5587
5588
5589 void wpas_p2p_update_channel_list(struct wpa_supplicant *wpa_s)
5590 {
5591         struct p2p_channels chan;
5592
5593         if (wpa_s->global == NULL || wpa_s->global->p2p == NULL)
5594                 return;
5595
5596         os_memset(&chan, 0, sizeof(chan));
5597         if (wpas_p2p_setup_channels(wpa_s, &chan)) {
5598                 wpa_printf(MSG_ERROR, "P2P: Failed to update supported "
5599                            "channel list");
5600                 return;
5601         }
5602
5603         p2p_update_channel_list(wpa_s->global->p2p, &chan);
5604 }
5605
5606
5607 static void wpas_p2p_scan_res_ignore(struct wpa_supplicant *wpa_s,
5608                                      struct wpa_scan_results *scan_res)
5609 {
5610         wpa_printf(MSG_DEBUG, "P2P: Ignore scan results");
5611 }
5612
5613
5614 int wpas_p2p_cancel(struct wpa_supplicant *wpa_s)
5615 {
5616         struct wpa_global *global = wpa_s->global;
5617         int found = 0;
5618         const u8 *peer;
5619
5620         if (global->p2p == NULL)
5621                 return -1;
5622
5623         wpa_printf(MSG_DEBUG, "P2P: Request to cancel group formation");
5624
5625         if (wpa_s->pending_interface_name[0] &&
5626             !is_zero_ether_addr(wpa_s->pending_interface_addr))
5627                 found = 1;
5628
5629         peer = p2p_get_go_neg_peer(global->p2p);
5630         if (peer) {
5631                 wpa_printf(MSG_DEBUG, "P2P: Unauthorize pending GO Neg peer "
5632                            MACSTR, MAC2STR(peer));
5633                 p2p_unauthorize(global->p2p, peer);
5634                 found = 1;
5635         }
5636
5637         if (wpa_s->scan_res_handler == wpas_p2p_scan_res_join) {
5638                 wpa_printf(MSG_DEBUG, "P2P: Stop pending scan for join");
5639                 wpa_s->scan_res_handler = wpas_p2p_scan_res_ignore;
5640                 found = 1;
5641         }
5642
5643         if (wpa_s->pending_pd_before_join) {
5644                 wpa_printf(MSG_DEBUG, "P2P: Stop pending PD before join");
5645                 wpa_s->pending_pd_before_join = 0;
5646                 found = 1;
5647         }
5648
5649         wpas_p2p_stop_find(wpa_s);
5650
5651         for (wpa_s = global->ifaces; wpa_s; wpa_s = wpa_s->next) {
5652                 if (wpa_s == global->p2p_group_formation &&
5653                     (wpa_s->p2p_in_provisioning ||
5654                      wpa_s->parent->pending_interface_type ==
5655                      WPA_IF_P2P_CLIENT)) {
5656                         wpa_printf(MSG_DEBUG, "P2P: Interface %s in group "
5657                                    "formation found - cancelling",
5658                                    wpa_s->ifname);
5659                         found = 1;
5660                         eloop_cancel_timeout(wpas_p2p_group_formation_timeout,
5661                                              wpa_s->parent, NULL);
5662                         if (wpa_s->p2p_in_provisioning) {
5663                                 wpas_group_formation_completed(wpa_s, 0);
5664                                 break;
5665                         }
5666                         wpas_p2p_group_delete(wpa_s,
5667                                               P2P_GROUP_REMOVAL_REQUESTED);
5668                         break;
5669                 }
5670         }
5671
5672         if (!found) {
5673                 wpa_printf(MSG_DEBUG, "P2P: No ongoing group formation found");
5674                 return -1;
5675         }
5676
5677         return 0;
5678 }
5679
5680
5681 void wpas_p2p_interface_unavailable(struct wpa_supplicant *wpa_s)
5682 {
5683         if (wpa_s->current_ssid == NULL || !wpa_s->current_ssid->p2p_group)
5684                 return;
5685
5686         wpa_printf(MSG_DEBUG, "P2P: Remove group due to driver resource not "
5687                    "being available anymore");
5688         wpas_p2p_group_delete(wpa_s, P2P_GROUP_REMOVAL_UNAVAILABLE);
5689 }
5690
5691
5692 void wpas_p2p_update_best_channels(struct wpa_supplicant *wpa_s,
5693                                    int freq_24, int freq_5, int freq_overall)
5694 {
5695         struct p2p_data *p2p = wpa_s->global->p2p;
5696         if (p2p == NULL || (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT))
5697                 return;
5698         p2p_set_best_channels(p2p, freq_24, freq_5, freq_overall);
5699 }
5700
5701
5702 int wpas_p2p_unauthorize(struct wpa_supplicant *wpa_s, const char *addr)
5703 {
5704         u8 peer[ETH_ALEN];
5705         struct p2p_data *p2p = wpa_s->global->p2p;
5706
5707         if (p2p == NULL || (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT))
5708                 return -1;
5709
5710         if (hwaddr_aton(addr, peer))
5711                 return -1;
5712
5713         return p2p_unauthorize(p2p, peer);
5714 }
5715
5716
5717 /**
5718  * wpas_p2p_disconnect - Disconnect from a P2P Group
5719  * @wpa_s: Pointer to wpa_supplicant data
5720  * Returns: 0 on success, -1 on failure
5721  *
5722  * This can be used to disconnect from a group in which the local end is a P2P
5723  * Client or to end a P2P Group in case the local end is the Group Owner. If a
5724  * virtual network interface was created for this group, that interface will be
5725  * removed. Otherwise, only the configured P2P group network will be removed
5726  * from the interface.
5727  */
5728 int wpas_p2p_disconnect(struct wpa_supplicant *wpa_s)
5729 {
5730
5731         if (wpa_s == NULL)
5732                 return -1;
5733
5734         return wpas_p2p_group_delete(wpa_s, P2P_GROUP_REMOVAL_REQUESTED) < 0 ?
5735                 -1 : 0;
5736 }
5737
5738
5739 int wpas_p2p_in_progress(struct wpa_supplicant *wpa_s)
5740 {
5741         int ret;
5742
5743         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
5744                 return 0;
5745
5746         ret = p2p_in_progress(wpa_s->global->p2p);
5747         if (ret == 0) {
5748                 /*
5749                  * Check whether there is an ongoing WPS provisioning step (or
5750                  * other parts of group formation) on another interface since
5751                  * p2p_in_progress() does not report this to avoid issues for
5752                  * scans during such provisioning step.
5753                  */
5754                 if (wpa_s->global->p2p_group_formation &&
5755                     wpa_s->global->p2p_group_formation != wpa_s) {
5756                         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Another interface (%s) "
5757                                 "in group formation",
5758                                 wpa_s->global->p2p_group_formation->ifname);
5759                         ret = 1;
5760                 }
5761         }
5762
5763         return ret;
5764 }
5765
5766
5767 void wpas_p2p_network_removed(struct wpa_supplicant *wpa_s,
5768                               struct wpa_ssid *ssid)
5769 {
5770         if (wpa_s->p2p_in_provisioning && ssid->p2p_group &&
5771             eloop_cancel_timeout(wpas_p2p_group_formation_timeout,
5772                                  wpa_s->parent, NULL) > 0) {
5773                 /**
5774                  * Remove the network by scheduling the group formation
5775                  * timeout to happen immediately. The teardown code
5776                  * needs to be scheduled to run asynch later so that we
5777                  * don't delete data from under ourselves unexpectedly.
5778                  * Calling wpas_p2p_group_formation_timeout directly
5779                  * causes a series of crashes in WPS failure scenarios.
5780                  */
5781                 wpa_printf(MSG_DEBUG, "P2P: Canceled group formation due to "
5782                            "P2P group network getting removed");
5783                 eloop_register_timeout(0, 0, wpas_p2p_group_formation_timeout,
5784                                        wpa_s->parent, NULL);
5785         }
5786 }
5787
5788
5789 struct wpa_ssid * wpas_p2p_get_persistent(struct wpa_supplicant *wpa_s,
5790                                           const u8 *addr, const u8 *ssid,
5791                                           size_t ssid_len)
5792 {
5793         struct wpa_ssid *s;
5794         size_t i;
5795
5796         for (s = wpa_s->conf->ssid; s; s = s->next) {
5797                 if (s->disabled != 2)
5798                         continue;
5799                 if (ssid &&
5800                     (ssid_len != s->ssid_len ||
5801                      os_memcmp(ssid, s->ssid, ssid_len) != 0))
5802                         continue;
5803                 if (os_memcmp(s->bssid, addr, ETH_ALEN) == 0)
5804                         return s; /* peer is GO in the persistent group */
5805                 if (s->mode != WPAS_MODE_P2P_GO || s->p2p_client_list == NULL)
5806                         continue;
5807                 for (i = 0; i < s->num_p2p_clients; i++) {
5808                         if (os_memcmp(s->p2p_client_list + i * ETH_ALEN,
5809                                       addr, ETH_ALEN) == 0)
5810                                 return s; /* peer is P2P client in persistent
5811                                            * group */
5812                 }
5813         }
5814
5815         return NULL;
5816 }
5817
5818
5819 void wpas_p2p_notify_ap_sta_authorized(struct wpa_supplicant *wpa_s,
5820                                        const u8 *addr)
5821 {
5822         if (addr == NULL)
5823                 return;
5824         wpas_p2p_add_persistent_group_client(wpa_s, addr);
5825 }
5826
5827
5828 static void wpas_p2p_fallback_to_go_neg(struct wpa_supplicant *wpa_s,
5829                                         int group_added)
5830 {
5831         struct wpa_supplicant *group = wpa_s;
5832         if (wpa_s->global->p2p_group_formation)
5833                 group = wpa_s->global->p2p_group_formation;
5834         wpa_s = wpa_s->parent;
5835         offchannel_send_action_done(wpa_s);
5836         if (group_added)
5837                 wpas_p2p_group_delete(group, P2P_GROUP_REMOVAL_SILENT);
5838         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Fall back to GO Negotiation");
5839         wpas_p2p_connect(wpa_s, wpa_s->pending_join_dev_addr, wpa_s->p2p_pin,
5840                          wpa_s->p2p_wps_method, wpa_s->p2p_persistent_group, 0,
5841                          0, 0, wpa_s->p2p_go_intent, wpa_s->p2p_connect_freq,
5842                          wpa_s->p2p_persistent_id,
5843                          wpa_s->p2p_pd_before_go_neg,
5844                          wpa_s->p2p_go_ht40);
5845 }
5846
5847
5848 int wpas_p2p_scan_no_go_seen(struct wpa_supplicant *wpa_s)
5849 {
5850         if (!wpa_s->p2p_fallback_to_go_neg ||
5851             wpa_s->p2p_in_provisioning <= 5)
5852                 return 0;
5853
5854         if (wpas_p2p_peer_go(wpa_s, wpa_s->pending_join_dev_addr) > 0)
5855                 return 0; /* peer operating as a GO */
5856
5857         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: GO not found for p2p_connect-auto - "
5858                 "fallback to GO Negotiation");
5859         wpas_p2p_fallback_to_go_neg(wpa_s, 1);
5860
5861         return 1;
5862 }
5863
5864
5865 unsigned int wpas_p2p_search_delay(struct wpa_supplicant *wpa_s)
5866 {
5867         const char *rn, *rn2;
5868         struct wpa_supplicant *ifs;
5869
5870         if (wpa_s->wpa_state > WPA_SCANNING) {
5871                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Use %u ms search delay due to "
5872                         "concurrent operation",
5873                         P2P_CONCURRENT_SEARCH_DELAY);
5874                 return P2P_CONCURRENT_SEARCH_DELAY;
5875         }
5876
5877         if (!wpa_s->driver->get_radio_name)
5878                 return 0;
5879         rn = wpa_s->driver->get_radio_name(wpa_s->drv_priv);
5880         if (rn == NULL || rn[0] == '\0')
5881                 return 0;
5882
5883         for (ifs = wpa_s->global->ifaces; ifs; ifs = ifs->next) {
5884                 if (ifs == wpa_s || !ifs->driver->get_radio_name)
5885                         continue;
5886
5887                 rn2 = ifs->driver->get_radio_name(ifs->drv_priv);
5888                 if (!rn2 || os_strcmp(rn, rn2) != 0)
5889                         continue;
5890                 if (ifs->wpa_state > WPA_SCANNING) {
5891                         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Use %u ms search "
5892                                 "delay due to concurrent operation on "
5893                                 "interface %s",
5894                                 P2P_CONCURRENT_SEARCH_DELAY, ifs->ifname);
5895                         return P2P_CONCURRENT_SEARCH_DELAY;
5896                 }
5897         }
5898
5899         return 0;
5900 }
5901
5902
5903 void wpas_p2p_continue_after_scan(struct wpa_supplicant *wpa_s)
5904 {
5905         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Station mode scan operation not "
5906                 "pending anymore (sta_scan_pending=%d "
5907                 "p2p_cb_on_scan_complete=%d)", wpa_s->sta_scan_pending,
5908                 wpa_s->global->p2p_cb_on_scan_complete);
5909         wpa_s->sta_scan_pending = 0;
5910
5911         if (!wpa_s->global->p2p_cb_on_scan_complete)
5912                 return;
5913         wpa_s->global->p2p_cb_on_scan_complete = 0;
5914
5915         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
5916                 return;
5917
5918         if (p2p_other_scan_completed(wpa_s->global->p2p) == 1) {
5919                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Pending P2P operation "
5920                         "continued after successful connection");
5921                 p2p_increase_search_delay(wpa_s->global->p2p,
5922                                           wpas_p2p_search_delay(wpa_s));
5923         }
5924 }