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