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