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