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 */
format_date(struct wpabuf * buf)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  */
uuid_make(u8 uuid[UUID_LEN])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  */
subscr_addr_delete(struct subscr_addr * a)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. */
subscr_addr_free_all(struct subscription * s)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 
local_network_addr(struct upnp_wps_device_sm * sm,struct sockaddr_in * addr)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 */
subscr_addr_add_url(struct subscription * s,const char * url,size_t url_len)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  */
subscr_addr_list_create(struct subscription * s,const char * url_list)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 
wpabuf_put_property(struct wpabuf * buf,const char * name,const char * value)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  */
upnp_wps_device_send_event(struct upnp_wps_device_sm * sm)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  */
subscription_destroy(struct subscription * s)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 */
subscription_list_age(struct upnp_wps_device_sm * sm,time_t now)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  */
subscription_find(struct upnp_wps_device_sm * sm,const u8 uuid[UUID_LEN])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 
build_fake_wsc_ack(void)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  */
subscription_first_event(struct subscription * s)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  */
subscription_start(struct upnp_wps_device_sm * sm,const char * callback_urls)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 */
subscription_renew(struct upnp_wps_device_sm * sm,const u8 uuid[UUID_LEN])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  */
upnp_wps_device_send_wlan_event(struct upnp_wps_device_sm * sm,const u8 from_mac_addr[ETH_ALEN],enum upnp_wps_wlanevent_type ev_type,const struct wpabuf * msg)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__) || defined(__DragonFly__)
865 #include <sys/sysctl.h>
866 #include <net/route.h>
867 #include <net/if_dl.h>
868 
eth_get(const char * device,u8 ea[ETH_ALEN])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  */
get_netif_info(const char * net_if,unsigned * ip_addr,char ** ip_addr_text,struct in_addr * netmask,u8 mac[ETH_ALEN])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 		addr = (struct sockaddr_in *) &req.ifr_netmask;
954 		netmask->s_addr = addr->sin_addr.s_addr;
955 	}
956 
957 #ifdef __linux__
958 	os_strlcpy(req.ifr_name, net_if, sizeof(req.ifr_name));
959 	if (ioctl(sock, SIOCGIFHWADDR, &req) < 0) {
960 		wpa_printf(MSG_ERROR, "WPS UPnP: SIOCGIFHWADDR failed: "
961 			   "%d (%s)", errno, strerror(errno));
962 		goto fail;
963 	}
964 	os_memcpy(mac, req.ifr_addr.sa_data, 6);
965 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
966 	if (eth_get(net_if, mac) < 0) {
967 		wpa_printf(MSG_ERROR, "WPS UPnP: Failed to get MAC address");
968 		goto fail;
969 	}
970 #else
971 #error MAC address fetch not implemented
972 #endif
973 
974 	close(sock);
975 	return 0;
976 
977 fail:
978 	if (sock >= 0)
979 		close(sock);
980 	os_free(*ip_addr_text);
981 	*ip_addr_text = NULL;
982 	return -1;
983 }
984 
985 
upnp_wps_free_msearchreply(struct dl_list * head)986 static void upnp_wps_free_msearchreply(struct dl_list *head)
987 {
988 	struct advertisement_state_machine *a, *tmp;
989 	dl_list_for_each_safe(a, tmp, head, struct advertisement_state_machine,
990 			      list)
991 		msearchreply_state_machine_stop(a);
992 }
993 
994 
upnp_wps_free_subscriptions(struct dl_list * head,struct wps_registrar * reg)995 static void upnp_wps_free_subscriptions(struct dl_list *head,
996 					struct wps_registrar *reg)
997 {
998 	struct subscription *s, *tmp;
999 	dl_list_for_each_safe(s, tmp, head, struct subscription, list) {
1000 		if (reg && s->reg != reg)
1001 			continue;
1002 		dl_list_del(&s->list);
1003 		subscription_destroy(s);
1004 	}
1005 }
1006 
1007 
1008 /**
1009  * upnp_wps_device_stop - Stop WPS UPnP operations on an interface
1010  * @sm: WPS UPnP state machine from upnp_wps_device_init()
1011  */
upnp_wps_device_stop(struct upnp_wps_device_sm * sm)1012 static void upnp_wps_device_stop(struct upnp_wps_device_sm *sm)
1013 {
1014 	if (!sm || !sm->started)
1015 		return;
1016 
1017 	wpa_printf(MSG_DEBUG, "WPS UPnP: Stop device");
1018 	web_listener_stop(sm);
1019 	ssdp_listener_stop(sm);
1020 	upnp_wps_free_msearchreply(&sm->msearch_replies);
1021 	upnp_wps_free_subscriptions(&sm->subscriptions, NULL);
1022 
1023 	advertisement_state_machine_stop(sm, 1);
1024 
1025 	event_send_stop_all(sm);
1026 	os_free(sm->wlanevent);
1027 	sm->wlanevent = NULL;
1028 	os_free(sm->ip_addr_text);
1029 	sm->ip_addr_text = NULL;
1030 	if (sm->multicast_sd >= 0)
1031 		close(sm->multicast_sd);
1032 	sm->multicast_sd = -1;
1033 
1034 	sm->started = 0;
1035 }
1036 
1037 
1038 /**
1039  * upnp_wps_device_start - Start WPS UPnP operations on an interface
1040  * @sm: WPS UPnP state machine from upnp_wps_device_init()
1041  * @net_if: Selected network interface name
1042  * Returns: 0 on success, -1 on failure
1043  */
upnp_wps_device_start(struct upnp_wps_device_sm * sm,char * net_if)1044 static int upnp_wps_device_start(struct upnp_wps_device_sm *sm, char *net_if)
1045 {
1046 	if (!sm || !net_if)
1047 		return -1;
1048 
1049 	if (sm->started)
1050 		upnp_wps_device_stop(sm);
1051 
1052 	sm->multicast_sd = -1;
1053 	sm->ssdp_sd = -1;
1054 	sm->started = 1;
1055 	sm->advertise_count = 0;
1056 
1057 	/* Fix up linux multicast handling */
1058 	if (add_ssdp_network(net_if))
1059 		goto fail;
1060 
1061 	/* Determine which IP and mac address we're using */
1062 	if (get_netif_info(net_if, &sm->ip_addr, &sm->ip_addr_text,
1063 			   &sm->netmask, sm->mac_addr)) {
1064 		wpa_printf(MSG_INFO, "WPS UPnP: Could not get IP/MAC address "
1065 			   "for %s. Does it have IP address?", net_if);
1066 		goto fail;
1067 	}
1068 	wpa_printf(MSG_DEBUG, "WPS UPnP: Local IP address %s netmask %s hwaddr "
1069 		   MACSTR,
1070 		   sm->ip_addr_text, inet_ntoa(sm->netmask),
1071 		   MAC2STR(sm->mac_addr));
1072 
1073 	/* Listen for incoming TCP connections so that others
1074 	 * can fetch our "xml files" from us.
1075 	 */
1076 	if (web_listener_start(sm))
1077 		goto fail;
1078 
1079 	/* Set up for receiving discovery (UDP) packets */
1080 	if (ssdp_listener_start(sm))
1081 		goto fail;
1082 
1083 	/* Set up for sending multicast */
1084 	if (ssdp_open_multicast(sm) < 0)
1085 		goto fail;
1086 
1087 	/*
1088 	 * Broadcast NOTIFY messages to let the world know we exist.
1089 	 * This is done via a state machine since the messages should not be
1090 	 * all sent out at once.
1091 	 */
1092 	if (advertisement_state_machine_start(sm))
1093 		goto fail;
1094 
1095 	return 0;
1096 
1097 fail:
1098 	upnp_wps_device_stop(sm);
1099 	return -1;
1100 }
1101 
1102 
1103 static struct upnp_wps_device_interface *
upnp_wps_get_iface(struct upnp_wps_device_sm * sm,void * priv)1104 upnp_wps_get_iface(struct upnp_wps_device_sm *sm, void *priv)
1105 {
1106 	struct upnp_wps_device_interface *iface;
1107 	dl_list_for_each(iface, &sm->interfaces,
1108 			 struct upnp_wps_device_interface, list) {
1109 		if (iface->priv == priv)
1110 			return iface;
1111 	}
1112 	return NULL;
1113 }
1114 
1115 
1116 /**
1117  * upnp_wps_device_deinit - Deinitialize WPS UPnP
1118  * @sm: WPS UPnP state machine from upnp_wps_device_init()
1119  * @priv: External context data that was used in upnp_wps_device_init() call
1120  */
upnp_wps_device_deinit(struct upnp_wps_device_sm * sm,void * priv)1121 void upnp_wps_device_deinit(struct upnp_wps_device_sm *sm, void *priv)
1122 {
1123 	struct upnp_wps_device_interface *iface;
1124 	struct upnp_wps_peer *peer;
1125 
1126 	if (!sm)
1127 		return;
1128 
1129 	iface = upnp_wps_get_iface(sm, priv);
1130 	if (iface == NULL) {
1131 		wpa_printf(MSG_ERROR, "WPS UPnP: Could not find the interface "
1132 			   "instance to deinit");
1133 		return;
1134 	}
1135 	wpa_printf(MSG_DEBUG, "WPS UPnP: Deinit interface instance %p", iface);
1136 	if (dl_list_len(&sm->interfaces) == 1) {
1137 		wpa_printf(MSG_DEBUG, "WPS UPnP: Deinitializing last instance "
1138 			   "- free global device instance");
1139 		upnp_wps_device_stop(sm);
1140 	} else
1141 		upnp_wps_free_subscriptions(&sm->subscriptions,
1142 					    iface->wps->registrar);
1143 	dl_list_del(&iface->list);
1144 
1145 	while ((peer = dl_list_first(&iface->peers, struct upnp_wps_peer,
1146 				     list))) {
1147 		if (peer->wps)
1148 			wps_deinit(peer->wps);
1149 		dl_list_del(&peer->list);
1150 		os_free(peer);
1151 	}
1152 	os_free(iface->ctx->ap_pin);
1153 	os_free(iface->ctx);
1154 	os_free(iface);
1155 
1156 	if (dl_list_empty(&sm->interfaces)) {
1157 		os_free(sm->root_dir);
1158 		os_free(sm->desc_url);
1159 		os_free(sm);
1160 		shared_upnp_device = NULL;
1161 	}
1162 }
1163 
1164 
1165 /**
1166  * upnp_wps_device_init - Initialize WPS UPnP
1167  * @ctx: callback table; we must eventually free it
1168  * @wps: Pointer to longterm WPS context
1169  * @priv: External context data that will be used in callbacks
1170  * @net_if: Selected network interface name
1171  * Returns: WPS UPnP state or %NULL on failure
1172  */
1173 struct upnp_wps_device_sm *
upnp_wps_device_init(struct upnp_wps_device_ctx * ctx,struct wps_context * wps,void * priv,char * net_if)1174 upnp_wps_device_init(struct upnp_wps_device_ctx *ctx, struct wps_context *wps,
1175 		     void *priv, char *net_if)
1176 {
1177 	struct upnp_wps_device_sm *sm;
1178 	struct upnp_wps_device_interface *iface;
1179 	int start = 0;
1180 
1181 	iface = os_zalloc(sizeof(*iface));
1182 	if (iface == NULL) {
1183 		os_free(ctx->ap_pin);
1184 		os_free(ctx);
1185 		return NULL;
1186 	}
1187 	wpa_printf(MSG_DEBUG, "WPS UPnP: Init interface instance %p", iface);
1188 
1189 	dl_list_init(&iface->peers);
1190 	iface->ctx = ctx;
1191 	iface->wps = wps;
1192 	iface->priv = priv;
1193 
1194 	if (shared_upnp_device) {
1195 		wpa_printf(MSG_DEBUG, "WPS UPnP: Share existing device "
1196 			   "context");
1197 		sm = shared_upnp_device;
1198 	} else {
1199 		wpa_printf(MSG_DEBUG, "WPS UPnP: Initialize device context");
1200 		sm = os_zalloc(sizeof(*sm));
1201 		if (!sm) {
1202 			wpa_printf(MSG_ERROR, "WPS UPnP: upnp_wps_device_init "
1203 				   "failed");
1204 			os_free(iface);
1205 			os_free(ctx->ap_pin);
1206 			os_free(ctx);
1207 			return NULL;
1208 		}
1209 		shared_upnp_device = sm;
1210 
1211 		dl_list_init(&sm->msearch_replies);
1212 		dl_list_init(&sm->subscriptions);
1213 		dl_list_init(&sm->interfaces);
1214 		start = 1;
1215 	}
1216 
1217 	dl_list_add(&sm->interfaces, &iface->list);
1218 
1219 	if (start && upnp_wps_device_start(sm, net_if)) {
1220 		upnp_wps_device_deinit(sm, priv);
1221 		return NULL;
1222 	}
1223 
1224 
1225 	return sm;
1226 }
1227 
1228 
1229 /**
1230  * upnp_wps_subscribers - Check whether there are any event subscribers
1231  * @sm: WPS UPnP state machine from upnp_wps_device_init()
1232  * Returns: 0 if no subscribers, 1 if subscribers
1233  */
upnp_wps_subscribers(struct upnp_wps_device_sm * sm)1234 int upnp_wps_subscribers(struct upnp_wps_device_sm *sm)
1235 {
1236 	return !dl_list_empty(&sm->subscriptions);
1237 }
1238 
1239 
upnp_wps_set_ap_pin(struct upnp_wps_device_sm * sm,const char * ap_pin)1240 int upnp_wps_set_ap_pin(struct upnp_wps_device_sm *sm, const char *ap_pin)
1241 {
1242 	struct upnp_wps_device_interface *iface;
1243 	if (sm == NULL)
1244 		return 0;
1245 
1246 	dl_list_for_each(iface, &sm->interfaces,
1247 			 struct upnp_wps_device_interface, list) {
1248 		os_free(iface->ctx->ap_pin);
1249 		if (ap_pin) {
1250 			iface->ctx->ap_pin = os_strdup(ap_pin);
1251 			if (iface->ctx->ap_pin == NULL)
1252 				return -1;
1253 		} else
1254 			iface->ctx->ap_pin = NULL;
1255 	}
1256 
1257 	return 0;
1258 }
1259