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