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  * -- The http error code generation is pretty bogus, hopefully noone 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 <assert.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 
213 /* Write the current date/time per RFC */
214 void format_date(struct wpabuf *buf)
215 {
216 	const char *weekday_str = "Sun\0Mon\0Tue\0Wed\0Thu\0Fri\0Sat";
217 	const char *month_str = "Jan\0Feb\0Mar\0Apr\0May\0Jun\0"
218 		"Jul\0Aug\0Sep\0Oct\0Nov\0Dec";
219 	struct tm *date;
220 	time_t t;
221 
222 	t = time(NULL);
223 	date = gmtime(&t);
224 	wpabuf_printf(buf, "%s, %02d %s %d %02d:%02d:%02d GMT",
225 		      &weekday_str[date->tm_wday * 4], date->tm_mday,
226 		      &month_str[date->tm_mon * 4], date->tm_year + 1900,
227 		      date->tm_hour, date->tm_min, date->tm_sec);
228 }
229 
230 
231 /***************************************************************************
232  * UUIDs (unique identifiers)
233  *
234  * These are supposed to be unique in all the world.
235  * Sometimes permanent ones are used, sometimes temporary ones
236  * based on random numbers... there are different rules for valid content
237  * of different types.
238  * Each uuid is 16 bytes long.
239  **************************************************************************/
240 
241 /* uuid_make -- construct a random UUID
242  * The UPnP documents don't seem to offer any guidelines as to which method to
243  * use for constructing UUIDs for subscriptions. Presumably any method from
244  * rfc4122 is good enough; I've chosen random number method.
245  */
246 static void uuid_make(u8 uuid[UUID_LEN])
247 {
248 	os_get_random(uuid, UUID_LEN);
249 
250 	/* Replace certain bits as specified in rfc4122 or X.667 */
251 	uuid[6] &= 0x0f; uuid[6] |= (4 << 4);   /* version 4 == random gen */
252 	uuid[8] &= 0x3f; uuid[8] |= 0x80;
253 }
254 
255 
256 /*
257  * Subscriber address handling.
258  * Since a subscriber may have an arbitrary number of addresses, we have to
259  * add a bunch of code to handle them.
260  *
261  * Addresses are passed in text, and MAY be domain names instead of the (usual
262  * and expected) dotted IP addresses. Resolving domain names consumes a lot of
263  * resources. Worse, we are currently using the standard Linux getaddrinfo()
264  * which will block the entire program until complete or timeout! The proper
265  * solution would be to use the "ares" library or similar with more state
266  * machine steps etc. or just disable domain name resolution by setting
267  * NO_DOMAIN_NAME_RESOLUTION to 1 at top of this file.
268  */
269 
270 /* subscr_addr_delete -- delete single unlinked subscriber address
271  * (be sure to unlink first if need be)
272  */
273 static void subscr_addr_delete(struct subscr_addr *a)
274 {
275 	/*
276 	 * Note: do NOT free domain_and_port or path because they point to
277 	 * memory within the allocation of "a".
278 	 */
279 	os_free(a);
280 }
281 
282 
283 /* subscr_addr_unlink -- unlink subscriber address from linked list */
284 static void subscr_addr_unlink(struct subscription *s, struct subscr_addr *a)
285 {
286 	struct subscr_addr **listp = &s->addr_list;
287 	s->n_addr--;
288 	a->next->prev = a->prev;
289 	a->prev->next = a->next;
290 	if (*listp == a) {
291 		if (a == a->next) {
292 			/* last in queue */
293 			*listp = NULL;
294 			assert(s->n_addr == 0);
295 		} else {
296 			*listp = a->next;
297 		}
298 	}
299 }
300 
301 
302 /* subscr_addr_free_all -- unlink and delete list of subscriber addresses. */
303 static void subscr_addr_free_all(struct subscription *s)
304 {
305 	struct subscr_addr **listp = &s->addr_list;
306 	struct subscr_addr *a;
307 	while ((a = *listp) != NULL) {
308 		subscr_addr_unlink(s, a);
309 		subscr_addr_delete(a);
310 	}
311 }
312 
313 
314 /* subscr_addr_link -- add subscriber address to list of addresses */
315 static void subscr_addr_link(struct subscription *s, struct subscr_addr *a)
316 {
317 	struct subscr_addr **listp = &s->addr_list;
318 	s->n_addr++;
319 	if (*listp == NULL) {
320 		*listp = a->next = a->prev = a;
321 	} else {
322 		a->next = *listp;
323 		a->prev = (*listp)->prev;
324 		a->prev->next = a;
325 		a->next->prev = a;
326 	}
327 }
328 
329 
330 /* subscr_addr_add_url -- add address(es) for one url to subscription */
331 static void subscr_addr_add_url(struct subscription *s, const char *url)
332 {
333 	int alloc_len;
334 	char *scratch_mem = NULL;
335 	char *mem;
336 	char *domain_and_port;
337 	char *delim;
338 	char *path;
339 	char *domain;
340 	int port = 80;  /* port to send to (default is port 80) */
341 	struct addrinfo hints;
342 	struct addrinfo *result = NULL;
343 	struct addrinfo *rp;
344 	int rerr;
345 	struct subscr_addr *a = NULL;
346 
347 	/* url MUST begin with http: */
348 	if (os_strncasecmp(url, "http://", 7))
349 		goto fail;
350 	url += 7;
351 
352 	/* allocate memory for the extra stuff we need */
353 	alloc_len = (2 * (os_strlen(url) + 1));
354 	scratch_mem = os_zalloc(alloc_len);
355 	if (scratch_mem == NULL)
356 		goto fail;
357 	mem = scratch_mem;
358 	strcpy(mem, url);
359 	domain_and_port = mem;
360 	mem += 1 + os_strlen(mem);
361 	delim = os_strchr(domain_and_port, '/');
362 	if (delim) {
363 		*delim++ = 0;   /* null terminate domain and port */
364 		path = delim;
365 	} else {
366 		path = domain_and_port + os_strlen(domain_and_port);
367 	}
368 	domain = mem;
369 	strcpy(domain, domain_and_port);
370 	delim = strchr(domain, ':');
371 	if (delim) {
372 		*delim++ = 0;   /* null terminate domain */
373 		if (isdigit(*delim))
374 			port = atol(delim);
375 	}
376 
377 	/*
378 	 * getaddrinfo does the right thing with dotted decimal notations, or
379 	 * will resolve domain names. Resolving domain names will unfortunately
380 	 * hang the entire program until it is resolved or it times out
381 	 * internal to getaddrinfo; fortunately we think that the use of actual
382 	 * domain names (vs. dotted decimal notations) should be uncommon.
383 	 */
384 	os_memset(&hints, 0, sizeof(struct addrinfo));
385 	hints.ai_family = AF_INET;      /* IPv4 */
386 	hints.ai_socktype = SOCK_STREAM;
387 #if NO_DOMAIN_NAME_RESOLUTION
388 	/* Suppress domain name resolutions that would halt
389 	 * the program for periods of time
390 	 */
391 	hints.ai_flags = AI_NUMERICHOST;
392 #else
393 	/* Allow domain name resolution. */
394 	hints.ai_flags = 0;
395 #endif
396 	hints.ai_protocol = 0;          /* Any protocol? */
397 	rerr = getaddrinfo(domain, NULL /* fill in port ourselves */,
398 			   &hints, &result);
399 	if (rerr) {
400 		wpa_printf(MSG_INFO, "WPS UPnP: Resolve error %d (%s) on: %s",
401 			   rerr, gai_strerror(rerr), domain);
402 		goto fail;
403 	}
404 	for (rp = result; rp; rp = rp->ai_next) {
405 		/* Limit no. of address to avoid denial of service attack */
406 		if (s->n_addr >= MAX_ADDR_PER_SUBSCRIPTION) {
407 			wpa_printf(MSG_INFO, "WPS UPnP: subscr_addr_add_url: "
408 				   "Ignoring excessive addresses");
409 			break;
410 		}
411 
412 		a = os_zalloc(sizeof(*a) + alloc_len);
413 		if (a == NULL)
414 			continue;
415 		a->s = s;
416 		mem = (void *) (a + 1);
417 		a->domain_and_port = mem;
418 		strcpy(mem, domain_and_port);
419 		mem += 1 + strlen(mem);
420 		a->path = mem;
421 		if (path[0] != '/')
422 			*mem++ = '/';
423 		strcpy(mem, path);
424 		mem += 1 + strlen(mem);
425 		os_memcpy(&a->saddr, rp->ai_addr, sizeof(a->saddr));
426 		a->saddr.sin_port = htons(port);
427 
428 		subscr_addr_link(s, a);
429 		a = NULL;       /* don't free it below */
430 	}
431 
432 fail:
433 	if (result)
434 		freeaddrinfo(result);
435 	os_free(scratch_mem);
436 	os_free(a);
437 }
438 
439 
440 /* subscr_addr_list_create -- create list from urls in string.
441  *      Each url is enclosed by angle brackets.
442  */
443 static void subscr_addr_list_create(struct subscription *s,
444 				    const char *url_list)
445 {
446 	char *end;
447 	for (;;) {
448 		while (*url_list == ' ' || *url_list == '\t')
449 			url_list++;
450 		if (*url_list != '<')
451 			break;
452 		url_list++;
453 		end = os_strchr(url_list, '>');
454 		if (end == NULL)
455 			break;
456 		*end++ = 0;
457 		subscr_addr_add_url(s, url_list);
458 		url_list = end;
459 	}
460 }
461 
462 
463 int send_wpabuf(int fd, struct wpabuf *buf)
464 {
465 	wpa_printf(MSG_DEBUG, "WPS UPnP: Send %lu byte message",
466 		   (unsigned long) wpabuf_len(buf));
467 	errno = 0;
468 	if (write(fd, wpabuf_head(buf), wpabuf_len(buf)) !=
469 	    (int) wpabuf_len(buf)) {
470 		wpa_printf(MSG_ERROR, "WPS UPnP: Failed to send buffer: "
471 			   "errno=%d (%s)",
472 			   errno, strerror(errno));
473 		return -1;
474 	}
475 
476 	return 0;
477 }
478 
479 
480 static void wpabuf_put_property(struct wpabuf *buf, const char *name,
481 				const char *value)
482 {
483 	wpabuf_put_str(buf, "<e:property>");
484 	wpabuf_printf(buf, "<%s>", name);
485 	if (value)
486 		wpabuf_put_str(buf, value);
487 	wpabuf_printf(buf, "</%s>", name);
488 	wpabuf_put_str(buf, "</e:property>\n");
489 }
490 
491 
492 /**
493  * upnp_wps_device_send_event - Queue event messages for subscribers
494  * @sm: WPS UPnP state machine from upnp_wps_device_init()
495  *
496  * This function queues the last WLANEvent to be sent for all currently
497  * subscribed UPnP control points. sm->wlanevent must have been set with the
498  * encoded data before calling this function.
499  */
500 static void upnp_wps_device_send_event(struct upnp_wps_device_sm *sm)
501 {
502 	/* Enqueue event message for all subscribers */
503 	struct wpabuf *buf; /* holds event message */
504 	int buf_size = 0;
505 	struct subscription *s;
506 	/* Actually, utf-8 is the default, but it doesn't hurt to specify it */
507 	const char *format_head =
508 		"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
509 		"<e:propertyset xmlns:e=\"urn:schemas-upnp-org:event-1-0\">\n";
510 	const char *format_tail = "</e:propertyset>\n";
511 
512 	if (sm->subscriptions == NULL) {
513 		/* optimize */
514 		return;
515 	}
516 
517 	/* Determine buffer size needed first */
518 	buf_size += os_strlen(format_head);
519 	buf_size += 50 + 2 * os_strlen("WLANEvent");
520 	if (sm->wlanevent)
521 		buf_size += os_strlen(sm->wlanevent);
522 	buf_size += os_strlen(format_tail);
523 
524 	buf = wpabuf_alloc(buf_size);
525 	if (buf == NULL)
526 		return;
527 	wpabuf_put_str(buf, format_head);
528 	wpabuf_put_property(buf, "WLANEvent", sm->wlanevent);
529 	wpabuf_put_str(buf, format_tail);
530 
531 	wpa_printf(MSG_MSGDUMP, "WPS UPnP: WLANEvent message:\n%s",
532 		   (char *) wpabuf_head(buf));
533 
534 	s = sm->subscriptions;
535 	do {
536 		if (event_add(s, buf)) {
537 			struct subscription *s_old = s;
538 			wpa_printf(MSG_INFO, "WPS UPnP: Dropping "
539 				   "subscriber due to event backlog");
540 			s = s_old->next;
541 			subscription_unlink(s_old);
542 			subscription_destroy(s_old);
543 		} else {
544 			s = s->next;
545 		}
546 	} while (s != sm->subscriptions);
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_unlink -- remove from the active list */
559 void subscription_unlink(struct subscription *s)
560 {
561 	struct upnp_wps_device_sm *sm = s->sm;
562 
563 	if (s->next == s) {
564 		/* only one? */
565 		sm->subscriptions = NULL;
566 	} else  {
567 		if (sm->subscriptions == s)
568 			sm->subscriptions = s->next;
569 		s->next->prev = s->prev;
570 		s->prev->next = s->next;
571 	}
572 	sm->n_subscriptions--;
573 }
574 
575 
576 /* subscription_link_to_end -- link to end of active list
577  * (should have high expiry time!)
578  */
579 static void subscription_link_to_end(struct subscription *s)
580 {
581 	struct upnp_wps_device_sm *sm = s->sm;
582 
583 	if (sm->subscriptions) {
584 		s->next = sm->subscriptions;
585 		s->prev = s->next->prev;
586 		s->prev->next = s;
587 		s->next->prev = s;
588 	} else {
589 		sm->subscriptions = s->next = s->prev = s;
590 	}
591 	sm->n_subscriptions++;
592 }
593 
594 
595 /* subscription_destroy -- destroy an unlinked subscription
596  * Be sure to unlink first if necessary.
597  */
598 void subscription_destroy(struct subscription *s)
599 {
600 	wpa_printf(MSG_DEBUG, "WPS UPnP: Destroy subscription %p", s);
601 	if (s->addr_list)
602 		subscr_addr_free_all(s);
603 	event_delete_all(s);
604 	os_free(s);
605 }
606 
607 
608 /* subscription_list_age -- remove expired subscriptions */
609 static void subscription_list_age(struct upnp_wps_device_sm *sm, time_t now)
610 {
611 	struct subscription *s;
612 	while ((s = sm->subscriptions) != NULL && s->timeout_time < now) {
613 		wpa_printf(MSG_DEBUG, "WPS UPnP: Removing aged subscription");
614 		subscription_unlink(s);
615 		subscription_destroy(s);
616 	}
617 }
618 
619 
620 /* subscription_find -- return existing subscription matching uuid, if any
621  * returns NULL if not found
622  */
623 struct subscription * subscription_find(struct upnp_wps_device_sm *sm,
624 					const u8 uuid[UUID_LEN])
625 {
626 	struct subscription *s0 = sm->subscriptions;
627 	struct subscription *s = s0;
628 
629 	if (s0 == NULL)
630 		return NULL;
631 	do {
632 		if (os_memcmp(s->uuid, uuid, UUID_LEN) == 0)
633 			return s; /* Found match */
634 		s = s->next;
635 	} while (s != s0);
636 
637 	return NULL;
638 }
639 
640 
641 static struct wpabuf * build_fake_wsc_ack(void)
642 {
643 	struct wpabuf *msg = wpabuf_alloc(100);
644 	if (msg == NULL)
645 		return NULL;
646 	wpabuf_put_u8(msg, UPNP_WPS_WLANEVENT_TYPE_EAP);
647 	wpabuf_put_str(msg, "00:00:00:00:00:00");
648 	wps_build_version(msg);
649 	wps_build_msg_type(msg, WPS_WSC_ACK);
650 	/* Enrollee Nonce */
651 	wpabuf_put_be16(msg, ATTR_ENROLLEE_NONCE);
652 	wpabuf_put_be16(msg, WPS_NONCE_LEN);
653 	wpabuf_put(msg, WPS_NONCE_LEN);
654 	/* Registrar Nonce */
655 	wpabuf_put_be16(msg, ATTR_REGISTRAR_NONCE);
656 	wpabuf_put_be16(msg, WPS_NONCE_LEN);
657 	wpabuf_put(msg, WPS_NONCE_LEN);
658 	return msg;
659 }
660 
661 
662 /* subscription_first_event -- send format/queue event that is automatically
663  * sent on a new subscription.
664  */
665 static int subscription_first_event(struct subscription *s)
666 {
667 	/*
668 	 * Actually, utf-8 is the default, but it doesn't hurt to specify it.
669 	 *
670 	 * APStatus is apparently a bit set,
671 	 * 0x1 = configuration change (but is always set?)
672 	 * 0x10 = ap is locked
673 	 *
674 	 * Per UPnP spec, we send out the last value of each variable, even
675 	 * for WLANEvent, whatever it was.
676 	 */
677 	char *wlan_event;
678 	struct wpabuf *buf;
679 	int ap_status = 1;      /* TODO: add 0x10 if access point is locked */
680 	const char *head =
681 		"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
682 		"<e:propertyset xmlns:e=\"urn:schemas-upnp-org:event-1-0\">\n";
683 	const char *tail = "</e:propertyset>\n";
684 	char txt[10];
685 
686 	if (s->sm->wlanevent == NULL) {
687 		/*
688 		 * There has been no events before the subscription. However,
689 		 * UPnP device architecture specification requires all the
690 		 * evented variables to be included, so generate a dummy event
691 		 * for this particular case using a WSC_ACK and all-zeros
692 		 * nonces. The ER (UPnP control point) will ignore this, but at
693 		 * least it will learn that WLANEvent variable will be used in
694 		 * event notifications in the future.
695 		 */
696 		struct wpabuf *msg;
697 		wpa_printf(MSG_DEBUG, "WPS UPnP: Use a fake WSC_ACK as the "
698 			   "initial WLANEvent");
699 		msg = build_fake_wsc_ack();
700 		if (msg) {
701 			s->sm->wlanevent = (char *)
702 				base64_encode(wpabuf_head(msg),
703 					      wpabuf_len(msg), NULL);
704 			wpabuf_free(msg);
705 		}
706 	}
707 
708 	wlan_event = s->sm->wlanevent;
709 	if (wlan_event == NULL || *wlan_event == '\0') {
710 		wpa_printf(MSG_DEBUG, "WPS UPnP: WLANEvent not known for "
711 			   "initial event message");
712 		wlan_event = "";
713 	}
714 	buf = wpabuf_alloc(500 + os_strlen(wlan_event));
715 	if (buf == NULL)
716 		return 1;
717 
718 	wpabuf_put_str(buf, head);
719 	wpabuf_put_property(buf, "STAStatus", "1");
720 	os_snprintf(txt, sizeof(txt), "%d", ap_status);
721 	wpabuf_put_property(buf, "APStatus", txt);
722 	if (*wlan_event)
723 		wpabuf_put_property(buf, "WLANEvent", wlan_event);
724 	wpabuf_put_str(buf, tail);
725 
726 	if (event_add(s, buf)) {
727 		wpabuf_free(buf);
728 		return 1;
729 	}
730 	wpabuf_free(buf);
731 
732 	return 0;
733 }
734 
735 
736 /**
737  * subscription_start - Remember a UPnP control point to send events to.
738  * @sm: WPS UPnP state machine from upnp_wps_device_init()
739  * @callback_urls: Callback URLs
740  * Returns: %NULL on error, or pointer to new subscription structure.
741  */
742 struct subscription * subscription_start(struct upnp_wps_device_sm *sm,
743 					 const char *callback_urls)
744 {
745 	struct subscription *s;
746 	time_t now = time(NULL);
747 	time_t expire = now + UPNP_SUBSCRIBE_SEC;
748 
749 	/* Get rid of expired subscriptions so we have room */
750 	subscription_list_age(sm, now);
751 
752 	/* If too many subscriptions, remove oldest */
753 	if (sm->n_subscriptions >= MAX_SUBSCRIPTIONS) {
754 		s = sm->subscriptions;
755 		wpa_printf(MSG_INFO, "WPS UPnP: Too many subscriptions, "
756 			   "trashing oldest");
757 		subscription_unlink(s);
758 		subscription_destroy(s);
759 	}
760 
761 	s = os_zalloc(sizeof(*s));
762 	if (s == NULL)
763 		return NULL;
764 
765 	s->sm = sm;
766 	s->timeout_time = expire;
767 	uuid_make(s->uuid);
768 	subscr_addr_list_create(s, callback_urls);
769 	/* Add to end of list, since it has the highest expiration time */
770 	subscription_link_to_end(s);
771 	/* Queue up immediate event message (our last event)
772 	 * as required by UPnP spec.
773 	 */
774 	if (subscription_first_event(s)) {
775 		wpa_printf(MSG_INFO, "WPS UPnP: Dropping subscriber due to "
776 			   "event backlog");
777 		subscription_unlink(s);
778 		subscription_destroy(s);
779 		return NULL;
780 	}
781 	wpa_printf(MSG_DEBUG, "WPS UPnP: Subscription %p started with %s",
782 		   s, callback_urls);
783 	/* Schedule sending this */
784 	event_send_all_later(sm);
785 	return s;
786 }
787 
788 
789 /* subscription_renew -- find subscription and reset timeout */
790 struct subscription * subscription_renew(struct upnp_wps_device_sm *sm,
791 					 const u8 uuid[UUID_LEN])
792 {
793 	time_t now = time(NULL);
794 	time_t expire = now + UPNP_SUBSCRIBE_SEC;
795 	struct subscription *s = subscription_find(sm, uuid);
796 	if (s == NULL)
797 		return NULL;
798 	wpa_printf(MSG_DEBUG, "WPS UPnP: Subscription renewed");
799 	subscription_unlink(s);
800 	s->timeout_time = expire;
801 	/* add back to end of list, since it now has highest expiry */
802 	subscription_link_to_end(s);
803 	return s;
804 }
805 
806 
807 /**
808  * upnp_wps_device_send_wlan_event - Event notification
809  * @sm: WPS UPnP state machine from upnp_wps_device_init()
810  * @from_mac_addr: Source (Enrollee) MAC address for the event
811  * @ev_type: Event type
812  * @msg: Event data
813  * Returns: 0 on success, -1 on failure
814  *
815  * Tell external Registrars (UPnP control points) that something happened. In
816  * particular, events include WPS messages from clients that are proxied to
817  * external Registrars.
818  */
819 int upnp_wps_device_send_wlan_event(struct upnp_wps_device_sm *sm,
820 				    const u8 from_mac_addr[ETH_ALEN],
821 				    enum upnp_wps_wlanevent_type ev_type,
822 				    const struct wpabuf *msg)
823 {
824 	int ret = -1;
825 	char type[2];
826 	const u8 *mac = from_mac_addr;
827 	char mac_text[18];
828 	u8 *raw = NULL;
829 	size_t raw_len;
830 	char *val;
831 	size_t val_len;
832 	int pos = 0;
833 
834 	if (!sm)
835 		goto fail;
836 
837 	os_snprintf(type, sizeof(type), "%1u", ev_type);
838 
839 	raw_len = 1 + 17 + (msg ? wpabuf_len(msg) : 0);
840 	raw = os_zalloc(raw_len);
841 	if (!raw)
842 		goto fail;
843 
844 	*(raw + pos) = (u8) ev_type;
845 	pos += 1;
846 	os_snprintf(mac_text, sizeof(mac_text), MACSTR, MAC2STR(mac));
847 	wpa_printf(MSG_DEBUG, "WPS UPnP: Proxying WLANEvent from %s",
848 		   mac_text);
849 	os_memcpy(raw + pos, mac_text, 17);
850 	pos += 17;
851 	if (msg) {
852 		os_memcpy(raw + pos, wpabuf_head(msg), wpabuf_len(msg));
853 		pos += wpabuf_len(msg);
854 	}
855 	raw_len = pos;
856 
857 	val = (char *) base64_encode(raw, raw_len, &val_len);
858 	if (val == NULL)
859 		goto fail;
860 
861 	os_free(sm->wlanevent);
862 	sm->wlanevent = val;
863 	upnp_wps_device_send_event(sm);
864 
865 	ret = 0;
866 
867 fail:
868 	os_free(raw);
869 
870 	return ret;
871 }
872 
873 
874 #ifdef __FreeBSD__
875 #include <sys/sysctl.h>
876 #include <net/route.h>
877 #include <net/if_dl.h>
878 
879 static int eth_get(const char *device, u8 ea[ETH_ALEN])
880 {
881 	struct if_msghdr *ifm;
882 	struct sockaddr_dl *sdl;
883 	u_char *p, *buf;
884 	size_t len;
885 	int mib[] = { CTL_NET, AF_ROUTE, 0, AF_LINK, NET_RT_IFLIST, 0 };
886 
887 	if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0)
888 		return -1;
889 	if ((buf = os_malloc(len)) == NULL)
890 		return -1;
891 	if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
892 		os_free(buf);
893 		return -1;
894 	}
895 	for (p = buf; p < buf + len; p += ifm->ifm_msglen) {
896 		ifm = (struct if_msghdr *)p;
897 		sdl = (struct sockaddr_dl *)(ifm + 1);
898 		if (ifm->ifm_type != RTM_IFINFO ||
899 		    (ifm->ifm_addrs & RTA_IFP) == 0)
900 			continue;
901 		if (sdl->sdl_family != AF_LINK || sdl->sdl_nlen == 0 ||
902 		    os_memcmp(sdl->sdl_data, device, sdl->sdl_nlen) != 0)
903 			continue;
904 		os_memcpy(ea, LLADDR(sdl), sdl->sdl_alen);
905 		break;
906 	}
907 	os_free(buf);
908 
909 	if (p >= buf + len) {
910 		errno = ESRCH;
911 		return -1;
912 	}
913 	return 0;
914 }
915 #endif /* __FreeBSD__ */
916 
917 
918 /**
919  * get_netif_info - Get hw and IP addresses for network device
920  * @net_if: Selected network interface name
921  * @ip_addr: Buffer for returning IP address in network byte order
922  * @ip_addr_text: Buffer for returning a pointer to allocated IP address text
923  * @mac: Buffer for returning MAC address
924  * @mac_addr_text: Buffer for returning allocated MAC address text
925  * Returns: 0 on success, -1 on failure
926  */
927 static int get_netif_info(const char *net_if, unsigned *ip_addr,
928 			  char **ip_addr_text, u8 mac[ETH_ALEN],
929 			  char **mac_addr_text)
930 {
931 	struct ifreq req;
932 	int sock = -1;
933 	struct sockaddr_in *addr;
934 	struct in_addr in_addr;
935 
936 	*ip_addr_text = os_zalloc(16);
937 	*mac_addr_text = os_zalloc(18);
938 	if (*ip_addr_text == NULL || *mac_addr_text == NULL)
939 		goto fail;
940 
941 	sock = socket(AF_INET, SOCK_DGRAM, 0);
942 	if (sock < 0)
943 		goto fail;
944 
945 	os_strlcpy(req.ifr_name, net_if, sizeof(req.ifr_name));
946 	if (ioctl(sock, SIOCGIFADDR, &req) < 0) {
947 		wpa_printf(MSG_ERROR, "WPS UPnP: SIOCGIFADDR failed: %d (%s)",
948 			   errno, strerror(errno));
949 		goto fail;
950 	}
951 	addr = (void *) &req.ifr_addr;
952 	*ip_addr = addr->sin_addr.s_addr;
953 	in_addr.s_addr = *ip_addr;
954 	os_snprintf(*ip_addr_text, 16, "%s", inet_ntoa(in_addr));
955 
956 #ifdef __linux__
957 	os_strlcpy(req.ifr_name, net_if, sizeof(req.ifr_name));
958 	if (ioctl(sock, SIOCGIFHWADDR, &req) < 0) {
959 		wpa_printf(MSG_ERROR, "WPS UPnP: SIOCGIFHWADDR failed: "
960 			   "%d (%s)", errno, strerror(errno));
961 		goto fail;
962 	}
963 	os_memcpy(mac, req.ifr_addr.sa_data, 6);
964 #elif defined(__FreeBSD__)
965 	if (eth_get(net_if, mac) < 0) {
966 		wpa_printf(MSG_ERROR, "WPS UPnP: Failed to get MAC address");
967 		goto fail;
968 	}
969 #else
970 #error MAC address fetch not implemented
971 #endif
972 	os_snprintf(*mac_addr_text, 18, MACSTR, MAC2STR(req.ifr_addr.sa_data));
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 	os_free(*mac_addr_text);
983 	*mac_addr_text = NULL;
984 	return -1;
985 }
986 
987 
988 /**
989  * upnp_wps_device_stop - Stop WPS UPnP operations on an interface
990  * @sm: WPS UPnP state machine from upnp_wps_device_init()
991  */
992 void upnp_wps_device_stop(struct upnp_wps_device_sm *sm)
993 {
994 	if (!sm || !sm->started)
995 		return;
996 
997 	wpa_printf(MSG_DEBUG, "WPS UPnP: Stop device");
998 	web_listener_stop(sm);
999 	while (sm->web_connections)
1000 		web_connection_stop(sm->web_connections);
1001 	while (sm->msearch_replies)
1002 		msearchreply_state_machine_stop(sm->msearch_replies);
1003 	while (sm->subscriptions)  {
1004 		struct subscription *s = sm->subscriptions;
1005 		subscription_unlink(s);
1006 		subscription_destroy(s);
1007 	}
1008 
1009 	advertisement_state_machine_stop(sm, 1);
1010 
1011 	event_send_stop_all(sm);
1012 	os_free(sm->wlanevent);
1013 	sm->wlanevent = NULL;
1014 	os_free(sm->net_if);
1015 	sm->net_if = NULL;
1016 	os_free(sm->mac_addr_text);
1017 	sm->mac_addr_text = NULL;
1018 	os_free(sm->ip_addr_text);
1019 	sm->ip_addr_text = NULL;
1020 	if (sm->multicast_sd >= 0)
1021 		close(sm->multicast_sd);
1022 	sm->multicast_sd = -1;
1023 	ssdp_listener_stop(sm);
1024 
1025 	sm->started = 0;
1026 }
1027 
1028 
1029 /**
1030  * upnp_wps_device_start - Start WPS UPnP operations on an interface
1031  * @sm: WPS UPnP state machine from upnp_wps_device_init()
1032  * @net_if: Selected network interface name
1033  * Returns: 0 on success, -1 on failure
1034  */
1035 int upnp_wps_device_start(struct upnp_wps_device_sm *sm, char *net_if)
1036 {
1037 	if (!sm || !net_if)
1038 		return -1;
1039 
1040 	if (sm->started)
1041 		upnp_wps_device_stop(sm);
1042 
1043 	sm->net_if = strdup(net_if);
1044 	sm->multicast_sd = -1;
1045 	sm->ssdp_sd = -1;
1046 	sm->started = 1;
1047 	sm->advertise_count = 0;
1048 
1049 	/* Fix up linux multicast handling */
1050 	if (add_ssdp_network(net_if))
1051 		goto fail;
1052 
1053 	/* Determine which IP and mac address we're using */
1054 	if (get_netif_info(net_if,
1055 			   &sm->ip_addr, &sm->ip_addr_text,
1056 			   sm->mac_addr, &sm->mac_addr_text)) {
1057 		wpa_printf(MSG_INFO, "WPS UPnP: Could not get IP/MAC address "
1058 			   "for %s. Does it have IP address?", net_if);
1059 		goto fail;
1060 	}
1061 
1062 	/* Listen for incoming TCP connections so that others
1063 	 * can fetch our "xml files" from us.
1064 	 */
1065 	if (web_listener_start(sm))
1066 		goto fail;
1067 
1068 	/* Set up for receiving discovery (UDP) packets */
1069 	if (ssdp_listener_start(sm))
1070 		goto fail;
1071 
1072 	/* Set up for sending multicast */
1073 	if (ssdp_open_multicast(sm) < 0)
1074 		goto fail;
1075 
1076 	/*
1077 	 * Broadcast NOTIFY messages to let the world know we exist.
1078 	 * This is done via a state machine since the messages should not be
1079 	 * all sent out at once.
1080 	 */
1081 	if (advertisement_state_machine_start(sm))
1082 		goto fail;
1083 
1084 	return 0;
1085 
1086 fail:
1087 	upnp_wps_device_stop(sm);
1088 	return -1;
1089 }
1090 
1091 
1092 /**
1093  * upnp_wps_device_deinit - Deinitialize WPS UPnP
1094  * @sm: WPS UPnP state machine from upnp_wps_device_init()
1095  */
1096 void upnp_wps_device_deinit(struct upnp_wps_device_sm *sm)
1097 {
1098 	if (!sm)
1099 		return;
1100 
1101 	upnp_wps_device_stop(sm);
1102 
1103 	if (sm->peer.wps)
1104 		wps_deinit(sm->peer.wps);
1105 	os_free(sm->root_dir);
1106 	os_free(sm->desc_url);
1107 	os_free(sm->ctx);
1108 	os_free(sm);
1109 }
1110 
1111 
1112 /**
1113  * upnp_wps_device_init - Initialize WPS UPnP
1114  * @ctx: callback table; we must eventually free it
1115  * @wps: Pointer to longterm WPS context
1116  * @priv: External context data that will be used in callbacks
1117  * Returns: WPS UPnP state or %NULL on failure
1118  */
1119 struct upnp_wps_device_sm *
1120 upnp_wps_device_init(struct upnp_wps_device_ctx *ctx, struct wps_context *wps,
1121 		     void *priv)
1122 {
1123 	struct upnp_wps_device_sm *sm;
1124 
1125 	sm = os_zalloc(sizeof(*sm));
1126 	if (!sm) {
1127 		wpa_printf(MSG_ERROR, "WPS UPnP: upnp_wps_device_init failed");
1128 		return NULL;
1129 	}
1130 
1131 	sm->ctx = ctx;
1132 	sm->wps = wps;
1133 	sm->priv = priv;
1134 
1135 	return sm;
1136 }
1137 
1138 
1139 /**
1140  * upnp_wps_subscribers - Check whether there are any event subscribers
1141  * @sm: WPS UPnP state machine from upnp_wps_device_init()
1142  * Returns: 0 if no subscribers, 1 if subscribers
1143  */
1144 int upnp_wps_subscribers(struct upnp_wps_device_sm *sm)
1145 {
1146 	return sm->subscriptions != NULL;
1147 }
1148