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