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