• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 		wps_upnp_event_add(
544 			s, buf,
545 			sm->wlanevent_type == UPNP_WPS_WLANEVENT_TYPE_PROBE);
546 	}
547 
548 	wpabuf_free(buf);
549 }
550 
551 
552 /*
553  * Event subscription (subscriber machines register with us to receive event
554  * messages).
555  * This is the result of an incoming HTTP over TCP SUBSCRIBE request.
556  */
557 
558 /* subscription_destroy -- destroy an unlinked subscription
559  * Be sure to unlink first if necessary.
560  */
subscription_destroy(struct subscription * s)561 void subscription_destroy(struct subscription *s)
562 {
563 	struct upnp_wps_device_interface *iface;
564 	wpa_printf(MSG_DEBUG, "WPS UPnP: Destroy subscription %p", s);
565 	subscr_addr_free_all(s);
566 	wps_upnp_event_delete_all(s);
567 	dl_list_for_each(iface, &s->sm->interfaces,
568 			 struct upnp_wps_device_interface, list)
569 		upnp_er_remove_notification(iface->wps->registrar, s);
570 	os_free(s);
571 }
572 
573 
574 /* subscription_list_age -- remove expired subscriptions */
subscription_list_age(struct upnp_wps_device_sm * sm,time_t now)575 static void subscription_list_age(struct upnp_wps_device_sm *sm, time_t now)
576 {
577 	struct subscription *s, *tmp;
578 	dl_list_for_each_safe(s, tmp, &sm->subscriptions,
579 			      struct subscription, list) {
580 		if (s->timeout_time > now)
581 			break;
582 		wpa_printf(MSG_DEBUG, "WPS UPnP: Removing aged subscription");
583 		dl_list_del(&s->list);
584 		subscription_destroy(s);
585 	}
586 }
587 
588 
589 /* subscription_find -- return existing subscription matching uuid, if any
590  * returns NULL if not found
591  */
subscription_find(struct upnp_wps_device_sm * sm,const u8 uuid[UUID_LEN])592 struct subscription * subscription_find(struct upnp_wps_device_sm *sm,
593 					const u8 uuid[UUID_LEN])
594 {
595 	struct subscription *s;
596 	dl_list_for_each(s, &sm->subscriptions, struct subscription, list) {
597 		if (os_memcmp(s->uuid, uuid, UUID_LEN) == 0)
598 			return s; /* Found match */
599 	}
600 	return NULL;
601 }
602 
603 
build_fake_wsc_ack(void)604 static struct wpabuf * build_fake_wsc_ack(void)
605 {
606 	struct wpabuf *msg = wpabuf_alloc(100);
607 	if (msg == NULL)
608 		return NULL;
609 	wpabuf_put_u8(msg, UPNP_WPS_WLANEVENT_TYPE_EAP);
610 	wpabuf_put_str(msg, "00:00:00:00:00:00");
611 	if (wps_build_version(msg) ||
612 	    wps_build_msg_type(msg, WPS_WSC_ACK)) {
613 		wpabuf_free(msg);
614 		return NULL;
615 	}
616 	/* Enrollee Nonce */
617 	wpabuf_put_be16(msg, ATTR_ENROLLEE_NONCE);
618 	wpabuf_put_be16(msg, WPS_NONCE_LEN);
619 	wpabuf_put(msg, WPS_NONCE_LEN);
620 	/* Registrar Nonce */
621 	wpabuf_put_be16(msg, ATTR_REGISTRAR_NONCE);
622 	wpabuf_put_be16(msg, WPS_NONCE_LEN);
623 	wpabuf_put(msg, WPS_NONCE_LEN);
624 	if (wps_build_wfa_ext(msg, 0, NULL, 0, 0)) {
625 		wpabuf_free(msg);
626 		return NULL;
627 	}
628 	return msg;
629 }
630 
631 
632 /* subscription_first_event -- send format/queue event that is automatically
633  * sent on a new subscription.
634  */
subscription_first_event(struct subscription * s)635 static int subscription_first_event(struct subscription *s)
636 {
637 	/*
638 	 * Actually, utf-8 is the default, but it doesn't hurt to specify it.
639 	 *
640 	 * APStatus is apparently a bit set,
641 	 * 0x1 = configuration change (but is always set?)
642 	 * 0x10 = ap is locked
643 	 *
644 	 * Per UPnP spec, we send out the last value of each variable, even
645 	 * for WLANEvent, whatever it was.
646 	 */
647 	char *wlan_event;
648 	struct wpabuf *buf;
649 	int ap_status = 1;      /* TODO: add 0x10 if access point is locked */
650 	const char *head =
651 		"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
652 		"<e:propertyset xmlns:e=\"urn:schemas-upnp-org:event-1-0\">\n";
653 	const char *tail = "</e:propertyset>\n";
654 	char txt[10];
655 	int ret;
656 
657 	if (s->sm->wlanevent == NULL) {
658 		/*
659 		 * There has been no events before the subscription. However,
660 		 * UPnP device architecture specification requires all the
661 		 * evented variables to be included, so generate a stub event
662 		 * for this particular case using a WSC_ACK and all-zeros
663 		 * nonces. The ER (UPnP control point) will ignore this, but at
664 		 * least it will learn that WLANEvent variable will be used in
665 		 * event notifications in the future.
666 		 */
667 		struct wpabuf *msg;
668 		wpa_printf(MSG_DEBUG, "WPS UPnP: Use a fake WSC_ACK as the "
669 			   "initial WLANEvent");
670 		msg = build_fake_wsc_ack();
671 		if (msg) {
672 			s->sm->wlanevent =
673 				base64_encode(wpabuf_head(msg),
674 					      wpabuf_len(msg), NULL);
675 			wpabuf_free(msg);
676 		}
677 	}
678 
679 	wlan_event = s->sm->wlanevent;
680 	if (wlan_event == NULL || *wlan_event == '\0') {
681 		wpa_printf(MSG_DEBUG, "WPS UPnP: WLANEvent not known for "
682 			   "initial event message");
683 		wlan_event = "";
684 	}
685 	buf = wpabuf_alloc(500 + os_strlen(wlan_event));
686 	if (buf == NULL)
687 		return -1;
688 
689 	wpabuf_put_str(buf, head);
690 	wpabuf_put_property(buf, "STAStatus", "1");
691 	os_snprintf(txt, sizeof(txt), "%d", ap_status);
692 	wpabuf_put_property(buf, "APStatus", txt);
693 	if (*wlan_event)
694 		wpabuf_put_property(buf, "WLANEvent", wlan_event);
695 	wpabuf_put_str(buf, tail);
696 
697 	ret = wps_upnp_event_add(s, buf, 0);
698 	if (ret) {
699 		wpabuf_free(buf);
700 		return ret;
701 	}
702 	wpabuf_free(buf);
703 
704 	return 0;
705 }
706 
707 
708 /**
709  * subscription_start - Remember a UPnP control point to send events to.
710  * @sm: WPS UPnP state machine from upnp_wps_device_init()
711  * @callback_urls: Callback URLs
712  * Returns: %NULL on error, or pointer to new subscription structure.
713  */
subscription_start(struct upnp_wps_device_sm * sm,const char * callback_urls)714 struct subscription * subscription_start(struct upnp_wps_device_sm *sm,
715 					 const char *callback_urls)
716 {
717 	struct subscription *s;
718 	time_t now = time(NULL);
719 	time_t expire = now + UPNP_SUBSCRIBE_SEC;
720 	char str[80];
721 
722 	/* Get rid of expired subscriptions so we have room */
723 	subscription_list_age(sm, now);
724 
725 	/* If too many subscriptions, remove oldest */
726 	if (dl_list_len(&sm->subscriptions) >= MAX_SUBSCRIPTIONS) {
727 		s = dl_list_first(&sm->subscriptions, struct subscription,
728 				  list);
729 		if (s) {
730 			wpa_printf(MSG_INFO,
731 				   "WPS UPnP: Too many subscriptions, trashing oldest");
732 			dl_list_del(&s->list);
733 			subscription_destroy(s);
734 		}
735 	}
736 
737 	s = os_zalloc(sizeof(*s));
738 	if (s == NULL)
739 		return NULL;
740 	dl_list_init(&s->addr_list);
741 	dl_list_init(&s->event_queue);
742 
743 	s->sm = sm;
744 	s->timeout_time = expire;
745 	if (uuid_make(s->uuid) < 0) {
746 		subscription_destroy(s);
747 		return NULL;
748 	}
749 	subscr_addr_list_create(s, callback_urls);
750 	if (dl_list_empty(&s->addr_list)) {
751 		wpa_printf(MSG_DEBUG, "WPS UPnP: No valid callback URLs in "
752 			   "'%s' - drop subscription", callback_urls);
753 		subscription_destroy(s);
754 		return NULL;
755 	}
756 
757 	/* Add to end of list, since it has the highest expiration time */
758 	dl_list_add_tail(&sm->subscriptions, &s->list);
759 	/* Queue up immediate event message (our last event)
760 	 * as required by UPnP spec.
761 	 */
762 	if (subscription_first_event(s)) {
763 		wpa_printf(MSG_INFO, "WPS UPnP: Dropping subscriber due to "
764 			   "event backlog");
765 		dl_list_del(&s->list);
766 		subscription_destroy(s);
767 		return NULL;
768 	}
769 	uuid_bin2str(s->uuid, str, sizeof(str));
770 	wpa_printf(MSG_DEBUG,
771 		   "WPS UPnP: Subscription %p (SID %s) started with %s",
772 		   s, str, callback_urls);
773 	/* Schedule sending this */
774 	wps_upnp_event_send_all_later(sm);
775 	return s;
776 }
777 
778 
779 /* subscription_renew -- find subscription and reset timeout */
subscription_renew(struct upnp_wps_device_sm * sm,const u8 uuid[UUID_LEN])780 struct subscription * subscription_renew(struct upnp_wps_device_sm *sm,
781 					 const u8 uuid[UUID_LEN])
782 {
783 	time_t now = time(NULL);
784 	time_t expire = now + UPNP_SUBSCRIBE_SEC;
785 	struct subscription *s = subscription_find(sm, uuid);
786 	if (s == NULL)
787 		return NULL;
788 	wpa_printf(MSG_DEBUG, "WPS UPnP: Subscription renewed");
789 	dl_list_del(&s->list);
790 	s->timeout_time = expire;
791 	/* add back to end of list, since it now has highest expiry */
792 	dl_list_add_tail(&sm->subscriptions, &s->list);
793 	return s;
794 }
795 
796 
797 /**
798  * upnp_wps_device_send_wlan_event - Event notification
799  * @sm: WPS UPnP state machine from upnp_wps_device_init()
800  * @from_mac_addr: Source (Enrollee) MAC address for the event
801  * @ev_type: Event type
802  * @msg: Event data
803  * Returns: 0 on success, -1 on failure
804  *
805  * Tell external Registrars (UPnP control points) that something happened. In
806  * particular, events include WPS messages from clients that are proxied to
807  * external Registrars.
808  */
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)809 int upnp_wps_device_send_wlan_event(struct upnp_wps_device_sm *sm,
810 				    const u8 from_mac_addr[ETH_ALEN],
811 				    enum upnp_wps_wlanevent_type ev_type,
812 				    const struct wpabuf *msg)
813 {
814 	int ret = -1;
815 	char type[2];
816 	const u8 *mac = from_mac_addr;
817 	char mac_text[18];
818 	u8 *raw = NULL;
819 	size_t raw_len;
820 	char *val;
821 	size_t val_len;
822 	int pos = 0;
823 
824 	if (!sm)
825 		goto fail;
826 
827 	os_snprintf(type, sizeof(type), "%1u", ev_type);
828 
829 	raw_len = 1 + 17 + (msg ? wpabuf_len(msg) : 0);
830 	raw = os_zalloc(raw_len);
831 	if (!raw)
832 		goto fail;
833 
834 	*(raw + pos) = (u8) ev_type;
835 	pos += 1;
836 	os_snprintf(mac_text, sizeof(mac_text), MACSTR, MAC2STR(mac));
837 	wpa_printf(MSG_DEBUG, "WPS UPnP: Proxying WLANEvent from %s",
838 		   mac_text);
839 	os_memcpy(raw + pos, mac_text, 17);
840 	pos += 17;
841 	if (msg) {
842 		os_memcpy(raw + pos, wpabuf_head(msg), wpabuf_len(msg));
843 		pos += wpabuf_len(msg);
844 	}
845 	raw_len = pos;
846 
847 	val = base64_encode(raw, raw_len, &val_len);
848 	if (val == NULL)
849 		goto fail;
850 
851 	os_free(sm->wlanevent);
852 	sm->wlanevent = val;
853 	sm->wlanevent_type = ev_type;
854 	upnp_wps_device_send_event(sm);
855 
856 	ret = 0;
857 
858 fail:
859 	os_free(raw);
860 
861 	return ret;
862 }
863 
864 
865 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__APPLE__)
866 #include <sys/sysctl.h>
867 #include <net/route.h>
868 #include <net/if_dl.h>
869 
eth_get(const char * device,u8 ea[ETH_ALEN])870 static int eth_get(const char *device, u8 ea[ETH_ALEN])
871 {
872 	struct if_msghdr *ifm;
873 	struct sockaddr_dl *sdl;
874 	u_char *p, *buf;
875 	size_t len;
876 	int mib[] = { CTL_NET, AF_ROUTE, 0, AF_LINK, NET_RT_IFLIST, 0 };
877 
878 	if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0)
879 		return -1;
880 	if ((buf = os_malloc(len)) == NULL)
881 		return -1;
882 	if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
883 		os_free(buf);
884 		return -1;
885 	}
886 	for (p = buf; p < buf + len; p += ifm->ifm_msglen) {
887 		ifm = (struct if_msghdr *)p;
888 		sdl = (struct sockaddr_dl *)(ifm + 1);
889 		if (ifm->ifm_type != RTM_IFINFO ||
890 		    (ifm->ifm_addrs & RTA_IFP) == 0)
891 			continue;
892 		if (sdl->sdl_family != AF_LINK || sdl->sdl_nlen == 0 ||
893 		    os_memcmp(sdl->sdl_data, device, sdl->sdl_nlen) != 0)
894 			continue;
895 		os_memcpy(ea, LLADDR(sdl), sdl->sdl_alen);
896 		break;
897 	}
898 	os_free(buf);
899 
900 	if (p >= buf + len) {
901 		errno = ESRCH;
902 		return -1;
903 	}
904 	return 0;
905 }
906 #endif /* __FreeBSD__ || __APPLE__ */
907 
908 
909 /**
910  * get_netif_info - Get hw and IP addresses for network device
911  * @net_if: Selected network interface name
912  * @ip_addr: Buffer for returning IP address in network byte order
913  * @ip_addr_text: Buffer for returning a pointer to allocated IP address text
914  * @netmask: Buffer for returning netmask or %NULL if not needed
915  * @mac: Buffer for returning MAC address
916  * Returns: 0 on success, -1 on failure
917  */
get_netif_info(const char * net_if,unsigned * ip_addr,char ** ip_addr_text,struct in_addr * netmask,u8 mac[ETH_ALEN])918 int get_netif_info(const char *net_if, unsigned *ip_addr, char **ip_addr_text,
919 		   struct in_addr *netmask, u8 mac[ETH_ALEN])
920 {
921 	struct ifreq req;
922 	int sock = -1;
923 	struct sockaddr_in *addr;
924 	struct in_addr in_addr;
925 
926 	*ip_addr_text = os_zalloc(16);
927 	if (*ip_addr_text == NULL)
928 		goto fail;
929 
930 	sock = socket(AF_INET, SOCK_DGRAM, 0);
931 	if (sock < 0)
932 		goto fail;
933 
934 	os_strlcpy(req.ifr_name, net_if, sizeof(req.ifr_name));
935 	if (ioctl(sock, SIOCGIFADDR, &req) < 0) {
936 		wpa_printf(MSG_ERROR, "WPS UPnP: SIOCGIFADDR failed: %d (%s)",
937 			   errno, strerror(errno));
938 		goto fail;
939 	}
940 	addr = (void *) &req.ifr_addr;
941 	*ip_addr = addr->sin_addr.s_addr;
942 	in_addr.s_addr = *ip_addr;
943 	os_snprintf(*ip_addr_text, 16, "%s", inet_ntoa(in_addr));
944 
945 	if (netmask) {
946 		os_memset(&req, 0, sizeof(req));
947 		os_strlcpy(req.ifr_name, net_if, sizeof(req.ifr_name));
948 		if (ioctl(sock, SIOCGIFNETMASK, &req) < 0) {
949 			wpa_printf(MSG_ERROR,
950 				   "WPS UPnP: SIOCGIFNETMASK failed: %d (%s)",
951 				   errno, strerror(errno));
952 			goto fail;
953 		}
954 		addr = (struct sockaddr_in *) &req.ifr_addr;
955 		netmask->s_addr = addr->sin_addr.s_addr;
956 	}
957 
958 #ifdef __linux__
959 	os_strlcpy(req.ifr_name, net_if, sizeof(req.ifr_name));
960 	if (ioctl(sock, SIOCGIFHWADDR, &req) < 0) {
961 		wpa_printf(MSG_ERROR, "WPS UPnP: SIOCGIFHWADDR failed: "
962 			   "%d (%s)", errno, strerror(errno));
963 		goto fail;
964 	}
965 	os_memcpy(mac, req.ifr_addr.sa_data, 6);
966 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__APPLE__)
967 	if (eth_get(net_if, mac) < 0) {
968 		wpa_printf(MSG_ERROR, "WPS UPnP: Failed to get MAC address");
969 		goto fail;
970 	}
971 #else
972 #error MAC address fetch not implemented
973 #endif
974 
975 	close(sock);
976 	return 0;
977 
978 fail:
979 	if (sock >= 0)
980 		close(sock);
981 	os_free(*ip_addr_text);
982 	*ip_addr_text = NULL;
983 	return -1;
984 }
985 
986 
upnp_wps_free_msearchreply(struct dl_list * head)987 static void upnp_wps_free_msearchreply(struct dl_list *head)
988 {
989 	struct advertisement_state_machine *a, *tmp;
990 	dl_list_for_each_safe(a, tmp, head, struct advertisement_state_machine,
991 			      list)
992 		msearchreply_state_machine_stop(a);
993 }
994 
995 
upnp_wps_free_subscriptions(struct dl_list * head,struct wps_registrar * reg)996 static void upnp_wps_free_subscriptions(struct dl_list *head,
997 					struct wps_registrar *reg)
998 {
999 	struct subscription *s, *tmp;
1000 	dl_list_for_each_safe(s, tmp, head, struct subscription, list) {
1001 		if (reg && s->reg != reg)
1002 			continue;
1003 		dl_list_del(&s->list);
1004 		subscription_destroy(s);
1005 	}
1006 }
1007 
1008 
1009 /**
1010  * upnp_wps_device_stop - Stop WPS UPnP operations on an interface
1011  * @sm: WPS UPnP state machine from upnp_wps_device_init()
1012  */
upnp_wps_device_stop(struct upnp_wps_device_sm * sm)1013 static void upnp_wps_device_stop(struct upnp_wps_device_sm *sm)
1014 {
1015 	if (!sm || !sm->started)
1016 		return;
1017 
1018 	wpa_printf(MSG_DEBUG, "WPS UPnP: Stop device");
1019 	web_listener_stop(sm);
1020 	ssdp_listener_stop(sm);
1021 	upnp_wps_free_msearchreply(&sm->msearch_replies);
1022 	upnp_wps_free_subscriptions(&sm->subscriptions, NULL);
1023 
1024 	advertisement_state_machine_stop(sm, 1);
1025 
1026 	wps_upnp_event_send_stop_all(sm);
1027 	os_free(sm->wlanevent);
1028 	sm->wlanevent = NULL;
1029 	os_free(sm->ip_addr_text);
1030 	sm->ip_addr_text = NULL;
1031 	if (sm->multicast_sd >= 0)
1032 		close(sm->multicast_sd);
1033 	sm->multicast_sd = -1;
1034 
1035 	sm->started = 0;
1036 }
1037 
1038 
1039 /**
1040  * upnp_wps_device_start - Start WPS UPnP operations on an interface
1041  * @sm: WPS UPnP state machine from upnp_wps_device_init()
1042  * @net_if: Selected network interface name
1043  * Returns: 0 on success, -1 on failure
1044  */
upnp_wps_device_start(struct upnp_wps_device_sm * sm,char * net_if)1045 static int upnp_wps_device_start(struct upnp_wps_device_sm *sm, char *net_if)
1046 {
1047 	if (!sm || !net_if)
1048 		return -1;
1049 
1050 	if (sm->started)
1051 		upnp_wps_device_stop(sm);
1052 
1053 	sm->multicast_sd = -1;
1054 	sm->ssdp_sd = -1;
1055 	sm->started = 1;
1056 	sm->advertise_count = 0;
1057 
1058 	/* Fix up linux multicast handling */
1059 	if (add_ssdp_network(net_if))
1060 		goto fail;
1061 
1062 	/* Determine which IP and mac address we're using */
1063 	if (get_netif_info(net_if, &sm->ip_addr, &sm->ip_addr_text,
1064 			   &sm->netmask, sm->mac_addr)) {
1065 		wpa_printf(MSG_INFO, "WPS UPnP: Could not get IP/MAC address "
1066 			   "for %s. Does it have IP address?", net_if);
1067 		goto fail;
1068 	}
1069 	wpa_printf(MSG_DEBUG, "WPS UPnP: Local IP address %s netmask %s hwaddr "
1070 		   MACSTR,
1071 		   sm->ip_addr_text, inet_ntoa(sm->netmask),
1072 		   MAC2STR(sm->mac_addr));
1073 
1074 	/* Listen for incoming TCP connections so that others
1075 	 * can fetch our "xml files" from us.
1076 	 */
1077 	if (web_listener_start(sm))
1078 		goto fail;
1079 
1080 	/* Set up for receiving discovery (UDP) packets */
1081 	if (ssdp_listener_start(sm))
1082 		goto fail;
1083 
1084 	/* Set up for sending multicast */
1085 	if (ssdp_open_multicast(sm) < 0)
1086 		goto fail;
1087 
1088 	/*
1089 	 * Broadcast NOTIFY messages to let the world know we exist.
1090 	 * This is done via a state machine since the messages should not be
1091 	 * all sent out at once.
1092 	 */
1093 	if (advertisement_state_machine_start(sm))
1094 		goto fail;
1095 
1096 	return 0;
1097 
1098 fail:
1099 	upnp_wps_device_stop(sm);
1100 	return -1;
1101 }
1102 
1103 
1104 static struct upnp_wps_device_interface *
upnp_wps_get_iface(struct upnp_wps_device_sm * sm,void * priv)1105 upnp_wps_get_iface(struct upnp_wps_device_sm *sm, void *priv)
1106 {
1107 	struct upnp_wps_device_interface *iface;
1108 	dl_list_for_each(iface, &sm->interfaces,
1109 			 struct upnp_wps_device_interface, list) {
1110 		if (iface->priv == priv)
1111 			return iface;
1112 	}
1113 	return NULL;
1114 }
1115 
1116 
1117 /**
1118  * upnp_wps_device_deinit - Deinitialize WPS UPnP
1119  * @sm: WPS UPnP state machine from upnp_wps_device_init()
1120  * @priv: External context data that was used in upnp_wps_device_init() call
1121  */
upnp_wps_device_deinit(struct upnp_wps_device_sm * sm,void * priv)1122 void upnp_wps_device_deinit(struct upnp_wps_device_sm *sm, void *priv)
1123 {
1124 	struct upnp_wps_device_interface *iface;
1125 	struct upnp_wps_peer *peer;
1126 
1127 	if (!sm)
1128 		return;
1129 
1130 	iface = upnp_wps_get_iface(sm, priv);
1131 	if (iface == NULL) {
1132 		wpa_printf(MSG_ERROR, "WPS UPnP: Could not find the interface "
1133 			   "instance to deinit");
1134 		return;
1135 	}
1136 	wpa_printf(MSG_DEBUG, "WPS UPnP: Deinit interface instance %p", iface);
1137 	if (dl_list_len(&sm->interfaces) == 1) {
1138 		wpa_printf(MSG_DEBUG, "WPS UPnP: Deinitializing last instance "
1139 			   "- free global device instance");
1140 		upnp_wps_device_stop(sm);
1141 	} else
1142 		upnp_wps_free_subscriptions(&sm->subscriptions,
1143 					    iface->wps->registrar);
1144 	dl_list_del(&iface->list);
1145 
1146 	while ((peer = dl_list_first(&iface->peers, struct upnp_wps_peer,
1147 				     list))) {
1148 		if (peer->wps)
1149 			wps_deinit(peer->wps);
1150 		dl_list_del(&peer->list);
1151 		os_free(peer);
1152 	}
1153 	os_free(iface->ctx->ap_pin);
1154 	os_free(iface->ctx);
1155 	os_free(iface);
1156 
1157 	if (dl_list_empty(&sm->interfaces)) {
1158 		os_free(sm->root_dir);
1159 		os_free(sm->desc_url);
1160 		os_free(sm);
1161 		shared_upnp_device = NULL;
1162 	}
1163 }
1164 
1165 
1166 /**
1167  * upnp_wps_device_init - Initialize WPS UPnP
1168  * @ctx: callback table; we must eventually free it
1169  * @wps: Pointer to longterm WPS context
1170  * @priv: External context data that will be used in callbacks
1171  * @net_if: Selected network interface name
1172  * Returns: WPS UPnP state or %NULL on failure
1173  */
1174 struct upnp_wps_device_sm *
upnp_wps_device_init(struct upnp_wps_device_ctx * ctx,struct wps_context * wps,void * priv,char * net_if)1175 upnp_wps_device_init(struct upnp_wps_device_ctx *ctx, struct wps_context *wps,
1176 		     void *priv, char *net_if)
1177 {
1178 	struct upnp_wps_device_sm *sm;
1179 	struct upnp_wps_device_interface *iface;
1180 	int start = 0;
1181 
1182 	iface = os_zalloc(sizeof(*iface));
1183 	if (iface == NULL) {
1184 		os_free(ctx->ap_pin);
1185 		os_free(ctx);
1186 		return NULL;
1187 	}
1188 	wpa_printf(MSG_DEBUG, "WPS UPnP: Init interface instance %p", iface);
1189 
1190 	dl_list_init(&iface->peers);
1191 	iface->ctx = ctx;
1192 	iface->wps = wps;
1193 	iface->priv = priv;
1194 
1195 	if (shared_upnp_device) {
1196 		wpa_printf(MSG_DEBUG, "WPS UPnP: Share existing device "
1197 			   "context");
1198 		sm = shared_upnp_device;
1199 	} else {
1200 		wpa_printf(MSG_DEBUG, "WPS UPnP: Initialize device context");
1201 		sm = os_zalloc(sizeof(*sm));
1202 		if (!sm) {
1203 			wpa_printf(MSG_ERROR, "WPS UPnP: upnp_wps_device_init "
1204 				   "failed");
1205 			os_free(iface);
1206 			os_free(ctx->ap_pin);
1207 			os_free(ctx);
1208 			return NULL;
1209 		}
1210 		shared_upnp_device = sm;
1211 
1212 		dl_list_init(&sm->msearch_replies);
1213 		dl_list_init(&sm->subscriptions);
1214 		dl_list_init(&sm->interfaces);
1215 		start = 1;
1216 	}
1217 
1218 	dl_list_add(&sm->interfaces, &iface->list);
1219 
1220 	if (start && upnp_wps_device_start(sm, net_if)) {
1221 		upnp_wps_device_deinit(sm, priv);
1222 		return NULL;
1223 	}
1224 
1225 
1226 	return sm;
1227 }
1228 
1229 
1230 /**
1231  * upnp_wps_subscribers - Check whether there are any event subscribers
1232  * @sm: WPS UPnP state machine from upnp_wps_device_init()
1233  * Returns: 0 if no subscribers, 1 if subscribers
1234  */
upnp_wps_subscribers(struct upnp_wps_device_sm * sm)1235 int upnp_wps_subscribers(struct upnp_wps_device_sm *sm)
1236 {
1237 	return !dl_list_empty(&sm->subscriptions);
1238 }
1239 
1240 
upnp_wps_set_ap_pin(struct upnp_wps_device_sm * sm,const char * ap_pin)1241 int upnp_wps_set_ap_pin(struct upnp_wps_device_sm *sm, const char *ap_pin)
1242 {
1243 	struct upnp_wps_device_interface *iface;
1244 	if (sm == NULL)
1245 		return 0;
1246 
1247 	dl_list_for_each(iface, &sm->interfaces,
1248 			 struct upnp_wps_device_interface, list) {
1249 		os_free(iface->ctx->ap_pin);
1250 		if (ap_pin) {
1251 			iface->ctx->ap_pin = os_strdup(ap_pin);
1252 			if (iface->ctx->ap_pin == NULL)
1253 				return -1;
1254 		} else
1255 			iface->ctx->ap_pin = NULL;
1256 	}
1257 
1258 	return 0;
1259 }
1260