WPS ER: Add PutWLANResponse generation and transmission
[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 void wps_er_sta_send_msg(struct wps_er_sta *sta, struct wpabuf *msg)
745 {
746         unsigned char *encoded;
747         size_t encoded_len;
748         struct wpabuf *buf;
749         char *len_ptr, *body_ptr;
750         char len_buf[10];
751         struct sockaddr_in dst;
752         char *url, *path;
753
754         if (sta->http) {
755                 wpa_printf(MSG_DEBUG, "WPS ER: Pending HTTP request for STA - "
756                            "ignore new request");
757                 return;
758         }
759
760         url = http_client_url_parse(sta->ap->control_url, &dst, &path);
761         if (url == NULL) {
762                 wpa_printf(MSG_DEBUG, "WPS ER: Failed to parse eventSubURL");
763                 return;
764         }
765
766         encoded = base64_encode(wpabuf_head(msg), wpabuf_len(msg),
767                                 &encoded_len);
768         wpabuf_free(msg);
769         if (encoded == NULL) {
770                 os_free(url);
771                 return;
772         }
773
774         buf = wpabuf_alloc(1000 + encoded_len);
775         if (buf == NULL) {
776                 os_free(encoded);
777                 os_free(url);
778                 return;
779         }
780
781         wpabuf_printf(buf,
782                       "POST %s HTTP/1.1\r\n"
783                       "Host: %s:%d\r\n"
784                       "Content-Type: text/xml; charset=\"utf-8\"\r\n"
785                       "Content-Length: ",
786                       path, inet_ntoa(dst.sin_addr), ntohs(dst.sin_port));
787         os_free(url);
788         len_ptr = wpabuf_put(buf, 0);
789         wpabuf_printf(buf,
790                       "        \r\n"
791                       "SOAPACTION: \"%s#PutWLANResponse\"\r\n"
792                       "\r\n",
793                       urn_wfawlanconfig);
794
795         body_ptr = wpabuf_put(buf, 0);
796
797         wpabuf_put_str(buf, soap_prefix);
798         wpabuf_put_str(buf, "<u:PutWLANResponse xmlns:u=\"");
799         wpabuf_put_str(buf, urn_wfawlanconfig);
800         wpabuf_put_str(buf, "\">\n");
801         wpabuf_printf(buf, "<NewMessage>%s</NewMessage>\n", (char *) encoded);
802         os_free(encoded);
803         wpabuf_printf(buf, "<NewWLANEventType>%d</NewWLANEventType>\n",
804                       UPNP_WPS_WLANEVENT_TYPE_EAP);
805         wpabuf_printf(buf, "<NewWLANEventMAC>" MACSTR "</NewWLANEventMAC>\n",
806                       MAC2STR(sta->addr));
807         wpabuf_put_str(buf, "</u:PutWLANResponse>\n");
808         wpabuf_put_str(buf, soap_postfix);
809
810         os_snprintf(len_buf, sizeof(len_buf), "%d",
811                     (int) ((char *) wpabuf_put(buf, 0) - body_ptr));
812         os_memcpy(len_ptr, len_buf, os_strlen(len_buf));
813
814         sta->http = http_client_addr(&dst, buf, 1000,
815                                      wps_er_http_put_wlan_response_cb, sta);
816         if (sta->http == NULL)
817                 wpabuf_free(buf);
818 }
819
820
821 static void wps_er_sta_process(struct wps_er_sta *sta, struct wpabuf *msg)
822 {
823         enum wps_process_res res;
824
825         res = wps_process_msg(sta->wps, WSC_MSG, msg);
826         if (res == WPS_CONTINUE) {
827                 enum wsc_op_code op_code;
828                 struct wpabuf *next = wps_get_msg(sta->wps, &op_code);
829                 if (next)
830                         wps_er_sta_send_msg(sta, next);
831         }
832 }
833
834
835 static void wps_er_sta_start(struct wps_er_sta *sta, struct wpabuf *msg)
836 {
837         struct wps_config cfg;
838
839         if (sta->wps)
840                 wps_deinit(sta->wps);
841
842         os_memset(&cfg, 0, sizeof(cfg));
843         cfg.wps = sta->ap->er->wps;
844         cfg.registrar = 1;
845         cfg.peer_addr = sta->addr;
846
847         sta->wps = wps_init(&cfg);
848         if (sta->wps == NULL)
849                 return;
850
851         wps_er_sta_process(sta, msg);
852 }
853
854
855 static void wps_er_process_wlanevent_eap(struct wps_er_ap *ap, const u8 *addr,
856                                          struct wpabuf *msg)
857 {
858         struct wps_parse_attr attr;
859         struct wps_er_sta *sta;
860
861         wpa_printf(MSG_DEBUG, "WPS ER: WLANEvent - EAP - from " MACSTR,
862                    MAC2STR(addr));
863         wpa_hexdump_buf(MSG_MSGDUMP, "WPS ER: WLANEvent - Enrollee's message "
864                         "(TLVs from EAP-WSC)", msg);
865
866         if (wps_parse_msg(msg, &attr) < 0) {
867                 wpa_printf(MSG_DEBUG, "WPS ER: Failed to parse TLVs in "
868                            "WLANEvent message");
869                 return;
870         }
871
872         sta = wps_er_add_sta_data(ap, addr, &attr, 0);
873
874         if (attr.msg_type && *attr.msg_type == WPS_M1)
875                 wps_er_sta_start(sta, msg);
876         else if (sta->wps)
877                 wps_er_sta_process(sta, msg);
878 }
879
880
881 static void wps_er_process_wlanevent(struct wps_er_ap *ap,
882                                      struct wpabuf *event)
883 {
884         u8 *data;
885         u8 wlan_event_type;
886         u8 wlan_event_mac[ETH_ALEN];
887         struct wpabuf msg;
888
889         wpa_hexdump(MSG_MSGDUMP, "WPS ER: Received WLANEvent",
890                     wpabuf_head(event), wpabuf_len(event));
891         if (wpabuf_len(event) < 1 + 17) {
892                 wpa_printf(MSG_DEBUG, "WPS ER: Too short WLANEvent");
893                 return;
894         }
895
896         data = wpabuf_mhead(event);
897         wlan_event_type = data[0];
898         if (hwaddr_aton((char *) data + 1, wlan_event_mac) < 0) {
899                 wpa_printf(MSG_DEBUG, "WPS ER: Invalid WLANEventMAC in "
900                            "WLANEvent");
901                 return;
902         }
903
904         wpabuf_set(&msg, data + 1 + 17, wpabuf_len(event) - (1 + 17));
905
906         switch (wlan_event_type) {
907         case 1:
908                 wps_er_process_wlanevent_probe_req(ap, wlan_event_mac, &msg);
909                 break;
910         case 2:
911                 wps_er_process_wlanevent_eap(ap, wlan_event_mac, &msg);
912                 break;
913         default:
914                 wpa_printf(MSG_DEBUG, "WPS ER: Unknown WLANEventType %d",
915                            wlan_event_type);
916                 break;
917         }
918 }
919
920
921 static void wps_er_http_event(struct wps_er *er, struct http_request *req,
922                               unsigned int ap_id)
923 {
924         struct wps_er_ap *ap = wps_er_ap_get_id(er, ap_id);
925         struct wpabuf *event;
926         enum http_reply_code ret;
927
928         if (ap == NULL) {
929                 wpa_printf(MSG_DEBUG, "WPS ER: HTTP event from unknown AP id "
930                            "%u", ap_id);
931                 wps_er_http_resp_not_found(req);
932                 return;
933         }
934         wpa_printf(MSG_MSGDUMP, "WPS ER: HTTP event from AP id %u: %s",
935                    ap_id, http_request_get_data(req));
936
937         event = xml_get_base64_item(http_request_get_data(req), "WLANEvent",
938                                     &ret);
939         if (event == NULL) {
940                 wpa_printf(MSG_DEBUG, "WPS ER: Could not extract WLANEvent "
941                            "from the event notification");
942                 /*
943                  * Reply with OK anyway to avoid getting unregistered from
944                  * events.
945                  */
946                 wps_er_http_resp_ok(req);
947                 return;
948         }
949
950         wps_er_process_wlanevent(ap, event);
951
952         wpabuf_free(event);
953         wps_er_http_resp_ok(req);
954 }
955
956
957 static void wps_er_http_notify(struct wps_er *er, struct http_request *req)
958 {
959         char *uri = http_request_get_uri(req);
960
961         if (os_strncmp(uri, "/event/", 7) == 0) {
962                 wps_er_http_event(er, req, atoi(uri + 7));
963         } else {
964                 wpa_printf(MSG_DEBUG, "WPS ER: Unknown HTTP NOTIFY for '%s'",
965                            uri);
966                 wps_er_http_resp_not_found(req);
967         }
968 }
969
970
971 static void wps_er_http_req(void *ctx, struct http_request *req)
972 {
973         struct wps_er *er = ctx;
974         struct sockaddr_in *cli = http_request_get_cli_addr(req);
975         enum httpread_hdr_type type = http_request_get_type(req);
976         struct wpabuf *buf;
977
978         wpa_printf(MSG_DEBUG, "WPS ER: HTTP request: '%s' (type %d) from "
979                    "%s:%d",
980                    http_request_get_uri(req), type,
981                    inet_ntoa(cli->sin_addr), ntohs(cli->sin_port));
982
983         switch (type) {
984         case HTTPREAD_HDR_TYPE_NOTIFY:
985                 wps_er_http_notify(er, req);
986                 break;
987         default:
988                 wpa_printf(MSG_DEBUG, "WPS ER: Unsupported HTTP request type "
989                            "%d", type);
990                 buf = wpabuf_alloc(200);
991                 if (buf == NULL) {
992                         http_request_deinit(req);
993                         return;
994                 }
995                 wpabuf_put_str(buf,
996                                "HTTP/1.1 501 Unimplemented\r\n"
997                                "Connection: close\r\n");
998                 http_put_date(buf);
999                 wpabuf_put_str(buf, "\r\n");
1000                 http_request_send_and_deinit(req, buf);
1001                 break;
1002         }
1003 }
1004
1005
1006 struct wps_er *
1007 wps_er_init(struct wps_context *wps, const char *ifname)
1008 {
1009         struct wps_er *er;
1010         struct in_addr addr;
1011
1012         er = os_zalloc(sizeof(*er));
1013         if (er == NULL)
1014                 return NULL;
1015
1016         er->multicast_sd = -1;
1017         er->ssdp_sd = -1;
1018
1019         os_strlcpy(er->ifname, ifname, sizeof(er->ifname));
1020         er->wps = wps;
1021
1022         if (get_netif_info(ifname,
1023                            &er->ip_addr, &er->ip_addr_text,
1024                            er->mac_addr, &er->mac_addr_text)) {
1025                 wpa_printf(MSG_INFO, "WPS UPnP: Could not get IP/MAC address "
1026                            "for %s. Does it have IP address?", ifname);
1027                 wps_er_deinit(er);
1028                 return NULL;
1029         }
1030
1031         if (add_ssdp_network(ifname)) {
1032                 wps_er_deinit(er);
1033                 return NULL;
1034         }
1035
1036         er->multicast_sd = ssdp_open_multicast_sock(er->ip_addr);
1037         if (er->multicast_sd < 0) {
1038                 wps_er_deinit(er);
1039                 return NULL;
1040         }
1041
1042         er->ssdp_sd = ssdp_listener_open();
1043         if (er->ssdp_sd < 0) {
1044                 wps_er_deinit(er);
1045                 return NULL;
1046         }
1047         if (eloop_register_sock(er->multicast_sd, EVENT_TYPE_READ,
1048                                 wps_er_ssdp_rx, er, NULL) ||
1049             eloop_register_sock(er->ssdp_sd, EVENT_TYPE_READ,
1050                                 wps_er_ssdp_rx, er, NULL)) {
1051                 wps_er_deinit(er);
1052                 return NULL;
1053         }
1054
1055         addr.s_addr = er->ip_addr;
1056         er->http_srv = http_server_init(&addr, -1, wps_er_http_req, er);
1057         if (er->http_srv == NULL) {
1058                 wps_er_deinit(er);
1059                 return NULL;
1060         }
1061         er->http_port = http_server_get_port(er->http_srv);
1062
1063         wpa_printf(MSG_DEBUG, "WPS ER: Start (ifname=%s ip_addr=%s "
1064                    "mac_addr=%s)",
1065                    er->ifname, er->ip_addr_text, er->mac_addr_text);
1066
1067         wps_er_send_ssdp_msearch(er);
1068
1069         return er;
1070 }
1071
1072
1073 void wps_er_deinit(struct wps_er *er)
1074 {
1075         if (er == NULL)
1076                 return;
1077         http_server_deinit(er->http_srv);
1078         wps_er_ap_remove_all(er);
1079         if (er->multicast_sd >= 0) {
1080                 eloop_unregister_sock(er->multicast_sd, EVENT_TYPE_READ);
1081                 close(er->multicast_sd);
1082         }
1083         if (er->ssdp_sd >= 0) {
1084                 eloop_unregister_sock(er->ssdp_sd, EVENT_TYPE_READ);
1085                 close(er->ssdp_sd);
1086         }
1087         os_free(er->ip_addr_text);
1088         os_free(er->mac_addr_text);
1089         os_free(er);
1090 }