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>
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 * -- Just what should be in the first event message sent after subscription
51 * for the WLANEvent field? If i pass it empty, Vista replies with OK
52 * but apparently barfs on the message.
53 * -- The http error code generation is pretty bogus, hopefully noone cares.
55 * Author: Ted Merrill, Atheros Communications, based upon earlier work
56 * as explained above and below.
59 * Copyright 2008 Atheros Communications.
61 * The original header (of upnp_wps_device.c) reads:
63 * Copyright (c) 2006-2007 Sony Corporation. All Rights Reserved.
65 * File Name: upnp_wps_device.c
66 * Description: EAP-WPS UPnP device source
68 * Redistribution and use in source and binary forms, with or without
69 * modification, are permitted provided that the following conditions
72 * * Redistributions of source code must retain the above copyright
73 * notice, this list of conditions and the following disclaimer.
74 * * Redistributions in binary form must reproduce the above copyright
75 * notice, this list of conditions and the following disclaimer in
76 * the documentation and/or other materials provided with the
78 * * Neither the name of Sony Corporation nor the names of its
79 * contributors may be used to endorse or promote products derived
80 * from this software without specific prior written permission.
82 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
83 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
84 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
85 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
86 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
87 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
88 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
89 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
90 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
91 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
92 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
94 * Portions from Intel libupnp files, e.g. genlib/net/http/httpreadwrite.c
97 * Copyright (c) 2000-2003 Intel Corporation
98 * All rights reserved.
100 * Redistribution and use in source and binary forms, with or without
101 * modification, are permitted provided that the following conditions are met:
103 * * Redistributions of source code must retain the above copyright notice,
104 * this list of conditions and the following disclaimer.
105 * * Redistributions in binary form must reproduce the above copyright notice,
106 * this list of conditions and the following disclaimer in the documentation
107 * and/or other materials provided with the distribution.
108 * * Neither name of Intel Corporation nor the names of its contributors
109 * may be used to endorse or promote products derived from this software
110 * without specific prior written permission.
112 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
113 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
114 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
115 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL INTEL OR
116 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
117 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
118 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
119 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
120 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
121 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
122 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
126 * Overview of WPS over UPnP:
128 * UPnP is a protocol that allows devices to discover each other and control
129 * each other. In UPnP terminology, a device is either a "device" (a server
130 * that provides information about itself and allows itself to be controlled)
131 * or a "control point" (a client that controls "devices") or possibly both.
132 * This file implements a UPnP "device".
134 * For us, we use mostly basic UPnP discovery, but the control part of interest
135 * is WPS carried via UPnP messages. There is quite a bit of basic UPnP
136 * discovery to do before we can get to WPS, however.
138 * UPnP discovery begins with "devices" send out multicast UDP packets to a
139 * certain fixed multicast IP address and port, and "control points" sending
140 * out other such UDP packets.
142 * The packets sent by devices are NOTIFY packets (not to be confused with TCP
143 * NOTIFY packets that are used later) and those sent by control points are
144 * M-SEARCH packets. These packets contain a simple HTTP style header. The
145 * packets are sent redundantly to get around packet loss. Devices respond to
146 * M-SEARCH packets with HTTP-like UDP packets containing HTTP/1.1 200 OK
147 * messages, which give similar information as the UDP NOTIFY packets.
149 * The above UDP packets advertise the (arbitrary) TCP ports that the
150 * respective parties will listen to. The control point can then do a HTTP
151 * SUBSCRIBE (something like an HTTP PUT) after which the device can do a
152 * separate HTTP NOTIFY (also like an HTTP PUT) to do event messaging.
154 * The control point will also do HTTP GET of the "device file" listed in the
155 * original UDP information from the device (see UPNP_WPS_DEVICE_XML_FILE
156 * data), and based on this will do additional GETs... HTTP POSTs are done to
159 * Beyond some basic information in HTTP headers, additional information is in
160 * the HTTP bodies, in a format set by the SOAP and XML standards, a markup
161 * language related to HTML used for web pages. This language is intended to
162 * provide the ultimate in self-documentation by providing a universal
163 * namespace based on pseudo-URLs called URIs. Note that although a URI looks
164 * like a URL (a web address), they are never accessed as such but are used
165 * only as identifiers.
167 * The POST of a GetDeviceInfo gets information similar to what might be
168 * obtained from a probe request or response on Wi-Fi. WPS messages M1-M8
169 * are passed via a POST of a PutMessage; the M1-M8 WPS messages are converted
170 * to a bin64 ascii representation for encapsulation. When proxying messages,
171 * WLANEvent and PutWLANResponse are used.
173 * This of course glosses over a lot of details.
176 #include "includes.h"
181 #include <sys/ioctl.h>
188 #include "wps_upnp.h"
189 #include "wps_upnp_i.h"
193 * UPnP allows a client ("control point") to send a server like us ("device")
194 * a domain name for registration, and we are supposed to resolve it. This is
195 * bad because, using the standard Linux library, we will stall the entire
196 * hostapd waiting for resolution.
198 * The "correct" solution would be to use an event driven library for domain
199 * name resolution such as "ares". However, this would increase code size
200 * further. Since it is unlikely that we'll actually see such domain names, we
201 * can just refuse to accept them.
203 #define NO_DOMAIN_NAME_RESOLUTION 1 /* 1 to allow only dotted ip addresses */
207 * UPnP does not scale well. If we were in a room with thousands of control
208 * points then potentially we could be expected to handle subscriptions for
209 * each of them, which would exhaust our memory. So we must set a limit. In
210 * practice we are unlikely to see more than one or two.
212 #define MAX_SUBSCRIPTIONS 4 /* how many subscribing clients we handle */
213 #define MAX_ADDR_PER_SUBSCRIPTION 8
216 /* Write the current date/time per RFC */
217 void format_date(struct wpabuf *buf)
219 const char *weekday_str = "Sun\0Mon\0Tue\0Wed\0Thu\0Fri\0Sat";
220 const char *month_str = "Jan\0Feb\0Mar\0Apr\0May\0Jun\0"
221 "Jul\0Aug\0Sep\0Oct\0Nov\0Dec";
227 wpabuf_printf(buf, "%s, %02d %s %d %02d:%02d:%02d GMT",
228 &weekday_str[date->tm_wday * 4], date->tm_mday,
229 &month_str[date->tm_mon * 4], date->tm_year + 1900,
230 date->tm_hour, date->tm_min, date->tm_sec);
234 /***************************************************************************
235 * UUIDs (unique identifiers)
237 * These are supposed to be unique in all the world.
238 * Sometimes permanent ones are used, sometimes temporary ones
239 * based on random numbers... there are different rules for valid content
240 * of different types.
241 * Each uuid is 16 bytes long.
242 **************************************************************************/
244 /* uuid_make -- construct a random UUID
245 * The UPnP documents don't seem to offer any guidelines as to which method to
246 * use for constructing UUIDs for subscriptions. Presumably any method from
247 * rfc4122 is good enough; I've chosen random number method.
249 static void uuid_make(u8 uuid[UUID_LEN])
251 os_get_random(uuid, UUID_LEN);
253 /* Replace certain bits as specified in rfc4122 or X.667 */
254 uuid[6] &= 0x0f; uuid[6] |= (4 << 4); /* version 4 == random gen */
255 uuid[8] &= 0x3f; uuid[8] |= 0x80;
260 * Subscriber address handling.
261 * Since a subscriber may have an arbitrary number of addresses, we have to
262 * add a bunch of code to handle them.
264 * Addresses are passed in text, and MAY be domain names instead of the (usual
265 * and expected) dotted IP addresses. Resolving domain names consumes a lot of
266 * resources. Worse, we are currently using the standard Linux getaddrinfo()
267 * which will block the entire program until complete or timeout! The proper
268 * solution would be to use the "ares" library or similar with more state
269 * machine steps etc. or just disable domain name resolution by setting
270 * NO_DOMAIN_NAME_RESOLUTION to 1 at top of this file.
273 /* subscr_addr_delete -- delete single unlinked subscriber address
274 * (be sure to unlink first if need be)
276 static void subscr_addr_delete(struct subscr_addr *a)
279 * Note: do NOT free domain_and_port or path because they point to
280 * memory within the allocation of "a".
286 /* subscr_addr_unlink -- unlink subscriber address from linked list */
287 static void subscr_addr_unlink(struct subscription *s, struct subscr_addr *a)
289 struct subscr_addr **listp = &s->addr_list;
291 a->next->prev = a->prev;
292 a->prev->next = a->next;
297 assert(s->n_addr == 0);
305 /* subscr_addr_free_all -- unlink and delete list of subscriber addresses. */
306 static void subscr_addr_free_all(struct subscription *s)
308 struct subscr_addr **listp = &s->addr_list;
309 struct subscr_addr *a;
310 while ((a = *listp) != NULL) {
311 subscr_addr_unlink(s, a);
312 subscr_addr_delete(a);
317 /* subscr_addr_link -- add subscriber address to list of addresses */
318 static void subscr_addr_link(struct subscription *s, struct subscr_addr *a)
320 struct subscr_addr **listp = &s->addr_list;
322 if (*listp == NULL) {
323 *listp = a->next = a->prev = a;
326 a->prev = (*listp)->prev;
333 /* subscr_addr_add_url -- add address(es) for one url to subscription */
334 static void subscr_addr_add_url(struct subscription *s, const char *url)
337 char *scratch_mem = NULL;
339 char *domain_and_port;
343 int port = 80; /* port to send to (default is port 80) */
344 struct addrinfo hints;
345 struct addrinfo *result = NULL;
348 struct subscr_addr *a = NULL;
350 /* url MUST begin with http: */
351 if (os_strncasecmp(url, "http://", 7))
355 /* allocate memory for the extra stuff we need */
356 alloc_len = (2 * (os_strlen(url) + 1));
357 scratch_mem = os_zalloc(alloc_len);
358 if (scratch_mem == NULL)
362 domain_and_port = mem;
363 mem += 1 + os_strlen(mem);
364 delim = os_strchr(domain_and_port, '/');
366 *delim++ = 0; /* null terminate domain and port */
369 path = domain_and_port + os_strlen(domain_and_port);
372 strcpy(domain, domain_and_port);
373 delim = strchr(domain, ':');
375 *delim++ = 0; /* null terminate domain */
381 * getaddrinfo does the right thing with dotted decimal notations, or
382 * will resolve domain names. Resolving domain names will unfortunately
383 * hang the entire program until it is resolved or it times out
384 * internal to getaddrinfo; fortunately we think that the use of actual
385 * domain names (vs. dotted decimal notations) should be uncommon.
387 os_memset(&hints, 0, sizeof(struct addrinfo));
388 hints.ai_family = AF_INET; /* IPv4 */
389 hints.ai_socktype = SOCK_STREAM;
390 #if NO_DOMAIN_NAME_RESOLUTION
391 /* Suppress domain name resolutions that would halt
392 * the program for periods of time
394 hints.ai_flags = AI_NUMERICHOST;
396 /* Allow domain name resolution. */
399 hints.ai_protocol = 0; /* Any protocol? */
400 rerr = getaddrinfo(domain, NULL /* fill in port ourselves */,
403 wpa_printf(MSG_INFO, "WPS UPnP: Resolve error %d (%s) on: %s",
404 rerr, gai_strerror(rerr), domain);
407 for (rp = result; rp; rp = rp->ai_next) {
408 /* Limit no. of address to avoid denial of service attack */
409 if (s->n_addr >= MAX_ADDR_PER_SUBSCRIPTION) {
410 wpa_printf(MSG_INFO, "WPS UPnP: subscr_addr_add_url: "
411 "Ignoring excessive addresses");
415 a = os_zalloc(sizeof(*a) + alloc_len);
419 mem = (void *) (a + 1);
420 a->domain_and_port = mem;
421 strcpy(mem, domain_and_port);
422 mem += 1 + strlen(mem);
427 mem += 1 + strlen(mem);
428 os_memcpy(&a->saddr, rp->ai_addr, sizeof(a->saddr));
429 a->saddr.sin_port = htons(port);
431 subscr_addr_link(s, a);
432 a = NULL; /* don't free it below */
437 freeaddrinfo(result);
438 os_free(scratch_mem);
443 /* subscr_addr_list_create -- create list from urls in string.
444 * Each url is enclosed by angle brackets.
446 static void subscr_addr_list_create(struct subscription *s,
447 const char *url_list)
451 while (*url_list == ' ' || *url_list == '\t')
453 if (*url_list != '<')
456 end = os_strchr(url_list, '>');
460 subscr_addr_add_url(s, url_list);
466 int send_wpabuf(int fd, struct wpabuf *buf)
468 wpa_printf(MSG_DEBUG, "WPS UPnP: Send %lu byte message",
469 (unsigned long) wpabuf_len(buf));
471 if (write(fd, wpabuf_head(buf), wpabuf_len(buf)) !=
472 (int) wpabuf_len(buf)) {
473 wpa_printf(MSG_ERROR, "WPS UPnP: Failed to send buffer: "
475 errno, strerror(errno));
483 static void wpabuf_put_property(struct wpabuf *buf, const char *name,
486 wpabuf_put_str(buf, "<e:property>");
487 wpabuf_printf(buf, "<%s>", name);
489 wpabuf_put_str(buf, value);
490 wpabuf_printf(buf, "</%s>", name);
491 wpabuf_put_str(buf, "</e:property>\n");
496 * upnp_wps_device_send_event - Queue event messages for subscribers
497 * @sm: WPS UPnP state machine from upnp_wps_device_init()
499 * This function queues the last WLANEvent to be sent for all currently
500 * subscribed UPnP control points. sm->wlanevent must have been set with the
501 * encoded data before calling this function.
503 static void upnp_wps_device_send_event(struct upnp_wps_device_sm *sm)
505 /* Enqueue event message for all subscribers */
506 struct wpabuf *buf; /* holds event message */
508 struct subscription *s;
509 /* Actually, utf-8 is the default, but it doesn't hurt to specify it */
510 const char *format_head =
511 "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
512 "<e:propertyset xmlns:e=\"urn:schemas-upnp-org:event-1-0\">\n";
513 const char *format_tail = "</e:propertyset>\n";
515 if (sm->subscriptions == NULL) {
520 /* Determine buffer size needed first */
521 buf_size += os_strlen(format_head);
522 buf_size += 50 + 2 * os_strlen("WLANEvent");
524 buf_size += os_strlen(sm->wlanevent);
525 buf_size += os_strlen(format_tail);
527 buf = wpabuf_alloc(buf_size);
530 wpabuf_put_str(buf, format_head);
531 wpabuf_put_property(buf, "WLANEvent", sm->wlanevent);
532 wpabuf_put_str(buf, format_tail);
534 wpa_printf(MSG_MSGDUMP, "WPS UPnP: WLANEvent message:\n%s",
535 (char *) wpabuf_head(buf));
537 s = sm->subscriptions;
539 if (event_add(s, buf)) {
540 struct subscription *s_old = s;
541 wpa_printf(MSG_INFO, "WPS UPnP: Dropping "
542 "subscriber due to event backlog");
544 subscription_unlink(s_old);
545 subscription_destroy(s_old);
549 } while (s != sm->subscriptions);
556 * Event subscription (subscriber machines register with us to receive event
558 * This is the result of an incoming HTTP over TCP SUBSCRIBE request.
561 /* subscription_unlink -- remove from the active list */
562 void subscription_unlink(struct subscription *s)
564 struct upnp_wps_device_sm *sm = s->sm;
568 sm->subscriptions = NULL;
570 if (sm->subscriptions == s)
571 sm->subscriptions = s->next;
572 s->next->prev = s->prev;
573 s->prev->next = s->next;
575 sm->n_subscriptions--;
579 /* subscription_link_to_end -- link to end of active list
580 * (should have high expiry time!)
582 static void subscription_link_to_end(struct subscription *s)
584 struct upnp_wps_device_sm *sm = s->sm;
586 if (sm->subscriptions) {
587 s->next = sm->subscriptions;
588 s->prev = s->next->prev;
592 sm->subscriptions = s->next = s->prev = s;
594 sm->n_subscriptions++;
598 /* subscription_destroy -- destroy an unlinked subscription
599 * Be sure to unlink first if necessary.
601 void subscription_destroy(struct subscription *s)
603 wpa_printf(MSG_DEBUG, "WPS UPnP: Destroy subscription %p", s);
605 subscr_addr_free_all(s);
611 /* subscription_list_age -- remove expired subscriptions */
612 static void subscription_list_age(struct upnp_wps_device_sm *sm, time_t now)
614 struct subscription *s;
615 while ((s = sm->subscriptions) != NULL && s->timeout_time < now) {
616 wpa_printf(MSG_DEBUG, "WPS UPnP: Removing aged subscription");
617 subscription_unlink(s);
618 subscription_destroy(s);
623 /* subscription_find -- return existing subscription matching uuid, if any
624 * returns NULL if not found
626 struct subscription * subscription_find(struct upnp_wps_device_sm *sm,
627 const u8 uuid[UUID_LEN])
629 struct subscription *s0 = sm->subscriptions;
630 struct subscription *s = s0;
635 if (os_memcmp(s->uuid, uuid, UUID_LEN) == 0)
636 return s; /* Found match */
644 /* subscription_first_event -- send format/queue event that is automatically
645 * sent on a new subscription.
647 static int subscription_first_event(struct subscription *s)
650 * Actually, utf-8 is the default, but it doesn't hurt to specify it.
652 * APStatus is apparently a bit set,
653 * 0x1 = configuration change (but is always set?)
654 * 0x10 = ap is locked
656 * Per UPnP spec, we send out the last value of each variable, even
657 * for WLANEvent, whatever it was.
661 int ap_status = 1; /* TODO: add 0x10 if access point is locked */
663 "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
664 "<e:propertyset xmlns:e=\"urn:schemas-upnp-org:event-1-0\">\n";
665 const char *tail = "</e:propertyset>\n";
668 wlan_event = s->sm->wlanevent;
669 if (wlan_event == NULL || *wlan_event == '\0') {
670 wpa_printf(MSG_DEBUG, "WPS UPnP: WLANEvent not known for "
671 "initial event message");
674 buf = wpabuf_alloc(500 + os_strlen(wlan_event));
678 wpabuf_put_str(buf, head);
679 wpabuf_put_property(buf, "STAStatus", "1");
680 os_snprintf(txt, sizeof(txt), "%d", ap_status);
681 wpabuf_put_property(buf, "APStatus", txt);
683 wpabuf_put_property(buf, "WLANEvent", wlan_event);
684 wpabuf_put_str(buf, tail);
686 if (event_add(s, buf)) {
697 * subscription_start - Rremember a UPnP control point to send events to.
698 * @sm: WPS UPnP state machine from upnp_wps_device_init()
699 * @callback_urls: malloc' mem given to the subscription
700 * Returns: %NULL on error, or pointer to new subscription structure.
702 struct subscription * subscription_start(struct upnp_wps_device_sm *sm,
705 struct subscription *s;
706 time_t now = time(NULL);
707 time_t expire = now + UPNP_SUBSCRIBE_SEC;
709 /* Get rid of expired subscriptions so we have room */
710 subscription_list_age(sm, now);
712 /* If too many subscriptions, remove oldest */
713 if (sm->n_subscriptions >= MAX_SUBSCRIPTIONS) {
714 s = sm->subscriptions;
715 wpa_printf(MSG_INFO, "WPS UPnP: Too many subscriptions, "
717 subscription_unlink(s);
718 subscription_destroy(s);
721 s = os_zalloc(sizeof(*s));
726 s->timeout_time = expire;
728 subscr_addr_list_create(s, callback_urls);
729 /* Add to end of list, since it has the highest expiration time */
730 subscription_link_to_end(s);
731 /* Queue up immediate event message (our last event)
732 * as required by UPnP spec.
734 if (subscription_first_event(s)) {
735 wpa_printf(MSG_INFO, "WPS UPnP: Dropping subscriber due to "
737 subscription_unlink(s);
738 subscription_destroy(s);
741 wpa_printf(MSG_DEBUG, "WPS UPnP: Subscription %p started with %s",
743 os_free(callback_urls);
744 /* Schedule sending this */
745 event_send_all_later(sm);
750 /* subscription_renew -- find subscription and reset timeout */
751 struct subscription * subscription_renew(struct upnp_wps_device_sm *sm,
752 const u8 uuid[UUID_LEN])
754 time_t now = time(NULL);
755 time_t expire = now + UPNP_SUBSCRIBE_SEC;
756 struct subscription *s = subscription_find(sm, uuid);
759 wpa_printf(MSG_DEBUG, "WPS UPnP: Subscription renewed");
760 subscription_unlink(s);
761 s->timeout_time = expire;
762 /* add back to end of list, since it now has highest expiry */
763 subscription_link_to_end(s);
769 * upnp_wps_device_send_wlan_event - Event notification
770 * @sm: WPS UPnP state machine from upnp_wps_device_init()
771 * @from_mac_addr: Source (Enrollee) MAC address for the event
772 * @ev_type: Event type
774 * Returns: 0 on success, -1 on failure
776 * Tell external Registrars (UPnP control points) that something happened. In
777 * particular, events include WPS messages from clients that are proxied to
778 * external Registrars.
780 int upnp_wps_device_send_wlan_event(struct upnp_wps_device_sm *sm,
781 const u8 from_mac_addr[ETH_ALEN],
782 enum upnp_wps_wlanevent_type ev_type,
783 const struct wpabuf *msg)
787 const u8 *mac = from_mac_addr;
798 os_snprintf(type, sizeof(type), "%1u", ev_type);
800 raw_len = 1 + 17 + (msg ? wpabuf_len(msg) : 0);
801 raw = os_zalloc(raw_len);
805 *(raw + pos) = (u8) ev_type;
807 os_snprintf(mac_text, sizeof(mac_text), MACSTR, MAC2STR(mac));
808 wpa_printf(MSG_DEBUG, "WPS UPnP: Proxying WLANEvent from %s",
810 os_memcpy(raw + pos, mac_text, 17);
813 os_memcpy(raw + pos, wpabuf_head(msg), wpabuf_len(msg));
814 pos += wpabuf_len(msg);
818 val = (char *) base64_encode(raw, raw_len, &val_len);
822 os_free(sm->wlanevent);
824 upnp_wps_device_send_event(sm);
836 * get_netif_info - Get hw and IP addresses for network device
837 * @net_if: Selected network interface name
838 * @ip_addr: Buffer for returning IP address in network byte order
839 * @ip_addr_text: Buffer for returning a pointer to allocated IP address text
840 * @mac: Buffer for returning MAC address
841 * @mac_addr_text: Buffer for returning allocated MAC address text
842 * Returns: 0 on success, -1 on failure
844 static int get_netif_info(const char *net_if, unsigned *ip_addr,
845 char **ip_addr_text, u8 mac[ETH_ALEN],
846 char **mac_addr_text)
850 struct sockaddr_in *addr;
851 struct in_addr in_addr;
853 *ip_addr_text = os_zalloc(16);
854 *mac_addr_text = os_zalloc(18);
855 if (*ip_addr_text == NULL || *mac_addr_text == NULL)
858 sock = socket(AF_INET, SOCK_DGRAM, 0);
862 os_strlcpy(req.ifr_name, net_if, sizeof(req.ifr_name));
863 if (ioctl(sock, SIOCGIFADDR, &req) < 0) {
864 wpa_printf(MSG_ERROR, "WPS UPnP: SIOCGIFADDR failed: %d (%s)",
865 errno, strerror(errno));
868 addr = (void *) &req.ifr_addr;
869 *ip_addr = addr->sin_addr.s_addr;
870 in_addr.s_addr = *ip_addr;
871 os_snprintf(*ip_addr_text, 16, "%s", inet_ntoa(in_addr));
873 os_strlcpy(req.ifr_name, net_if, sizeof(req.ifr_name));
874 if (ioctl(sock, SIOCGIFHWADDR, &req) < 0) {
875 wpa_printf(MSG_ERROR, "WPS UPnP: SIOCGIFHWADDR failed: "
876 "%d (%s)", errno, strerror(errno));
879 os_memcpy(mac, req.ifr_addr.sa_data, 6);
880 os_snprintf(*mac_addr_text, 18, MACSTR, MAC2STR(req.ifr_addr.sa_data));
888 os_free(*ip_addr_text);
889 *ip_addr_text = NULL;
890 os_free(*mac_addr_text);
891 *mac_addr_text = NULL;
897 * upnp_wps_device_stop - Stop WPS UPnP operations on an interface
898 * @sm: WPS UPnP state machine from upnp_wps_device_init()
900 void upnp_wps_device_stop(struct upnp_wps_device_sm *sm)
902 if (!sm || !sm->started)
905 wpa_printf(MSG_DEBUG, "WPS UPnP: Stop device");
906 web_listener_stop(sm);
907 while (sm->web_connections)
908 web_connection_stop(sm->web_connections);
909 while (sm->msearch_replies)
910 msearchreply_state_machine_stop(sm->msearch_replies);
911 while (sm->subscriptions) {
912 struct subscription *s = sm->subscriptions;
913 subscription_unlink(s);
914 subscription_destroy(s);
917 advertisement_state_machine_stop(sm);
918 /* TODO: send byebye notifications */
920 event_send_stop_all(sm);
921 os_free(sm->wlanevent);
922 sm->wlanevent = NULL;
925 os_free(sm->mac_addr_text);
926 sm->mac_addr_text = NULL;
927 os_free(sm->ip_addr_text);
928 sm->ip_addr_text = NULL;
929 if (sm->multicast_sd >= 0)
930 close(sm->multicast_sd);
931 sm->multicast_sd = -1;
932 ssdp_listener_stop(sm);
939 * upnp_wps_device_start - Start WPS UPnP operations on an interface
940 * @sm: WPS UPnP state machine from upnp_wps_device_init()
941 * @net_if: Selected network interface name
942 * Returns: 0 on success, -1 on failure
944 int upnp_wps_device_start(struct upnp_wps_device_sm *sm, char *net_if)
950 upnp_wps_device_stop(sm);
952 sm->net_if = strdup(net_if);
953 sm->multicast_sd = -1;
956 sm->advertise_count = 0;
958 /* Fix up linux multicast handling */
959 if (add_ssdp_network(net_if))
962 /* Determine which IP and mac address we're using */
963 if (get_netif_info(net_if,
964 &sm->ip_addr, &sm->ip_addr_text,
965 sm->mac_addr, &sm->mac_addr_text)) {
966 wpa_printf(MSG_INFO, "WPS UPnP: Could not get IP/MAC address "
967 "for %s. Does it have IP address?", net_if);
971 /* Listen for incoming TCP connections so that others
972 * can fetch our "xml files" from us.
974 if (web_listener_start(sm))
977 /* Set up for receiving discovery (UDP) packets */
978 if (ssdp_listener_start(sm))
981 /* Set up for sending multicast */
982 if (ssdp_open_multicast(sm) < 0)
986 * Broadcast NOTIFY messages to let the world know we exist.
987 * This is done via a state machine since the messages should not be
988 * all sent out at once.
990 if (advertisement_state_machine_start(sm))
996 upnp_wps_device_stop(sm);
1002 * upnp_wps_device_deinit - Deinitialize WPS UPnP
1003 * @sm: WPS UPnP state machine from upnp_wps_device_init()
1005 void upnp_wps_device_deinit(struct upnp_wps_device_sm *sm)
1010 upnp_wps_device_stop(sm);
1013 wps_deinit(sm->peer.wps);
1014 os_free(sm->root_dir);
1015 os_free(sm->desc_url);
1022 * upnp_wps_device_init - Initialize WPS UPnP
1023 * @ctx: callback table; we must eventually free it
1024 * @wps: Pointer to longterm WPS context
1025 * @priv: External context data that will be used in callbacks
1026 * Returns: WPS UPnP state or %NULL on failure
1028 struct upnp_wps_device_sm *
1029 upnp_wps_device_init(struct upnp_wps_device_ctx *ctx, struct wps_context *wps,
1032 struct upnp_wps_device_sm *sm;
1034 sm = os_zalloc(sizeof(*sm));
1036 wpa_printf(MSG_ERROR, "WPS UPnP: upnp_wps_device_init failed");
1049 * upnp_wps_subscribers - Check whether there are any event subscribers
1050 * @sm: WPS UPnP state machine from upnp_wps_device_init()
1051 * Returns: 0 if no subscribers, 1 if subscribers
1053 int upnp_wps_subscribers(struct upnp_wps_device_sm *sm)
1055 return sm->subscriptions != NULL;