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