WPS ER: Add PIN configuration and SetSelectedRegistrar call
[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
67         char *friendly_name;
68         char *manufacturer;
69         char *manufacturer_url;
70         char *model_description;
71         char *model_name;
72         char *model_number;
73         char *model_url;
74         char *serial_number;
75         char *udn;
76         char *upc;
77
78         char *scpd_url;
79         char *control_url;
80         char *event_sub_url;
81
82         int subscribed;
83         unsigned int id;
84 };
85
86 struct wps_er {
87         struct wps_context *wps;
88         char ifname[17];
89         char *mac_addr_text; /* mac addr of network i.f. we use */
90         u8 mac_addr[ETH_ALEN]; /* mac addr of network i.f. we use */
91         char *ip_addr_text; /* IP address of network i.f. we use */
92         unsigned ip_addr; /* IP address of network i.f. we use (host order) */
93         int multicast_sd;
94         int ssdp_sd;
95         struct wps_er_ap *ap;
96         struct http_server *http_srv;
97         int http_port;
98         unsigned int next_ap_id;
99 };
100
101
102 static struct wps_er_sta * wps_er_sta_get(struct wps_er_ap *ap, const u8 *addr)
103 {
104         struct wps_er_sta *sta = ap->sta;
105         while (sta) {
106                 if (os_memcmp(sta->addr, addr, ETH_ALEN) == 0)
107                         return sta;
108                 sta = sta->next;
109         }
110         return NULL;
111 }
112
113
114 static void wps_er_sta_free(struct wps_er_sta *sta)
115 {
116         if (sta->wps)
117                 wps_deinit(sta->wps);
118         os_free(sta->manufacturer);
119         os_free(sta->model_name);
120         os_free(sta->model_number);
121         os_free(sta->serial_number);
122         os_free(sta->dev_name);
123         http_client_free(sta->http);
124         eloop_cancel_timeout(wps_er_sta_timeout, sta, NULL);
125         os_free(sta);
126 }
127
128
129 static void wps_er_sta_remove_all(struct wps_er_ap *ap)
130 {
131         struct wps_er_sta *prev, *sta;
132
133         sta = ap->sta;
134         ap->sta = NULL;
135
136         while (sta) {
137                 prev = sta;
138                 sta = sta->next;
139                 wps_er_sta_free(prev);
140         }
141 }
142
143
144 static struct wps_er_ap * wps_er_ap_get(struct wps_er *er,
145                                         struct in_addr *addr)
146 {
147         struct wps_er_ap *ap;
148         for (ap = er->ap; ap; ap = ap->next) {
149                 if (ap->addr.s_addr == addr->s_addr)
150                         break;
151         }
152         return ap;
153 }
154
155
156 static struct wps_er_ap * wps_er_ap_get_id(struct wps_er *er, unsigned int id)
157 {
158         struct wps_er_ap *ap;
159         for (ap = er->ap; ap; ap = ap->next) {
160                 if (ap->id == id)
161                         break;
162         }
163         return ap;
164 }
165
166
167 static void wps_er_ap_free(struct wps_er *er, struct wps_er_ap *ap)
168 {
169         /* TODO: if ap->subscribed, unsubscribe from events if the AP is still
170          * alive */
171         wpa_printf(MSG_DEBUG, "WPS ER: Removing AP entry for %s (%s)",
172                    inet_ntoa(ap->addr), ap->location);
173         eloop_cancel_timeout(wps_er_ap_timeout, er, ap);
174         os_free(ap->location);
175         http_client_free(ap->http);
176
177         os_free(ap->friendly_name);
178         os_free(ap->manufacturer);
179         os_free(ap->manufacturer_url);
180         os_free(ap->model_description);
181         os_free(ap->model_name);
182         os_free(ap->model_number);
183         os_free(ap->model_url);
184         os_free(ap->serial_number);
185         os_free(ap->udn);
186         os_free(ap->upc);
187
188         os_free(ap->scpd_url);
189         os_free(ap->control_url);
190         os_free(ap->event_sub_url);
191
192         wps_er_sta_remove_all(ap);
193
194         os_free(ap);
195 }
196
197
198 static void wps_er_ap_timeout(void *eloop_data, void *user_ctx)
199 {
200         struct wps_er *er = eloop_data;
201         struct wps_er_ap *ap = user_ctx;
202         wpa_printf(MSG_DEBUG, "WPS ER: AP advertisement timed out");
203         wps_er_ap_free(er, ap);
204 }
205
206
207 static void wps_er_http_subscribe_cb(void *ctx, struct http_client *c,
208                                      enum http_client_event event)
209 {
210         struct wps_er_ap *ap = ctx;
211
212         switch (event) {
213         case HTTP_CLIENT_OK:
214                 wpa_printf(MSG_DEBUG, "WPS ER: Subscribed to events");
215                 break;
216         case HTTP_CLIENT_FAILED:
217         case HTTP_CLIENT_INVALID_REPLY:
218         case HTTP_CLIENT_TIMEOUT:
219                 wpa_printf(MSG_DEBUG, "WPS ER: Failed to subscribe to events");
220                 break;
221         }
222         http_client_free(ap->http);
223         ap->http = NULL;
224 }
225
226
227 static void wps_er_subscribe(struct wps_er_ap *ap)
228 {
229         struct wpabuf *req;
230         struct sockaddr_in dst;
231         char *url, *path;
232
233         if (ap->event_sub_url == NULL) {
234                 wpa_printf(MSG_DEBUG, "WPS ER: No eventSubURL - cannot "
235                            "subscribe");
236                 return;
237         }
238         if (ap->http) {
239                 wpa_printf(MSG_DEBUG, "WPS ER: Pending HTTP request - cannot "
240                            "send subscribe request");
241                 return;
242         }
243
244         url = http_client_url_parse(ap->event_sub_url, &dst, &path);
245         if (url == NULL) {
246                 wpa_printf(MSG_DEBUG, "WPS ER: Failed to parse eventSubURL");
247                 return;
248         }
249
250         req = wpabuf_alloc(os_strlen(ap->event_sub_url) + 1000);
251         if (req == NULL) {
252                 os_free(url);
253                 return;
254         }
255         wpabuf_printf(req,
256                       "SUBSCRIBE %s HTTP/1.1\r\n"
257                       "HOST: %s:%d\r\n"
258                       "CALLBACK: <http://%s:%d/event/%d>\r\n"
259                       "NT: upnp:event\r\n"
260                       "TIMEOUT: Second-%d\r\n"
261                       "\r\n",
262                       path, inet_ntoa(dst.sin_addr), ntohs(dst.sin_port),
263                       ap->er->ip_addr_text, ap->er->http_port, ap->id, 1800);
264         os_free(url);
265         wpa_hexdump_ascii(MSG_MSGDUMP, "WPS ER: Subscription request",
266                           wpabuf_head(req), wpabuf_len(req));
267
268         ap->http = http_client_addr(&dst, req, 1000, wps_er_http_subscribe_cb,
269                                     ap);
270         if (ap->http == NULL)
271                 wpabuf_free(req);
272 }
273
274
275 static void wps_er_parse_device_description(struct wps_er_ap *ap,
276                                             struct wpabuf *reply)
277 {
278         /* Note: reply includes null termination after the buffer data */
279         const char *data = wpabuf_head(reply);
280
281         wpa_hexdump_ascii(MSG_MSGDUMP, "WPS ER: Device info",
282                           wpabuf_head(reply), wpabuf_len(reply));
283
284         ap->friendly_name = xml_get_first_item(data, "friendlyName");
285         wpa_printf(MSG_DEBUG, "WPS ER: friendlyName='%s'", ap->friendly_name);
286
287         ap->manufacturer = xml_get_first_item(data, "manufacturer");
288         wpa_printf(MSG_DEBUG, "WPS ER: manufacturer='%s'", ap->manufacturer);
289
290         ap->manufacturer_url = xml_get_first_item(data, "manufacturerURL");
291         wpa_printf(MSG_DEBUG, "WPS ER: manufacturerURL='%s'",
292                    ap->manufacturer_url);
293
294         ap->model_description = xml_get_first_item(data, "modelDescription");
295         wpa_printf(MSG_DEBUG, "WPS ER: modelDescription='%s'",
296                    ap->model_description);
297
298         ap->model_name = xml_get_first_item(data, "modelName");
299         wpa_printf(MSG_DEBUG, "WPS ER: modelName='%s'", ap->model_name);
300
301         ap->model_number = xml_get_first_item(data, "modelNumber");
302         wpa_printf(MSG_DEBUG, "WPS ER: modelNumber='%s'", ap->model_number);
303
304         ap->model_url = xml_get_first_item(data, "modelURL");
305         wpa_printf(MSG_DEBUG, "WPS ER: modelURL='%s'", ap->model_url);
306
307         ap->serial_number = xml_get_first_item(data, "serialNumber");
308         wpa_printf(MSG_DEBUG, "WPS ER: serialNumber='%s'", ap->serial_number);
309
310         ap->udn = xml_get_first_item(data, "UDN");
311         wpa_printf(MSG_DEBUG, "WPS ER: UDN='%s'", ap->udn);
312
313         ap->upc = xml_get_first_item(data, "UPC");
314         wpa_printf(MSG_DEBUG, "WPS ER: UPC='%s'", ap->upc);
315
316         ap->scpd_url = http_link_update(
317                 xml_get_first_item(data, "SCPDURL"), ap->location);
318         wpa_printf(MSG_DEBUG, "WPS ER: SCPDURL='%s'", ap->scpd_url);
319
320         ap->control_url = http_link_update(
321                 xml_get_first_item(data, "controlURL"), ap->location);
322         wpa_printf(MSG_DEBUG, "WPS ER: controlURL='%s'", ap->control_url);
323
324         ap->event_sub_url = http_link_update(
325                 xml_get_first_item(data, "eventSubURL"), ap->location);
326         wpa_printf(MSG_DEBUG, "WPS ER: eventSubURL='%s'", ap->event_sub_url);
327 }
328
329
330 static void wps_er_http_dev_desc_cb(void *ctx, struct http_client *c,
331                                     enum http_client_event event)
332 {
333         struct wps_er_ap *ap = ctx;
334         struct wpabuf *reply;
335         int subscribe = 0;
336
337         switch (event) {
338         case HTTP_CLIENT_OK:
339                 reply = http_client_get_body(c);
340                 if (reply == NULL)
341                         break;
342                 wps_er_parse_device_description(ap, reply);
343                 subscribe = 1;
344                 break;
345         case HTTP_CLIENT_FAILED:
346         case HTTP_CLIENT_INVALID_REPLY:
347         case HTTP_CLIENT_TIMEOUT:
348                 wpa_printf(MSG_DEBUG, "WPS ER: Failed to fetch device info");
349                 break;
350         }
351         http_client_free(ap->http);
352         ap->http = NULL;
353         if (subscribe)
354                 wps_er_subscribe(ap);
355 }
356
357
358 static void wps_er_ap_add(struct wps_er *er, struct in_addr *addr,
359                           const char *location, int max_age)
360 {
361         struct wps_er_ap *ap;
362
363         ap = wps_er_ap_get(er, addr);
364         if (ap) {
365                 /* Update advertisement timeout */
366                 eloop_cancel_timeout(wps_er_ap_timeout, er, ap);
367                 eloop_register_timeout(max_age, 0, wps_er_ap_timeout, er, ap);
368                 return;
369         }
370
371         ap = os_zalloc(sizeof(*ap));
372         if (ap == NULL)
373                 return;
374         ap->er = er;
375         ap->id = ++er->next_ap_id;
376         ap->location = os_strdup(location);
377         if (ap->location == NULL) {
378                 os_free(ap);
379                 return;
380         }
381         ap->next = er->ap;
382         er->ap = ap;
383
384         ap->addr.s_addr = addr->s_addr;
385         eloop_register_timeout(max_age, 0, wps_er_ap_timeout, er, ap);
386
387         wpa_printf(MSG_DEBUG, "WPS ER: Added AP entry for %s (%s)",
388                    inet_ntoa(ap->addr), ap->location);
389
390         /* Fetch device description */
391         ap->http = http_client_url(ap->location, NULL, 10000,
392                                    wps_er_http_dev_desc_cb, ap);
393 }
394
395
396 static void wps_er_ap_remove(struct wps_er *er, struct in_addr *addr)
397 {
398         struct wps_er_ap *prev = NULL, *ap = er->ap;
399
400         while (ap) {
401                 if (ap->addr.s_addr == addr->s_addr) {
402                         if (prev)
403                                 prev->next = ap->next;
404                         else
405                                 er->ap = ap->next;
406                         wps_er_ap_free(er, ap);
407                         return;
408                 }
409                 prev = ap;
410                 ap = ap->next;
411         }
412 }
413
414
415 static void wps_er_ap_remove_all(struct wps_er *er)
416 {
417         struct wps_er_ap *prev, *ap;
418
419         ap = er->ap;
420         er->ap = NULL;
421
422         while (ap) {
423                 prev = ap;
424                 ap = ap->next;
425                 wps_er_ap_free(er, prev);
426         }
427 }
428
429
430 static void wps_er_ssdp_rx(int sd, void *eloop_ctx, void *sock_ctx)
431 {
432         struct wps_er *er = eloop_ctx;
433         struct sockaddr_in addr; /* client address */
434         socklen_t addr_len;
435         int nread;
436         char buf[MULTICAST_MAX_READ], *pos, *pos2, *start;
437         int wfa = 0, byebye = 0;
438         int max_age = -1;
439         char *location = NULL;
440
441         addr_len = sizeof(addr);
442         nread = recvfrom(sd, buf, sizeof(buf) - 1, 0,
443                          (struct sockaddr *) &addr, &addr_len);
444         if (nread <= 0)
445                 return;
446         buf[nread] = '\0';
447
448         wpa_printf(MSG_DEBUG, "WPS ER: Received SSDP from %s",
449                    inet_ntoa(addr.sin_addr));
450         wpa_hexdump_ascii(MSG_MSGDUMP, "WPS ER: Received SSDP contents",
451                           (u8 *) buf, nread);
452
453         if (sd == er->multicast_sd) {
454                 /* Reply to M-SEARCH */
455                 if (os_strncmp(buf, "HTTP/1.1 200 OK", 15) != 0)
456                         return; /* unexpected response header */
457         } else {
458                 /* Unsolicited message (likely NOTIFY or M-SEARCH) */
459                 if (os_strncmp(buf, "NOTIFY ", 7) != 0)
460                         return; /* only process notifications */
461         }
462
463         for (start = buf; start && *start; start = pos) {
464                 pos = os_strchr(start, '\n');
465                 if (pos) {
466                         if (pos[-1] == '\r')
467                                 pos[-1] = '\0';
468                         *pos++ = '\0';
469                 }
470                 if (os_strstr(start, "schemas-wifialliance-org:device:"
471                               "WFADevice:1"))
472                         wfa = 1;
473                 if (os_strstr(start, "schemas-wifialliance-org:service:"
474                               "WFAWLANConfig:1"))
475                         wfa = 1;
476                 if (os_strncasecmp(start, "LOCATION:", 9) == 0) {
477                         start += 9;
478                         while (*start == ' ')
479                                 start++;
480                         location = start;
481                 } else if (os_strncasecmp(start, "NTS:", 4) == 0) {
482                         if (os_strstr(start, "ssdp:byebye"))
483                                 byebye = 1;
484                 } else if (os_strncasecmp(start, "CACHE-CONTROL:", 14) == 0) {
485                         start += 9;
486                         while (*start == ' ')
487                                 start++;
488                         pos2 = os_strstr(start, "max-age=");
489                         if (pos2 == NULL)
490                                 continue;
491                         pos2 += 8;
492                         max_age = atoi(pos2);
493                 }
494         }
495
496         if (!wfa)
497                 return; /* Not WPS advertisement/reply */
498
499         if (byebye) {
500                 wps_er_ap_remove(er, &addr.sin_addr);
501                 return;
502         }
503
504         if (!location)
505                 return; /* Unknown location */
506
507         if (max_age < 1)
508                 return; /* No max-age reported */
509
510         wpa_printf(MSG_DEBUG, "WPS ER: AP discovered: %s "
511                    "(packet source: %s  max-age: %d)",
512                    location, inet_ntoa(addr.sin_addr), max_age);
513
514         wps_er_ap_add(er, &addr.sin_addr, location, max_age);
515 }
516
517
518 static void wps_er_send_ssdp_msearch(struct wps_er *er)
519 {
520         struct wpabuf *msg;
521         struct sockaddr_in dest;
522
523         msg = wpabuf_alloc(500);
524         if (msg == NULL)
525                 return;
526
527         wpabuf_put_str(msg,
528                        "M-SEARCH * HTTP/1.1\r\n"
529                        "HOST: 239.255.255.250:1900\r\n"
530                        "MAN: \"ssdp:discover\"\r\n"
531                        "MX: 3\r\n"
532                        "ST: urn:schemas-wifialliance-org:device:WFADevice:1"
533                        "\r\n"
534                        "\r\n");
535
536         os_memset(&dest, 0, sizeof(dest));
537         dest.sin_family = AF_INET;
538         dest.sin_addr.s_addr = inet_addr(UPNP_MULTICAST_ADDRESS);
539         dest.sin_port = htons(UPNP_MULTICAST_PORT);
540
541         if (sendto(er->multicast_sd, wpabuf_head(msg), wpabuf_len(msg), 0,
542                    (struct sockaddr *) &dest, sizeof(dest)) < 0)
543                 wpa_printf(MSG_DEBUG, "WPS ER: M-SEARCH sendto failed: "
544                            "%d (%s)", errno, strerror(errno));
545
546         wpabuf_free(msg);
547 }
548
549
550 static void http_put_date(struct wpabuf *buf)
551 {
552         wpabuf_put_str(buf, "Date: ");
553         format_date(buf);
554         wpabuf_put_str(buf, "\r\n");
555 }
556
557
558 static void wps_er_http_resp_not_found(struct http_request *req)
559 {
560         struct wpabuf *buf;
561         buf = wpabuf_alloc(200);
562         if (buf == NULL) {
563                 http_request_deinit(req);
564                 return;
565         }
566
567         wpabuf_put_str(buf,
568                        "HTTP/1.1 404 Not Found\r\n"
569                        "Server: unspecified, UPnP/1.0, unspecified\r\n"
570                        "Connection: close\r\n");
571         http_put_date(buf);
572         wpabuf_put_str(buf, "\r\n");
573         http_request_send_and_deinit(req, buf);
574 }
575
576
577 static void wps_er_http_resp_ok(struct http_request *req)
578 {
579         struct wpabuf *buf;
580         buf = wpabuf_alloc(200);
581         if (buf == NULL) {
582                 http_request_deinit(req);
583                 return;
584         }
585
586         wpabuf_put_str(buf,
587                        "HTTP/1.1 200 OK\r\n"
588                        "Server: unspecified, UPnP/1.0, unspecified\r\n"
589                        "Connection: close\r\n"
590                        "Content-Length: 0\r\n");
591         http_put_date(buf);
592         wpabuf_put_str(buf, "\r\n");
593         http_request_send_and_deinit(req, buf);
594 }
595
596
597 static void wps_er_sta_timeout(void *eloop_data, void *user_ctx)
598 {
599         struct wps_er_sta *sta = eloop_data;
600         wpa_printf(MSG_DEBUG, "WPS ER: STA entry timed out");
601         wps_er_sta_free(sta);
602 }
603
604
605 static struct wps_er_sta * wps_er_add_sta_data(struct wps_er_ap *ap,
606                                                const u8 *addr,
607                                                struct wps_parse_attr *attr,
608                                                int probe_req)
609 {
610         struct wps_er_sta *sta = wps_er_sta_get(ap, addr);
611
612         if (sta == NULL) {
613                 sta = os_zalloc(sizeof(*sta));
614                 if (sta == NULL)
615                         return NULL;
616                 os_memcpy(sta->addr, addr, ETH_ALEN);
617                 sta->ap = ap;
618                 sta->next = ap->sta;
619                 ap->sta = sta;
620         }
621
622         if (!probe_req)
623                 sta->m1_received = 1;
624
625         if (attr->config_methods && (!probe_req || !sta->m1_received))
626                 sta->config_methods = WPA_GET_BE16(attr->config_methods);
627         if (attr->uuid_e && (!probe_req || !sta->m1_received))
628                 os_memcpy(sta->uuid, attr->uuid_e, WPS_UUID_LEN);
629         if (attr->primary_dev_type && (!probe_req || !sta->m1_received))
630                 os_memcpy(sta->pri_dev_type, attr->primary_dev_type, 8);
631         if (attr->dev_password_id && (!probe_req || !sta->m1_received))
632                 sta->dev_passwd_id = WPA_GET_BE16(attr->dev_password_id);
633
634         if (attr->manufacturer) {
635                 os_free(sta->manufacturer);
636                 sta->manufacturer = os_malloc(attr->manufacturer_len + 1);
637                 if (sta->manufacturer) {
638                         os_memcpy(sta->manufacturer, attr->manufacturer,
639                                   attr->manufacturer_len);
640                         sta->manufacturer[attr->manufacturer_len] = '\0';
641                 }
642         }
643
644         if (attr->model_name) {
645                 os_free(sta->model_name);
646                 sta->model_name = os_malloc(attr->model_name_len + 1);
647                 if (sta->model_name) {
648                         os_memcpy(sta->model_name, attr->model_name,
649                                   attr->model_name_len);
650                         sta->model_name[attr->model_name_len] = '\0';
651                 }
652         }
653
654         if (attr->model_number) {
655                 os_free(sta->model_number);
656                 sta->model_number = os_malloc(attr->model_number_len + 1);
657                 if (sta->model_number) {
658                         os_memcpy(sta->model_number, attr->model_number,
659                                   attr->model_number_len);
660                         sta->model_number[attr->model_number_len] = '\0';
661                 }
662         }
663
664         if (attr->serial_number) {
665                 os_free(sta->serial_number);
666                 sta->serial_number = os_malloc(attr->serial_number_len + 1);
667                 if (sta->serial_number) {
668                         os_memcpy(sta->serial_number, attr->serial_number,
669                                   attr->serial_number_len);
670                         sta->serial_number[attr->serial_number_len] = '\0';
671                 }
672         }
673
674         if (attr->dev_name) {
675                 os_free(sta->dev_name);
676                 sta->dev_name = os_malloc(attr->dev_name_len + 1);
677                 if (sta->dev_name) {
678                         os_memcpy(sta->dev_name, attr->dev_name,
679                                   attr->dev_name_len);
680                         sta->dev_name[attr->dev_name_len] = '\0';
681                 }
682         }
683
684         eloop_cancel_timeout(wps_er_sta_timeout, sta, NULL);
685         eloop_register_timeout(300, 0, wps_er_sta_timeout, sta, NULL);
686
687         /* TODO: wpa_msg indication if new STA */
688
689         return sta;
690 }
691
692
693 static void wps_er_process_wlanevent_probe_req(struct wps_er_ap *ap,
694                                                const u8 *addr,
695                                                struct wpabuf *msg)
696 {
697         struct wps_parse_attr attr;
698
699         wpa_printf(MSG_DEBUG, "WPS ER: WLANEvent - Probe Request - from "
700                    MACSTR, MAC2STR(addr));
701         wpa_hexdump_buf(MSG_MSGDUMP, "WPS ER: WLANEvent - Enrollee's message "
702                         "(TLVs from Probe Request)", msg);
703
704         if (wps_parse_msg(msg, &attr) < 0) {
705                 wpa_printf(MSG_DEBUG, "WPS ER: Failed to parse TLVs in "
706                            "WLANEvent message");
707                 return;
708         }
709
710         wps_er_add_sta_data(ap, addr, &attr, 1);
711 }
712
713
714 static void wps_er_http_put_wlan_response_cb(void *ctx, struct http_client *c,
715                                              enum http_client_event event)
716 {
717         struct wps_er_sta *sta = ctx;
718
719         switch (event) {
720         case HTTP_CLIENT_OK:
721                 wpa_printf(MSG_DEBUG, "WPS ER: PutWLANResponse OK");
722                 break;
723         case HTTP_CLIENT_FAILED:
724         case HTTP_CLIENT_INVALID_REPLY:
725         case HTTP_CLIENT_TIMEOUT:
726                 wpa_printf(MSG_DEBUG, "WPS ER: PutWLANResponse failed");
727                 break;
728         }
729         http_client_free(sta->http);
730         sta->http = NULL;
731 }
732
733
734 static const char *soap_prefix =
735         "<?xml version=\"1.0\"?>\n"
736         "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" "
737         "s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n"
738         "<s:Body>\n";
739 static const char *soap_postfix =
740         "</s:Body>\n</s:Envelope>\n";
741 static const char *urn_wfawlanconfig =
742         "urn:schemas-wifialliance-org:service:WFAWLANConfig:1";
743
744 static struct wpabuf * wps_er_soap_hdr(const struct wpabuf *msg,
745                                        const char *name, const char *path,
746                                        const struct sockaddr_in *dst,
747                                        char **len_ptr, char **body_ptr)
748 {
749         unsigned char *encoded;
750         size_t encoded_len;
751         struct wpabuf *buf;
752
753         encoded = base64_encode(wpabuf_head(msg), wpabuf_len(msg),
754                                 &encoded_len);
755         if (encoded == NULL)
756                 return NULL;
757
758         buf = wpabuf_alloc(1000 + encoded_len);
759         if (buf == NULL) {
760                 os_free(encoded);
761                 return NULL;
762         }
763
764         wpabuf_printf(buf,
765                       "POST %s HTTP/1.1\r\n"
766                       "Host: %s:%d\r\n"
767                       "Content-Type: text/xml; charset=\"utf-8\"\r\n"
768                       "Content-Length: ",
769                       path, inet_ntoa(dst->sin_addr), ntohs(dst->sin_port));
770
771         *len_ptr = wpabuf_put(buf, 0);
772         wpabuf_printf(buf,
773                       "        \r\n"
774                       "SOAPACTION: \"%s#%s\"\r\n"
775                       "\r\n",
776                       urn_wfawlanconfig, name);
777
778         *body_ptr = wpabuf_put(buf, 0);
779
780         wpabuf_put_str(buf, soap_prefix);
781         wpabuf_printf(buf, "<u:%s xmlns:u=\"", name);
782         wpabuf_put_str(buf, urn_wfawlanconfig);
783         wpabuf_put_str(buf, "\">\n");
784         wpabuf_printf(buf, "<NewMessage>%s</NewMessage>\n", (char *) encoded);
785         os_free(encoded);
786
787         return buf;
788 }
789
790
791 static void wps_er_soap_end(struct wpabuf *buf, const char *name,
792                             char *len_ptr, char *body_ptr)
793 {
794         char len_buf[10];
795         wpabuf_printf(buf, "</u:%s>\n", name);
796         wpabuf_put_str(buf, soap_postfix);
797         os_snprintf(len_buf, sizeof(len_buf), "%d",
798                     (int) ((char *) wpabuf_put(buf, 0) - body_ptr));
799         os_memcpy(len_ptr, len_buf, os_strlen(len_buf));
800 }
801
802
803 static void wps_er_sta_send_msg(struct wps_er_sta *sta, struct wpabuf *msg)
804 {
805         struct wpabuf *buf;
806         char *len_ptr, *body_ptr;
807         struct sockaddr_in dst;
808         char *url, *path;
809
810         if (sta->http) {
811                 wpa_printf(MSG_DEBUG, "WPS ER: Pending HTTP request for STA - "
812                            "ignore new request");
813                 wpabuf_free(msg);
814                 return;
815         }
816
817         if (sta->ap->control_url == NULL) {
818                 wpa_printf(MSG_DEBUG, "WPS ER: No controlURL for AP");
819                 wpabuf_free(msg);
820                 return;
821         }
822
823         url = http_client_url_parse(sta->ap->control_url, &dst, &path);
824         if (url == NULL) {
825                 wpa_printf(MSG_DEBUG, "WPS ER: Failed to parse controlURL");
826                 wpabuf_free(msg);
827                 return;
828         }
829
830         buf = wps_er_soap_hdr(msg, "PutWLANResponse", path, &dst, &len_ptr,
831                               &body_ptr);
832         wpabuf_free(msg);
833         os_free(url);
834         if (buf == NULL)
835                 return;
836         wpabuf_printf(buf, "<NewWLANEventType>%d</NewWLANEventType>\n",
837                       UPNP_WPS_WLANEVENT_TYPE_EAP);
838         wpabuf_printf(buf, "<NewWLANEventMAC>" MACSTR "</NewWLANEventMAC>\n",
839                       MAC2STR(sta->addr));
840
841         wps_er_soap_end(buf, "PutWLANResponse", len_ptr, body_ptr);
842
843         sta->http = http_client_addr(&dst, buf, 1000,
844                                      wps_er_http_put_wlan_response_cb, sta);
845         if (sta->http == NULL)
846                 wpabuf_free(buf);
847 }
848
849
850 static void wps_er_sta_process(struct wps_er_sta *sta, struct wpabuf *msg)
851 {
852         enum wps_process_res res;
853
854         res = wps_process_msg(sta->wps, WSC_MSG, msg);
855         if (res == WPS_CONTINUE) {
856                 enum wsc_op_code op_code;
857                 struct wpabuf *next = wps_get_msg(sta->wps, &op_code);
858                 if (next)
859                         wps_er_sta_send_msg(sta, next);
860         }
861 }
862
863
864 static void wps_er_sta_start(struct wps_er_sta *sta, struct wpabuf *msg)
865 {
866         struct wps_config cfg;
867
868         if (sta->wps)
869                 wps_deinit(sta->wps);
870
871         os_memset(&cfg, 0, sizeof(cfg));
872         cfg.wps = sta->ap->er->wps;
873         cfg.registrar = 1;
874         cfg.peer_addr = sta->addr;
875
876         sta->wps = wps_init(&cfg);
877         if (sta->wps == NULL)
878                 return;
879
880         wps_er_sta_process(sta, msg);
881 }
882
883
884 static void wps_er_process_wlanevent_eap(struct wps_er_ap *ap, const u8 *addr,
885                                          struct wpabuf *msg)
886 {
887         struct wps_parse_attr attr;
888         struct wps_er_sta *sta;
889
890         wpa_printf(MSG_DEBUG, "WPS ER: WLANEvent - EAP - from " MACSTR,
891                    MAC2STR(addr));
892         wpa_hexdump_buf(MSG_MSGDUMP, "WPS ER: WLANEvent - Enrollee's message "
893                         "(TLVs from EAP-WSC)", msg);
894
895         if (wps_parse_msg(msg, &attr) < 0) {
896                 wpa_printf(MSG_DEBUG, "WPS ER: Failed to parse TLVs in "
897                            "WLANEvent message");
898                 return;
899         }
900
901         sta = wps_er_add_sta_data(ap, addr, &attr, 0);
902
903         if (attr.msg_type && *attr.msg_type == WPS_M1)
904                 wps_er_sta_start(sta, msg);
905         else if (sta->wps)
906                 wps_er_sta_process(sta, msg);
907 }
908
909
910 static void wps_er_process_wlanevent(struct wps_er_ap *ap,
911                                      struct wpabuf *event)
912 {
913         u8 *data;
914         u8 wlan_event_type;
915         u8 wlan_event_mac[ETH_ALEN];
916         struct wpabuf msg;
917
918         wpa_hexdump(MSG_MSGDUMP, "WPS ER: Received WLANEvent",
919                     wpabuf_head(event), wpabuf_len(event));
920         if (wpabuf_len(event) < 1 + 17) {
921                 wpa_printf(MSG_DEBUG, "WPS ER: Too short WLANEvent");
922                 return;
923         }
924
925         data = wpabuf_mhead(event);
926         wlan_event_type = data[0];
927         if (hwaddr_aton((char *) data + 1, wlan_event_mac) < 0) {
928                 wpa_printf(MSG_DEBUG, "WPS ER: Invalid WLANEventMAC in "
929                            "WLANEvent");
930                 return;
931         }
932
933         wpabuf_set(&msg, data + 1 + 17, wpabuf_len(event) - (1 + 17));
934
935         switch (wlan_event_type) {
936         case 1:
937                 wps_er_process_wlanevent_probe_req(ap, wlan_event_mac, &msg);
938                 break;
939         case 2:
940                 wps_er_process_wlanevent_eap(ap, wlan_event_mac, &msg);
941                 break;
942         default:
943                 wpa_printf(MSG_DEBUG, "WPS ER: Unknown WLANEventType %d",
944                            wlan_event_type);
945                 break;
946         }
947 }
948
949
950 static void wps_er_http_event(struct wps_er *er, struct http_request *req,
951                               unsigned int ap_id)
952 {
953         struct wps_er_ap *ap = wps_er_ap_get_id(er, ap_id);
954         struct wpabuf *event;
955         enum http_reply_code ret;
956
957         if (ap == NULL) {
958                 wpa_printf(MSG_DEBUG, "WPS ER: HTTP event from unknown AP id "
959                            "%u", ap_id);
960                 wps_er_http_resp_not_found(req);
961                 return;
962         }
963         wpa_printf(MSG_MSGDUMP, "WPS ER: HTTP event from AP id %u: %s",
964                    ap_id, http_request_get_data(req));
965
966         event = xml_get_base64_item(http_request_get_data(req), "WLANEvent",
967                                     &ret);
968         if (event == NULL) {
969                 wpa_printf(MSG_DEBUG, "WPS ER: Could not extract WLANEvent "
970                            "from the event notification");
971                 /*
972                  * Reply with OK anyway to avoid getting unregistered from
973                  * events.
974                  */
975                 wps_er_http_resp_ok(req);
976                 return;
977         }
978
979         wps_er_process_wlanevent(ap, event);
980
981         wpabuf_free(event);
982         wps_er_http_resp_ok(req);
983 }
984
985
986 static void wps_er_http_notify(struct wps_er *er, struct http_request *req)
987 {
988         char *uri = http_request_get_uri(req);
989
990         if (os_strncmp(uri, "/event/", 7) == 0) {
991                 wps_er_http_event(er, req, atoi(uri + 7));
992         } else {
993                 wpa_printf(MSG_DEBUG, "WPS ER: Unknown HTTP NOTIFY for '%s'",
994                            uri);
995                 wps_er_http_resp_not_found(req);
996         }
997 }
998
999
1000 static void wps_er_http_req(void *ctx, struct http_request *req)
1001 {
1002         struct wps_er *er = ctx;
1003         struct sockaddr_in *cli = http_request_get_cli_addr(req);
1004         enum httpread_hdr_type type = http_request_get_type(req);
1005         struct wpabuf *buf;
1006
1007         wpa_printf(MSG_DEBUG, "WPS ER: HTTP request: '%s' (type %d) from "
1008                    "%s:%d",
1009                    http_request_get_uri(req), type,
1010                    inet_ntoa(cli->sin_addr), ntohs(cli->sin_port));
1011
1012         switch (type) {
1013         case HTTPREAD_HDR_TYPE_NOTIFY:
1014                 wps_er_http_notify(er, req);
1015                 break;
1016         default:
1017                 wpa_printf(MSG_DEBUG, "WPS ER: Unsupported HTTP request type "
1018                            "%d", type);
1019                 buf = wpabuf_alloc(200);
1020                 if (buf == NULL) {
1021                         http_request_deinit(req);
1022                         return;
1023                 }
1024                 wpabuf_put_str(buf,
1025                                "HTTP/1.1 501 Unimplemented\r\n"
1026                                "Connection: close\r\n");
1027                 http_put_date(buf);
1028                 wpabuf_put_str(buf, "\r\n");
1029                 http_request_send_and_deinit(req, buf);
1030                 break;
1031         }
1032 }
1033
1034
1035 struct wps_er *
1036 wps_er_init(struct wps_context *wps, const char *ifname)
1037 {
1038         struct wps_er *er;
1039         struct in_addr addr;
1040
1041         er = os_zalloc(sizeof(*er));
1042         if (er == NULL)
1043                 return NULL;
1044
1045         er->multicast_sd = -1;
1046         er->ssdp_sd = -1;
1047
1048         os_strlcpy(er->ifname, ifname, sizeof(er->ifname));
1049         er->wps = wps;
1050
1051         if (get_netif_info(ifname,
1052                            &er->ip_addr, &er->ip_addr_text,
1053                            er->mac_addr, &er->mac_addr_text)) {
1054                 wpa_printf(MSG_INFO, "WPS UPnP: Could not get IP/MAC address "
1055                            "for %s. Does it have IP address?", ifname);
1056                 wps_er_deinit(er);
1057                 return NULL;
1058         }
1059
1060         if (add_ssdp_network(ifname)) {
1061                 wps_er_deinit(er);
1062                 return NULL;
1063         }
1064
1065         er->multicast_sd = ssdp_open_multicast_sock(er->ip_addr);
1066         if (er->multicast_sd < 0) {
1067                 wps_er_deinit(er);
1068                 return NULL;
1069         }
1070
1071         er->ssdp_sd = ssdp_listener_open();
1072         if (er->ssdp_sd < 0) {
1073                 wps_er_deinit(er);
1074                 return NULL;
1075         }
1076         if (eloop_register_sock(er->multicast_sd, EVENT_TYPE_READ,
1077                                 wps_er_ssdp_rx, er, NULL) ||
1078             eloop_register_sock(er->ssdp_sd, EVENT_TYPE_READ,
1079                                 wps_er_ssdp_rx, er, NULL)) {
1080                 wps_er_deinit(er);
1081                 return NULL;
1082         }
1083
1084         addr.s_addr = er->ip_addr;
1085         er->http_srv = http_server_init(&addr, -1, wps_er_http_req, er);
1086         if (er->http_srv == NULL) {
1087                 wps_er_deinit(er);
1088                 return NULL;
1089         }
1090         er->http_port = http_server_get_port(er->http_srv);
1091
1092         wpa_printf(MSG_DEBUG, "WPS ER: Start (ifname=%s ip_addr=%s "
1093                    "mac_addr=%s)",
1094                    er->ifname, er->ip_addr_text, er->mac_addr_text);
1095
1096         wps_er_send_ssdp_msearch(er);
1097
1098         return er;
1099 }
1100
1101
1102 void wps_er_deinit(struct wps_er *er)
1103 {
1104         if (er == NULL)
1105                 return;
1106         http_server_deinit(er->http_srv);
1107         wps_er_ap_remove_all(er);
1108         if (er->multicast_sd >= 0) {
1109                 eloop_unregister_sock(er->multicast_sd, EVENT_TYPE_READ);
1110                 close(er->multicast_sd);
1111         }
1112         if (er->ssdp_sd >= 0) {
1113                 eloop_unregister_sock(er->ssdp_sd, EVENT_TYPE_READ);
1114                 close(er->ssdp_sd);
1115         }
1116         os_free(er->ip_addr_text);
1117         os_free(er->mac_addr_text);
1118         os_free(er);
1119 }
1120
1121
1122 static void wps_er_http_set_sel_reg_cb(void *ctx, struct http_client *c,
1123                                        enum http_client_event event)
1124 {
1125         struct wps_er_ap *ap = ctx;
1126
1127         switch (event) {
1128         case HTTP_CLIENT_OK:
1129                 wpa_printf(MSG_DEBUG, "WPS ER: SetSelectedRegistrar OK");
1130                 break;
1131         case HTTP_CLIENT_FAILED:
1132         case HTTP_CLIENT_INVALID_REPLY:
1133         case HTTP_CLIENT_TIMEOUT:
1134                 wpa_printf(MSG_DEBUG, "WPS ER: SetSelectedRegistrar failed");
1135                 break;
1136         }
1137         http_client_free(ap->http);
1138         ap->http = NULL;
1139 }
1140
1141
1142 static void wps_er_send_set_sel_reg(struct wps_er_ap *ap, struct wpabuf *msg)
1143 {
1144         struct wpabuf *buf;
1145         char *len_ptr, *body_ptr;
1146         struct sockaddr_in dst;
1147         char *url, *path;
1148
1149         if (ap->control_url == NULL) {
1150                 wpa_printf(MSG_DEBUG, "WPS ER: No controlURL for AP");
1151                 return;
1152         }
1153
1154         if (ap->http) {
1155                 wpa_printf(MSG_DEBUG, "WPS ER: Pending HTTP request for AP - "
1156                            "ignore new request");
1157                 return;
1158         }
1159
1160         url = http_client_url_parse(ap->control_url, &dst, &path);
1161         if (url == NULL) {
1162                 wpa_printf(MSG_DEBUG, "WPS ER: Failed to parse controlURL");
1163                 return;
1164         }
1165
1166         buf = wps_er_soap_hdr(msg, "SetSelectedRegistrar", path, &dst,
1167                               &len_ptr, &body_ptr);
1168         os_free(url);
1169         if (buf == NULL)
1170                 return;
1171
1172         wps_er_soap_end(buf, "SetSelectedRegistrar", len_ptr, body_ptr);
1173
1174         ap->http = http_client_addr(&dst, buf, 1000,
1175                                     wps_er_http_set_sel_reg_cb, ap);
1176         if (ap->http == NULL)
1177                 wpabuf_free(buf);
1178 }
1179
1180
1181 static int wps_er_build_selected_registrar(struct wpabuf *msg, int sel_reg)
1182 {
1183         wpabuf_put_be16(msg, ATTR_SELECTED_REGISTRAR);
1184         wpabuf_put_be16(msg, 1);
1185         wpabuf_put_u8(msg, !!sel_reg);
1186         return 0;
1187 }
1188
1189
1190 static int wps_er_build_dev_password_id(struct wpabuf *msg, u16 dev_passwd_id)
1191 {
1192         wpabuf_put_be16(msg, ATTR_DEV_PASSWORD_ID);
1193         wpabuf_put_be16(msg, 2);
1194         wpabuf_put_be16(msg, dev_passwd_id);
1195         return 0;
1196 }
1197
1198
1199 static int wps_er_build_sel_reg_config_methods(struct wpabuf *msg,
1200                                                u16 sel_reg_config_methods)
1201 {
1202         wpabuf_put_be16(msg, ATTR_SELECTED_REGISTRAR_CONFIG_METHODS);
1203         wpabuf_put_be16(msg, 2);
1204         wpabuf_put_be16(msg, sel_reg_config_methods);
1205         return 0;
1206 }
1207
1208
1209 void wps_er_set_sel_reg(struct wps_er *er, int sel_reg, u16 dev_passwd_id,
1210                         u16 sel_reg_config_methods)
1211 {
1212         struct wpabuf *msg;
1213         struct wps_er_ap *ap;
1214
1215         msg = wpabuf_alloc(500);
1216         if (msg == NULL)
1217                 return;
1218
1219         if (wps_build_version(msg) ||
1220             wps_er_build_selected_registrar(msg, sel_reg) ||
1221             wps_er_build_dev_password_id(msg, dev_passwd_id) ||
1222             wps_er_build_sel_reg_config_methods(msg, sel_reg_config_methods)) {
1223                 wpabuf_free(msg);
1224                 return;
1225         }
1226
1227         for (ap = er->ap; ap; ap = ap->next)
1228                 wps_er_send_set_sel_reg(ap, msg);
1229
1230         wpabuf_free(msg);
1231 }