xref: /freebsd/contrib/wpa/src/wps/wps_upnp.c (revision 195ebc7e9e4b129de810833791a19dfb4349d6a9)
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, 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  * -- Just what should be in the first event message sent after subscription
51  * for the WLANEvent field? If i pass it empty, Vista replies with OK
52  * but apparently barfs on the message.
53  * -- The http error code generation is pretty bogus, hopefully noone cares.
54  *
55  * Author: Ted Merrill, Atheros Communications, based upon earlier work
56  * as explained above and below.
57  *
58  * Copyright:
59  * Copyright 2008 Atheros Communications.
60  *
61  * The original header (of upnp_wps_device.c) reads:
62  *
63  *  Copyright (c) 2006-2007 Sony Corporation. All Rights Reserved.
64  *
65  *  File Name: upnp_wps_device.c
66  *  Description: EAP-WPS UPnP device source
67  *
68  *   Redistribution and use in source and binary forms, with or without
69  *   modification, are permitted provided that the following conditions
70  *   are met:
71  *
72  *     * Redistributions of source code must retain the above copyright
73  *       notice, this list of conditions and the following disclaimer.
74  *     * Redistributions in binary form must reproduce the above copyright
75  *       notice, this list of conditions and the following disclaimer in
76  *       the documentation and/or other materials provided with the
77  *       distribution.
78  *     * Neither the name of Sony Corporation nor the names of its
79  *       contributors may be used to endorse or promote products derived
80  *       from this software without specific prior written permission.
81  *
82  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
83  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
84  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
85  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
86  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
87  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
88  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
89  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
90  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
91  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
92  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
93  *
94  * Portions from Intel libupnp files, e.g. genlib/net/http/httpreadwrite.c
95  * typical header:
96  *
97  * Copyright (c) 2000-2003 Intel Corporation
98  * All rights reserved.
99  *
100  * Redistribution and use in source and binary forms, with or without
101  * modification, are permitted provided that the following conditions are met:
102  *
103  * * Redistributions of source code must retain the above copyright notice,
104  * this list of conditions and the following disclaimer.
105  * * Redistributions in binary form must reproduce the above copyright notice,
106  * this list of conditions and the following disclaimer in the documentation
107  * and/or other materials provided with the distribution.
108  * * Neither name of Intel Corporation nor the names of its contributors
109  * may be used to endorse or promote products derived from this software
110  * without specific prior written permission.
111  *
112  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
113  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
114  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
115  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL INTEL OR
116  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
117  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
118  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
119  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
120  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
121  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
122  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
123 */
124 
125 /*
126  * Overview of WPS over UPnP:
127  *
128  * UPnP is a protocol that allows devices to discover each other and control
129  * each other. In UPnP terminology, a device is either a "device" (a server
130  * that provides information about itself and allows itself to be controlled)
131  * or a "control point" (a client that controls "devices") or possibly both.
132  * This file implements a UPnP "device".
133  *
134  * For us, we use mostly basic UPnP discovery, but the control part of interest
135  * is WPS carried via UPnP messages. There is quite a bit of basic UPnP
136  * discovery to do before we can get to WPS, however.
137  *
138  * UPnP discovery begins with "devices" send out multicast UDP packets to a
139  * certain fixed multicast IP address and port, and "control points" sending
140  * out other such UDP packets.
141  *
142  * The packets sent by devices are NOTIFY packets (not to be confused with TCP
143  * NOTIFY packets that are used later) and those sent by control points are
144  * M-SEARCH packets. These packets contain a simple HTTP style header. The
145  * packets are sent redundantly to get around packet loss. Devices respond to
146  * M-SEARCH packets with HTTP-like UDP packets containing HTTP/1.1 200 OK
147  * messages, which give similar information as the UDP NOTIFY packets.
148  *
149  * The above UDP packets advertise the (arbitrary) TCP ports that the
150  * respective parties will listen to. The control point can then do a HTTP
151  * SUBSCRIBE (something like an HTTP PUT) after which the device can do a
152  * separate HTTP NOTIFY (also like an HTTP PUT) to do event messaging.
153  *
154  * The control point will also do HTTP GET of the "device file" listed in the
155  * original UDP information from the device (see UPNP_WPS_DEVICE_XML_FILE
156  * data), and based on this will do additional GETs... HTTP POSTs are done to
157  * cause an action.
158  *
159  * Beyond some basic information in HTTP headers, additional information is in
160  * the HTTP bodies, in a format set by the SOAP and XML standards, a markup
161  * language related to HTML used for web pages. This language is intended to
162  * provide the ultimate in self-documentation by providing a universal
163  * namespace based on pseudo-URLs called URIs. Note that although a URI looks
164  * like a URL (a web address), they are never accessed as such but are used
165  * only as identifiers.
166  *
167  * The POST of a GetDeviceInfo gets information similar to what might be
168  * obtained from a probe request or response on Wi-Fi. WPS messages M1-M8
169  * are passed via a POST of a PutMessage; the M1-M8 WPS messages are converted
170  * to a bin64 ascii representation for encapsulation. When proxying messages,
171  * WLANEvent and PutWLANResponse are used.
172  *
173  * This of course glosses over a lot of details.
174  */
175 
176 #include "includes.h"
177 
178 #include <assert.h>
179 #include <net/if.h>
180 #include <netdb.h>
181 #include <sys/ioctl.h>
182 
183 #include "common.h"
184 #include "uuid.h"
185 #include "base64.h"
186 #include "wps.h"
187 #include "wps_i.h"
188 #include "wps_upnp.h"
189 #include "wps_upnp_i.h"
190 
191 
192 /*
193  * UPnP allows a client ("control point") to send a server like us ("device")
194  * a domain name for registration, and we are supposed to resolve it. This is
195  * bad because, using the standard Linux library, we will stall the entire
196  * hostapd waiting for resolution.
197  *
198  * The "correct" solution would be to use an event driven library for domain
199  * name resolution such as "ares". However, this would increase code size
200  * further. Since it is unlikely that we'll actually see such domain names, we
201  * can just refuse to accept them.
202  */
203 #define NO_DOMAIN_NAME_RESOLUTION 1  /* 1 to allow only dotted ip addresses */
204 
205 
206 /*
207  * UPnP does not scale well. If we were in a room with thousands of control
208  * points then potentially we could be expected to handle subscriptions for
209  * each of them, which would exhaust our memory. So we must set a limit. In
210  * practice we are unlikely to see more than one or two.
211  */
212 #define MAX_SUBSCRIPTIONS 4    /* how many subscribing clients we handle */
213 #define MAX_ADDR_PER_SUBSCRIPTION 8
214 
215 
216 /* Write the current date/time per RFC */
217 void format_date(struct wpabuf *buf)
218 {
219 	const char *weekday_str = "Sun\0Mon\0Tue\0Wed\0Thu\0Fri\0Sat";
220 	const char *month_str = "Jan\0Feb\0Mar\0Apr\0May\0Jun\0"
221 		"Jul\0Aug\0Sep\0Oct\0Nov\0Dec";
222 	struct tm *date;
223 	time_t t;
224 
225 	t = time(NULL);
226 	date = gmtime(&t);
227 	wpabuf_printf(buf, "%s, %02d %s %d %02d:%02d:%02d GMT",
228 		      &weekday_str[date->tm_wday * 4], date->tm_mday,
229 		      &month_str[date->tm_mon * 4], date->tm_year + 1900,
230 		      date->tm_hour, date->tm_min, date->tm_sec);
231 }
232 
233 
234 /***************************************************************************
235  * UUIDs (unique identifiers)
236  *
237  * These are supposed to be unique in all the world.
238  * Sometimes permanent ones are used, sometimes temporary ones
239  * based on random numbers... there are different rules for valid content
240  * of different types.
241  * Each uuid is 16 bytes long.
242  **************************************************************************/
243 
244 /* uuid_make -- construct a random UUID
245  * The UPnP documents don't seem to offer any guidelines as to which method to
246  * use for constructing UUIDs for subscriptions. Presumably any method from
247  * rfc4122 is good enough; I've chosen random number method.
248  */
249 static void uuid_make(u8 uuid[UUID_LEN])
250 {
251 	os_get_random(uuid, UUID_LEN);
252 
253 	/* Replace certain bits as specified in rfc4122 or X.667 */
254 	uuid[6] &= 0x0f; uuid[6] |= (4 << 4);   /* version 4 == random gen */
255 	uuid[8] &= 0x3f; uuid[8] |= 0x80;
256 }
257 
258 
259 /*
260  * Subscriber address handling.
261  * Since a subscriber may have an arbitrary number of addresses, we have to
262  * add a bunch of code to handle them.
263  *
264  * Addresses are passed in text, and MAY be domain names instead of the (usual
265  * and expected) dotted IP addresses. Resolving domain names consumes a lot of
266  * resources. Worse, we are currently using the standard Linux getaddrinfo()
267  * which will block the entire program until complete or timeout! The proper
268  * solution would be to use the "ares" library or similar with more state
269  * machine steps etc. or just disable domain name resolution by setting
270  * NO_DOMAIN_NAME_RESOLUTION to 1 at top of this file.
271  */
272 
273 /* subscr_addr_delete -- delete single unlinked subscriber address
274  * (be sure to unlink first if need be)
275  */
276 static void subscr_addr_delete(struct subscr_addr *a)
277 {
278 	/*
279 	 * Note: do NOT free domain_and_port or path because they point to
280 	 * memory within the allocation of "a".
281 	 */
282 	os_free(a);
283 }
284 
285 
286 /* subscr_addr_unlink -- unlink subscriber address from linked list */
287 static void subscr_addr_unlink(struct subscription *s, struct subscr_addr *a)
288 {
289 	struct subscr_addr **listp = &s->addr_list;
290 	s->n_addr--;
291 	a->next->prev = a->prev;
292 	a->prev->next = a->next;
293 	if (*listp == a) {
294 		if (a == a->next) {
295 			/* last in queue */
296 			*listp = NULL;
297 			assert(s->n_addr == 0);
298 		} else {
299 			*listp = a->next;
300 		}
301 	}
302 }
303 
304 
305 /* subscr_addr_free_all -- unlink and delete list of subscriber addresses. */
306 static void subscr_addr_free_all(struct subscription *s)
307 {
308 	struct subscr_addr **listp = &s->addr_list;
309 	struct subscr_addr *a;
310 	while ((a = *listp) != NULL) {
311 		subscr_addr_unlink(s, a);
312 		subscr_addr_delete(a);
313 	}
314 }
315 
316 
317 /* subscr_addr_link -- add subscriber address to list of addresses */
318 static void subscr_addr_link(struct subscription *s, struct subscr_addr *a)
319 {
320 	struct subscr_addr **listp = &s->addr_list;
321 	s->n_addr++;
322 	if (*listp == NULL) {
323 		*listp = a->next = a->prev = a;
324 	} else {
325 		a->next = *listp;
326 		a->prev = (*listp)->prev;
327 		a->prev->next = a;
328 		a->next->prev = a;
329 	}
330 }
331 
332 
333 /* subscr_addr_add_url -- add address(es) for one url to subscription */
334 static void subscr_addr_add_url(struct subscription *s, const char *url)
335 {
336 	int alloc_len;
337 	char *scratch_mem = NULL;
338 	char *mem;
339 	char *domain_and_port;
340 	char *delim;
341 	char *path;
342 	char *domain;
343 	int port = 80;  /* port to send to (default is port 80) */
344 	struct addrinfo hints;
345 	struct addrinfo *result = NULL;
346 	struct addrinfo *rp;
347 	int rerr;
348 	struct subscr_addr *a = NULL;
349 
350 	/* url MUST begin with http: */
351 	if (os_strncasecmp(url, "http://", 7))
352 		goto fail;
353 	url += 7;
354 
355 	/* allocate memory for the extra stuff we need */
356 	alloc_len = (2 * (os_strlen(url) + 1));
357 	scratch_mem = os_zalloc(alloc_len);
358 	if (scratch_mem == NULL)
359 		goto fail;
360 	mem = scratch_mem;
361 	strcpy(mem, url);
362 	domain_and_port = mem;
363 	mem += 1 + os_strlen(mem);
364 	delim = os_strchr(domain_and_port, '/');
365 	if (delim) {
366 		*delim++ = 0;   /* null terminate domain and port */
367 		path = delim;
368 	} else {
369 		path = domain_and_port + os_strlen(domain_and_port);
370 	}
371 	domain = mem;
372 	strcpy(domain, domain_and_port);
373 	delim = strchr(domain, ':');
374 	if (delim) {
375 		*delim++ = 0;   /* null terminate domain */
376 		if (isdigit(*delim))
377 			port = atol(delim);
378 	}
379 
380 	/*
381 	 * getaddrinfo does the right thing with dotted decimal notations, or
382 	 * will resolve domain names. Resolving domain names will unfortunately
383 	 * hang the entire program until it is resolved or it times out
384 	 * internal to getaddrinfo; fortunately we think that the use of actual
385 	 * domain names (vs. dotted decimal notations) should be uncommon.
386 	 */
387 	os_memset(&hints, 0, sizeof(struct addrinfo));
388 	hints.ai_family = AF_INET;      /* IPv4 */
389 	hints.ai_socktype = SOCK_STREAM;
390 #if NO_DOMAIN_NAME_RESOLUTION
391 	/* Suppress domain name resolutions that would halt
392 	 * the program for periods of time
393 	 */
394 	hints.ai_flags = AI_NUMERICHOST;
395 #else
396 	/* Allow domain name resolution. */
397 	hints.ai_flags = 0;
398 #endif
399 	hints.ai_protocol = 0;          /* Any protocol? */
400 	rerr = getaddrinfo(domain, NULL /* fill in port ourselves */,
401 			   &hints, &result);
402 	if (rerr) {
403 		wpa_printf(MSG_INFO, "WPS UPnP: Resolve error %d (%s) on: %s",
404 			   rerr, gai_strerror(rerr), domain);
405 		goto fail;
406 	}
407 	for (rp = result; rp; rp = rp->ai_next) {
408 		/* Limit no. of address to avoid denial of service attack */
409 		if (s->n_addr >= MAX_ADDR_PER_SUBSCRIPTION) {
410 			wpa_printf(MSG_INFO, "WPS UPnP: subscr_addr_add_url: "
411 				   "Ignoring excessive addresses");
412 			break;
413 		}
414 
415 		a = os_zalloc(sizeof(*a) + alloc_len);
416 		if (a == NULL)
417 			continue;
418 		a->s = s;
419 		mem = (void *) (a + 1);
420 		a->domain_and_port = mem;
421 		strcpy(mem, domain_and_port);
422 		mem += 1 + strlen(mem);
423 		a->path = mem;
424 		if (path[0] != '/')
425 			*mem++ = '/';
426 		strcpy(mem, path);
427 		mem += 1 + strlen(mem);
428 		os_memcpy(&a->saddr, rp->ai_addr, sizeof(a->saddr));
429 		a->saddr.sin_port = htons(port);
430 
431 		subscr_addr_link(s, a);
432 		a = NULL;       /* don't free it below */
433 	}
434 
435 fail:
436 	if (result)
437 		freeaddrinfo(result);
438 	os_free(scratch_mem);
439 	os_free(a);
440 }
441 
442 
443 /* subscr_addr_list_create -- create list from urls in string.
444  *      Each url is enclosed by angle brackets.
445  */
446 static void subscr_addr_list_create(struct subscription *s,
447 				    const char *url_list)
448 {
449 	char *end;
450 	for (;;) {
451 		while (*url_list == ' ' || *url_list == '\t')
452 			url_list++;
453 		if (*url_list != '<')
454 			break;
455 		url_list++;
456 		end = os_strchr(url_list, '>');
457 		if (end == NULL)
458 			break;
459 		*end++ = 0;
460 		subscr_addr_add_url(s, url_list);
461 		url_list = end;
462 	}
463 }
464 
465 
466 int send_wpabuf(int fd, struct wpabuf *buf)
467 {
468 	wpa_printf(MSG_DEBUG, "WPS UPnP: Send %lu byte message",
469 		   (unsigned long) wpabuf_len(buf));
470 	errno = 0;
471 	if (write(fd, wpabuf_head(buf), wpabuf_len(buf)) !=
472 	    (int) wpabuf_len(buf)) {
473 		wpa_printf(MSG_ERROR, "WPS UPnP: Failed to send buffer: "
474 			   "errno=%d (%s)",
475 			   errno, strerror(errno));
476 		return -1;
477 	}
478 
479 	return 0;
480 }
481 
482 
483 static void wpabuf_put_property(struct wpabuf *buf, const char *name,
484 				const char *value)
485 {
486 	wpabuf_put_str(buf, "<e:property>");
487 	wpabuf_printf(buf, "<%s>", name);
488 	if (value)
489 		wpabuf_put_str(buf, value);
490 	wpabuf_printf(buf, "</%s>", name);
491 	wpabuf_put_str(buf, "</e:property>\n");
492 }
493 
494 
495 /**
496  * upnp_wps_device_send_event - Queue event messages for subscribers
497  * @sm: WPS UPnP state machine from upnp_wps_device_init()
498  *
499  * This function queues the last WLANEvent to be sent for all currently
500  * subscribed UPnP control points. sm->wlanevent must have been set with the
501  * encoded data before calling this function.
502  */
503 static void upnp_wps_device_send_event(struct upnp_wps_device_sm *sm)
504 {
505 	/* Enqueue event message for all subscribers */
506 	struct wpabuf *buf; /* holds event message */
507 	int buf_size = 0;
508 	struct subscription *s;
509 	/* Actually, utf-8 is the default, but it doesn't hurt to specify it */
510 	const char *format_head =
511 		"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
512 		"<e:propertyset xmlns:e=\"urn:schemas-upnp-org:event-1-0\">\n";
513 	const char *format_tail = "</e:propertyset>\n";
514 
515 	if (sm->subscriptions == NULL) {
516 		/* optimize */
517 		return;
518 	}
519 
520 	/* Determine buffer size needed first */
521 	buf_size += os_strlen(format_head);
522 	buf_size += 50 + 2 * os_strlen("WLANEvent");
523 	if (sm->wlanevent)
524 		buf_size += os_strlen(sm->wlanevent);
525 	buf_size += os_strlen(format_tail);
526 
527 	buf = wpabuf_alloc(buf_size);
528 	if (buf == NULL)
529 		return;
530 	wpabuf_put_str(buf, format_head);
531 	wpabuf_put_property(buf, "WLANEvent", sm->wlanevent);
532 	wpabuf_put_str(buf, format_tail);
533 
534 	wpa_printf(MSG_MSGDUMP, "WPS UPnP: WLANEvent message:\n%s",
535 		   (char *) wpabuf_head(buf));
536 
537 	s = sm->subscriptions;
538 	do {
539 		if (event_add(s, buf)) {
540 			struct subscription *s_old = s;
541 			wpa_printf(MSG_INFO, "WPS UPnP: Dropping "
542 				   "subscriber due to event backlog");
543 			s = s_old->next;
544 			subscription_unlink(s_old);
545 			subscription_destroy(s_old);
546 		} else {
547 			s = s->next;
548 		}
549 	} while (s != sm->subscriptions);
550 
551 	wpabuf_free(buf);
552 }
553 
554 
555 /*
556  * Event subscription (subscriber machines register with us to receive event
557  * messages).
558  * This is the result of an incoming HTTP over TCP SUBSCRIBE request.
559  */
560 
561 /* subscription_unlink -- remove from the active list */
562 void subscription_unlink(struct subscription *s)
563 {
564 	struct upnp_wps_device_sm *sm = s->sm;
565 
566 	if (s->next == s) {
567 		/* only one? */
568 		sm->subscriptions = NULL;
569 	} else  {
570 		if (sm->subscriptions == s)
571 			sm->subscriptions = s->next;
572 		s->next->prev = s->prev;
573 		s->prev->next = s->next;
574 	}
575 	sm->n_subscriptions--;
576 }
577 
578 
579 /* subscription_link_to_end -- link to end of active list
580  * (should have high expiry time!)
581  */
582 static void subscription_link_to_end(struct subscription *s)
583 {
584 	struct upnp_wps_device_sm *sm = s->sm;
585 
586 	if (sm->subscriptions) {
587 		s->next = sm->subscriptions;
588 		s->prev = s->next->prev;
589 		s->prev->next = s;
590 		s->next->prev = s;
591 	} else {
592 		sm->subscriptions = s->next = s->prev = s;
593 	}
594 	sm->n_subscriptions++;
595 }
596 
597 
598 /* subscription_destroy -- destroy an unlinked subscription
599  * Be sure to unlink first if necessary.
600  */
601 void subscription_destroy(struct subscription *s)
602 {
603 	wpa_printf(MSG_DEBUG, "WPS UPnP: Destroy subscription %p", s);
604 	if (s->addr_list)
605 		subscr_addr_free_all(s);
606 	event_delete_all(s);
607 	os_free(s);
608 }
609 
610 
611 /* subscription_list_age -- remove expired subscriptions */
612 static void subscription_list_age(struct upnp_wps_device_sm *sm, time_t now)
613 {
614 	struct subscription *s;
615 	while ((s = sm->subscriptions) != NULL && s->timeout_time < now) {
616 		wpa_printf(MSG_DEBUG, "WPS UPnP: Removing aged subscription");
617 		subscription_unlink(s);
618 		subscription_destroy(s);
619 	}
620 }
621 
622 
623 /* subscription_find -- return existing subscription matching uuid, if any
624  * returns NULL if not found
625  */
626 struct subscription * subscription_find(struct upnp_wps_device_sm *sm,
627 					const u8 uuid[UUID_LEN])
628 {
629 	struct subscription *s0 = sm->subscriptions;
630 	struct subscription *s = s0;
631 
632 	if (s0 == NULL)
633 		return NULL;
634 	do {
635 		if (os_memcmp(s->uuid, uuid, UUID_LEN) == 0)
636 			return s; /* Found match */
637 		s = s->next;
638 	} while (s != s0);
639 
640 	return NULL;
641 }
642 
643 
644 /* subscription_first_event -- send format/queue event that is automatically
645  * sent on a new subscription.
646  */
647 static int subscription_first_event(struct subscription *s)
648 {
649 	/*
650 	 * Actually, utf-8 is the default, but it doesn't hurt to specify it.
651 	 *
652 	 * APStatus is apparently a bit set,
653 	 * 0x1 = configuration change (but is always set?)
654 	 * 0x10 = ap is locked
655 	 *
656 	 * Per UPnP spec, we send out the last value of each variable, even
657 	 * for WLANEvent, whatever it was.
658 	 */
659 	char *wlan_event;
660 	struct wpabuf *buf;
661 	int ap_status = 1;      /* TODO: add 0x10 if access point is locked */
662 	const char *head =
663 		"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
664 		"<e:propertyset xmlns:e=\"urn:schemas-upnp-org:event-1-0\">\n";
665 	const char *tail = "</e:propertyset>\n";
666 	char txt[10];
667 
668 	wlan_event = s->sm->wlanevent;
669 	if (wlan_event == NULL || *wlan_event == '\0') {
670 		wpa_printf(MSG_DEBUG, "WPS UPnP: WLANEvent not known for "
671 			   "initial event message");
672 		wlan_event = "";
673 	}
674 	buf = wpabuf_alloc(500 + os_strlen(wlan_event));
675 	if (buf == NULL)
676 		return 1;
677 
678 	wpabuf_put_str(buf, head);
679 	wpabuf_put_property(buf, "STAStatus", "1");
680 	os_snprintf(txt, sizeof(txt), "%d", ap_status);
681 	wpabuf_put_property(buf, "APStatus", txt);
682 	if (*wlan_event)
683 		wpabuf_put_property(buf, "WLANEvent", wlan_event);
684 	wpabuf_put_str(buf, tail);
685 
686 	if (event_add(s, buf)) {
687 		wpabuf_free(buf);
688 		return 1;
689 	}
690 	wpabuf_free(buf);
691 
692 	return 0;
693 }
694 
695 
696 /**
697  * subscription_start - Rremember a UPnP control point to send events to.
698  * @sm: WPS UPnP state machine from upnp_wps_device_init()
699  * @callback_urls: malloc' mem given to the subscription
700  * Returns: %NULL on error, or pointer to new subscription structure.
701  */
702 struct subscription * subscription_start(struct upnp_wps_device_sm *sm,
703 					 char *callback_urls)
704 {
705 	struct subscription *s;
706 	time_t now = time(NULL);
707 	time_t expire = now + UPNP_SUBSCRIBE_SEC;
708 
709 	/* Get rid of expired subscriptions so we have room */
710 	subscription_list_age(sm, now);
711 
712 	/* If too many subscriptions, remove oldest */
713 	if (sm->n_subscriptions >= MAX_SUBSCRIPTIONS) {
714 		s = sm->subscriptions;
715 		wpa_printf(MSG_INFO, "WPS UPnP: Too many subscriptions, "
716 			   "trashing oldest");
717 		subscription_unlink(s);
718 		subscription_destroy(s);
719 	}
720 
721 	s = os_zalloc(sizeof(*s));
722 	if (s == NULL)
723 		return NULL;
724 
725 	s->sm = sm;
726 	s->timeout_time = expire;
727 	uuid_make(s->uuid);
728 	subscr_addr_list_create(s, callback_urls);
729 	/* Add to end of list, since it has the highest expiration time */
730 	subscription_link_to_end(s);
731 	/* Queue up immediate event message (our last event)
732 	 * as required by UPnP spec.
733 	 */
734 	if (subscription_first_event(s)) {
735 		wpa_printf(MSG_INFO, "WPS UPnP: Dropping subscriber due to "
736 			   "event backlog");
737 		subscription_unlink(s);
738 		subscription_destroy(s);
739 		return NULL;
740 	}
741 	wpa_printf(MSG_DEBUG, "WPS UPnP: Subscription %p started with %s",
742 		   s, callback_urls);
743 	os_free(callback_urls);
744 	/* Schedule sending this */
745 	event_send_all_later(sm);
746 	return s;
747 }
748 
749 
750 /* subscription_renew -- find subscription and reset timeout */
751 struct subscription * subscription_renew(struct upnp_wps_device_sm *sm,
752 					 const u8 uuid[UUID_LEN])
753 {
754 	time_t now = time(NULL);
755 	time_t expire = now + UPNP_SUBSCRIBE_SEC;
756 	struct subscription *s = subscription_find(sm, uuid);
757 	if (s == NULL)
758 		return NULL;
759 	wpa_printf(MSG_DEBUG, "WPS UPnP: Subscription renewed");
760 	subscription_unlink(s);
761 	s->timeout_time = expire;
762 	/* add back to end of list, since it now has highest expiry */
763 	subscription_link_to_end(s);
764 	return s;
765 }
766 
767 
768 /**
769  * upnp_wps_device_send_wlan_event - Event notification
770  * @sm: WPS UPnP state machine from upnp_wps_device_init()
771  * @from_mac_addr: Source (Enrollee) MAC address for the event
772  * @ev_type: Event type
773  * @msg: Event data
774  * Returns: 0 on success, -1 on failure
775  *
776  * Tell external Registrars (UPnP control points) that something happened. In
777  * particular, events include WPS messages from clients that are proxied to
778  * external Registrars.
779  */
780 int upnp_wps_device_send_wlan_event(struct upnp_wps_device_sm *sm,
781 				    const u8 from_mac_addr[ETH_ALEN],
782 				    enum upnp_wps_wlanevent_type ev_type,
783 				    const struct wpabuf *msg)
784 {
785 	int ret = -1;
786 	char type[2];
787 	const u8 *mac = from_mac_addr;
788 	char mac_text[18];
789 	u8 *raw = NULL;
790 	size_t raw_len;
791 	char *val;
792 	size_t val_len;
793 	int pos = 0;
794 
795 	if (!sm)
796 		goto fail;
797 
798 	os_snprintf(type, sizeof(type), "%1u", ev_type);
799 
800 	raw_len = 1 + 17 + (msg ? wpabuf_len(msg) : 0);
801 	raw = os_zalloc(raw_len);
802 	if (!raw)
803 		goto fail;
804 
805 	*(raw + pos) = (u8) ev_type;
806 	pos += 1;
807 	os_snprintf(mac_text, sizeof(mac_text), MACSTR, MAC2STR(mac));
808 	wpa_printf(MSG_DEBUG, "WPS UPnP: Proxying WLANEvent from %s",
809 		   mac_text);
810 	os_memcpy(raw + pos, mac_text, 17);
811 	pos += 17;
812 	if (msg) {
813 		os_memcpy(raw + pos, wpabuf_head(msg), wpabuf_len(msg));
814 		pos += wpabuf_len(msg);
815 	}
816 	raw_len = pos;
817 
818 	val = (char *) base64_encode(raw, raw_len, &val_len);
819 	if (val == NULL)
820 		goto fail;
821 
822 	os_free(sm->wlanevent);
823 	sm->wlanevent = val;
824 	upnp_wps_device_send_event(sm);
825 
826 	ret = 0;
827 
828 fail:
829 	os_free(raw);
830 
831 	return ret;
832 }
833 
834 
835 /**
836  * get_netif_info - Get hw and IP addresses for network device
837  * @net_if: Selected network interface name
838  * @ip_addr: Buffer for returning IP address in network byte order
839  * @ip_addr_text: Buffer for returning a pointer to allocated IP address text
840  * @mac: Buffer for returning MAC address
841  * @mac_addr_text: Buffer for returning allocated MAC address text
842  * Returns: 0 on success, -1 on failure
843  */
844 static int get_netif_info(const char *net_if, unsigned *ip_addr,
845 			  char **ip_addr_text, u8 mac[ETH_ALEN],
846 			  char **mac_addr_text)
847 {
848 	struct ifreq req;
849 	int sock = -1;
850 	struct sockaddr_in *addr;
851 	struct in_addr in_addr;
852 
853 	*ip_addr_text = os_zalloc(16);
854 	*mac_addr_text = os_zalloc(18);
855 	if (*ip_addr_text == NULL || *mac_addr_text == NULL)
856 		goto fail;
857 
858 	sock = socket(AF_INET, SOCK_DGRAM, 0);
859 	if (sock < 0)
860 		goto fail;
861 
862 	os_strlcpy(req.ifr_name, net_if, sizeof(req.ifr_name));
863 	if (ioctl(sock, SIOCGIFADDR, &req) < 0) {
864 		wpa_printf(MSG_ERROR, "WPS UPnP: SIOCGIFADDR failed: %d (%s)",
865 			   errno, strerror(errno));
866 		goto fail;
867 	}
868 	addr = (void *) &req.ifr_addr;
869 	*ip_addr = addr->sin_addr.s_addr;
870 	in_addr.s_addr = *ip_addr;
871 	os_snprintf(*ip_addr_text, 16, "%s", inet_ntoa(in_addr));
872 
873 	os_strlcpy(req.ifr_name, net_if, sizeof(req.ifr_name));
874 	if (ioctl(sock, SIOCGIFHWADDR, &req) < 0) {
875 		wpa_printf(MSG_ERROR, "WPS UPnP: SIOCGIFHWADDR failed: "
876 			   "%d (%s)", errno, strerror(errno));
877 		goto fail;
878 	}
879 	os_memcpy(mac, req.ifr_addr.sa_data, 6);
880 	os_snprintf(*mac_addr_text, 18, MACSTR, MAC2STR(req.ifr_addr.sa_data));
881 
882 	close(sock);
883 	return 0;
884 
885 fail:
886 	if (sock >= 0)
887 		close(sock);
888 	os_free(*ip_addr_text);
889 	*ip_addr_text = NULL;
890 	os_free(*mac_addr_text);
891 	*mac_addr_text = NULL;
892 	return -1;
893 }
894 
895 
896 /**
897  * upnp_wps_device_stop - Stop WPS UPnP operations on an interface
898  * @sm: WPS UPnP state machine from upnp_wps_device_init()
899  */
900 void upnp_wps_device_stop(struct upnp_wps_device_sm *sm)
901 {
902 	if (!sm || !sm->started)
903 		return;
904 
905 	wpa_printf(MSG_DEBUG, "WPS UPnP: Stop device");
906 	web_listener_stop(sm);
907 	while (sm->web_connections)
908 		web_connection_stop(sm->web_connections);
909 	while (sm->msearch_replies)
910 		msearchreply_state_machine_stop(sm->msearch_replies);
911 	while (sm->subscriptions)  {
912 		struct subscription *s = sm->subscriptions;
913 		subscription_unlink(s);
914 		subscription_destroy(s);
915 	}
916 
917 	advertisement_state_machine_stop(sm);
918 	/* TODO: send byebye notifications */
919 
920 	event_send_stop_all(sm);
921 	os_free(sm->wlanevent);
922 	sm->wlanevent = NULL;
923 	os_free(sm->net_if);
924 	sm->net_if = NULL;
925 	os_free(sm->mac_addr_text);
926 	sm->mac_addr_text = NULL;
927 	os_free(sm->ip_addr_text);
928 	sm->ip_addr_text = NULL;
929 	if (sm->multicast_sd >= 0)
930 		close(sm->multicast_sd);
931 	sm->multicast_sd = -1;
932 	ssdp_listener_stop(sm);
933 
934 	sm->started = 0;
935 }
936 
937 
938 /**
939  * upnp_wps_device_start - Start WPS UPnP operations on an interface
940  * @sm: WPS UPnP state machine from upnp_wps_device_init()
941  * @net_if: Selected network interface name
942  * Returns: 0 on success, -1 on failure
943  */
944 int upnp_wps_device_start(struct upnp_wps_device_sm *sm, char *net_if)
945 {
946 	if (!sm || !net_if)
947 		return -1;
948 
949 	if (sm->started)
950 		upnp_wps_device_stop(sm);
951 
952 	sm->net_if = strdup(net_if);
953 	sm->multicast_sd = -1;
954 	sm->ssdp_sd = -1;
955 	sm->started = 1;
956 	sm->advertise_count = 0;
957 
958 	/* Fix up linux multicast handling */
959 	if (add_ssdp_network(net_if))
960 		goto fail;
961 
962 	/* Determine which IP and mac address we're using */
963 	if (get_netif_info(net_if,
964 			   &sm->ip_addr, &sm->ip_addr_text,
965 			   sm->mac_addr, &sm->mac_addr_text)) {
966 		wpa_printf(MSG_INFO, "WPS UPnP: Could not get IP/MAC address "
967 			   "for %s. Does it have IP address?", net_if);
968 		goto fail;
969 	}
970 
971 	/* Listen for incoming TCP connections so that others
972 	 * can fetch our "xml files" from us.
973 	 */
974 	if (web_listener_start(sm))
975 		goto fail;
976 
977 	/* Set up for receiving discovery (UDP) packets */
978 	if (ssdp_listener_start(sm))
979 		goto fail;
980 
981 	/* Set up for sending multicast */
982 	if (ssdp_open_multicast(sm) < 0)
983 		goto fail;
984 
985 	/*
986 	 * Broadcast NOTIFY messages to let the world know we exist.
987 	 * This is done via a state machine since the messages should not be
988 	 * all sent out at once.
989 	 */
990 	if (advertisement_state_machine_start(sm))
991 		goto fail;
992 
993 	return 0;
994 
995 fail:
996 	upnp_wps_device_stop(sm);
997 	return -1;
998 }
999 
1000 
1001 /**
1002  * upnp_wps_device_deinit - Deinitialize WPS UPnP
1003  * @sm: WPS UPnP state machine from upnp_wps_device_init()
1004  */
1005 void upnp_wps_device_deinit(struct upnp_wps_device_sm *sm)
1006 {
1007 	if (!sm)
1008 		return;
1009 
1010 	upnp_wps_device_stop(sm);
1011 
1012 	if (sm->peer.wps)
1013 		wps_deinit(sm->peer.wps);
1014 	os_free(sm->root_dir);
1015 	os_free(sm->desc_url);
1016 	os_free(sm->ctx);
1017 	os_free(sm);
1018 }
1019 
1020 
1021 /**
1022  * upnp_wps_device_init - Initialize WPS UPnP
1023  * @ctx: callback table; we must eventually free it
1024  * @wps: Pointer to longterm WPS context
1025  * @priv: External context data that will be used in callbacks
1026  * Returns: WPS UPnP state or %NULL on failure
1027  */
1028 struct upnp_wps_device_sm *
1029 upnp_wps_device_init(struct upnp_wps_device_ctx *ctx, struct wps_context *wps,
1030 		     void *priv)
1031 {
1032 	struct upnp_wps_device_sm *sm;
1033 
1034 	sm = os_zalloc(sizeof(*sm));
1035 	if (!sm) {
1036 		wpa_printf(MSG_ERROR, "WPS UPnP: upnp_wps_device_init failed");
1037 		return NULL;
1038 	}
1039 
1040 	sm->ctx = ctx;
1041 	sm->wps = wps;
1042 	sm->priv = priv;
1043 
1044 	return sm;
1045 }
1046 
1047 
1048 /**
1049  * upnp_wps_subscribers - Check whether there are any event subscribers
1050  * @sm: WPS UPnP state machine from upnp_wps_device_init()
1051  * Returns: 0 if no subscribers, 1 if subscribers
1052  */
1053 int upnp_wps_subscribers(struct upnp_wps_device_sm *sm)
1054 {
1055 	return sm->subscriptions != NULL;
1056 }
1057