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>
8 * See below for more details on licensing and code history.
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.
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.
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.
52 * Author: Ted Merrill, Atheros Communications, based upon earlier work
53 * as explained above and below.
56 * Copyright 2008 Atheros Communications.
58 * The original header (of upnp_wps_device.c) reads:
60 * Copyright (c) 2006-2007 Sony Corporation. All Rights Reserved.
62 * File Name: upnp_wps_device.c
63 * Description: EAP-WPS UPnP device source
65 * Redistribution and use in source and binary forms, with or without
66 * modification, are permitted provided that the following conditions
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
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.
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.
91 * Portions from Intel libupnp files, e.g. genlib/net/http/httpreadwrite.c
94 * Copyright (c) 2000-2003 Intel Corporation
95 * All rights reserved.
97 * Redistribution and use in source and binary forms, with or without
98 * modification, are permitted provided that the following conditions are met:
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.
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.
123 * Overview of WPS over UPnP:
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".
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.
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.
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.
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.
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
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.
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.
170 * This of course glosses over a lot of details.
173 #include "includes.h"
178 #include <sys/ioctl.h>
185 #include "wps_upnp.h"
186 #include "wps_upnp_i.h"
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.
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.
200 #define NO_DOMAIN_NAME_RESOLUTION 1 /* 1 to allow only dotted ip addresses */
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.
209 #define MAX_SUBSCRIPTIONS 4 /* how many subscribing clients we handle */
210 #define MAX_ADDR_PER_SUBSCRIPTION 8
212 /* Maximum number of Probe Request events per second */
213 #define MAX_EVENTS_PER_SEC 5
216 static struct upnp_wps_device_sm
*shared_upnp_device
= NULL
;
219 /* Write the current date/time per RFC */
220 void format_date(struct wpabuf
*buf
)
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";
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
);
239 /***************************************************************************
240 * UUIDs (unique identifiers)
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 **************************************************************************/
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.
254 static int uuid_make(u8 uuid
[UUID_LEN
])
256 if (os_get_random(uuid
, UUID_LEN
) < 0)
259 /* Replace certain bits as specified in rfc4122 or X.667 */
260 uuid
[6] &= 0x0f; uuid
[6] |= (4 << 4); /* version 4 == random gen */
261 uuid
[8] &= 0x3f; uuid
[8] |= 0x80;
268 * Subscriber address handling.
269 * Since a subscriber may have an arbitrary number of addresses, we have to
270 * add a bunch of code to handle them.
272 * Addresses are passed in text, and MAY be domain names instead of the (usual
273 * and expected) dotted IP addresses. Resolving domain names consumes a lot of
274 * resources. Worse, we are currently using the standard Linux getaddrinfo()
275 * which will block the entire program until complete or timeout! The proper
276 * solution would be to use the "ares" library or similar with more state
277 * machine steps etc. or just disable domain name resolution by setting
278 * NO_DOMAIN_NAME_RESOLUTION to 1 at top of this file.
281 /* subscr_addr_delete -- delete single unlinked subscriber address
282 * (be sure to unlink first if need be)
284 void subscr_addr_delete(struct subscr_addr
*a
)
287 * Note: do NOT free domain_and_port or path because they point to
288 * memory within the allocation of "a".
294 /* subscr_addr_free_all -- unlink and delete list of subscriber addresses. */
295 static void subscr_addr_free_all(struct subscription
*s
)
297 struct subscr_addr
*a
, *tmp
;
298 dl_list_for_each_safe(a
, tmp
, &s
->addr_list
, struct subscr_addr
, list
)
300 dl_list_del(&a
->list
);
301 subscr_addr_delete(a
);
306 /* subscr_addr_add_url -- add address(es) for one url to subscription */
307 static void subscr_addr_add_url(struct subscription
*s
, const char *url
,
311 char *scratch_mem
= NULL
;
316 int port
= 80; /* port to send to (default is port 80) */
317 struct addrinfo hints
;
318 struct addrinfo
*result
= NULL
;
321 size_t host_len
, path_len
;
323 /* url MUST begin with http: */
324 if (url_len
< 7 || os_strncasecmp(url
, "http://", 7))
329 /* Make a copy of the string to allow modification during parsing */
330 scratch_mem
= dup_binstr(url
, url_len
);
331 if (scratch_mem
== NULL
)
333 wpa_printf(MSG_DEBUG
, "WPS UPnP: Adding URL '%s'", scratch_mem
);
335 path
= os_strchr(host
, '/');
337 *path
++ = '\0'; /* null terminate host */
339 /* Process and remove optional port component */
340 delim
= os_strchr(host
, ':');
342 *delim
= '\0'; /* null terminate host name for now */
343 if (isdigit(delim
[1]))
344 port
= atol(delim
+ 1);
348 * getaddrinfo does the right thing with dotted decimal notations, or
349 * will resolve domain names. Resolving domain names will unfortunately
350 * hang the entire program until it is resolved or it times out
351 * internal to getaddrinfo; fortunately we think that the use of actual
352 * domain names (vs. dotted decimal notations) should be uncommon.
354 os_memset(&hints
, 0, sizeof(struct addrinfo
));
355 hints
.ai_family
= AF_INET
; /* IPv4 */
356 hints
.ai_socktype
= SOCK_STREAM
;
357 #if NO_DOMAIN_NAME_RESOLUTION
358 /* Suppress domain name resolutions that would halt
359 * the program for periods of time
361 hints
.ai_flags
= AI_NUMERICHOST
;
363 /* Allow domain name resolution. */
366 hints
.ai_protocol
= 0; /* Any protocol? */
367 rerr
= getaddrinfo(host
, NULL
/* fill in port ourselves */,
370 wpa_printf(MSG_INFO
, "WPS UPnP: Resolve error %d (%s) on: %s",
371 rerr
, gai_strerror(rerr
), host
);
376 *delim
= ':'; /* Restore port */
378 host_len
= os_strlen(host
);
379 path_len
= path
? os_strlen(path
) : 0;
380 alloc_len
= host_len
+ 1 + 1 + path_len
+ 1;
382 for (rp
= result
; rp
; rp
= rp
->ai_next
) {
383 struct subscr_addr
*a
;
385 /* Limit no. of address to avoid denial of service attack */
386 if (dl_list_len(&s
->addr_list
) >= MAX_ADDR_PER_SUBSCRIPTION
) {
387 wpa_printf(MSG_INFO
, "WPS UPnP: subscr_addr_add_url: "
388 "Ignoring excessive addresses");
392 a
= os_zalloc(sizeof(*a
) + alloc_len
);
395 mem
= (char *) (a
+ 1);
396 a
->domain_and_port
= mem
;
397 os_memcpy(mem
, host
, host_len
);
400 if (path
== NULL
|| path
[0] != '/')
403 os_memcpy(mem
, path
, path_len
);
404 os_memcpy(&a
->saddr
, rp
->ai_addr
, sizeof(a
->saddr
));
405 a
->saddr
.sin_port
= htons(port
);
407 dl_list_add(&s
->addr_list
, &a
->list
);
412 freeaddrinfo(result
);
413 os_free(scratch_mem
);
417 /* subscr_addr_list_create -- create list from urls in string.
418 * Each url is enclosed by angle brackets.
420 static void subscr_addr_list_create(struct subscription
*s
,
421 const char *url_list
)
424 wpa_printf(MSG_DEBUG
, "WPS UPnP: Parsing URL list '%s'", url_list
);
426 while (*url_list
== ' ' || *url_list
== '\t')
428 if (*url_list
!= '<')
431 end
= os_strchr(url_list
, '>');
434 subscr_addr_add_url(s
, url_list
, end
- url_list
);
440 static void wpabuf_put_property(struct wpabuf
*buf
, const char *name
,
443 wpabuf_put_str(buf
, "<e:property>");
444 wpabuf_printf(buf
, "<%s>", name
);
446 wpabuf_put_str(buf
, value
);
447 wpabuf_printf(buf
, "</%s>", name
);
448 wpabuf_put_str(buf
, "</e:property>\n");
453 * upnp_wps_device_send_event - Queue event messages for subscribers
454 * @sm: WPS UPnP state machine from upnp_wps_device_init()
456 * This function queues the last WLANEvent to be sent for all currently
457 * subscribed UPnP control points. sm->wlanevent must have been set with the
458 * encoded data before calling this function.
460 static void upnp_wps_device_send_event(struct upnp_wps_device_sm
*sm
)
462 /* Enqueue event message for all subscribers */
463 struct wpabuf
*buf
; /* holds event message */
465 struct subscription
*s
, *tmp
;
466 /* Actually, utf-8 is the default, but it doesn't hurt to specify it */
467 const char *format_head
=
468 "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
469 "<e:propertyset xmlns:e=\"urn:schemas-upnp-org:event-1-0\">\n";
470 const char *format_tail
= "</e:propertyset>\n";
471 struct os_reltime now
;
473 if (dl_list_empty(&sm
->subscriptions
)) {
478 if (os_get_reltime(&now
) == 0) {
479 if (now
.sec
!= sm
->last_event_sec
) {
480 sm
->last_event_sec
= now
.sec
;
481 sm
->num_events_in_sec
= 1;
483 sm
->num_events_in_sec
++;
485 * In theory, this should apply to all WLANEvent
486 * notifications, but EAP messages are of much higher
487 * priority and Probe Request notifications should not
488 * be allowed to drop EAP messages, so only throttle
489 * Probe Request notifications.
491 if (sm
->num_events_in_sec
> MAX_EVENTS_PER_SEC
&&
492 sm
->wlanevent_type
==
493 UPNP_WPS_WLANEVENT_TYPE_PROBE
) {
494 wpa_printf(MSG_DEBUG
, "WPS UPnP: Throttle "
495 "event notifications (%u seen "
496 "during one second)",
497 sm
->num_events_in_sec
);
503 /* Determine buffer size needed first */
504 buf_size
+= os_strlen(format_head
);
505 buf_size
+= 50 + 2 * os_strlen("WLANEvent");
507 buf_size
+= os_strlen(sm
->wlanevent
);
508 buf_size
+= os_strlen(format_tail
);
510 buf
= wpabuf_alloc(buf_size
);
513 wpabuf_put_str(buf
, format_head
);
514 wpabuf_put_property(buf
, "WLANEvent", sm
->wlanevent
);
515 wpabuf_put_str(buf
, format_tail
);
517 wpa_printf(MSG_MSGDUMP
, "WPS UPnP: WLANEvent message:\n%s",
518 (char *) wpabuf_head(buf
));
520 dl_list_for_each_safe(s
, tmp
, &sm
->subscriptions
, struct subscription
,
523 sm
->wlanevent_type
== UPNP_WPS_WLANEVENT_TYPE_PROBE
);
531 * Event subscription (subscriber machines register with us to receive event
533 * This is the result of an incoming HTTP over TCP SUBSCRIBE request.
536 /* subscription_destroy -- destroy an unlinked subscription
537 * Be sure to unlink first if necessary.
539 void subscription_destroy(struct subscription
*s
)
541 struct upnp_wps_device_interface
*iface
;
542 wpa_printf(MSG_DEBUG
, "WPS UPnP: Destroy subscription %p", s
);
543 subscr_addr_free_all(s
);
545 dl_list_for_each(iface
, &s
->sm
->interfaces
,
546 struct upnp_wps_device_interface
, list
)
547 upnp_er_remove_notification(iface
->wps
->registrar
, s
);
552 /* subscription_list_age -- remove expired subscriptions */
553 static void subscription_list_age(struct upnp_wps_device_sm
*sm
, time_t now
)
555 struct subscription
*s
, *tmp
;
556 dl_list_for_each_safe(s
, tmp
, &sm
->subscriptions
,
557 struct subscription
, list
) {
558 if (s
->timeout_time
> now
)
560 wpa_printf(MSG_DEBUG
, "WPS UPnP: Removing aged subscription");
561 dl_list_del(&s
->list
);
562 subscription_destroy(s
);
567 /* subscription_find -- return existing subscription matching uuid, if any
568 * returns NULL if not found
570 struct subscription
* subscription_find(struct upnp_wps_device_sm
*sm
,
571 const u8 uuid
[UUID_LEN
])
573 struct subscription
*s
;
574 dl_list_for_each(s
, &sm
->subscriptions
, struct subscription
, list
) {
575 if (os_memcmp(s
->uuid
, uuid
, UUID_LEN
) == 0)
576 return s
; /* Found match */
582 static struct wpabuf
* build_fake_wsc_ack(void)
584 struct wpabuf
*msg
= wpabuf_alloc(100);
587 wpabuf_put_u8(msg
, UPNP_WPS_WLANEVENT_TYPE_EAP
);
588 wpabuf_put_str(msg
, "00:00:00:00:00:00");
589 if (wps_build_version(msg
) ||
590 wps_build_msg_type(msg
, WPS_WSC_ACK
)) {
595 wpabuf_put_be16(msg
, ATTR_ENROLLEE_NONCE
);
596 wpabuf_put_be16(msg
, WPS_NONCE_LEN
);
597 wpabuf_put(msg
, WPS_NONCE_LEN
);
598 /* Registrar Nonce */
599 wpabuf_put_be16(msg
, ATTR_REGISTRAR_NONCE
);
600 wpabuf_put_be16(msg
, WPS_NONCE_LEN
);
601 wpabuf_put(msg
, WPS_NONCE_LEN
);
602 if (wps_build_wfa_ext(msg
, 0, NULL
, 0, 0)) {
610 /* subscription_first_event -- send format/queue event that is automatically
611 * sent on a new subscription.
613 static int subscription_first_event(struct subscription
*s
)
616 * Actually, utf-8 is the default, but it doesn't hurt to specify it.
618 * APStatus is apparently a bit set,
619 * 0x1 = configuration change (but is always set?)
620 * 0x10 = ap is locked
622 * Per UPnP spec, we send out the last value of each variable, even
623 * for WLANEvent, whatever it was.
627 int ap_status
= 1; /* TODO: add 0x10 if access point is locked */
629 "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
630 "<e:propertyset xmlns:e=\"urn:schemas-upnp-org:event-1-0\">\n";
631 const char *tail
= "</e:propertyset>\n";
635 if (s
->sm
->wlanevent
== NULL
) {
637 * There has been no events before the subscription. However,
638 * UPnP device architecture specification requires all the
639 * evented variables to be included, so generate a dummy event
640 * for this particular case using a WSC_ACK and all-zeros
641 * nonces. The ER (UPnP control point) will ignore this, but at
642 * least it will learn that WLANEvent variable will be used in
643 * event notifications in the future.
646 wpa_printf(MSG_DEBUG
, "WPS UPnP: Use a fake WSC_ACK as the "
647 "initial WLANEvent");
648 msg
= build_fake_wsc_ack();
650 s
->sm
->wlanevent
= (char *)
651 base64_encode(wpabuf_head(msg
),
652 wpabuf_len(msg
), NULL
);
657 wlan_event
= s
->sm
->wlanevent
;
658 if (wlan_event
== NULL
|| *wlan_event
== '\0') {
659 wpa_printf(MSG_DEBUG
, "WPS UPnP: WLANEvent not known for "
660 "initial event message");
663 buf
= wpabuf_alloc(500 + os_strlen(wlan_event
));
667 wpabuf_put_str(buf
, head
);
668 wpabuf_put_property(buf
, "STAStatus", "1");
669 os_snprintf(txt
, sizeof(txt
), "%d", ap_status
);
670 wpabuf_put_property(buf
, "APStatus", txt
);
672 wpabuf_put_property(buf
, "WLANEvent", wlan_event
);
673 wpabuf_put_str(buf
, tail
);
675 ret
= event_add(s
, buf
, 0);
687 * subscription_start - Remember a UPnP control point to send events to.
688 * @sm: WPS UPnP state machine from upnp_wps_device_init()
689 * @callback_urls: Callback URLs
690 * Returns: %NULL on error, or pointer to new subscription structure.
692 struct subscription
* subscription_start(struct upnp_wps_device_sm
*sm
,
693 const char *callback_urls
)
695 struct subscription
*s
;
696 time_t now
= time(NULL
);
697 time_t expire
= now
+ UPNP_SUBSCRIBE_SEC
;
700 /* Get rid of expired subscriptions so we have room */
701 subscription_list_age(sm
, now
);
703 /* If too many subscriptions, remove oldest */
704 if (dl_list_len(&sm
->subscriptions
) >= MAX_SUBSCRIPTIONS
) {
705 s
= dl_list_first(&sm
->subscriptions
, struct subscription
,
709 "WPS UPnP: Too many subscriptions, trashing oldest");
710 dl_list_del(&s
->list
);
711 subscription_destroy(s
);
715 s
= os_zalloc(sizeof(*s
));
718 dl_list_init(&s
->addr_list
);
719 dl_list_init(&s
->event_queue
);
722 s
->timeout_time
= expire
;
723 if (uuid_make(s
->uuid
) < 0) {
724 subscription_destroy(s
);
727 subscr_addr_list_create(s
, callback_urls
);
728 if (dl_list_empty(&s
->addr_list
)) {
729 wpa_printf(MSG_DEBUG
, "WPS UPnP: No valid callback URLs in "
730 "'%s' - drop subscription", callback_urls
);
731 subscription_destroy(s
);
735 /* Add to end of list, since it has the highest expiration time */
736 dl_list_add_tail(&sm
->subscriptions
, &s
->list
);
737 /* Queue up immediate event message (our last event)
738 * as required by UPnP spec.
740 if (subscription_first_event(s
)) {
741 wpa_printf(MSG_INFO
, "WPS UPnP: Dropping subscriber due to "
743 dl_list_del(&s
->list
);
744 subscription_destroy(s
);
747 uuid_bin2str(s
->uuid
, str
, sizeof(str
));
748 wpa_printf(MSG_DEBUG
,
749 "WPS UPnP: Subscription %p (SID %s) started with %s",
750 s
, str
, callback_urls
);
751 /* Schedule sending this */
752 event_send_all_later(sm
);
757 /* subscription_renew -- find subscription and reset timeout */
758 struct subscription
* subscription_renew(struct upnp_wps_device_sm
*sm
,
759 const u8 uuid
[UUID_LEN
])
761 time_t now
= time(NULL
);
762 time_t expire
= now
+ UPNP_SUBSCRIBE_SEC
;
763 struct subscription
*s
= subscription_find(sm
, uuid
);
766 wpa_printf(MSG_DEBUG
, "WPS UPnP: Subscription renewed");
767 dl_list_del(&s
->list
);
768 s
->timeout_time
= expire
;
769 /* add back to end of list, since it now has highest expiry */
770 dl_list_add_tail(&sm
->subscriptions
, &s
->list
);
776 * upnp_wps_device_send_wlan_event - Event notification
777 * @sm: WPS UPnP state machine from upnp_wps_device_init()
778 * @from_mac_addr: Source (Enrollee) MAC address for the event
779 * @ev_type: Event type
781 * Returns: 0 on success, -1 on failure
783 * Tell external Registrars (UPnP control points) that something happened. In
784 * particular, events include WPS messages from clients that are proxied to
785 * external Registrars.
787 int upnp_wps_device_send_wlan_event(struct upnp_wps_device_sm
*sm
,
788 const u8 from_mac_addr
[ETH_ALEN
],
789 enum upnp_wps_wlanevent_type ev_type
,
790 const struct wpabuf
*msg
)
794 const u8
*mac
= from_mac_addr
;
805 os_snprintf(type
, sizeof(type
), "%1u", ev_type
);
807 raw_len
= 1 + 17 + (msg
? wpabuf_len(msg
) : 0);
808 raw
= os_zalloc(raw_len
);
812 *(raw
+ pos
) = (u8
) ev_type
;
814 os_snprintf(mac_text
, sizeof(mac_text
), MACSTR
, MAC2STR(mac
));
815 wpa_printf(MSG_DEBUG
, "WPS UPnP: Proxying WLANEvent from %s",
817 os_memcpy(raw
+ pos
, mac_text
, 17);
820 os_memcpy(raw
+ pos
, wpabuf_head(msg
), wpabuf_len(msg
));
821 pos
+= wpabuf_len(msg
);
825 val
= (char *) base64_encode(raw
, raw_len
, &val_len
);
829 os_free(sm
->wlanevent
);
831 sm
->wlanevent_type
= ev_type
;
832 upnp_wps_device_send_event(sm
);
843 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
844 #include <sys/sysctl.h>
845 #include <net/route.h>
846 #include <net/if_dl.h>
848 static int eth_get(const char *device
, u8 ea
[ETH_ALEN
])
850 struct if_msghdr
*ifm
;
851 struct sockaddr_dl
*sdl
;
854 int mib
[] = { CTL_NET
, AF_ROUTE
, 0, AF_LINK
, NET_RT_IFLIST
, 0 };
856 if (sysctl(mib
, 6, NULL
, &len
, NULL
, 0) < 0)
858 if ((buf
= os_malloc(len
)) == NULL
)
860 if (sysctl(mib
, 6, buf
, &len
, NULL
, 0) < 0) {
864 for (p
= buf
; p
< buf
+ len
; p
+= ifm
->ifm_msglen
) {
865 ifm
= (struct if_msghdr
*)p
;
866 sdl
= (struct sockaddr_dl
*)(ifm
+ 1);
867 if (ifm
->ifm_type
!= RTM_IFINFO
||
868 (ifm
->ifm_addrs
& RTA_IFP
) == 0)
870 if (sdl
->sdl_family
!= AF_LINK
|| sdl
->sdl_nlen
== 0 ||
871 os_memcmp(sdl
->sdl_data
, device
, sdl
->sdl_nlen
) != 0)
873 os_memcpy(ea
, LLADDR(sdl
), sdl
->sdl_alen
);
878 if (p
>= buf
+ len
) {
884 #endif /* __FreeBSD__ */
888 * get_netif_info - Get hw and IP addresses for network device
889 * @net_if: Selected network interface name
890 * @ip_addr: Buffer for returning IP address in network byte order
891 * @ip_addr_text: Buffer for returning a pointer to allocated IP address text
892 * @mac: Buffer for returning MAC address
893 * Returns: 0 on success, -1 on failure
895 int get_netif_info(const char *net_if
, unsigned *ip_addr
, char **ip_addr_text
,
900 struct sockaddr_in
*addr
;
901 struct in_addr in_addr
;
903 *ip_addr_text
= os_zalloc(16);
904 if (*ip_addr_text
== NULL
)
907 sock
= socket(AF_INET
, SOCK_DGRAM
, 0);
911 os_strlcpy(req
.ifr_name
, net_if
, sizeof(req
.ifr_name
));
912 if (ioctl(sock
, SIOCGIFADDR
, &req
) < 0) {
913 wpa_printf(MSG_ERROR
, "WPS UPnP: SIOCGIFADDR failed: %d (%s)",
914 errno
, strerror(errno
));
917 addr
= (void *) &req
.ifr_addr
;
918 *ip_addr
= addr
->sin_addr
.s_addr
;
919 in_addr
.s_addr
= *ip_addr
;
920 os_snprintf(*ip_addr_text
, 16, "%s", inet_ntoa(in_addr
));
923 os_strlcpy(req
.ifr_name
, net_if
, sizeof(req
.ifr_name
));
924 if (ioctl(sock
, SIOCGIFHWADDR
, &req
) < 0) {
925 wpa_printf(MSG_ERROR
, "WPS UPnP: SIOCGIFHWADDR failed: "
926 "%d (%s)", errno
, strerror(errno
));
929 os_memcpy(mac
, req
.ifr_addr
.sa_data
, 6);
930 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
931 if (eth_get(net_if
, mac
) < 0) {
932 wpa_printf(MSG_ERROR
, "WPS UPnP: Failed to get MAC address");
936 #error MAC address fetch not implemented
945 os_free(*ip_addr_text
);
946 *ip_addr_text
= NULL
;
951 static void upnp_wps_free_msearchreply(struct dl_list
*head
)
953 struct advertisement_state_machine
*a
, *tmp
;
954 dl_list_for_each_safe(a
, tmp
, head
, struct advertisement_state_machine
,
956 msearchreply_state_machine_stop(a
);
960 static void upnp_wps_free_subscriptions(struct dl_list
*head
,
961 struct wps_registrar
*reg
)
963 struct subscription
*s
, *tmp
;
964 dl_list_for_each_safe(s
, tmp
, head
, struct subscription
, list
) {
965 if (reg
&& s
->reg
!= reg
)
967 dl_list_del(&s
->list
);
968 subscription_destroy(s
);
974 * upnp_wps_device_stop - Stop WPS UPnP operations on an interface
975 * @sm: WPS UPnP state machine from upnp_wps_device_init()
977 static void upnp_wps_device_stop(struct upnp_wps_device_sm
*sm
)
979 if (!sm
|| !sm
->started
)
982 wpa_printf(MSG_DEBUG
, "WPS UPnP: Stop device");
983 web_listener_stop(sm
);
984 ssdp_listener_stop(sm
);
985 upnp_wps_free_msearchreply(&sm
->msearch_replies
);
986 upnp_wps_free_subscriptions(&sm
->subscriptions
, NULL
);
988 advertisement_state_machine_stop(sm
, 1);
990 event_send_stop_all(sm
);
991 os_free(sm
->wlanevent
);
992 sm
->wlanevent
= NULL
;
993 os_free(sm
->ip_addr_text
);
994 sm
->ip_addr_text
= NULL
;
995 if (sm
->multicast_sd
>= 0)
996 close(sm
->multicast_sd
);
997 sm
->multicast_sd
= -1;
1004 * upnp_wps_device_start - Start WPS UPnP operations on an interface
1005 * @sm: WPS UPnP state machine from upnp_wps_device_init()
1006 * @net_if: Selected network interface name
1007 * Returns: 0 on success, -1 on failure
1009 static int upnp_wps_device_start(struct upnp_wps_device_sm
*sm
, char *net_if
)
1015 upnp_wps_device_stop(sm
);
1017 sm
->multicast_sd
= -1;
1020 sm
->advertise_count
= 0;
1022 /* Fix up linux multicast handling */
1023 if (add_ssdp_network(net_if
))
1026 /* Determine which IP and mac address we're using */
1027 if (get_netif_info(net_if
, &sm
->ip_addr
, &sm
->ip_addr_text
,
1029 wpa_printf(MSG_INFO
, "WPS UPnP: Could not get IP/MAC address "
1030 "for %s. Does it have IP address?", net_if
);
1034 /* Listen for incoming TCP connections so that others
1035 * can fetch our "xml files" from us.
1037 if (web_listener_start(sm
))
1040 /* Set up for receiving discovery (UDP) packets */
1041 if (ssdp_listener_start(sm
))
1044 /* Set up for sending multicast */
1045 if (ssdp_open_multicast(sm
) < 0)
1049 * Broadcast NOTIFY messages to let the world know we exist.
1050 * This is done via a state machine since the messages should not be
1051 * all sent out at once.
1053 if (advertisement_state_machine_start(sm
))
1059 upnp_wps_device_stop(sm
);
1064 static struct upnp_wps_device_interface
*
1065 upnp_wps_get_iface(struct upnp_wps_device_sm
*sm
, void *priv
)
1067 struct upnp_wps_device_interface
*iface
;
1068 dl_list_for_each(iface
, &sm
->interfaces
,
1069 struct upnp_wps_device_interface
, list
) {
1070 if (iface
->priv
== priv
)
1078 * upnp_wps_device_deinit - Deinitialize WPS UPnP
1079 * @sm: WPS UPnP state machine from upnp_wps_device_init()
1080 * @priv: External context data that was used in upnp_wps_device_init() call
1082 void upnp_wps_device_deinit(struct upnp_wps_device_sm
*sm
, void *priv
)
1084 struct upnp_wps_device_interface
*iface
;
1085 struct upnp_wps_peer
*peer
;
1090 iface
= upnp_wps_get_iface(sm
, priv
);
1091 if (iface
== NULL
) {
1092 wpa_printf(MSG_ERROR
, "WPS UPnP: Could not find the interface "
1093 "instance to deinit");
1096 wpa_printf(MSG_DEBUG
, "WPS UPnP: Deinit interface instance %p", iface
);
1097 if (dl_list_len(&sm
->interfaces
) == 1) {
1098 wpa_printf(MSG_DEBUG
, "WPS UPnP: Deinitializing last instance "
1099 "- free global device instance");
1100 upnp_wps_device_stop(sm
);
1102 upnp_wps_free_subscriptions(&sm
->subscriptions
,
1103 iface
->wps
->registrar
);
1104 dl_list_del(&iface
->list
);
1106 while ((peer
= dl_list_first(&iface
->peers
, struct upnp_wps_peer
,
1109 wps_deinit(peer
->wps
);
1110 dl_list_del(&peer
->list
);
1113 os_free(iface
->ctx
->ap_pin
);
1114 os_free(iface
->ctx
);
1117 if (dl_list_empty(&sm
->interfaces
)) {
1118 os_free(sm
->root_dir
);
1119 os_free(sm
->desc_url
);
1121 shared_upnp_device
= NULL
;
1127 * upnp_wps_device_init - Initialize WPS UPnP
1128 * @ctx: callback table; we must eventually free it
1129 * @wps: Pointer to longterm WPS context
1130 * @priv: External context data that will be used in callbacks
1131 * @net_if: Selected network interface name
1132 * Returns: WPS UPnP state or %NULL on failure
1134 struct upnp_wps_device_sm
*
1135 upnp_wps_device_init(struct upnp_wps_device_ctx
*ctx
, struct wps_context
*wps
,
1136 void *priv
, char *net_if
)
1138 struct upnp_wps_device_sm
*sm
;
1139 struct upnp_wps_device_interface
*iface
;
1142 iface
= os_zalloc(sizeof(*iface
));
1143 if (iface
== NULL
) {
1144 os_free(ctx
->ap_pin
);
1148 wpa_printf(MSG_DEBUG
, "WPS UPnP: Init interface instance %p", iface
);
1150 dl_list_init(&iface
->peers
);
1155 if (shared_upnp_device
) {
1156 wpa_printf(MSG_DEBUG
, "WPS UPnP: Share existing device "
1158 sm
= shared_upnp_device
;
1160 wpa_printf(MSG_DEBUG
, "WPS UPnP: Initialize device context");
1161 sm
= os_zalloc(sizeof(*sm
));
1163 wpa_printf(MSG_ERROR
, "WPS UPnP: upnp_wps_device_init "
1166 os_free(ctx
->ap_pin
);
1170 shared_upnp_device
= sm
;
1172 dl_list_init(&sm
->msearch_replies
);
1173 dl_list_init(&sm
->subscriptions
);
1174 dl_list_init(&sm
->interfaces
);
1178 dl_list_add(&sm
->interfaces
, &iface
->list
);
1180 if (start
&& upnp_wps_device_start(sm
, net_if
)) {
1181 upnp_wps_device_deinit(sm
, priv
);
1191 * upnp_wps_subscribers - Check whether there are any event subscribers
1192 * @sm: WPS UPnP state machine from upnp_wps_device_init()
1193 * Returns: 0 if no subscribers, 1 if subscribers
1195 int upnp_wps_subscribers(struct upnp_wps_device_sm
*sm
)
1197 return !dl_list_empty(&sm
->subscriptions
);
1201 int upnp_wps_set_ap_pin(struct upnp_wps_device_sm
*sm
, const char *ap_pin
)
1203 struct upnp_wps_device_interface
*iface
;
1207 dl_list_for_each(iface
, &sm
->interfaces
,
1208 struct upnp_wps_device_interface
, list
) {
1209 os_free(iface
->ctx
->ap_pin
);
1211 iface
->ctx
->ap_pin
= os_strdup(ap_pin
);
1212 if (iface
->ctx
->ap_pin
== NULL
)
1215 iface
->ctx
->ap_pin
= NULL
;