WPS ER: Fix Enrollee entry freeing on timeout
[libeap.git] / src / wps / wps_er.c
1 /*
2  * Wi-Fi Protected Setup - External Registrar
3  * Copyright (c) 2009, Jouni Malinen <j@w1.fi>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License version 2 as
7  * published by the Free Software Foundation.
8  *
9  * Alternatively, this software may be distributed under the terms of BSD
10  * license.
11  *
12  * See README and COPYING for more details.
13  */
14
15 #include "includes.h"
16
17 #include "common.h"
18 #include "base64.h"
19 #include "uuid.h"
20 #include "eloop.h"
21 #include "httpread.h"
22 #include "http_client.h"
23 #include "http_server.h"
24 #include "upnp_xml.h"
25 #include "wps_i.h"
26 #include "wps_upnp.h"
27 #include "wps_upnp_i.h"
28
29
30 /* TODO:
31  * send notification of new AP device with wpa_msg
32  * re-send notifications with wpa_msg if ER re-started (to update wpa_gui-qt4)
33  * (also re-send SSDP M-SEARCH in this case to find new APs)
34  * parse UPnP event messages
35  */
36
37 static void wps_er_ap_timeout(void *eloop_data, void *user_ctx);
38 static void wps_er_sta_timeout(void *eloop_data, void *user_ctx);
39
40
41 struct wps_er_sta {
42         struct wps_er_sta *next;
43         struct wps_er_ap *ap;
44         u8 addr[ETH_ALEN];
45         u16 config_methods;
46         u8 uuid[WPS_UUID_LEN];
47         u8 pri_dev_type[8];
48         u16 dev_passwd_id;
49         int m1_received;
50         char *manufacturer;
51         char *model_name;
52         char *model_number;
53         char *serial_number;
54         char *dev_name;
55         struct wps_data *wps;
56         struct http_client *http;
57 };
58
59 struct wps_er_ap {
60         struct wps_er_ap *next;
61         struct wps_er *er;
62         struct wps_er_sta *sta; /* list of STAs/Enrollees using this AP */
63         struct in_addr addr;
64         char *location;
65         struct http_client *http;
66         struct wps_data *wps;
67
68         u8 uuid[WPS_UUID_LEN];
69         char *friendly_name;
70         char *manufacturer;
71         char *manufacturer_url;
72         char *model_description;
73         char *model_name;
74         char *model_number;
75         char *model_url;
76         char *serial_number;
77         char *udn;
78         char *upc;
79
80         char *scpd_url;
81         char *control_url;
82         char *event_sub_url;
83
84         int subscribed;
85         unsigned int id;
86
87         struct wps_credential *ap_settings;
88 };
89
90 struct wps_er {
91         struct wps_context *wps;
92         char ifname[17];
93         char *mac_addr_text; /* mac addr of network i.f. we use */
94         u8 mac_addr[ETH_ALEN]; /* mac addr of network i.f. we use */
95         char *ip_addr_text; /* IP address of network i.f. we use */
96         unsigned ip_addr; /* IP address of network i.f. we use (host order) */
97         int multicast_sd;
98         int ssdp_sd;
99         struct wps_er_ap *ap;
100         struct http_server *http_srv;
101         int http_port;
102         unsigned int next_ap_id;
103 };
104
105
106 static void wps_er_ap_process(struct wps_er_ap *ap, struct wpabuf *msg);
107
108
109 static void wps_er_sta_event(struct wps_context *wps, struct wps_er_sta *sta,
110                              enum wps_event event)
111 {
112         union wps_event_data data;
113         struct wps_event_er_enrollee *ev = &data.enrollee;
114
115         if (wps->event_cb == NULL)
116                 return;
117
118         os_memset(&data, 0, sizeof(data));
119         ev->uuid = sta->uuid;
120         ev->mac_addr = sta->addr;
121         ev->m1_received = sta->m1_received;
122         ev->config_methods = sta->config_methods;
123         ev->dev_passwd_id = sta->dev_passwd_id;
124         ev->pri_dev_type = sta->pri_dev_type;
125         ev->dev_name = sta->dev_name;
126         ev->manufacturer = sta->manufacturer;
127         ev->model_name = sta->model_name;
128         ev->model_number = sta->model_number;
129         ev->serial_number = sta->serial_number;
130         wps->event_cb(wps->cb_ctx, event, &data);
131 }
132
133
134 static struct wps_er_sta * wps_er_sta_get(struct wps_er_ap *ap, const u8 *addr)
135 {
136         struct wps_er_sta *sta = ap->sta;
137         while (sta) {
138                 if (os_memcmp(sta->addr, addr, ETH_ALEN) == 0)
139                         return sta;
140                 sta = sta->next;
141         }
142         return NULL;
143 }
144
145
146 static void wps_er_sta_free(struct wps_er_sta *sta)
147 {
148         wps_er_sta_event(sta->ap->er->wps, sta, WPS_EV_ER_ENROLLEE_REMOVE);
149         if (sta->wps)
150                 wps_deinit(sta->wps);
151         os_free(sta->manufacturer);
152         os_free(sta->model_name);
153         os_free(sta->model_number);
154         os_free(sta->serial_number);
155         os_free(sta->dev_name);
156         http_client_free(sta->http);
157         eloop_cancel_timeout(wps_er_sta_timeout, sta, NULL);
158         os_free(sta);
159 }
160
161
162 static void wps_er_sta_remove_all(struct wps_er_ap *ap)
163 {
164         struct wps_er_sta *prev, *sta;
165
166         sta = ap->sta;
167         ap->sta = NULL;
168
169         while (sta) {
170                 prev = sta;
171                 sta = sta->next;
172                 wps_er_sta_free(prev);
173         }
174 }
175
176
177 static struct wps_er_ap * wps_er_ap_get(struct wps_er *er,
178                                         struct in_addr *addr)
179 {
180         struct wps_er_ap *ap;
181         for (ap = er->ap; ap; ap = ap->next) {
182                 if (ap->addr.s_addr == addr->s_addr)
183                         break;
184         }
185         return ap;
186 }
187
188
189 static struct wps_er_ap * wps_er_ap_get_uuid(struct wps_er *er, const u8 *uuid)
190 {
191         struct wps_er_ap *ap;
192         for (ap = er->ap; ap; ap = ap->next) {
193                 if (os_memcmp(uuid, ap->uuid, WPS_UUID_LEN) == 0)
194                         break;
195         }
196         return ap;
197 }
198
199
200 static struct wps_er_ap * wps_er_ap_get_id(struct wps_er *er, unsigned int id)
201 {
202         struct wps_er_ap *ap;
203         for (ap = er->ap; ap; ap = ap->next) {
204                 if (ap->id == id)
205                         break;
206         }
207         return ap;
208 }
209
210
211 static void wps_er_ap_event(struct wps_context *wps, struct wps_er_ap *ap,
212                             enum wps_event event)
213 {
214         union wps_event_data data;
215         struct wps_event_er_ap *evap = &data.ap;
216
217         if (wps->event_cb == NULL)
218                 return;
219
220         os_memset(&data, 0, sizeof(data));
221         evap->uuid = ap->uuid;
222         evap->friendly_name = ap->friendly_name;
223         evap->manufacturer = ap->manufacturer;
224         evap->manufacturer_url = ap->manufacturer_url;
225         evap->model_description = ap->model_description;
226         evap->model_name = ap->model_name;
227         evap->model_number = ap->model_number;
228         evap->model_url = ap->model_url;
229         evap->serial_number = ap->serial_number;
230         evap->upc = ap->upc;
231         wps->event_cb(wps->cb_ctx, event, &data);
232 }
233
234
235 static void wps_er_ap_free(struct wps_er *er, struct wps_er_ap *ap)
236 {
237         /* TODO: if ap->subscribed, unsubscribe from events if the AP is still
238          * alive */
239         wpa_printf(MSG_DEBUG, "WPS ER: Removing AP entry for %s (%s)",
240                    inet_ntoa(ap->addr), ap->location);
241         eloop_cancel_timeout(wps_er_ap_timeout, er, ap);
242         wps_er_ap_event(er->wps, ap, WPS_EV_ER_AP_REMOVE);
243         os_free(ap->location);
244         http_client_free(ap->http);
245         if (ap->wps)
246                 wps_deinit(ap->wps);
247
248         os_free(ap->friendly_name);
249         os_free(ap->manufacturer);
250         os_free(ap->manufacturer_url);
251         os_free(ap->model_description);
252         os_free(ap->model_name);
253         os_free(ap->model_number);
254         os_free(ap->model_url);
255         os_free(ap->serial_number);
256         os_free(ap->udn);
257         os_free(ap->upc);
258
259         os_free(ap->scpd_url);
260         os_free(ap->control_url);
261         os_free(ap->event_sub_url);
262
263         os_free(ap->ap_settings);
264
265         wps_er_sta_remove_all(ap);
266
267         os_free(ap);
268 }
269
270
271 static void wps_er_ap_timeout(void *eloop_data, void *user_ctx)
272 {
273         struct wps_er *er = eloop_data;
274         struct wps_er_ap *ap = user_ctx;
275         wpa_printf(MSG_DEBUG, "WPS ER: AP advertisement timed out");
276         wps_er_ap_free(er, ap);
277 }
278
279
280 static void wps_er_http_subscribe_cb(void *ctx, struct http_client *c,
281                                      enum http_client_event event)
282 {
283         struct wps_er_ap *ap = ctx;
284
285         switch (event) {
286         case HTTP_CLIENT_OK:
287                 wpa_printf(MSG_DEBUG, "WPS ER: Subscribed to events");
288                 wps_er_ap_event(ap->er->wps, ap, WPS_EV_ER_AP_ADD);
289                 break;
290         case HTTP_CLIENT_FAILED:
291         case HTTP_CLIENT_INVALID_REPLY:
292         case HTTP_CLIENT_TIMEOUT:
293                 wpa_printf(MSG_DEBUG, "WPS ER: Failed to subscribe to events");
294                 break;
295         }
296         http_client_free(ap->http);
297         ap->http = NULL;
298 }
299
300
301 static void wps_er_subscribe(struct wps_er_ap *ap)
302 {
303         struct wpabuf *req;
304         struct sockaddr_in dst;
305         char *url, *path;
306
307         if (ap->event_sub_url == NULL) {
308                 wpa_printf(MSG_DEBUG, "WPS ER: No eventSubURL - cannot "
309                            "subscribe");
310                 return;
311         }
312         if (ap->http) {
313                 wpa_printf(MSG_DEBUG, "WPS ER: Pending HTTP request - cannot "
314                            "send subscribe request");
315                 return;
316         }
317
318         url = http_client_url_parse(ap->event_sub_url, &dst, &path);
319         if (url == NULL) {
320                 wpa_printf(MSG_DEBUG, "WPS ER: Failed to parse eventSubURL");
321                 return;
322         }
323
324         req = wpabuf_alloc(os_strlen(ap->event_sub_url) + 1000);
325         if (req == NULL) {
326                 os_free(url);
327                 return;
328         }
329         wpabuf_printf(req,
330                       "SUBSCRIBE %s HTTP/1.1\r\n"
331                       "HOST: %s:%d\r\n"
332                       "CALLBACK: <http://%s:%d/event/%d>\r\n"
333                       "NT: upnp:event\r\n"
334                       "TIMEOUT: Second-%d\r\n"
335                       "\r\n",
336                       path, inet_ntoa(dst.sin_addr), ntohs(dst.sin_port),
337                       ap->er->ip_addr_text, ap->er->http_port, ap->id, 1800);
338         os_free(url);
339         wpa_hexdump_ascii(MSG_MSGDUMP, "WPS ER: Subscription request",
340                           wpabuf_head(req), wpabuf_len(req));
341
342         ap->http = http_client_addr(&dst, req, 1000, wps_er_http_subscribe_cb,
343                                     ap);
344         if (ap->http == NULL)
345                 wpabuf_free(req);
346 }
347
348
349 static void wps_er_parse_device_description(struct wps_er_ap *ap,
350                                             struct wpabuf *reply)
351 {
352         /* Note: reply includes null termination after the buffer data */
353         const char *data = wpabuf_head(reply);
354         char *pos;
355
356         wpa_hexdump_ascii(MSG_MSGDUMP, "WPS ER: Device info",
357                           wpabuf_head(reply), wpabuf_len(reply));
358
359         ap->friendly_name = xml_get_first_item(data, "friendlyName");
360         wpa_printf(MSG_DEBUG, "WPS ER: friendlyName='%s'", ap->friendly_name);
361
362         ap->manufacturer = xml_get_first_item(data, "manufacturer");
363         wpa_printf(MSG_DEBUG, "WPS ER: manufacturer='%s'", ap->manufacturer);
364
365         ap->manufacturer_url = xml_get_first_item(data, "manufacturerURL");
366         wpa_printf(MSG_DEBUG, "WPS ER: manufacturerURL='%s'",
367                    ap->manufacturer_url);
368
369         ap->model_description = xml_get_first_item(data, "modelDescription");
370         wpa_printf(MSG_DEBUG, "WPS ER: modelDescription='%s'",
371                    ap->model_description);
372
373         ap->model_name = xml_get_first_item(data, "modelName");
374         wpa_printf(MSG_DEBUG, "WPS ER: modelName='%s'", ap->model_name);
375
376         ap->model_number = xml_get_first_item(data, "modelNumber");
377         wpa_printf(MSG_DEBUG, "WPS ER: modelNumber='%s'", ap->model_number);
378
379         ap->model_url = xml_get_first_item(data, "modelURL");
380         wpa_printf(MSG_DEBUG, "WPS ER: modelURL='%s'", ap->model_url);
381
382         ap->serial_number = xml_get_first_item(data, "serialNumber");
383         wpa_printf(MSG_DEBUG, "WPS ER: serialNumber='%s'", ap->serial_number);
384
385         ap->udn = xml_get_first_item(data, "UDN");
386         wpa_printf(MSG_DEBUG, "WPS ER: UDN='%s'", ap->udn);
387         pos = os_strstr(ap->udn, "uuid:");
388         if (pos) {
389                 pos += 5;
390                 uuid_str2bin(pos, ap->uuid);
391         }
392
393         ap->upc = xml_get_first_item(data, "UPC");
394         wpa_printf(MSG_DEBUG, "WPS ER: UPC='%s'", ap->upc);
395
396         ap->scpd_url = http_link_update(
397                 xml_get_first_item(data, "SCPDURL"), ap->location);
398         wpa_printf(MSG_DEBUG, "WPS ER: SCPDURL='%s'", ap->scpd_url);
399
400         ap->control_url = http_link_update(
401                 xml_get_first_item(data, "controlURL"), ap->location);
402         wpa_printf(MSG_DEBUG, "WPS ER: controlURL='%s'", ap->control_url);
403
404         ap->event_sub_url = http_link_update(
405                 xml_get_first_item(data, "eventSubURL"), ap->location);
406         wpa_printf(MSG_DEBUG, "WPS ER: eventSubURL='%s'", ap->event_sub_url);
407 }
408
409
410 static void wps_er_http_dev_desc_cb(void *ctx, struct http_client *c,
411                                     enum http_client_event event)
412 {
413         struct wps_er_ap *ap = ctx;
414         struct wpabuf *reply;
415         int subscribe = 0;
416
417         switch (event) {
418         case HTTP_CLIENT_OK:
419                 reply = http_client_get_body(c);
420                 if (reply == NULL)
421                         break;
422                 wps_er_parse_device_description(ap, reply);
423                 subscribe = 1;
424                 break;
425         case HTTP_CLIENT_FAILED:
426         case HTTP_CLIENT_INVALID_REPLY:
427         case HTTP_CLIENT_TIMEOUT:
428                 wpa_printf(MSG_DEBUG, "WPS ER: Failed to fetch device info");
429                 break;
430         }
431         http_client_free(ap->http);
432         ap->http = NULL;
433         if (subscribe)
434                 wps_er_subscribe(ap);
435 }
436
437
438 static void wps_er_ap_add(struct wps_er *er, struct in_addr *addr,
439                           const char *location, int max_age)
440 {
441         struct wps_er_ap *ap;
442
443         ap = wps_er_ap_get(er, addr);
444         if (ap) {
445                 /* Update advertisement timeout */
446                 eloop_cancel_timeout(wps_er_ap_timeout, er, ap);
447                 eloop_register_timeout(max_age, 0, wps_er_ap_timeout, er, ap);
448                 return;
449         }
450
451         ap = os_zalloc(sizeof(*ap));
452         if (ap == NULL)
453                 return;
454         ap->er = er;
455         ap->id = ++er->next_ap_id;
456         ap->location = os_strdup(location);
457         if (ap->location == NULL) {
458                 os_free(ap);
459                 return;
460         }
461         ap->next = er->ap;
462         er->ap = ap;
463
464         ap->addr.s_addr = addr->s_addr;
465         eloop_register_timeout(max_age, 0, wps_er_ap_timeout, er, ap);
466
467         wpa_printf(MSG_DEBUG, "WPS ER: Added AP entry for %s (%s)",
468                    inet_ntoa(ap->addr), ap->location);
469
470         /* Fetch device description */
471         ap->http = http_client_url(ap->location, NULL, 10000,
472                                    wps_er_http_dev_desc_cb, ap);
473 }
474
475
476 static void wps_er_ap_remove(struct wps_er *er, struct in_addr *addr)
477 {
478         struct wps_er_ap *prev = NULL, *ap = er->ap;
479
480         while (ap) {
481                 if (ap->addr.s_addr == addr->s_addr) {
482                         if (prev)
483                                 prev->next = ap->next;
484                         else
485                                 er->ap = ap->next;
486                         wps_er_ap_free(er, ap);
487                         return;
488                 }
489                 prev = ap;
490                 ap = ap->next;
491         }
492 }
493
494
495 static void wps_er_ap_remove_all(struct wps_er *er)
496 {
497         struct wps_er_ap *prev, *ap;
498
499         ap = er->ap;
500         er->ap = NULL;
501
502         while (ap) {
503                 prev = ap;
504                 ap = ap->next;
505                 wps_er_ap_free(er, prev);
506         }
507 }
508
509
510 static void wps_er_ssdp_rx(int sd, void *eloop_ctx, void *sock_ctx)
511 {
512         struct wps_er *er = eloop_ctx;
513         struct sockaddr_in addr; /* client address */
514         socklen_t addr_len;
515         int nread;
516         char buf[MULTICAST_MAX_READ], *pos, *pos2, *start;
517         int wfa = 0, byebye = 0;
518         int max_age = -1;
519         char *location = NULL;
520
521         addr_len = sizeof(addr);
522         nread = recvfrom(sd, buf, sizeof(buf) - 1, 0,
523                          (struct sockaddr *) &addr, &addr_len);
524         if (nread <= 0)
525                 return;
526         buf[nread] = '\0';
527
528         wpa_printf(MSG_DEBUG, "WPS ER: Received SSDP from %s",
529                    inet_ntoa(addr.sin_addr));
530         wpa_hexdump_ascii(MSG_MSGDUMP, "WPS ER: Received SSDP contents",
531                           (u8 *) buf, nread);
532
533         if (sd == er->multicast_sd) {
534                 /* Reply to M-SEARCH */
535                 if (os_strncmp(buf, "HTTP/1.1 200 OK", 15) != 0)
536                         return; /* unexpected response header */
537         } else {
538                 /* Unsolicited message (likely NOTIFY or M-SEARCH) */
539                 if (os_strncmp(buf, "NOTIFY ", 7) != 0)
540                         return; /* only process notifications */
541         }
542
543         for (start = buf; start && *start; start = pos) {
544                 pos = os_strchr(start, '\n');
545                 if (pos) {
546                         if (pos[-1] == '\r')
547                                 pos[-1] = '\0';
548                         *pos++ = '\0';
549                 }
550                 if (os_strstr(start, "schemas-wifialliance-org:device:"
551                               "WFADevice:1"))
552                         wfa = 1;
553                 if (os_strstr(start, "schemas-wifialliance-org:service:"
554                               "WFAWLANConfig:1"))
555                         wfa = 1;
556                 if (os_strncasecmp(start, "LOCATION:", 9) == 0) {
557                         start += 9;
558                         while (*start == ' ')
559                                 start++;
560                         location = start;
561                 } else if (os_strncasecmp(start, "NTS:", 4) == 0) {
562                         if (os_strstr(start, "ssdp:byebye"))
563                                 byebye = 1;
564                 } else if (os_strncasecmp(start, "CACHE-CONTROL:", 14) == 0) {
565                         start += 9;
566                         while (*start == ' ')
567                                 start++;
568                         pos2 = os_strstr(start, "max-age=");
569                         if (pos2 == NULL)
570                                 continue;
571                         pos2 += 8;
572                         max_age = atoi(pos2);
573                 }
574         }
575
576         if (!wfa)
577                 return; /* Not WPS advertisement/reply */
578
579         if (byebye) {
580                 wps_er_ap_remove(er, &addr.sin_addr);
581                 return;
582         }
583
584         if (!location)
585                 return; /* Unknown location */
586
587         if (max_age < 1)
588                 return; /* No max-age reported */
589
590         wpa_printf(MSG_DEBUG, "WPS ER: AP discovered: %s "
591                    "(packet source: %s  max-age: %d)",
592                    location, inet_ntoa(addr.sin_addr), max_age);
593
594         wps_er_ap_add(er, &addr.sin_addr, location, max_age);
595 }
596
597
598 static void wps_er_send_ssdp_msearch(struct wps_er *er)
599 {
600         struct wpabuf *msg;
601         struct sockaddr_in dest;
602
603         msg = wpabuf_alloc(500);
604         if (msg == NULL)
605                 return;
606
607         wpabuf_put_str(msg,
608                        "M-SEARCH * HTTP/1.1\r\n"
609                        "HOST: 239.255.255.250:1900\r\n"
610                        "MAN: \"ssdp:discover\"\r\n"
611                        "MX: 3\r\n"
612                        "ST: urn:schemas-wifialliance-org:device:WFADevice:1"
613                        "\r\n"
614                        "\r\n");
615
616         os_memset(&dest, 0, sizeof(dest));
617         dest.sin_family = AF_INET;
618         dest.sin_addr.s_addr = inet_addr(UPNP_MULTICAST_ADDRESS);
619         dest.sin_port = htons(UPNP_MULTICAST_PORT);
620
621         if (sendto(er->multicast_sd, wpabuf_head(msg), wpabuf_len(msg), 0,
622                    (struct sockaddr *) &dest, sizeof(dest)) < 0)
623                 wpa_printf(MSG_DEBUG, "WPS ER: M-SEARCH sendto failed: "
624                            "%d (%s)", errno, strerror(errno));
625
626         wpabuf_free(msg);
627 }
628
629
630 static void http_put_date(struct wpabuf *buf)
631 {
632         wpabuf_put_str(buf, "Date: ");
633         format_date(buf);
634         wpabuf_put_str(buf, "\r\n");
635 }
636
637
638 static void wps_er_http_resp_not_found(struct http_request *req)
639 {
640         struct wpabuf *buf;
641         buf = wpabuf_alloc(200);
642         if (buf == NULL) {
643                 http_request_deinit(req);
644                 return;
645         }
646
647         wpabuf_put_str(buf,
648                        "HTTP/1.1 404 Not Found\r\n"
649                        "Server: unspecified, UPnP/1.0, unspecified\r\n"
650                        "Connection: close\r\n");
651         http_put_date(buf);
652         wpabuf_put_str(buf, "\r\n");
653         http_request_send_and_deinit(req, buf);
654 }
655
656
657 static void wps_er_http_resp_ok(struct http_request *req)
658 {
659         struct wpabuf *buf;
660         buf = wpabuf_alloc(200);
661         if (buf == NULL) {
662                 http_request_deinit(req);
663                 return;
664         }
665
666         wpabuf_put_str(buf,
667                        "HTTP/1.1 200 OK\r\n"
668                        "Server: unspecified, UPnP/1.0, unspecified\r\n"
669                        "Connection: close\r\n"
670                        "Content-Length: 0\r\n");
671         http_put_date(buf);
672         wpabuf_put_str(buf, "\r\n");
673         http_request_send_and_deinit(req, buf);
674 }
675
676
677 static void wps_er_sta_timeout(void *eloop_data, void *user_ctx)
678 {
679         struct wps_er_sta *prev, *tmp, *sta = eloop_data;
680         wpa_printf(MSG_DEBUG, "WPS ER: STA entry timed out");
681         tmp = sta->ap->sta;
682         prev = NULL;
683         while (tmp) {
684                 if (tmp == sta)
685                         break;
686                 prev = tmp;
687                 tmp = tmp->next;
688         }
689         if (tmp) {
690                 if (prev)
691                         prev->next = sta->next;
692                 else
693                         sta->ap->sta = sta->next;
694         }
695         wps_er_sta_free(sta);
696 }
697
698
699 static struct wps_er_sta * wps_er_add_sta_data(struct wps_er_ap *ap,
700                                                const u8 *addr,
701                                                struct wps_parse_attr *attr,
702                                                int probe_req)
703 {
704         struct wps_er_sta *sta = wps_er_sta_get(ap, addr);
705         int new_sta = 0;
706         int m1;
707
708         m1 = !probe_req && attr->msg_type && *attr->msg_type == WPS_M1;
709
710         if (sta == NULL) {
711                 /*
712                  * Only allow new STA entry to be added based on Probe Request
713                  * or M1. This will filter out bogus events and anything that
714                  * may have been ongoing at the time ER subscribed for events.
715                  */
716                 if (!probe_req && !m1)
717                         return NULL;
718
719                 sta = os_zalloc(sizeof(*sta));
720                 if (sta == NULL)
721                         return NULL;
722                 os_memcpy(sta->addr, addr, ETH_ALEN);
723                 sta->ap = ap;
724                 sta->next = ap->sta;
725                 ap->sta = sta;
726                 new_sta = 1;
727         }
728
729         if (m1)
730                 sta->m1_received = 1;
731
732         if (attr->config_methods && (!probe_req || !sta->m1_received))
733                 sta->config_methods = WPA_GET_BE16(attr->config_methods);
734         if (attr->uuid_e && (!probe_req || !sta->m1_received))
735                 os_memcpy(sta->uuid, attr->uuid_e, WPS_UUID_LEN);
736         if (attr->primary_dev_type && (!probe_req || !sta->m1_received))
737                 os_memcpy(sta->pri_dev_type, attr->primary_dev_type, 8);
738         if (attr->dev_password_id && (!probe_req || !sta->m1_received))
739                 sta->dev_passwd_id = WPA_GET_BE16(attr->dev_password_id);
740
741         if (attr->manufacturer) {
742                 os_free(sta->manufacturer);
743                 sta->manufacturer = os_malloc(attr->manufacturer_len + 1);
744                 if (sta->manufacturer) {
745                         os_memcpy(sta->manufacturer, attr->manufacturer,
746                                   attr->manufacturer_len);
747                         sta->manufacturer[attr->manufacturer_len] = '\0';
748                 }
749         }
750
751         if (attr->model_name) {
752                 os_free(sta->model_name);
753                 sta->model_name = os_malloc(attr->model_name_len + 1);
754                 if (sta->model_name) {
755                         os_memcpy(sta->model_name, attr->model_name,
756                                   attr->model_name_len);
757                         sta->model_name[attr->model_name_len] = '\0';
758                 }
759         }
760
761         if (attr->model_number) {
762                 os_free(sta->model_number);
763                 sta->model_number = os_malloc(attr->model_number_len + 1);
764                 if (sta->model_number) {
765                         os_memcpy(sta->model_number, attr->model_number,
766                                   attr->model_number_len);
767                         sta->model_number[attr->model_number_len] = '\0';
768                 }
769         }
770
771         if (attr->serial_number) {
772                 os_free(sta->serial_number);
773                 sta->serial_number = os_malloc(attr->serial_number_len + 1);
774                 if (sta->serial_number) {
775                         os_memcpy(sta->serial_number, attr->serial_number,
776                                   attr->serial_number_len);
777                         sta->serial_number[attr->serial_number_len] = '\0';
778                 }
779         }
780
781         if (attr->dev_name) {
782                 os_free(sta->dev_name);
783                 sta->dev_name = os_malloc(attr->dev_name_len + 1);
784                 if (sta->dev_name) {
785                         os_memcpy(sta->dev_name, attr->dev_name,
786                                   attr->dev_name_len);
787                         sta->dev_name[attr->dev_name_len] = '\0';
788                 }
789         }
790
791         eloop_cancel_timeout(wps_er_sta_timeout, sta, NULL);
792         eloop_register_timeout(300, 0, wps_er_sta_timeout, sta, NULL);
793
794         if (m1 || new_sta)
795                 wps_er_sta_event(ap->er->wps, sta, WPS_EV_ER_ENROLLEE_ADD);
796
797         return sta;
798 }
799
800
801 static void wps_er_process_wlanevent_probe_req(struct wps_er_ap *ap,
802                                                const u8 *addr,
803                                                struct wpabuf *msg)
804 {
805         struct wps_parse_attr attr;
806
807         wpa_printf(MSG_DEBUG, "WPS ER: WLANEvent - Probe Request - from "
808                    MACSTR, MAC2STR(addr));
809         wpa_hexdump_buf(MSG_MSGDUMP, "WPS ER: WLANEvent - Enrollee's message "
810                         "(TLVs from Probe Request)", msg);
811
812         if (wps_parse_msg(msg, &attr) < 0) {
813                 wpa_printf(MSG_DEBUG, "WPS ER: Failed to parse TLVs in "
814                            "WLANEvent message");
815                 return;
816         }
817
818         wps_er_add_sta_data(ap, addr, &attr, 1);
819 }
820
821
822 static void wps_er_http_put_wlan_response_cb(void *ctx, struct http_client *c,
823                                              enum http_client_event event)
824 {
825         struct wps_er_sta *sta = ctx;
826
827         switch (event) {
828         case HTTP_CLIENT_OK:
829                 wpa_printf(MSG_DEBUG, "WPS ER: PutWLANResponse OK");
830                 break;
831         case HTTP_CLIENT_FAILED:
832         case HTTP_CLIENT_INVALID_REPLY:
833         case HTTP_CLIENT_TIMEOUT:
834                 wpa_printf(MSG_DEBUG, "WPS ER: PutWLANResponse failed");
835                 break;
836         }
837         http_client_free(sta->http);
838         sta->http = NULL;
839 }
840
841
842 static const char *soap_prefix =
843         "<?xml version=\"1.0\"?>\n"
844         "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" "
845         "s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n"
846         "<s:Body>\n";
847 static const char *soap_postfix =
848         "</s:Body>\n</s:Envelope>\n";
849 static const char *urn_wfawlanconfig =
850         "urn:schemas-wifialliance-org:service:WFAWLANConfig:1";
851
852 static struct wpabuf * wps_er_soap_hdr(const struct wpabuf *msg,
853                                        const char *name, const char *arg_name,
854                                        const char *path,
855                                        const struct sockaddr_in *dst,
856                                        char **len_ptr, char **body_ptr)
857 {
858         unsigned char *encoded;
859         size_t encoded_len;
860         struct wpabuf *buf;
861
862         if (msg) {
863                 encoded = base64_encode(wpabuf_head(msg), wpabuf_len(msg),
864                                         &encoded_len);
865                 if (encoded == NULL)
866                         return NULL;
867         } else {
868                 encoded = NULL;
869                 encoded_len = 0;
870         }
871
872         buf = wpabuf_alloc(1000 + encoded_len);
873         if (buf == NULL) {
874                 os_free(encoded);
875                 return NULL;
876         }
877
878         wpabuf_printf(buf,
879                       "POST %s HTTP/1.1\r\n"
880                       "Host: %s:%d\r\n"
881                       "Content-Type: text/xml; charset=\"utf-8\"\r\n"
882                       "Content-Length: ",
883                       path, inet_ntoa(dst->sin_addr), ntohs(dst->sin_port));
884
885         *len_ptr = wpabuf_put(buf, 0);
886         wpabuf_printf(buf,
887                       "        \r\n"
888                       "SOAPACTION: \"%s#%s\"\r\n"
889                       "\r\n",
890                       urn_wfawlanconfig, name);
891
892         *body_ptr = wpabuf_put(buf, 0);
893
894         wpabuf_put_str(buf, soap_prefix);
895         wpabuf_printf(buf, "<u:%s xmlns:u=\"", name);
896         wpabuf_put_str(buf, urn_wfawlanconfig);
897         wpabuf_put_str(buf, "\">\n");
898         if (encoded) {
899                 wpabuf_printf(buf, "<%s>%s</%s>\n",
900                               arg_name, (char *) encoded, arg_name);
901                 os_free(encoded);
902         }
903
904         return buf;
905 }
906
907
908 static void wps_er_soap_end(struct wpabuf *buf, const char *name,
909                             char *len_ptr, char *body_ptr)
910 {
911         char len_buf[10];
912         wpabuf_printf(buf, "</u:%s>\n", name);
913         wpabuf_put_str(buf, soap_postfix);
914         os_snprintf(len_buf, sizeof(len_buf), "%d",
915                     (int) ((char *) wpabuf_put(buf, 0) - body_ptr));
916         os_memcpy(len_ptr, len_buf, os_strlen(len_buf));
917 }
918
919
920 static void wps_er_sta_send_msg(struct wps_er_sta *sta, struct wpabuf *msg)
921 {
922         struct wpabuf *buf;
923         char *len_ptr, *body_ptr;
924         struct sockaddr_in dst;
925         char *url, *path;
926
927         if (sta->http) {
928                 wpa_printf(MSG_DEBUG, "WPS ER: Pending HTTP request for STA - "
929                            "ignore new request");
930                 wpabuf_free(msg);
931                 return;
932         }
933
934         if (sta->ap->control_url == NULL) {
935                 wpa_printf(MSG_DEBUG, "WPS ER: No controlURL for AP");
936                 wpabuf_free(msg);
937                 return;
938         }
939
940         url = http_client_url_parse(sta->ap->control_url, &dst, &path);
941         if (url == NULL) {
942                 wpa_printf(MSG_DEBUG, "WPS ER: Failed to parse controlURL");
943                 wpabuf_free(msg);
944                 return;
945         }
946
947         buf = wps_er_soap_hdr(msg, "PutWLANResponse", "NewMessage", path, &dst,
948                               &len_ptr, &body_ptr);
949         wpabuf_free(msg);
950         os_free(url);
951         if (buf == NULL)
952                 return;
953         wpabuf_printf(buf, "<NewWLANEventType>%d</NewWLANEventType>\n",
954                       UPNP_WPS_WLANEVENT_TYPE_EAP);
955         wpabuf_printf(buf, "<NewWLANEventMAC>" MACSTR "</NewWLANEventMAC>\n",
956                       MAC2STR(sta->addr));
957
958         wps_er_soap_end(buf, "PutWLANResponse", len_ptr, body_ptr);
959
960         sta->http = http_client_addr(&dst, buf, 1000,
961                                      wps_er_http_put_wlan_response_cb, sta);
962         if (sta->http == NULL)
963                 wpabuf_free(buf);
964 }
965
966
967 static void wps_er_sta_process(struct wps_er_sta *sta, struct wpabuf *msg,
968                                enum wsc_op_code op_code)
969 {
970         enum wps_process_res res;
971
972         res = wps_process_msg(sta->wps, op_code, msg);
973         if (res == WPS_CONTINUE) {
974                 struct wpabuf *next = wps_get_msg(sta->wps, &op_code);
975                 if (next)
976                         wps_er_sta_send_msg(sta, next);
977         }
978 }
979
980
981 static void wps_er_sta_start(struct wps_er_sta *sta, struct wpabuf *msg)
982 {
983         struct wps_config cfg;
984
985         if (sta->wps)
986                 wps_deinit(sta->wps);
987
988         os_memset(&cfg, 0, sizeof(cfg));
989         cfg.wps = sta->ap->er->wps;
990         cfg.registrar = 1;
991         cfg.peer_addr = sta->addr;
992
993         sta->wps = wps_init(&cfg);
994         if (sta->wps == NULL)
995                 return;
996         sta->wps->er = 1;
997         sta->wps->use_cred = sta->ap->ap_settings;
998
999         wps_er_sta_process(sta, msg, WSC_MSG);
1000 }
1001
1002
1003 static void wps_er_process_wlanevent_eap(struct wps_er_ap *ap, const u8 *addr,
1004                                          struct wpabuf *msg)
1005 {
1006         struct wps_parse_attr attr;
1007         struct wps_er_sta *sta;
1008
1009         wpa_printf(MSG_DEBUG, "WPS ER: WLANEvent - EAP - from " MACSTR,
1010                    MAC2STR(addr));
1011         wpa_hexdump_buf(MSG_MSGDUMP, "WPS ER: WLANEvent - Enrollee's message "
1012                         "(TLVs from EAP-WSC)", msg);
1013
1014         if (wps_parse_msg(msg, &attr) < 0) {
1015                 wpa_printf(MSG_DEBUG, "WPS ER: Failed to parse TLVs in "
1016                            "WLANEvent message");
1017                 return;
1018         }
1019
1020         sta = wps_er_add_sta_data(ap, addr, &attr, 0);
1021         if (sta == NULL)
1022                 return;
1023
1024         if (attr.msg_type && *attr.msg_type == WPS_M1)
1025                 wps_er_sta_start(sta, msg);
1026         else if (sta->wps) {
1027                 enum wsc_op_code op_code = WSC_MSG;
1028                 if (attr.msg_type) {
1029                         switch (*attr.msg_type) {
1030                         case WPS_WSC_ACK:
1031                                 op_code = WSC_ACK;
1032                                 break;
1033                         case WPS_WSC_NACK:
1034                                 op_code = WSC_NACK;
1035                                 break;
1036                         case WPS_WSC_DONE:
1037                                 op_code = WSC_Done;
1038                                 break;
1039                         }
1040                 }
1041                 wps_er_sta_process(sta, msg, op_code);
1042         }
1043 }
1044
1045
1046 static void wps_er_process_wlanevent(struct wps_er_ap *ap,
1047                                      struct wpabuf *event)
1048 {
1049         u8 *data;
1050         u8 wlan_event_type;
1051         u8 wlan_event_mac[ETH_ALEN];
1052         struct wpabuf msg;
1053
1054         wpa_hexdump(MSG_MSGDUMP, "WPS ER: Received WLANEvent",
1055                     wpabuf_head(event), wpabuf_len(event));
1056         if (wpabuf_len(event) < 1 + 17) {
1057                 wpa_printf(MSG_DEBUG, "WPS ER: Too short WLANEvent");
1058                 return;
1059         }
1060
1061         data = wpabuf_mhead(event);
1062         wlan_event_type = data[0];
1063         if (hwaddr_aton((char *) data + 1, wlan_event_mac) < 0) {
1064                 wpa_printf(MSG_DEBUG, "WPS ER: Invalid WLANEventMAC in "
1065                            "WLANEvent");
1066                 return;
1067         }
1068
1069         wpabuf_set(&msg, data + 1 + 17, wpabuf_len(event) - (1 + 17));
1070
1071         switch (wlan_event_type) {
1072         case 1:
1073                 wps_er_process_wlanevent_probe_req(ap, wlan_event_mac, &msg);
1074                 break;
1075         case 2:
1076                 wps_er_process_wlanevent_eap(ap, wlan_event_mac, &msg);
1077                 break;
1078         default:
1079                 wpa_printf(MSG_DEBUG, "WPS ER: Unknown WLANEventType %d",
1080                            wlan_event_type);
1081                 break;
1082         }
1083 }
1084
1085
1086 static void wps_er_http_event(struct wps_er *er, struct http_request *req,
1087                               unsigned int ap_id)
1088 {
1089         struct wps_er_ap *ap = wps_er_ap_get_id(er, ap_id);
1090         struct wpabuf *event;
1091         enum http_reply_code ret;
1092
1093         if (ap == NULL) {
1094                 wpa_printf(MSG_DEBUG, "WPS ER: HTTP event from unknown AP id "
1095                            "%u", ap_id);
1096                 wps_er_http_resp_not_found(req);
1097                 return;
1098         }
1099         wpa_printf(MSG_MSGDUMP, "WPS ER: HTTP event from AP id %u: %s",
1100                    ap_id, http_request_get_data(req));
1101
1102         event = xml_get_base64_item(http_request_get_data(req), "WLANEvent",
1103                                     &ret);
1104         if (event == NULL) {
1105                 wpa_printf(MSG_DEBUG, "WPS ER: Could not extract WLANEvent "
1106                            "from the event notification");
1107                 /*
1108                  * Reply with OK anyway to avoid getting unregistered from
1109                  * events.
1110                  */
1111                 wps_er_http_resp_ok(req);
1112                 return;
1113         }
1114
1115         wps_er_process_wlanevent(ap, event);
1116
1117         wpabuf_free(event);
1118         wps_er_http_resp_ok(req);
1119 }
1120
1121
1122 static void wps_er_http_notify(struct wps_er *er, struct http_request *req)
1123 {
1124         char *uri = http_request_get_uri(req);
1125
1126         if (os_strncmp(uri, "/event/", 7) == 0) {
1127                 wps_er_http_event(er, req, atoi(uri + 7));
1128         } else {
1129                 wpa_printf(MSG_DEBUG, "WPS ER: Unknown HTTP NOTIFY for '%s'",
1130                            uri);
1131                 wps_er_http_resp_not_found(req);
1132         }
1133 }
1134
1135
1136 static void wps_er_http_req(void *ctx, struct http_request *req)
1137 {
1138         struct wps_er *er = ctx;
1139         struct sockaddr_in *cli = http_request_get_cli_addr(req);
1140         enum httpread_hdr_type type = http_request_get_type(req);
1141         struct wpabuf *buf;
1142
1143         wpa_printf(MSG_DEBUG, "WPS ER: HTTP request: '%s' (type %d) from "
1144                    "%s:%d",
1145                    http_request_get_uri(req), type,
1146                    inet_ntoa(cli->sin_addr), ntohs(cli->sin_port));
1147
1148         switch (type) {
1149         case HTTPREAD_HDR_TYPE_NOTIFY:
1150                 wps_er_http_notify(er, req);
1151                 break;
1152         default:
1153                 wpa_printf(MSG_DEBUG, "WPS ER: Unsupported HTTP request type "
1154                            "%d", type);
1155                 buf = wpabuf_alloc(200);
1156                 if (buf == NULL) {
1157                         http_request_deinit(req);
1158                         return;
1159                 }
1160                 wpabuf_put_str(buf,
1161                                "HTTP/1.1 501 Unimplemented\r\n"
1162                                "Connection: close\r\n");
1163                 http_put_date(buf);
1164                 wpabuf_put_str(buf, "\r\n");
1165                 http_request_send_and_deinit(req, buf);
1166                 break;
1167         }
1168 }
1169
1170
1171 struct wps_er *
1172 wps_er_init(struct wps_context *wps, const char *ifname)
1173 {
1174         struct wps_er *er;
1175         struct in_addr addr;
1176
1177         er = os_zalloc(sizeof(*er));
1178         if (er == NULL)
1179                 return NULL;
1180
1181         er->multicast_sd = -1;
1182         er->ssdp_sd = -1;
1183
1184         os_strlcpy(er->ifname, ifname, sizeof(er->ifname));
1185         er->wps = wps;
1186
1187         if (get_netif_info(ifname,
1188                            &er->ip_addr, &er->ip_addr_text,
1189                            er->mac_addr, &er->mac_addr_text)) {
1190                 wpa_printf(MSG_INFO, "WPS UPnP: Could not get IP/MAC address "
1191                            "for %s. Does it have IP address?", ifname);
1192                 wps_er_deinit(er);
1193                 return NULL;
1194         }
1195
1196         if (add_ssdp_network(ifname)) {
1197                 wps_er_deinit(er);
1198                 return NULL;
1199         }
1200
1201         er->multicast_sd = ssdp_open_multicast_sock(er->ip_addr);
1202         if (er->multicast_sd < 0) {
1203                 wps_er_deinit(er);
1204                 return NULL;
1205         }
1206
1207         er->ssdp_sd = ssdp_listener_open();
1208         if (er->ssdp_sd < 0) {
1209                 wps_er_deinit(er);
1210                 return NULL;
1211         }
1212         if (eloop_register_sock(er->multicast_sd, EVENT_TYPE_READ,
1213                                 wps_er_ssdp_rx, er, NULL) ||
1214             eloop_register_sock(er->ssdp_sd, EVENT_TYPE_READ,
1215                                 wps_er_ssdp_rx, er, NULL)) {
1216                 wps_er_deinit(er);
1217                 return NULL;
1218         }
1219
1220         addr.s_addr = er->ip_addr;
1221         er->http_srv = http_server_init(&addr, -1, wps_er_http_req, er);
1222         if (er->http_srv == NULL) {
1223                 wps_er_deinit(er);
1224                 return NULL;
1225         }
1226         er->http_port = http_server_get_port(er->http_srv);
1227
1228         wpa_printf(MSG_DEBUG, "WPS ER: Start (ifname=%s ip_addr=%s "
1229                    "mac_addr=%s)",
1230                    er->ifname, er->ip_addr_text, er->mac_addr_text);
1231
1232         wps_er_send_ssdp_msearch(er);
1233
1234         return er;
1235 }
1236
1237
1238 void wps_er_deinit(struct wps_er *er)
1239 {
1240         if (er == NULL)
1241                 return;
1242         http_server_deinit(er->http_srv);
1243         wps_er_ap_remove_all(er);
1244         if (er->multicast_sd >= 0) {
1245                 eloop_unregister_sock(er->multicast_sd, EVENT_TYPE_READ);
1246                 close(er->multicast_sd);
1247         }
1248         if (er->ssdp_sd >= 0) {
1249                 eloop_unregister_sock(er->ssdp_sd, EVENT_TYPE_READ);
1250                 close(er->ssdp_sd);
1251         }
1252         os_free(er->ip_addr_text);
1253         os_free(er->mac_addr_text);
1254         os_free(er);
1255 }
1256
1257
1258 static void wps_er_http_set_sel_reg_cb(void *ctx, struct http_client *c,
1259                                        enum http_client_event event)
1260 {
1261         struct wps_er_ap *ap = ctx;
1262
1263         switch (event) {
1264         case HTTP_CLIENT_OK:
1265                 wpa_printf(MSG_DEBUG, "WPS ER: SetSelectedRegistrar OK");
1266                 break;
1267         case HTTP_CLIENT_FAILED:
1268         case HTTP_CLIENT_INVALID_REPLY:
1269         case HTTP_CLIENT_TIMEOUT:
1270                 wpa_printf(MSG_DEBUG, "WPS ER: SetSelectedRegistrar failed");
1271                 break;
1272         }
1273         http_client_free(ap->http);
1274         ap->http = NULL;
1275 }
1276
1277
1278 static void wps_er_send_set_sel_reg(struct wps_er_ap *ap, struct wpabuf *msg)
1279 {
1280         struct wpabuf *buf;
1281         char *len_ptr, *body_ptr;
1282         struct sockaddr_in dst;
1283         char *url, *path;
1284
1285         if (ap->control_url == NULL) {
1286                 wpa_printf(MSG_DEBUG, "WPS ER: No controlURL for AP");
1287                 return;
1288         }
1289
1290         if (ap->http) {
1291                 wpa_printf(MSG_DEBUG, "WPS ER: Pending HTTP request for AP - "
1292                            "ignore new request");
1293                 return;
1294         }
1295
1296         url = http_client_url_parse(ap->control_url, &dst, &path);
1297         if (url == NULL) {
1298                 wpa_printf(MSG_DEBUG, "WPS ER: Failed to parse controlURL");
1299                 return;
1300         }
1301
1302         buf = wps_er_soap_hdr(msg, "SetSelectedRegistrar", "NewMessage", path,
1303                               &dst, &len_ptr, &body_ptr);
1304         os_free(url);
1305         if (buf == NULL)
1306                 return;
1307
1308         wps_er_soap_end(buf, "SetSelectedRegistrar", len_ptr, body_ptr);
1309
1310         ap->http = http_client_addr(&dst, buf, 1000,
1311                                     wps_er_http_set_sel_reg_cb, ap);
1312         if (ap->http == NULL)
1313                 wpabuf_free(buf);
1314 }
1315
1316
1317 static int wps_er_build_selected_registrar(struct wpabuf *msg, int sel_reg)
1318 {
1319         wpabuf_put_be16(msg, ATTR_SELECTED_REGISTRAR);
1320         wpabuf_put_be16(msg, 1);
1321         wpabuf_put_u8(msg, !!sel_reg);
1322         return 0;
1323 }
1324
1325
1326 static int wps_er_build_dev_password_id(struct wpabuf *msg, u16 dev_passwd_id)
1327 {
1328         wpabuf_put_be16(msg, ATTR_DEV_PASSWORD_ID);
1329         wpabuf_put_be16(msg, 2);
1330         wpabuf_put_be16(msg, dev_passwd_id);
1331         return 0;
1332 }
1333
1334
1335 static int wps_er_build_sel_reg_config_methods(struct wpabuf *msg,
1336                                                u16 sel_reg_config_methods)
1337 {
1338         wpabuf_put_be16(msg, ATTR_SELECTED_REGISTRAR_CONFIG_METHODS);
1339         wpabuf_put_be16(msg, 2);
1340         wpabuf_put_be16(msg, sel_reg_config_methods);
1341         return 0;
1342 }
1343
1344
1345 void wps_er_set_sel_reg(struct wps_er *er, int sel_reg, u16 dev_passwd_id,
1346                         u16 sel_reg_config_methods)
1347 {
1348         struct wpabuf *msg;
1349         struct wps_er_ap *ap;
1350
1351         msg = wpabuf_alloc(500);
1352         if (msg == NULL)
1353                 return;
1354
1355         if (wps_build_version(msg) ||
1356             wps_er_build_selected_registrar(msg, sel_reg) ||
1357             wps_er_build_dev_password_id(msg, dev_passwd_id) ||
1358             wps_er_build_sel_reg_config_methods(msg, sel_reg_config_methods)) {
1359                 wpabuf_free(msg);
1360                 return;
1361         }
1362
1363         for (ap = er->ap; ap; ap = ap->next)
1364                 wps_er_send_set_sel_reg(ap, msg);
1365
1366         wpabuf_free(msg);
1367 }
1368
1369
1370 int wps_er_pbc(struct wps_er *er, const u8 *uuid)
1371 {
1372         if (er == NULL || er->wps == NULL)
1373                 return -1;
1374
1375         /*
1376          * TODO: Should enable PBC mode only in a single AP based on which AP
1377          * the Enrollee (uuid) is using. Now, we may end up enabling multiple
1378          * APs in PBC mode which could result in session overlap at the
1379          * Enrollee.
1380          */
1381         if (wps_registrar_button_pushed(er->wps->registrar))
1382                 return -1;
1383
1384         return 0;
1385 }
1386
1387
1388 static void wps_er_ap_settings_cb(void *ctx, const struct wps_credential *cred)
1389 {
1390         struct wps_er_ap *ap = ctx;
1391         wpa_printf(MSG_DEBUG, "WPS ER: AP Settings received");
1392         os_free(ap->ap_settings);
1393         ap->ap_settings = os_malloc(sizeof(*cred));
1394         if (ap->ap_settings) {
1395                 os_memcpy(ap->ap_settings, cred, sizeof(*cred));
1396                 ap->ap_settings->cred_attr = NULL;
1397         }
1398
1399         /* TODO: send info through ctrl_iface */
1400 }
1401
1402
1403 static void wps_er_http_put_message_cb(void *ctx, struct http_client *c,
1404                                        enum http_client_event event)
1405 {
1406         struct wps_er_ap *ap = ctx;
1407         struct wpabuf *reply;
1408         char *msg = NULL;
1409
1410         switch (event) {
1411         case HTTP_CLIENT_OK:
1412                 wpa_printf(MSG_DEBUG, "WPS ER: PutMessage OK");
1413                 reply = http_client_get_body(c);
1414                 if (reply == NULL)
1415                         break;
1416                 msg = os_zalloc(wpabuf_len(reply) + 1);
1417                 if (msg == NULL)
1418                         break;
1419                 os_memcpy(msg, wpabuf_head(reply), wpabuf_len(reply));
1420                 break;
1421         case HTTP_CLIENT_FAILED:
1422         case HTTP_CLIENT_INVALID_REPLY:
1423         case HTTP_CLIENT_TIMEOUT:
1424                 wpa_printf(MSG_DEBUG, "WPS ER: PutMessage failed");
1425                 if (ap->wps) {
1426                         wps_deinit(ap->wps);
1427                         ap->wps = NULL;
1428                 }
1429                 break;
1430         }
1431         http_client_free(ap->http);
1432         ap->http = NULL;
1433
1434         if (msg) {
1435                 struct wpabuf *buf;
1436                 enum http_reply_code ret;
1437                 buf = xml_get_base64_item(msg, "NewOutMessage", &ret);
1438                 os_free(msg);
1439                 if (buf == NULL) {
1440                         wpa_printf(MSG_DEBUG, "WPS ER: Could not extract "
1441                                    "NewOutMessage from PutMessage response");
1442                         return;
1443                 }
1444                 wps_er_ap_process(ap, buf);
1445                 wpabuf_free(buf);
1446         }
1447 }
1448
1449
1450 static void wps_er_ap_put_message(struct wps_er_ap *ap,
1451                                   const struct wpabuf *msg)
1452 {
1453         struct wpabuf *buf;
1454         char *len_ptr, *body_ptr;
1455         struct sockaddr_in dst;
1456         char *url, *path;
1457
1458         if (ap->http) {
1459                 wpa_printf(MSG_DEBUG, "WPS ER: Pending HTTP operation ongoing "
1460                            "with the AP - cannot continue learn");
1461                 return;
1462         }
1463
1464         if (ap->control_url == NULL) {
1465                 wpa_printf(MSG_DEBUG, "WPS ER: No controlURL for AP");
1466                 return;
1467         }
1468
1469         url = http_client_url_parse(ap->control_url, &dst, &path);
1470         if (url == NULL) {
1471                 wpa_printf(MSG_DEBUG, "WPS ER: Failed to parse controlURL");
1472                 return;
1473         }
1474
1475         buf = wps_er_soap_hdr(msg, "PutMessage", "NewInMessage", path, &dst,
1476                               &len_ptr, &body_ptr);
1477         os_free(url);
1478         if (buf == NULL)
1479                 return;
1480
1481         wps_er_soap_end(buf, "PutMessage", len_ptr, body_ptr);
1482
1483         ap->http = http_client_addr(&dst, buf, 10000,
1484                                     wps_er_http_put_message_cb, ap);
1485         if (ap->http == NULL)
1486                 wpabuf_free(buf);
1487 }
1488
1489
1490 static void wps_er_ap_process(struct wps_er_ap *ap, struct wpabuf *msg)
1491 {
1492         enum wps_process_res res;
1493
1494         res = wps_process_msg(ap->wps, WSC_MSG, msg);
1495         if (res == WPS_CONTINUE) {
1496                 enum wsc_op_code op_code;
1497                 struct wpabuf *next = wps_get_msg(ap->wps, &op_code);
1498                 if (next) {
1499                         wps_er_ap_put_message(ap, next);
1500                         wpabuf_free(next);
1501                 } else {
1502                         wpa_printf(MSG_DEBUG, "WPS ER: Failed to build "
1503                                    "message");
1504                         wps_deinit(ap->wps);
1505                         ap->wps = NULL;
1506                 }
1507         } else {
1508                 wpa_printf(MSG_DEBUG, "WPS ER: Failed to process message from "
1509                            "AP (res=%d)", res);
1510                 wps_deinit(ap->wps);
1511                 ap->wps = NULL;
1512         }
1513 }
1514
1515
1516 static void wps_er_ap_learn(struct wps_er_ap *ap, const char *dev_info)
1517 {
1518         struct wpabuf *info;
1519         enum http_reply_code ret;
1520         struct wps_config cfg;
1521
1522         wpa_printf(MSG_DEBUG, "WPS ER: Received GetDeviceInfo response (M1) "
1523                    "from the AP");
1524         info = xml_get_base64_item(dev_info, "NewDeviceInfo", &ret);
1525         if (info == NULL) {
1526                 wpa_printf(MSG_DEBUG, "WPS ER: Could not extract "
1527                            "NewDeviceInfo from GetDeviceInfo response");
1528                 return;
1529         }
1530
1531         if (ap->wps) {
1532                 wpa_printf(MSG_DEBUG, "WPS ER: Protocol run already in "
1533                            "progress with this AP");
1534                 wpabuf_free(info);
1535                 return;
1536         }
1537
1538         os_memset(&cfg, 0, sizeof(cfg));
1539         cfg.wps = ap->er->wps;
1540         cfg.registrar = 1;
1541         ap->wps = wps_init(&cfg);
1542         if (ap->wps == NULL) {
1543                 wpabuf_free(info);
1544                 return;
1545         }
1546         ap->wps->ap_settings_cb = wps_er_ap_settings_cb;
1547         ap->wps->ap_settings_cb_ctx = ap;
1548
1549         wps_er_ap_process(ap, info);
1550         wpabuf_free(info);
1551 }
1552
1553
1554 static void wps_er_http_get_dev_info_cb(void *ctx, struct http_client *c,
1555                                         enum http_client_event event)
1556 {
1557         struct wps_er_ap *ap = ctx;
1558         struct wpabuf *reply;
1559         char *dev_info = NULL;
1560
1561         switch (event) {
1562         case HTTP_CLIENT_OK:
1563                 wpa_printf(MSG_DEBUG, "WPS ER: GetDeviceInfo OK");
1564                 reply = http_client_get_body(c);
1565                 if (reply == NULL)
1566                         break;
1567                 dev_info = os_zalloc(wpabuf_len(reply) + 1);
1568                 if (dev_info == NULL)
1569                         break;
1570                 os_memcpy(dev_info, wpabuf_head(reply), wpabuf_len(reply));
1571                 break;
1572         case HTTP_CLIENT_FAILED:
1573         case HTTP_CLIENT_INVALID_REPLY:
1574         case HTTP_CLIENT_TIMEOUT:
1575                 wpa_printf(MSG_DEBUG, "WPS ER: GetDeviceInfo failed");
1576                 break;
1577         }
1578         http_client_free(ap->http);
1579         ap->http = NULL;
1580
1581         if (dev_info) {
1582                 wps_er_ap_learn(ap, dev_info);
1583                 os_free(dev_info);
1584         }
1585 }
1586
1587
1588 int wps_er_learn(struct wps_er *er, const u8 *uuid, const u8 *pin,
1589                  size_t pin_len)
1590 {
1591         struct wps_er_ap *ap;
1592         struct wpabuf *buf;
1593         char *len_ptr, *body_ptr;
1594         struct sockaddr_in dst;
1595         char *url, *path;
1596
1597         if (er == NULL)
1598                 return -1;
1599
1600         ap = wps_er_ap_get_uuid(er, uuid);
1601         if (ap == NULL) {
1602                 wpa_printf(MSG_DEBUG, "WPS ER: AP not found for learn "
1603                            "request");
1604                 return -1;
1605         }
1606         if (ap->wps || ap->http) {
1607                 wpa_printf(MSG_DEBUG, "WPS ER: Pending operation ongoing "
1608                            "with the AP - cannot start learn");
1609                 return -1;
1610         }
1611
1612         if (ap->control_url == NULL) {
1613                 wpa_printf(MSG_DEBUG, "WPS ER: No controlURL for AP");
1614                 return -1;
1615         }
1616
1617         url = http_client_url_parse(ap->control_url, &dst, &path);
1618         if (url == NULL) {
1619                 wpa_printf(MSG_DEBUG, "WPS ER: Failed to parse controlURL");
1620                 return -1;
1621         }
1622
1623         buf = wps_er_soap_hdr(NULL, "GetDeviceInfo", NULL, path, &dst,
1624                               &len_ptr, &body_ptr);
1625         os_free(url);
1626         if (buf == NULL)
1627                 return -1;
1628
1629         wps_er_soap_end(buf, "GetDeviceInfo", len_ptr, body_ptr);
1630
1631         ap->http = http_client_addr(&dst, buf, 10000,
1632                                     wps_er_http_get_dev_info_cb, ap);
1633         if (ap->http == NULL) {
1634                 wpabuf_free(buf);
1635                 return -1;
1636         }
1637
1638         /* TODO: add PIN without SetSelectedRegistrar trigger to all APs */
1639         wps_registrar_add_pin(er->wps->registrar, uuid, pin, pin_len, 0);
1640
1641         return 0;
1642 }