xref: /freebsd/contrib/wpa/src/wps/wps_upnp.c (revision 6419bb52)
1 /*
2  * UPnP WPS Device
3  * Copyright (c) 2000-2003 Intel Corporation
4  * Copyright (c) 2006-2007 Sony Corporation
5  * Copyright (c) 2008-2009 Atheros Communications
6  * Copyright (c) 2009-2010, Jouni Malinen <j@w1.fi>
7  *
8  * See below for more details on licensing and code history.
9  */
10 
11 /*
12  * This has been greatly stripped down from the original file
13  * (upnp_wps_device.c) by Ted Merrill, Atheros Communications
14  * in order to eliminate use of the bulky libupnp library etc.
15  *
16  * History:
17  * upnp_wps_device.c is/was a shim layer between wps_opt_upnp.c and
18  * the libupnp library.
19  * The layering (by Sony) was well done; only a very minor modification
20  * to API of upnp_wps_device.c was required.
21  * libupnp was found to be undesirable because:
22  * -- It consumed too much code and data space
23  * -- It uses multiple threads, making debugging more difficult
24  *      and possibly reducing reliability.
25  * -- It uses static variables and only supports one instance.
26  * The shim and libupnp are here replaced by special code written
27  * specifically for the needs of hostapd.
28  * Various shortcuts can and are taken to keep the code size small.
29  * Generally, execution time is not as crucial.
30  *
31  * BUGS:
32  * -- UPnP requires that we be able to resolve domain names.
33  * While uncommon, if we have to do it then it will stall the entire
34  * hostapd program, which is bad.
35  * This is because we use the standard linux getaddrinfo() function
36  * which is syncronous.
37  * An asyncronous solution would be to use the free "ares" library.
38  * -- Does not have a robust output buffering scheme.  Uses a single
39  * fixed size output buffer per TCP/HTTP connection, with possible (although
40  * unlikely) possibility of overflow and likely excessive use of RAM.
41  * A better solution would be to write the HTTP output as a buffered stream,
42  * using chunking: (handle header specially, then) generate data with
43  * a printf-like function into a buffer, catching buffer full condition,
44  * then send it out surrounded by http chunking.
45  * -- There is some code that could be separated out into the common
46  * library to be shared with wpa_supplicant.
47  * -- Needs renaming with module prefix to avoid polluting the debugger
48  * namespace and causing possible collisions with other static fncs
49  * and structure declarations when using the debugger.
50  * -- The http error code generation is pretty bogus, hopefully no one cares.
51  *
52  * Author: Ted Merrill, Atheros Communications, based upon earlier work
53  * as explained above and below.
54  *
55  * Copyright:
56  * Copyright 2008 Atheros Communications.
57  *
58  * The original header (of upnp_wps_device.c) reads:
59  *
60  *  Copyright (c) 2006-2007 Sony Corporation. All Rights Reserved.
61  *
62  *  File Name: upnp_wps_device.c
63  *  Description: EAP-WPS UPnP device source
64  *
65  *   Redistribution and use in source and binary forms, with or without
66  *   modification, are permitted provided that the following conditions
67  *   are met:
68  *
69  *     * Redistributions of source code must retain the above copyright
70  *       notice, this list of conditions and the following disclaimer.
71  *     * Redistributions in binary form must reproduce the above copyright
72  *       notice, this list of conditions and the following disclaimer in
73  *       the documentation and/or other materials provided with the
74  *       distribution.
75  *     * Neither the name of Sony Corporation nor the names of its
76  *       contributors may be used to endorse or promote products derived
77  *       from this software without specific prior written permission.
78  *
79  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
80  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
81  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
82  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
83  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
84  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
85  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
86  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
87  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
88  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
89  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
90  *
91  * Portions from Intel libupnp files, e.g. genlib/net/http/httpreadwrite.c
92  * typical header:
93  *
94  * Copyright (c) 2000-2003 Intel Corporation
95  * All rights reserved.
96  *
97  * Redistribution and use in source and binary forms, with or without
98  * modification, are permitted provided that the following conditions are met:
99  *
100  * * Redistributions of source code must retain the above copyright notice,
101  * this list of conditions and the following disclaimer.
102  * * Redistributions in binary form must reproduce the above copyright notice,
103  * this list of conditions and the following disclaimer in the documentation
104  * and/or other materials provided with the distribution.
105  * * Neither name of Intel Corporation nor the names of its contributors
106  * may be used to endorse or promote products derived from this software
107  * without specific prior written permission.
108  *
109  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
110  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
111  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
112  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL INTEL OR
113  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
114  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
115  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
116  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
117  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
118  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
119  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
120 */
121 
122 /*
123  * Overview of WPS over UPnP:
124  *
125  * UPnP is a protocol that allows devices to discover each other and control
126  * each other. In UPnP terminology, a device is either a "device" (a server
127  * that provides information about itself and allows itself to be controlled)
128  * or a "control point" (a client that controls "devices") or possibly both.
129  * This file implements a UPnP "device".
130  *
131  * For us, we use mostly basic UPnP discovery, but the control part of interest
132  * is WPS carried via UPnP messages. There is quite a bit of basic UPnP
133  * discovery to do before we can get to WPS, however.
134  *
135  * UPnP discovery begins with "devices" send out multicast UDP packets to a
136  * certain fixed multicast IP address and port, and "control points" sending
137  * out other such UDP packets.
138  *
139  * The packets sent by devices are NOTIFY packets (not to be confused with TCP
140  * NOTIFY packets that are used later) and those sent by control points are
141  * M-SEARCH packets. These packets contain a simple HTTP style header. The
142  * packets are sent redundantly to get around packet loss. Devices respond to
143  * M-SEARCH packets with HTTP-like UDP packets containing HTTP/1.1 200 OK
144  * messages, which give similar information as the UDP NOTIFY packets.
145  *
146  * The above UDP packets advertise the (arbitrary) TCP ports that the
147  * respective parties will listen to. The control point can then do a HTTP
148  * SUBSCRIBE (something like an HTTP PUT) after which the device can do a
149  * separate HTTP NOTIFY (also like an HTTP PUT) to do event messaging.
150  *
151  * The control point will also do HTTP GET of the "device file" listed in the
152  * original UDP information from the device (see UPNP_WPS_DEVICE_XML_FILE
153  * data), and based on this will do additional GETs... HTTP POSTs are done to
154  * cause an action.
155  *
156  * Beyond some basic information in HTTP headers, additional information is in
157  * the HTTP bodies, in a format set by the SOAP and XML standards, a markup
158  * language related to HTML used for web pages. This language is intended to
159  * provide the ultimate in self-documentation by providing a universal
160  * namespace based on pseudo-URLs called URIs. Note that although a URI looks
161  * like a URL (a web address), they are never accessed as such but are used
162  * only as identifiers.
163  *
164  * The POST of a GetDeviceInfo gets information similar to what might be
165  * obtained from a probe request or response on Wi-Fi. WPS messages M1-M8
166  * are passed via a POST of a PutMessage; the M1-M8 WPS messages are converted
167  * to a bin64 ascii representation for encapsulation. When proxying messages,
168  * WLANEvent and PutWLANResponse are used.
169  *
170  * This of course glosses over a lot of details.
171  */
172 
173 #include "includes.h"
174 
175 #include <time.h>
176 #include <net/if.h>
177 #include <netdb.h>
178 #include <sys/ioctl.h>
179 
180 #include "common.h"
181 #include "uuid.h"
182 #include "base64.h"
183 #include "wps.h"
184 #include "wps_i.h"
185 #include "wps_upnp.h"
186 #include "wps_upnp_i.h"
187 
188 
189 /*
190  * UPnP allows a client ("control point") to send a server like us ("device")
191  * a domain name for registration, and we are supposed to resolve it. This is
192  * bad because, using the standard Linux library, we will stall the entire
193  * hostapd waiting for resolution.
194  *
195  * The "correct" solution would be to use an event driven library for domain
196  * name resolution such as "ares". However, this would increase code size
197  * further. Since it is unlikely that we'll actually see such domain names, we
198  * can just refuse to accept them.
199  */
200 #define NO_DOMAIN_NAME_RESOLUTION 1  /* 1 to allow only dotted ip addresses */
201 
202 
203 /*
204  * UPnP does not scale well. If we were in a room with thousands of control
205  * points then potentially we could be expected to handle subscriptions for
206  * each of them, which would exhaust our memory. So we must set a limit. In
207  * practice we are unlikely to see more than one or two.
208  */
209 #define MAX_SUBSCRIPTIONS 4    /* how many subscribing clients we handle */
210 #define MAX_ADDR_PER_SUBSCRIPTION 8
211 
212 /* Maximum number of Probe Request events per second */
213 #define MAX_EVENTS_PER_SEC 5
214 
215 
216 static struct upnp_wps_device_sm *shared_upnp_device = NULL;
217 
218 
219 /* Write the current date/time per RFC */
220 void format_date(struct wpabuf *buf)
221 {
222 	const char *weekday_str = "Sun\0Mon\0Tue\0Wed\0Thu\0Fri\0Sat";
223 	const char *month_str = "Jan\0Feb\0Mar\0Apr\0May\0Jun\0"
224 		"Jul\0Aug\0Sep\0Oct\0Nov\0Dec";
225 	struct tm *date;
226 	time_t t;
227 
228 	t = time(NULL);
229 	date = gmtime(&t);
230 	if (date == NULL)
231 		return;
232 	wpabuf_printf(buf, "%s, %02d %s %d %02d:%02d:%02d GMT",
233 		      &weekday_str[date->tm_wday * 4], date->tm_mday,
234 		      &month_str[date->tm_mon * 4], date->tm_year + 1900,
235 		      date->tm_hour, date->tm_min, date->tm_sec);
236 }
237 
238 
239 /***************************************************************************
240  * UUIDs (unique identifiers)
241  *
242  * These are supposed to be unique in all the world.
243  * Sometimes permanent ones are used, sometimes temporary ones
244  * based on random numbers... there are different rules for valid content
245  * of different types.
246  * Each uuid is 16 bytes long.
247  **************************************************************************/
248 
249 /* uuid_make -- construct a random UUID
250  * The UPnP documents don't seem to offer any guidelines as to which method to
251  * use for constructing UUIDs for subscriptions. Presumably any method from
252  * rfc4122 is good enough; I've chosen random number method.
253  */
254 static int uuid_make(u8 uuid[UUID_LEN])
255 {
256 	if (os_get_random(uuid, UUID_LEN) < 0)
257 		return -1;
258 
259 	/* Replace certain bits as specified in rfc4122 or X.667 */
260 	uuid[6] &= 0x0f; uuid[6] |= (4 << 4);   /* version 4 == random gen */
261 	uuid[8] &= 0x3f; uuid[8] |= 0x80;
262 
263 	return 0;
264 }
265 
266 
267 /*
268  * Subscriber address handling.
269  * Since a subscriber may have an arbitrary number of addresses, we have to
270  * add a bunch of code to handle them.
271  *
272  * Addresses are passed in text, and MAY be domain names instead of the (usual
273  * and expected) dotted IP addresses. Resolving domain names consumes a lot of
274  * resources. Worse, we are currently using the standard Linux getaddrinfo()
275  * which will block the entire program until complete or timeout! The proper
276  * solution would be to use the "ares" library or similar with more state
277  * machine steps etc. or just disable domain name resolution by setting
278  * NO_DOMAIN_NAME_RESOLUTION to 1 at top of this file.
279  */
280 
281 /* subscr_addr_delete -- delete single unlinked subscriber address
282  * (be sure to unlink first if need be)
283  */
284 void subscr_addr_delete(struct subscr_addr *a)
285 {
286 	/*
287 	 * Note: do NOT free domain_and_port or path because they point to
288 	 * memory within the allocation of "a".
289 	 */
290 	os_free(a);
291 }
292 
293 
294 /* subscr_addr_free_all -- unlink and delete list of subscriber addresses. */
295 static void subscr_addr_free_all(struct subscription *s)
296 {
297 	struct subscr_addr *a, *tmp;
298 	dl_list_for_each_safe(a, tmp, &s->addr_list, struct subscr_addr, list)
299 	{
300 		dl_list_del(&a->list);
301 		subscr_addr_delete(a);
302 	}
303 }
304 
305 
306 static int local_network_addr(struct upnp_wps_device_sm *sm,
307 			      struct sockaddr_in *addr)
308 {
309 	return (addr->sin_addr.s_addr & sm->netmask.s_addr) ==
310 		(sm->ip_addr & sm->netmask.s_addr);
311 }
312 
313 
314 /* subscr_addr_add_url -- add address(es) for one url to subscription */
315 static void subscr_addr_add_url(struct subscription *s, const char *url,
316 				size_t url_len)
317 {
318 	int alloc_len;
319 	char *scratch_mem = NULL;
320 	char *mem;
321 	char *host;
322 	char *delim;
323 	char *path;
324 	int port = 80;  /* port to send to (default is port 80) */
325 	struct addrinfo hints;
326 	struct addrinfo *result = NULL;
327 	struct addrinfo *rp;
328 	int rerr;
329 	size_t host_len, path_len;
330 
331 	/* URL MUST begin with HTTP scheme. In addition, limit the length of
332 	 * the URL to 700 characters which is around the limit that was
333 	 * implicitly enforced for more than 10 years due to a bug in
334 	 * generating the event messages. */
335 	if (url_len < 7 || os_strncasecmp(url, "http://", 7) || url_len > 700) {
336 		wpa_printf(MSG_DEBUG, "WPS UPnP: Reject an unacceptable URL");
337 		goto fail;
338 	}
339 	url += 7;
340 	url_len -= 7;
341 
342 	/* Make a copy of the string to allow modification during parsing */
343 	scratch_mem = dup_binstr(url, url_len);
344 	if (scratch_mem == NULL)
345 		goto fail;
346 	wpa_printf(MSG_DEBUG, "WPS UPnP: Adding URL '%s'", scratch_mem);
347 	host = scratch_mem;
348 	path = os_strchr(host, '/');
349 	if (path)
350 		*path++ = '\0'; /* null terminate host */
351 
352 	/* Process and remove optional port component */
353 	delim = os_strchr(host, ':');
354 	if (delim) {
355 		*delim = '\0'; /* null terminate host name for now */
356 		if (isdigit(delim[1]))
357 			port = atol(delim + 1);
358 	}
359 
360 	/*
361 	 * getaddrinfo does the right thing with dotted decimal notations, or
362 	 * will resolve domain names. Resolving domain names will unfortunately
363 	 * hang the entire program until it is resolved or it times out
364 	 * internal to getaddrinfo; fortunately we think that the use of actual
365 	 * domain names (vs. dotted decimal notations) should be uncommon.
366 	 */
367 	os_memset(&hints, 0, sizeof(struct addrinfo));
368 	hints.ai_family = AF_INET;      /* IPv4 */
369 	hints.ai_socktype = SOCK_STREAM;
370 #if NO_DOMAIN_NAME_RESOLUTION
371 	/* Suppress domain name resolutions that would halt
372 	 * the program for periods of time
373 	 */
374 	hints.ai_flags = AI_NUMERICHOST;
375 #else
376 	/* Allow domain name resolution. */
377 	hints.ai_flags = 0;
378 #endif
379 	hints.ai_protocol = 0;          /* Any protocol? */
380 	rerr = getaddrinfo(host, NULL /* fill in port ourselves */,
381 			   &hints, &result);
382 	if (rerr) {
383 		wpa_printf(MSG_INFO, "WPS UPnP: Resolve error %d (%s) on: %s",
384 			   rerr, gai_strerror(rerr), host);
385 		goto fail;
386 	}
387 
388 	if (delim)
389 		*delim = ':'; /* Restore port */
390 
391 	host_len = os_strlen(host);
392 	path_len = path ? os_strlen(path) : 0;
393 	alloc_len = host_len + 1 + 1 + path_len + 1;
394 
395 	for (rp = result; rp; rp = rp->ai_next) {
396 		struct subscr_addr *a;
397 		struct sockaddr_in *addr = (struct sockaddr_in *) rp->ai_addr;
398 
399 		/* Limit no. of address to avoid denial of service attack */
400 		if (dl_list_len(&s->addr_list) >= MAX_ADDR_PER_SUBSCRIPTION) {
401 			wpa_printf(MSG_INFO, "WPS UPnP: subscr_addr_add_url: "
402 				   "Ignoring excessive addresses");
403 			break;
404 		}
405 
406 		if (!local_network_addr(s->sm, addr)) {
407 			wpa_printf(MSG_INFO,
408 				   "WPS UPnP: Ignore a delivery URL that points to another network %s",
409 				   inet_ntoa(addr->sin_addr));
410 			continue;
411 		}
412 
413 		a = os_zalloc(sizeof(*a) + alloc_len);
414 		if (a == NULL)
415 			break;
416 		mem = (char *) (a + 1);
417 		a->domain_and_port = mem;
418 		os_memcpy(mem, host, host_len);
419 		mem += host_len + 1;
420 		a->path = mem;
421 		if (path == NULL || path[0] != '/')
422 			*mem++ = '/';
423 		if (path)
424 			os_memcpy(mem, path, path_len);
425 		os_memcpy(&a->saddr, rp->ai_addr, sizeof(a->saddr));
426 		a->saddr.sin_port = htons(port);
427 
428 		dl_list_add(&s->addr_list, &a->list);
429 	}
430 
431 fail:
432 	if (result)
433 		freeaddrinfo(result);
434 	os_free(scratch_mem);
435 }
436 
437 
438 /* subscr_addr_list_create -- create list from urls in string.
439  *      Each url is enclosed by angle brackets.
440  */
441 static void subscr_addr_list_create(struct subscription *s,
442 				    const char *url_list)
443 {
444 	const char *end;
445 	wpa_printf(MSG_DEBUG, "WPS UPnP: Parsing URL list '%s'", url_list);
446 	for (;;) {
447 		while (*url_list == ' ' || *url_list == '\t')
448 			url_list++;
449 		if (*url_list != '<')
450 			break;
451 		url_list++;
452 		end = os_strchr(url_list, '>');
453 		if (end == NULL)
454 			break;
455 		subscr_addr_add_url(s, url_list, end - url_list);
456 		url_list = end + 1;
457 	}
458 }
459 
460 
461 static void wpabuf_put_property(struct wpabuf *buf, const char *name,
462 				const char *value)
463 {
464 	wpabuf_put_str(buf, "<e:property>");
465 	wpabuf_printf(buf, "<%s>", name);
466 	if (value)
467 		wpabuf_put_str(buf, value);
468 	wpabuf_printf(buf, "</%s>", name);
469 	wpabuf_put_str(buf, "</e:property>\n");
470 }
471 
472 
473 /**
474  * upnp_wps_device_send_event - Queue event messages for subscribers
475  * @sm: WPS UPnP state machine from upnp_wps_device_init()
476  *
477  * This function queues the last WLANEvent to be sent for all currently
478  * subscribed UPnP control points. sm->wlanevent must have been set with the
479  * encoded data before calling this function.
480  */
481 static void upnp_wps_device_send_event(struct upnp_wps_device_sm *sm)
482 {
483 	/* Enqueue event message for all subscribers */
484 	struct wpabuf *buf; /* holds event message */
485 	int buf_size = 0;
486 	struct subscription *s, *tmp;
487 	/* Actually, utf-8 is the default, but it doesn't hurt to specify it */
488 	const char *format_head =
489 		"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
490 		"<e:propertyset xmlns:e=\"urn:schemas-upnp-org:event-1-0\">\n";
491 	const char *format_tail = "</e:propertyset>\n";
492 	struct os_reltime now;
493 
494 	if (dl_list_empty(&sm->subscriptions)) {
495 		/* optimize */
496 		return;
497 	}
498 
499 	if (os_get_reltime(&now) == 0) {
500 		if (now.sec != sm->last_event_sec) {
501 			sm->last_event_sec = now.sec;
502 			sm->num_events_in_sec = 1;
503 		} else {
504 			sm->num_events_in_sec++;
505 			/*
506 			 * In theory, this should apply to all WLANEvent
507 			 * notifications, but EAP messages are of much higher
508 			 * priority and Probe Request notifications should not
509 			 * be allowed to drop EAP messages, so only throttle
510 			 * Probe Request notifications.
511 			 */
512 			if (sm->num_events_in_sec > MAX_EVENTS_PER_SEC &&
513 			    sm->wlanevent_type ==
514 			    UPNP_WPS_WLANEVENT_TYPE_PROBE) {
515 				wpa_printf(MSG_DEBUG, "WPS UPnP: Throttle "
516 					   "event notifications (%u seen "
517 					   "during one second)",
518 					   sm->num_events_in_sec);
519 				return;
520 			}
521 		}
522 	}
523 
524 	/* Determine buffer size needed first */
525 	buf_size += os_strlen(format_head);
526 	buf_size += 50 + 2 * os_strlen("WLANEvent");
527 	if (sm->wlanevent)
528 		buf_size += os_strlen(sm->wlanevent);
529 	buf_size += os_strlen(format_tail);
530 
531 	buf = wpabuf_alloc(buf_size);
532 	if (buf == NULL)
533 		return;
534 	wpabuf_put_str(buf, format_head);
535 	wpabuf_put_property(buf, "WLANEvent", sm->wlanevent);
536 	wpabuf_put_str(buf, format_tail);
537 
538 	wpa_printf(MSG_MSGDUMP, "WPS UPnP: WLANEvent message:\n%s",
539 		   (char *) wpabuf_head(buf));
540 
541 	dl_list_for_each_safe(s, tmp, &sm->subscriptions, struct subscription,
542 			      list) {
543 		event_add(s, buf,
544 			  sm->wlanevent_type == UPNP_WPS_WLANEVENT_TYPE_PROBE);
545 	}
546 
547 	wpabuf_free(buf);
548 }
549 
550 
551 /*
552  * Event subscription (subscriber machines register with us to receive event
553  * messages).
554  * This is the result of an incoming HTTP over TCP SUBSCRIBE request.
555  */
556 
557 /* subscription_destroy -- destroy an unlinked subscription
558  * Be sure to unlink first if necessary.
559  */
560 void subscription_destroy(struct subscription *s)
561 {
562 	struct upnp_wps_device_interface *iface;
563 	wpa_printf(MSG_DEBUG, "WPS UPnP: Destroy subscription %p", s);
564 	subscr_addr_free_all(s);
565 	event_delete_all(s);
566 	dl_list_for_each(iface, &s->sm->interfaces,
567 			 struct upnp_wps_device_interface, list)
568 		upnp_er_remove_notification(iface->wps->registrar, s);
569 	os_free(s);
570 }
571 
572 
573 /* subscription_list_age -- remove expired subscriptions */
574 static void subscription_list_age(struct upnp_wps_device_sm *sm, time_t now)
575 {
576 	struct subscription *s, *tmp;
577 	dl_list_for_each_safe(s, tmp, &sm->subscriptions,
578 			      struct subscription, list) {
579 		if (s->timeout_time > now)
580 			break;
581 		wpa_printf(MSG_DEBUG, "WPS UPnP: Removing aged subscription");
582 		dl_list_del(&s->list);
583 		subscription_destroy(s);
584 	}
585 }
586 
587 
588 /* subscription_find -- return existing subscription matching uuid, if any
589  * returns NULL if not found
590  */
591 struct subscription * subscription_find(struct upnp_wps_device_sm *sm,
592 					const u8 uuid[UUID_LEN])
593 {
594 	struct subscription *s;
595 	dl_list_for_each(s, &sm->subscriptions, struct subscription, list) {
596 		if (os_memcmp(s->uuid, uuid, UUID_LEN) == 0)
597 			return s; /* Found match */
598 	}
599 	return NULL;
600 }
601 
602 
603 static struct wpabuf * build_fake_wsc_ack(void)
604 {
605 	struct wpabuf *msg = wpabuf_alloc(100);
606 	if (msg == NULL)
607 		return NULL;
608 	wpabuf_put_u8(msg, UPNP_WPS_WLANEVENT_TYPE_EAP);
609 	wpabuf_put_str(msg, "00:00:00:00:00:00");
610 	if (wps_build_version(msg) ||
611 	    wps_build_msg_type(msg, WPS_WSC_ACK)) {
612 		wpabuf_free(msg);
613 		return NULL;
614 	}
615 	/* Enrollee Nonce */
616 	wpabuf_put_be16(msg, ATTR_ENROLLEE_NONCE);
617 	wpabuf_put_be16(msg, WPS_NONCE_LEN);
618 	wpabuf_put(msg, WPS_NONCE_LEN);
619 	/* Registrar Nonce */
620 	wpabuf_put_be16(msg, ATTR_REGISTRAR_NONCE);
621 	wpabuf_put_be16(msg, WPS_NONCE_LEN);
622 	wpabuf_put(msg, WPS_NONCE_LEN);
623 	if (wps_build_wfa_ext(msg, 0, NULL, 0, 0)) {
624 		wpabuf_free(msg);
625 		return NULL;
626 	}
627 	return msg;
628 }
629 
630 
631 /* subscription_first_event -- send format/queue event that is automatically
632  * sent on a new subscription.
633  */
634 static int subscription_first_event(struct subscription *s)
635 {
636 	/*
637 	 * Actually, utf-8 is the default, but it doesn't hurt to specify it.
638 	 *
639 	 * APStatus is apparently a bit set,
640 	 * 0x1 = configuration change (but is always set?)
641 	 * 0x10 = ap is locked
642 	 *
643 	 * Per UPnP spec, we send out the last value of each variable, even
644 	 * for WLANEvent, whatever it was.
645 	 */
646 	char *wlan_event;
647 	struct wpabuf *buf;
648 	int ap_status = 1;      /* TODO: add 0x10 if access point is locked */
649 	const char *head =
650 		"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
651 		"<e:propertyset xmlns:e=\"urn:schemas-upnp-org:event-1-0\">\n";
652 	const char *tail = "</e:propertyset>\n";
653 	char txt[10];
654 	int ret;
655 
656 	if (s->sm->wlanevent == NULL) {
657 		/*
658 		 * There has been no events before the subscription. However,
659 		 * UPnP device architecture specification requires all the
660 		 * evented variables to be included, so generate a dummy event
661 		 * for this particular case using a WSC_ACK and all-zeros
662 		 * nonces. The ER (UPnP control point) will ignore this, but at
663 		 * least it will learn that WLANEvent variable will be used in
664 		 * event notifications in the future.
665 		 */
666 		struct wpabuf *msg;
667 		wpa_printf(MSG_DEBUG, "WPS UPnP: Use a fake WSC_ACK as the "
668 			   "initial WLANEvent");
669 		msg = build_fake_wsc_ack();
670 		if (msg) {
671 			s->sm->wlanevent = (char *)
672 				base64_encode(wpabuf_head(msg),
673 					      wpabuf_len(msg), NULL);
674 			wpabuf_free(msg);
675 		}
676 	}
677 
678 	wlan_event = s->sm->wlanevent;
679 	if (wlan_event == NULL || *wlan_event == '\0') {
680 		wpa_printf(MSG_DEBUG, "WPS UPnP: WLANEvent not known for "
681 			   "initial event message");
682 		wlan_event = "";
683 	}
684 	buf = wpabuf_alloc(500 + os_strlen(wlan_event));
685 	if (buf == NULL)
686 		return -1;
687 
688 	wpabuf_put_str(buf, head);
689 	wpabuf_put_property(buf, "STAStatus", "1");
690 	os_snprintf(txt, sizeof(txt), "%d", ap_status);
691 	wpabuf_put_property(buf, "APStatus", txt);
692 	if (*wlan_event)
693 		wpabuf_put_property(buf, "WLANEvent", wlan_event);
694 	wpabuf_put_str(buf, tail);
695 
696 	ret = event_add(s, buf, 0);
697 	if (ret) {
698 		wpabuf_free(buf);
699 		return ret;
700 	}
701 	wpabuf_free(buf);
702 
703 	return 0;
704 }
705 
706 
707 /**
708  * subscription_start - Remember a UPnP control point to send events to.
709  * @sm: WPS UPnP state machine from upnp_wps_device_init()
710  * @callback_urls: Callback URLs
711  * Returns: %NULL on error, or pointer to new subscription structure.
712  */
713 struct subscription * subscription_start(struct upnp_wps_device_sm *sm,
714 					 const char *callback_urls)
715 {
716 	struct subscription *s;
717 	time_t now = time(NULL);
718 	time_t expire = now + UPNP_SUBSCRIBE_SEC;
719 	char str[80];
720 
721 	/* Get rid of expired subscriptions so we have room */
722 	subscription_list_age(sm, now);
723 
724 	/* If too many subscriptions, remove oldest */
725 	if (dl_list_len(&sm->subscriptions) >= MAX_SUBSCRIPTIONS) {
726 		s = dl_list_first(&sm->subscriptions, struct subscription,
727 				  list);
728 		if (s) {
729 			wpa_printf(MSG_INFO,
730 				   "WPS UPnP: Too many subscriptions, trashing oldest");
731 			dl_list_del(&s->list);
732 			subscription_destroy(s);
733 		}
734 	}
735 
736 	s = os_zalloc(sizeof(*s));
737 	if (s == NULL)
738 		return NULL;
739 	dl_list_init(&s->addr_list);
740 	dl_list_init(&s->event_queue);
741 
742 	s->sm = sm;
743 	s->timeout_time = expire;
744 	if (uuid_make(s->uuid) < 0) {
745 		subscription_destroy(s);
746 		return NULL;
747 	}
748 	subscr_addr_list_create(s, callback_urls);
749 	if (dl_list_empty(&s->addr_list)) {
750 		wpa_printf(MSG_DEBUG, "WPS UPnP: No valid callback URLs in "
751 			   "'%s' - drop subscription", callback_urls);
752 		subscription_destroy(s);
753 		return NULL;
754 	}
755 
756 	/* Add to end of list, since it has the highest expiration time */
757 	dl_list_add_tail(&sm->subscriptions, &s->list);
758 	/* Queue up immediate event message (our last event)
759 	 * as required by UPnP spec.
760 	 */
761 	if (subscription_first_event(s)) {
762 		wpa_printf(MSG_INFO, "WPS UPnP: Dropping subscriber due to "
763 			   "event backlog");
764 		dl_list_del(&s->list);
765 		subscription_destroy(s);
766 		return NULL;
767 	}
768 	uuid_bin2str(s->uuid, str, sizeof(str));
769 	wpa_printf(MSG_DEBUG,
770 		   "WPS UPnP: Subscription %p (SID %s) started with %s",
771 		   s, str, callback_urls);
772 	/* Schedule sending this */
773 	event_send_all_later(sm);
774 	return s;
775 }
776 
777 
778 /* subscription_renew -- find subscription and reset timeout */
779 struct subscription * subscription_renew(struct upnp_wps_device_sm *sm,
780 					 const u8 uuid[UUID_LEN])
781 {
782 	time_t now = time(NULL);
783 	time_t expire = now + UPNP_SUBSCRIBE_SEC;
784 	struct subscription *s = subscription_find(sm, uuid);
785 	if (s == NULL)
786 		return NULL;
787 	wpa_printf(MSG_DEBUG, "WPS UPnP: Subscription renewed");
788 	dl_list_del(&s->list);
789 	s->timeout_time = expire;
790 	/* add back to end of list, since it now has highest expiry */
791 	dl_list_add_tail(&sm->subscriptions, &s->list);
792 	return s;
793 }
794 
795 
796 /**
797  * upnp_wps_device_send_wlan_event - Event notification
798  * @sm: WPS UPnP state machine from upnp_wps_device_init()
799  * @from_mac_addr: Source (Enrollee) MAC address for the event
800  * @ev_type: Event type
801  * @msg: Event data
802  * Returns: 0 on success, -1 on failure
803  *
804  * Tell external Registrars (UPnP control points) that something happened. In
805  * particular, events include WPS messages from clients that are proxied to
806  * external Registrars.
807  */
808 int upnp_wps_device_send_wlan_event(struct upnp_wps_device_sm *sm,
809 				    const u8 from_mac_addr[ETH_ALEN],
810 				    enum upnp_wps_wlanevent_type ev_type,
811 				    const struct wpabuf *msg)
812 {
813 	int ret = -1;
814 	char type[2];
815 	const u8 *mac = from_mac_addr;
816 	char mac_text[18];
817 	u8 *raw = NULL;
818 	size_t raw_len;
819 	char *val;
820 	size_t val_len;
821 	int pos = 0;
822 
823 	if (!sm)
824 		goto fail;
825 
826 	os_snprintf(type, sizeof(type), "%1u", ev_type);
827 
828 	raw_len = 1 + 17 + (msg ? wpabuf_len(msg) : 0);
829 	raw = os_zalloc(raw_len);
830 	if (!raw)
831 		goto fail;
832 
833 	*(raw + pos) = (u8) ev_type;
834 	pos += 1;
835 	os_snprintf(mac_text, sizeof(mac_text), MACSTR, MAC2STR(mac));
836 	wpa_printf(MSG_DEBUG, "WPS UPnP: Proxying WLANEvent from %s",
837 		   mac_text);
838 	os_memcpy(raw + pos, mac_text, 17);
839 	pos += 17;
840 	if (msg) {
841 		os_memcpy(raw + pos, wpabuf_head(msg), wpabuf_len(msg));
842 		pos += wpabuf_len(msg);
843 	}
844 	raw_len = pos;
845 
846 	val = (char *) base64_encode(raw, raw_len, &val_len);
847 	if (val == NULL)
848 		goto fail;
849 
850 	os_free(sm->wlanevent);
851 	sm->wlanevent = val;
852 	sm->wlanevent_type = ev_type;
853 	upnp_wps_device_send_event(sm);
854 
855 	ret = 0;
856 
857 fail:
858 	os_free(raw);
859 
860 	return ret;
861 }
862 
863 
864 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
865 #include <sys/sysctl.h>
866 #include <net/route.h>
867 #include <net/if_dl.h>
868 
869 static int eth_get(const char *device, u8 ea[ETH_ALEN])
870 {
871 	struct if_msghdr *ifm;
872 	struct sockaddr_dl *sdl;
873 	u_char *p, *buf;
874 	size_t len;
875 	int mib[] = { CTL_NET, AF_ROUTE, 0, AF_LINK, NET_RT_IFLIST, 0 };
876 
877 	if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0)
878 		return -1;
879 	if ((buf = os_malloc(len)) == NULL)
880 		return -1;
881 	if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
882 		os_free(buf);
883 		return -1;
884 	}
885 	for (p = buf; p < buf + len; p += ifm->ifm_msglen) {
886 		ifm = (struct if_msghdr *)p;
887 		sdl = (struct sockaddr_dl *)(ifm + 1);
888 		if (ifm->ifm_type != RTM_IFINFO ||
889 		    (ifm->ifm_addrs & RTA_IFP) == 0)
890 			continue;
891 		if (sdl->sdl_family != AF_LINK || sdl->sdl_nlen == 0 ||
892 		    os_memcmp(sdl->sdl_data, device, sdl->sdl_nlen) != 0)
893 			continue;
894 		os_memcpy(ea, LLADDR(sdl), sdl->sdl_alen);
895 		break;
896 	}
897 	os_free(buf);
898 
899 	if (p >= buf + len) {
900 		errno = ESRCH;
901 		return -1;
902 	}
903 	return 0;
904 }
905 #endif /* __FreeBSD__ */
906 
907 
908 /**
909  * get_netif_info - Get hw and IP addresses for network device
910  * @net_if: Selected network interface name
911  * @ip_addr: Buffer for returning IP address in network byte order
912  * @ip_addr_text: Buffer for returning a pointer to allocated IP address text
913  * @netmask: Buffer for returning netmask or %NULL if not needed
914  * @mac: Buffer for returning MAC address
915  * Returns: 0 on success, -1 on failure
916  */
917 int get_netif_info(const char *net_if, unsigned *ip_addr, char **ip_addr_text,
918 		   struct in_addr *netmask, u8 mac[ETH_ALEN])
919 {
920 	struct ifreq req;
921 	int sock = -1;
922 	struct sockaddr_in *addr;
923 	struct in_addr in_addr;
924 
925 	*ip_addr_text = os_zalloc(16);
926 	if (*ip_addr_text == NULL)
927 		goto fail;
928 
929 	sock = socket(AF_INET, SOCK_DGRAM, 0);
930 	if (sock < 0)
931 		goto fail;
932 
933 	os_strlcpy(req.ifr_name, net_if, sizeof(req.ifr_name));
934 	if (ioctl(sock, SIOCGIFADDR, &req) < 0) {
935 		wpa_printf(MSG_ERROR, "WPS UPnP: SIOCGIFADDR failed: %d (%s)",
936 			   errno, strerror(errno));
937 		goto fail;
938 	}
939 	addr = (void *) &req.ifr_addr;
940 	*ip_addr = addr->sin_addr.s_addr;
941 	in_addr.s_addr = *ip_addr;
942 	os_snprintf(*ip_addr_text, 16, "%s", inet_ntoa(in_addr));
943 
944 	if (netmask) {
945 		os_memset(&req, 0, sizeof(req));
946 		os_strlcpy(req.ifr_name, net_if, sizeof(req.ifr_name));
947 		if (ioctl(sock, SIOCGIFNETMASK, &req) < 0) {
948 			wpa_printf(MSG_ERROR,
949 				   "WPS UPnP: SIOCGIFNETMASK failed: %d (%s)",
950 				   errno, strerror(errno));
951 			goto fail;
952 		}
953 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
954 		addr = (struct sockaddr_in *) &req.ifr_addr;
955 #else
956 		addr = (struct sockaddr_in *) &req.ifr_netmask;
957 #endif
958 		netmask->s_addr = addr->sin_addr.s_addr;
959 	}
960 
961 #ifdef __linux__
962 	os_strlcpy(req.ifr_name, net_if, sizeof(req.ifr_name));
963 	if (ioctl(sock, SIOCGIFHWADDR, &req) < 0) {
964 		wpa_printf(MSG_ERROR, "WPS UPnP: SIOCGIFHWADDR failed: "
965 			   "%d (%s)", errno, strerror(errno));
966 		goto fail;
967 	}
968 	os_memcpy(mac, req.ifr_addr.sa_data, 6);
969 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
970 	if (eth_get(net_if, mac) < 0) {
971 		wpa_printf(MSG_ERROR, "WPS UPnP: Failed to get MAC address");
972 		goto fail;
973 	}
974 #else
975 #error MAC address fetch not implemented
976 #endif
977 
978 	close(sock);
979 	return 0;
980 
981 fail:
982 	if (sock >= 0)
983 		close(sock);
984 	os_free(*ip_addr_text);
985 	*ip_addr_text = NULL;
986 	return -1;
987 }
988 
989 
990 static void upnp_wps_free_msearchreply(struct dl_list *head)
991 {
992 	struct advertisement_state_machine *a, *tmp;
993 	dl_list_for_each_safe(a, tmp, head, struct advertisement_state_machine,
994 			      list)
995 		msearchreply_state_machine_stop(a);
996 }
997 
998 
999 static void upnp_wps_free_subscriptions(struct dl_list *head,
1000 					struct wps_registrar *reg)
1001 {
1002 	struct subscription *s, *tmp;
1003 	dl_list_for_each_safe(s, tmp, head, struct subscription, list) {
1004 		if (reg && s->reg != reg)
1005 			continue;
1006 		dl_list_del(&s->list);
1007 		subscription_destroy(s);
1008 	}
1009 }
1010 
1011 
1012 /**
1013  * upnp_wps_device_stop - Stop WPS UPnP operations on an interface
1014  * @sm: WPS UPnP state machine from upnp_wps_device_init()
1015  */
1016 static void upnp_wps_device_stop(struct upnp_wps_device_sm *sm)
1017 {
1018 	if (!sm || !sm->started)
1019 		return;
1020 
1021 	wpa_printf(MSG_DEBUG, "WPS UPnP: Stop device");
1022 	web_listener_stop(sm);
1023 	ssdp_listener_stop(sm);
1024 	upnp_wps_free_msearchreply(&sm->msearch_replies);
1025 	upnp_wps_free_subscriptions(&sm->subscriptions, NULL);
1026 
1027 	advertisement_state_machine_stop(sm, 1);
1028 
1029 	event_send_stop_all(sm);
1030 	os_free(sm->wlanevent);
1031 	sm->wlanevent = NULL;
1032 	os_free(sm->ip_addr_text);
1033 	sm->ip_addr_text = NULL;
1034 	if (sm->multicast_sd >= 0)
1035 		close(sm->multicast_sd);
1036 	sm->multicast_sd = -1;
1037 
1038 	sm->started = 0;
1039 }
1040 
1041 
1042 /**
1043  * upnp_wps_device_start - Start WPS UPnP operations on an interface
1044  * @sm: WPS UPnP state machine from upnp_wps_device_init()
1045  * @net_if: Selected network interface name
1046  * Returns: 0 on success, -1 on failure
1047  */
1048 static int upnp_wps_device_start(struct upnp_wps_device_sm *sm, char *net_if)
1049 {
1050 	if (!sm || !net_if)
1051 		return -1;
1052 
1053 	if (sm->started)
1054 		upnp_wps_device_stop(sm);
1055 
1056 	sm->multicast_sd = -1;
1057 	sm->ssdp_sd = -1;
1058 	sm->started = 1;
1059 	sm->advertise_count = 0;
1060 
1061 	/* Fix up linux multicast handling */
1062 	if (add_ssdp_network(net_if))
1063 		goto fail;
1064 
1065 	/* Determine which IP and mac address we're using */
1066 	if (get_netif_info(net_if, &sm->ip_addr, &sm->ip_addr_text,
1067 			   &sm->netmask, sm->mac_addr)) {
1068 		wpa_printf(MSG_INFO, "WPS UPnP: Could not get IP/MAC address "
1069 			   "for %s. Does it have IP address?", net_if);
1070 		goto fail;
1071 	}
1072 	wpa_printf(MSG_DEBUG, "WPS UPnP: Local IP address %s netmask %s hwaddr "
1073 		   MACSTR,
1074 		   sm->ip_addr_text, inet_ntoa(sm->netmask),
1075 		   MAC2STR(sm->mac_addr));
1076 
1077 	/* Listen for incoming TCP connections so that others
1078 	 * can fetch our "xml files" from us.
1079 	 */
1080 	if (web_listener_start(sm))
1081 		goto fail;
1082 
1083 	/* Set up for receiving discovery (UDP) packets */
1084 	if (ssdp_listener_start(sm))
1085 		goto fail;
1086 
1087 	/* Set up for sending multicast */
1088 	if (ssdp_open_multicast(sm) < 0)
1089 		goto fail;
1090 
1091 	/*
1092 	 * Broadcast NOTIFY messages to let the world know we exist.
1093 	 * This is done via a state machine since the messages should not be
1094 	 * all sent out at once.
1095 	 */
1096 	if (advertisement_state_machine_start(sm))
1097 		goto fail;
1098 
1099 	return 0;
1100 
1101 fail:
1102 	upnp_wps_device_stop(sm);
1103 	return -1;
1104 }
1105 
1106 
1107 static struct upnp_wps_device_interface *
1108 upnp_wps_get_iface(struct upnp_wps_device_sm *sm, void *priv)
1109 {
1110 	struct upnp_wps_device_interface *iface;
1111 	dl_list_for_each(iface, &sm->interfaces,
1112 			 struct upnp_wps_device_interface, list) {
1113 		if (iface->priv == priv)
1114 			return iface;
1115 	}
1116 	return NULL;
1117 }
1118 
1119 
1120 /**
1121  * upnp_wps_device_deinit - Deinitialize WPS UPnP
1122  * @sm: WPS UPnP state machine from upnp_wps_device_init()
1123  * @priv: External context data that was used in upnp_wps_device_init() call
1124  */
1125 void upnp_wps_device_deinit(struct upnp_wps_device_sm *sm, void *priv)
1126 {
1127 	struct upnp_wps_device_interface *iface;
1128 	struct upnp_wps_peer *peer;
1129 
1130 	if (!sm)
1131 		return;
1132 
1133 	iface = upnp_wps_get_iface(sm, priv);
1134 	if (iface == NULL) {
1135 		wpa_printf(MSG_ERROR, "WPS UPnP: Could not find the interface "
1136 			   "instance to deinit");
1137 		return;
1138 	}
1139 	wpa_printf(MSG_DEBUG, "WPS UPnP: Deinit interface instance %p", iface);
1140 	if (dl_list_len(&sm->interfaces) == 1) {
1141 		wpa_printf(MSG_DEBUG, "WPS UPnP: Deinitializing last instance "
1142 			   "- free global device instance");
1143 		upnp_wps_device_stop(sm);
1144 	} else
1145 		upnp_wps_free_subscriptions(&sm->subscriptions,
1146 					    iface->wps->registrar);
1147 	dl_list_del(&iface->list);
1148 
1149 	while ((peer = dl_list_first(&iface->peers, struct upnp_wps_peer,
1150 				     list))) {
1151 		if (peer->wps)
1152 			wps_deinit(peer->wps);
1153 		dl_list_del(&peer->list);
1154 		os_free(peer);
1155 	}
1156 	os_free(iface->ctx->ap_pin);
1157 	os_free(iface->ctx);
1158 	os_free(iface);
1159 
1160 	if (dl_list_empty(&sm->interfaces)) {
1161 		os_free(sm->root_dir);
1162 		os_free(sm->desc_url);
1163 		os_free(sm);
1164 		shared_upnp_device = NULL;
1165 	}
1166 }
1167 
1168 
1169 /**
1170  * upnp_wps_device_init - Initialize WPS UPnP
1171  * @ctx: callback table; we must eventually free it
1172  * @wps: Pointer to longterm WPS context
1173  * @priv: External context data that will be used in callbacks
1174  * @net_if: Selected network interface name
1175  * Returns: WPS UPnP state or %NULL on failure
1176  */
1177 struct upnp_wps_device_sm *
1178 upnp_wps_device_init(struct upnp_wps_device_ctx *ctx, struct wps_context *wps,
1179 		     void *priv, char *net_if)
1180 {
1181 	struct upnp_wps_device_sm *sm;
1182 	struct upnp_wps_device_interface *iface;
1183 	int start = 0;
1184 
1185 	iface = os_zalloc(sizeof(*iface));
1186 	if (iface == NULL) {
1187 		os_free(ctx->ap_pin);
1188 		os_free(ctx);
1189 		return NULL;
1190 	}
1191 	wpa_printf(MSG_DEBUG, "WPS UPnP: Init interface instance %p", iface);
1192 
1193 	dl_list_init(&iface->peers);
1194 	iface->ctx = ctx;
1195 	iface->wps = wps;
1196 	iface->priv = priv;
1197 
1198 	if (shared_upnp_device) {
1199 		wpa_printf(MSG_DEBUG, "WPS UPnP: Share existing device "
1200 			   "context");
1201 		sm = shared_upnp_device;
1202 	} else {
1203 		wpa_printf(MSG_DEBUG, "WPS UPnP: Initialize device context");
1204 		sm = os_zalloc(sizeof(*sm));
1205 		if (!sm) {
1206 			wpa_printf(MSG_ERROR, "WPS UPnP: upnp_wps_device_init "
1207 				   "failed");
1208 			os_free(iface);
1209 			os_free(ctx->ap_pin);
1210 			os_free(ctx);
1211 			return NULL;
1212 		}
1213 		shared_upnp_device = sm;
1214 
1215 		dl_list_init(&sm->msearch_replies);
1216 		dl_list_init(&sm->subscriptions);
1217 		dl_list_init(&sm->interfaces);
1218 		start = 1;
1219 	}
1220 
1221 	dl_list_add(&sm->interfaces, &iface->list);
1222 
1223 	if (start && upnp_wps_device_start(sm, net_if)) {
1224 		upnp_wps_device_deinit(sm, priv);
1225 		return NULL;
1226 	}
1227 
1228 
1229 	return sm;
1230 }
1231 
1232 
1233 /**
1234  * upnp_wps_subscribers - Check whether there are any event subscribers
1235  * @sm: WPS UPnP state machine from upnp_wps_device_init()
1236  * Returns: 0 if no subscribers, 1 if subscribers
1237  */
1238 int upnp_wps_subscribers(struct upnp_wps_device_sm *sm)
1239 {
1240 	return !dl_list_empty(&sm->subscriptions);
1241 }
1242 
1243 
1244 int upnp_wps_set_ap_pin(struct upnp_wps_device_sm *sm, const char *ap_pin)
1245 {
1246 	struct upnp_wps_device_interface *iface;
1247 	if (sm == NULL)
1248 		return 0;
1249 
1250 	dl_list_for_each(iface, &sm->interfaces,
1251 			 struct upnp_wps_device_interface, list) {
1252 		os_free(iface->ctx->ap_pin);
1253 		if (ap_pin) {
1254 			iface->ctx->ap_pin = os_strdup(ap_pin);
1255 			if (iface->ctx->ap_pin == NULL)
1256 				return -1;
1257 		} else
1258 			iface->ctx->ap_pin = NULL;
1259 	}
1260 
1261 	return 0;
1262 }
1263