wps_upnp.c

Go to the documentation of this file.
00001 
00012 /*
00013  * This has been greatly stripped down from the original file
00014  * (upnp_wps_device.c) by Ted Merrill, Atheros Communications
00015  * in order to eliminate use of the bulky libupnp library etc.
00016  *
00017  * History:
00018  * upnp_wps_device.c is/was a shim layer between wps_opt_upnp.c and
00019  * the libupnp library.
00020  * The layering (by Sony) was well done; only a very minor modification
00021  * to API of upnp_wps_device.c was required.
00022  * libupnp was found to be undesirable because:
00023  * -- It consumed too much code and data space
00024  * -- It uses multiple threads, making debugging more difficult
00025  *      and possibly reducing reliability.
00026  * -- It uses static variables and only supports one instance.
00027  * The shim and libupnp are here replaced by special code written
00028  * specifically for the needs of hostapd.
00029  * Various shortcuts can and are taken to keep the code size small.
00030  * Generally, execution time is not as crucial.
00031  *
00032  * BUGS:
00033  * -- UPnP requires that we be able to resolve domain names.
00034  * While uncommon, if we have to do it then it will stall the entire
00035  * hostapd program, which is bad.
00036  * This is because we use the standard linux getaddrinfo() function
00037  * which is syncronous.
00038  * An asyncronous solution would be to use the free "ares" library.
00039  * -- Does not have a robust output buffering scheme.  Uses a single
00040  * fixed size output buffer per TCP/HTTP connection, with possible (although
00041  * unlikely) possibility of overflow and likely excessive use of RAM.
00042  * A better solution would be to write the HTTP output as a buffered stream,
00043  * using chunking: (handle header specially, then) generate data with
00044  * a printf-like function into a buffer, catching buffer full condition,
00045  * then send it out surrounded by http chunking.
00046  * -- There is some code that could be separated out into the common
00047  * library to be shared with wpa_supplicant.
00048  * -- Needs renaming with module prefix to avoid polluting the debugger
00049  * namespace and causing possible collisions with other static fncs
00050  * and structure declarations when using the debugger.
00051  * -- The http error code generation is pretty bogus, hopefully noone cares.
00052  *
00053  * Author: Ted Merrill, Atheros Communications, based upon earlier work
00054  * as explained above and below.
00055  *
00056  * Copyright:
00057  * Copyright 2008 Atheros Communications.
00058  *
00059  * The original header (of upnp_wps_device.c) reads:
00060  *
00061  *  Copyright (c) 2006-2007 Sony Corporation. All Rights Reserved.
00062  *
00063  *  File Name: upnp_wps_device.c
00064  *  Description: EAP-WPS UPnP device source
00065  *
00066  *   Redistribution and use in source and binary forms, with or without
00067  *   modification, are permitted provided that the following conditions
00068  *   are met:
00069  *
00070  *     * Redistributions of source code must retain the above copyright
00071  *       notice, this list of conditions and the following disclaimer.
00072  *     * Redistributions in binary form must reproduce the above copyright
00073  *       notice, this list of conditions and the following disclaimer in
00074  *       the documentation and/or other materials provided with the
00075  *       distribution.
00076  *     * Neither the name of Sony Corporation nor the names of its
00077  *       contributors may be used to endorse or promote products derived
00078  *       from this software without specific prior written permission.
00079  *
00080  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
00081  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
00082  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
00083  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
00084  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
00085  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
00086  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
00087  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
00088  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
00089  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
00090  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00091  *
00092  * Portions from Intel libupnp files, e.g. genlib/net/http/httpreadwrite.c
00093  * typical header:
00094  *
00095  * Copyright (c) 2000-2003 Intel Corporation
00096  * All rights reserved.
00097  *
00098  * Redistribution and use in source and binary forms, with or without
00099  * modification, are permitted provided that the following conditions are met:
00100  *
00101  * * Redistributions of source code must retain the above copyright notice,
00102  * this list of conditions and the following disclaimer.
00103  * * Redistributions in binary form must reproduce the above copyright notice,
00104  * this list of conditions and the following disclaimer in the documentation
00105  * and/or other materials provided with the distribution.
00106  * * Neither name of Intel Corporation nor the names of its contributors
00107  * may be used to endorse or promote products derived from this software
00108  * without specific prior written permission.
00109  *
00110  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
00111  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
00112  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
00113  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL INTEL OR
00114  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
00115  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
00116  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
00117  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
00118  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
00119  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
00120  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00121 */
00122 
00123 /*
00124  * Overview of WPS over UPnP:
00125  *
00126  * UPnP is a protocol that allows devices to discover each other and control
00127  * each other. In UPnP terminology, a device is either a "device" (a server
00128  * that provides information about itself and allows itself to be controlled)
00129  * or a "control point" (a client that controls "devices") or possibly both.
00130  * This file implements a UPnP "device".
00131  *
00132  * For us, we use mostly basic UPnP discovery, but the control part of interest
00133  * is WPS carried via UPnP messages. There is quite a bit of basic UPnP
00134  * discovery to do before we can get to WPS, however.
00135  *
00136  * UPnP discovery begins with "devices" send out multicast UDP packets to a
00137  * certain fixed multicast IP address and port, and "control points" sending
00138  * out other such UDP packets.
00139  *
00140  * The packets sent by devices are NOTIFY packets (not to be confused with TCP
00141  * NOTIFY packets that are used later) and those sent by control points are
00142  * M-SEARCH packets. These packets contain a simple HTTP style header. The
00143  * packets are sent redundantly to get around packet loss. Devices respond to
00144  * M-SEARCH packets with HTTP-like UDP packets containing HTTP/1.1 200 OK
00145  * messages, which give similar information as the UDP NOTIFY packets.
00146  *
00147  * The above UDP packets advertise the (arbitrary) TCP ports that the
00148  * respective parties will listen to. The control point can then do a HTTP
00149  * SUBSCRIBE (something like an HTTP PUT) after which the device can do a
00150  * separate HTTP NOTIFY (also like an HTTP PUT) to do event messaging.
00151  *
00152  * The control point will also do HTTP GET of the "device file" listed in the
00153  * original UDP information from the device (see UPNP_WPS_DEVICE_XML_FILE
00154  * data), and based on this will do additional GETs... HTTP POSTs are done to
00155  * cause an action.
00156  *
00157  * Beyond some basic information in HTTP headers, additional information is in
00158  * the HTTP bodies, in a format set by the SOAP and XML standards, a markup
00159  * language related to HTML used for web pages. This language is intended to
00160  * provide the ultimate in self-documentation by providing a universal
00161  * namespace based on pseudo-URLs called URIs. Note that although a URI looks
00162  * like a URL (a web address), they are never accessed as such but are used
00163  * only as identifiers.
00164  *
00165  * The POST of a GetDeviceInfo gets information similar to what might be
00166  * obtained from a probe request or response on Wi-Fi. WPS messages M1-M8
00167  * are passed via a POST of a PutMessage; the M1-M8 WPS messages are converted
00168  * to a bin64 ascii representation for encapsulation. When proxying messages,
00169  * WLANEvent and PutWLANResponse are used.
00170  *
00171  * This of course glosses over a lot of details.
00172  */
00173 
00174 #include "includes.h"
00175 
00176 #include <assert.h>
00177 #include <net/if.h>
00178 #include <netdb.h>
00179 #include <sys/ioctl.h>
00180 
00181 #include "common.h"
00182 #include "uuid.h"
00183 #include "base64.h"
00184 #include "wps.h"
00185 #include "wps_i.h"
00186 #include "wps_upnp.h"
00187 #include "wps_upnp_i.h"
00188 
00189 
00190 /*
00191  * UPnP allows a client ("control point") to send a server like us ("device")
00192  * a domain name for registration, and we are supposed to resolve it. This is
00193  * bad because, using the standard Linux library, we will stall the entire
00194  * hostapd waiting for resolution.
00195  *
00196  * The "correct" solution would be to use an event driven library for domain
00197  * name resolution such as "ares". However, this would increase code size
00198  * further. Since it is unlikely that we'll actually see such domain names, we
00199  * can just refuse to accept them.
00200  */
00201 #define NO_DOMAIN_NAME_RESOLUTION 1  /* 1 to allow only dotted ip addresses */
00202 
00203 
00204 /*
00205  * UPnP does not scale well. If we were in a room with thousands of control
00206  * points then potentially we could be expected to handle subscriptions for
00207  * each of them, which would exhaust our memory. So we must set a limit. In
00208  * practice we are unlikely to see more than one or two.
00209  */
00210 #define MAX_SUBSCRIPTIONS 4    /* how many subscribing clients we handle */
00211 #define MAX_ADDR_PER_SUBSCRIPTION 8
00212 
00213 
00214 /* Write the current date/time per RFC */
00215 void format_date(struct wpabuf *buf)
00216 {
00217         const char *weekday_str = "Sun\0Mon\0Tue\0Wed\0Thu\0Fri\0Sat";
00218         const char *month_str = "Jan\0Feb\0Mar\0Apr\0May\0Jun\0"
00219                 "Jul\0Aug\0Sep\0Oct\0Nov\0Dec";
00220         struct tm *date;
00221         time_t t;
00222 
00223         t = time(NULL);
00224         date = gmtime(&t);
00225         wpabuf_printf(buf, "%s, %02d %s %d %02d:%02d:%02d GMT",
00226                       &weekday_str[date->tm_wday * 4], date->tm_mday,
00227                       &month_str[date->tm_mon * 4], date->tm_year + 1900,
00228                       date->tm_hour, date->tm_min, date->tm_sec);
00229 }
00230 
00231 
00232 /* *************************************************************************
00233  * UUIDs (unique identifiers)
00234  *
00235  * These are supposed to be unique in all the world.
00236  * Sometimes permanent ones are used, sometimes temporary ones
00237  * based on random numbers... there are different rules for valid content
00238  * of different types.
00239  * Each uuid is 16 bytes long.
00240  **************************************************************************/
00241 
00242 /* uuid_make -- construct a random UUID
00243  * The UPnP documents don't seem to offer any guidelines as to which method to
00244  * use for constructing UUIDs for subscriptions. Presumably any method from
00245  * rfc4122 is good enough; I've chosen random number method.
00246  */
00247 static void uuid_make(u8 uuid[UUID_LEN])
00248 {
00249         os_get_random(uuid, UUID_LEN);
00250 
00251         /* Replace certain bits as specified in rfc4122 or X.667 */
00252         uuid[6] &= 0x0f; uuid[6] |= (4 << 4);   /* version 4 == random gen */
00253         uuid[8] &= 0x3f; uuid[8] |= 0x80;
00254 }
00255 
00256 
00257 /*
00258  * Subscriber address handling.
00259  * Since a subscriber may have an arbitrary number of addresses, we have to
00260  * add a bunch of code to handle them.
00261  *
00262  * Addresses are passed in text, and MAY be domain names instead of the (usual
00263  * and expected) dotted IP addresses. Resolving domain names consumes a lot of
00264  * resources. Worse, we are currently using the standard Linux getaddrinfo()
00265  * which will block the entire program until complete or timeout! The proper
00266  * solution would be to use the "ares" library or similar with more state
00267  * machine steps etc. or just disable domain name resolution by setting
00268  * NO_DOMAIN_NAME_RESOLUTION to 1 at top of this file.
00269  */
00270 
00271 /* subscr_addr_delete -- delete single unlinked subscriber address
00272  * (be sure to unlink first if need be)
00273  */
00274 static void subscr_addr_delete(struct subscr_addr *a)
00275 {
00276         /*
00277          * Note: do NOT free domain_and_port or path because they point to
00278          * memory within the allocation of "a".
00279          */
00280         os_free(a);
00281 }
00282 
00283 
00284 /* subscr_addr_unlink -- unlink subscriber address from linked list */
00285 static void subscr_addr_unlink(struct subscription *s, struct subscr_addr *a)
00286 {
00287         struct subscr_addr **listp = &s->addr_list;
00288         s->n_addr--;
00289         a->next->prev = a->prev;
00290         a->prev->next = a->next;
00291         if (*listp == a) {
00292                 if (a == a->next) {
00293                         /* last in queue */
00294                         *listp = NULL;
00295                         assert(s->n_addr == 0);
00296                 } else {
00297                         *listp = a->next;
00298                 }
00299         }
00300 }
00301 
00302 
00303 /* subscr_addr_free_all -- unlink and delete list of subscriber addresses. */
00304 static void subscr_addr_free_all(struct subscription *s)
00305 {
00306         struct subscr_addr **listp = &s->addr_list;
00307         struct subscr_addr *a;
00308         while ((a = *listp) != NULL) {
00309                 subscr_addr_unlink(s, a);
00310                 subscr_addr_delete(a);
00311         }
00312 }
00313 
00314 
00315 /* subscr_addr_link -- add subscriber address to list of addresses */
00316 static void subscr_addr_link(struct subscription *s, struct subscr_addr *a)
00317 {
00318         struct subscr_addr **listp = &s->addr_list;
00319         s->n_addr++;
00320         if (*listp == NULL) {
00321                 *listp = a->next = a->prev = a;
00322         } else {
00323                 a->next = *listp;
00324                 a->prev = (*listp)->prev;
00325                 a->prev->next = a;
00326                 a->next->prev = a;
00327         }
00328 }
00329 
00330 
00331 /* subscr_addr_add_url -- add address(es) for one url to subscription */
00332 static void subscr_addr_add_url(struct subscription *s, const char *url)
00333 {
00334         int alloc_len;
00335         char *scratch_mem = NULL;
00336         char *mem;
00337         char *domain_and_port;
00338         char *delim;
00339         char *path;
00340         char *domain;
00341         int port = 80;  /* port to send to (default is port 80) */
00342         struct addrinfo hints;
00343         struct addrinfo *result = NULL;
00344         struct addrinfo *rp;
00345         int rerr;
00346         struct subscr_addr *a = NULL;
00347 
00348         /* url MUST begin with http: */
00349         if (os_strncasecmp(url, "http://", 7))
00350                 goto fail;
00351         url += 7;
00352 
00353         /* allocate memory for the extra stuff we need */
00354         alloc_len = (2 * (os_strlen(url) + 1));
00355         scratch_mem = os_zalloc(alloc_len);
00356         if (scratch_mem == NULL)
00357                 goto fail;
00358         mem = scratch_mem;
00359         strcpy(mem, url);
00360         domain_and_port = mem;
00361         mem += 1 + os_strlen(mem);
00362         delim = os_strchr(domain_and_port, '/');
00363         if (delim) {
00364                 *delim++ = 0;   /* null terminate domain and port */
00365                 path = delim;
00366         } else {
00367                 path = domain_and_port + os_strlen(domain_and_port);
00368         }
00369         domain = mem;
00370         strcpy(domain, domain_and_port);
00371         delim = strchr(domain, ':');
00372         if (delim) {
00373                 *delim++ = 0;   /* null terminate domain */
00374                 if (isdigit(*delim))
00375                         port = atol(delim);
00376         }
00377 
00378         /*
00379          * getaddrinfo does the right thing with dotted decimal notations, or
00380          * will resolve domain names. Resolving domain names will unfortunately
00381          * hang the entire program until it is resolved or it times out
00382          * internal to getaddrinfo; fortunately we think that the use of actual
00383          * domain names (vs. dotted decimal notations) should be uncommon.
00384          */
00385         os_memset(&hints, 0, sizeof(struct addrinfo));
00386         hints.ai_family = AF_INET;      /* IPv4 */
00387         hints.ai_socktype = SOCK_STREAM;
00388 #if NO_DOMAIN_NAME_RESOLUTION
00389         /* Suppress domain name resolutions that would halt
00390          * the program for periods of time
00391          */
00392         hints.ai_flags = AI_NUMERICHOST;
00393 #else
00394         /* Allow domain name resolution. */
00395         hints.ai_flags = 0;
00396 #endif
00397         hints.ai_protocol = 0;          /* Any protocol? */
00398         rerr = getaddrinfo(domain, NULL /* fill in port ourselves */,
00399                            &hints, &result);
00400         if (rerr) {
00401                 wpa_printf(MSG_INFO, "WPS UPnP: Resolve error %d (%s) on: %s",
00402                            rerr, gai_strerror(rerr), domain);
00403                 goto fail;
00404         }
00405         for (rp = result; rp; rp = rp->ai_next) {
00406                 /* Limit no. of address to avoid denial of service attack */
00407                 if (s->n_addr >= MAX_ADDR_PER_SUBSCRIPTION) {
00408                         wpa_printf(MSG_INFO, "WPS UPnP: subscr_addr_add_url: "
00409                                    "Ignoring excessive addresses");
00410                         break;
00411                 }
00412 
00413                 a = os_zalloc(sizeof(*a) + alloc_len);
00414                 if (a == NULL)
00415                         continue;
00416                 a->s = s;
00417                 mem = (void *) (a + 1);
00418                 a->domain_and_port = mem;
00419                 strcpy(mem, domain_and_port);
00420                 mem += 1 + strlen(mem);
00421                 a->path = mem;
00422                 if (path[0] != '/')
00423                         *mem++ = '/';
00424                 strcpy(mem, path);
00425                 mem += 1 + strlen(mem);
00426                 os_memcpy(&a->saddr, rp->ai_addr, sizeof(a->saddr));
00427                 a->saddr.sin_port = htons(port);
00428 
00429                 subscr_addr_link(s, a);
00430                 a = NULL;       /* don't free it below */
00431         }
00432 
00433 fail:
00434         if (result)
00435                 freeaddrinfo(result);
00436         os_free(scratch_mem);
00437         os_free(a);
00438 }
00439 
00440 
00441 /* subscr_addr_list_create -- create list from urls in string.
00442  *      Each url is enclosed by angle brackets.
00443  */
00444 static void subscr_addr_list_create(struct subscription *s,
00445                                     const char *url_list)
00446 {
00447         char *end;
00448         for (;;) {
00449                 while (*url_list == ' ' || *url_list == '\t')
00450                         url_list++;
00451                 if (*url_list != '<')
00452                         break;
00453                 url_list++;
00454                 end = os_strchr(url_list, '>');
00455                 if (end == NULL)
00456                         break;
00457                 *end++ = 0;
00458                 subscr_addr_add_url(s, url_list);
00459                 url_list = end;
00460         }
00461 }
00462 
00463 
00464 int send_wpabuf(int fd, struct wpabuf *buf)
00465 {
00466         wpa_printf(MSG_DEBUG, "WPS UPnP: Send %lu byte message",
00467                    (unsigned long) wpabuf_len(buf));
00468         errno = 0;
00469         if (write(fd, wpabuf_head(buf), wpabuf_len(buf)) !=
00470             (int) wpabuf_len(buf)) {
00471                 wpa_printf(MSG_ERROR, "WPS UPnP: Failed to send buffer: "
00472                            "errno=%d (%s)",
00473                            errno, strerror(errno));
00474                 return -1;
00475         }
00476 
00477         return 0;
00478 }
00479 
00480 
00481 static void wpabuf_put_property(struct wpabuf *buf, const char *name,
00482                                 const char *value)
00483 {
00484         wpabuf_put_str(buf, "<e:property>");
00485         wpabuf_printf(buf, "<%s>", name);
00486         if (value)
00487                 wpabuf_put_str(buf, value);
00488         wpabuf_printf(buf, "</%s>", name);
00489         wpabuf_put_str(buf, "</e:property>\n");
00490 }
00491 
00492 
00502 static void upnp_wps_device_send_event(struct upnp_wps_device_sm *sm)
00503 {
00504         /* Enqueue event message for all subscribers */
00505         struct wpabuf *buf; /* holds event message */
00506         int buf_size = 0;
00507         struct subscription *s;
00508         /* Actually, utf-8 is the default, but it doesn't hurt to specify it */
00509         const char *format_head =
00510                 "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
00511                 "<e:propertyset xmlns:e=\"urn:schemas-upnp-org:event-1-0\">\n";
00512         const char *format_tail = "</e:propertyset>\n";
00513 
00514         if (sm->subscriptions == NULL) {
00515                 /* optimize */
00516                 return;
00517         }
00518 
00519         /* Determine buffer size needed first */
00520         buf_size += os_strlen(format_head);
00521         buf_size += 50 + 2 * os_strlen("WLANEvent");
00522         if (sm->wlanevent)
00523                 buf_size += os_strlen(sm->wlanevent);
00524         buf_size += os_strlen(format_tail);
00525 
00526         buf = wpabuf_alloc(buf_size);
00527         if (buf == NULL)
00528                 return;
00529         wpabuf_put_str(buf, format_head);
00530         wpabuf_put_property(buf, "WLANEvent", sm->wlanevent);
00531         wpabuf_put_str(buf, format_tail);
00532 
00533         wpa_printf(MSG_MSGDUMP, "WPS UPnP: WLANEvent message:\n%s",
00534                    (char *) wpabuf_head(buf));
00535 
00536         s = sm->subscriptions;
00537         do {
00538                 if (event_add(s, buf)) {
00539                         struct subscription *s_old = s;
00540                         wpa_printf(MSG_INFO, "WPS UPnP: Dropping "
00541                                    "subscriber due to event backlog");
00542                         s = s_old->next;
00543                         subscription_unlink(s_old);
00544                         subscription_destroy(s_old);
00545                 } else {
00546                         s = s->next;
00547                 }
00548         } while (s != sm->subscriptions);
00549 
00550         wpabuf_free(buf);
00551 }
00552 
00553 
00554 /*
00555  * Event subscription (subscriber machines register with us to receive event
00556  * messages).
00557  * This is the result of an incoming HTTP over TCP SUBSCRIBE request.
00558  */
00559 
00560 /* subscription_unlink -- remove from the active list */
00561 void subscription_unlink(struct subscription *s)
00562 {
00563         struct upnp_wps_device_sm *sm = s->sm;
00564 
00565         if (s->next == s) {
00566                 /* only one? */
00567                 sm->subscriptions = NULL;
00568         } else  {
00569                 if (sm->subscriptions == s)
00570                         sm->subscriptions = s->next;
00571                 s->next->prev = s->prev;
00572                 s->prev->next = s->next;
00573         }
00574         sm->n_subscriptions--;
00575 }
00576 
00577 
00578 /* subscription_link_to_end -- link to end of active list
00579  * (should have high expiry time!)
00580  */
00581 static void subscription_link_to_end(struct subscription *s)
00582 {
00583         struct upnp_wps_device_sm *sm = s->sm;
00584 
00585         if (sm->subscriptions) {
00586                 s->next = sm->subscriptions;
00587                 s->prev = s->next->prev;
00588                 s->prev->next = s;
00589                 s->next->prev = s;
00590         } else {
00591                 sm->subscriptions = s->next = s->prev = s;
00592         }
00593         sm->n_subscriptions++;
00594 }
00595 
00596 
00597 /* subscription_destroy -- destroy an unlinked subscription
00598  * Be sure to unlink first if necessary.
00599  */
00600 void subscription_destroy(struct subscription *s)
00601 {
00602         wpa_printf(MSG_DEBUG, "WPS UPnP: Destroy subscription %p", s);
00603         if (s->addr_list)
00604                 subscr_addr_free_all(s);
00605         event_delete_all(s);
00606         os_free(s);
00607 }
00608 
00609 
00610 /* subscription_list_age -- remove expired subscriptions */
00611 static void subscription_list_age(struct upnp_wps_device_sm *sm, time_t now)
00612 {
00613         struct subscription *s;
00614         while ((s = sm->subscriptions) != NULL && s->timeout_time < now) {
00615                 wpa_printf(MSG_DEBUG, "WPS UPnP: Removing aged subscription");
00616                 subscription_unlink(s);
00617                 subscription_destroy(s);
00618         }
00619 }
00620 
00621 
00622 /* subscription_find -- return existing subscription matching uuid, if any
00623  * returns NULL if not found
00624  */
00625 struct subscription * subscription_find(struct upnp_wps_device_sm *sm,
00626                                         const u8 uuid[UUID_LEN])
00627 {
00628         struct subscription *s0 = sm->subscriptions;
00629         struct subscription *s = s0;
00630 
00631         if (s0 == NULL)
00632                 return NULL;
00633         do {
00634                 if (os_memcmp(s->uuid, uuid, UUID_LEN) == 0)
00635                         return s; /* Found match */
00636                 s = s->next;
00637         } while (s != s0);
00638 
00639         return NULL;
00640 }
00641 
00642 
00643 static struct wpabuf * build_fake_wsc_ack(void)
00644 {
00645         struct wpabuf *msg = wpabuf_alloc(100);
00646         if (msg == NULL)
00647                 return NULL;
00648         wpabuf_put_u8(msg, UPNP_WPS_WLANEVENT_TYPE_EAP);
00649         wpabuf_put_str(msg, "00:00:00:00:00:00");
00650         wps_build_version(msg);
00651         wps_build_msg_type(msg, WPS_WSC_ACK);
00652         /* Enrollee Nonce */
00653         wpabuf_put_be16(msg, ATTR_ENROLLEE_NONCE);
00654         wpabuf_put_be16(msg, WPS_NONCE_LEN);
00655         wpabuf_put(msg, WPS_NONCE_LEN);
00656         /* Registrar Nonce */
00657         wpabuf_put_be16(msg, ATTR_REGISTRAR_NONCE);
00658         wpabuf_put_be16(msg, WPS_NONCE_LEN);
00659         wpabuf_put(msg, WPS_NONCE_LEN);
00660         return msg;
00661 }
00662 
00663 
00664 /* subscription_first_event -- send format/queue event that is automatically
00665  * sent on a new subscription.
00666  */
00667 static int subscription_first_event(struct subscription *s)
00668 {
00669         /*
00670          * Actually, utf-8 is the default, but it doesn't hurt to specify it.
00671          *
00672          * APStatus is apparently a bit set,
00673          * 0x1 = configuration change (but is always set?)
00674          * 0x10 = ap is locked
00675          *
00676          * Per UPnP spec, we send out the last value of each variable, even
00677          * for WLANEvent, whatever it was.
00678          */
00679         char *wlan_event;
00680         struct wpabuf *buf;
00681         int ap_status = 1;      /* TODO: add 0x10 if access point is locked */
00682         const char *head =
00683                 "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
00684                 "<e:propertyset xmlns:e=\"urn:schemas-upnp-org:event-1-0\">\n";
00685         const char *tail = "</e:propertyset>\n";
00686         char txt[10];
00687 
00688         if (s->sm->wlanevent == NULL) {
00689                 /*
00690                  * There has been no events before the subscription. However,
00691                  * UPnP device architecture specification requires all the
00692                  * evented variables to be included, so generate a dummy event
00693                  * for this particular case using a WSC_ACK and all-zeros
00694                  * nonces. The ER (UPnP control point) will ignore this, but at
00695                  * least it will learn that WLANEvent variable will be used in
00696                  * event notifications in the future.
00697                  */
00698                 struct wpabuf *msg;
00699                 wpa_printf(MSG_DEBUG, "WPS UPnP: Use a fake WSC_ACK as the "
00700                            "initial WLANEvent");
00701                 msg = build_fake_wsc_ack();
00702                 if (msg) {
00703                         s->sm->wlanevent = (char *)
00704                                 base64_encode(wpabuf_head(msg),
00705                                               wpabuf_len(msg), NULL);
00706                         wpabuf_free(msg);
00707                 }
00708         }
00709 
00710         wlan_event = s->sm->wlanevent;
00711         if (wlan_event == NULL || *wlan_event == '\0') {
00712                 wpa_printf(MSG_DEBUG, "WPS UPnP: WLANEvent not known for "
00713                            "initial event message");
00714                 wlan_event = "";
00715         }
00716         buf = wpabuf_alloc(500 + os_strlen(wlan_event));
00717         if (buf == NULL)
00718                 return 1;
00719 
00720         wpabuf_put_str(buf, head);
00721         wpabuf_put_property(buf, "STAStatus", "1");
00722         os_snprintf(txt, sizeof(txt), "%d", ap_status);
00723         wpabuf_put_property(buf, "APStatus", txt);
00724         if (*wlan_event)
00725                 wpabuf_put_property(buf, "WLANEvent", wlan_event);
00726         wpabuf_put_str(buf, tail);
00727 
00728         if (event_add(s, buf)) {
00729                 wpabuf_free(buf);
00730                 return 1;
00731         }
00732         wpabuf_free(buf);
00733 
00734         return 0;
00735 }
00736 
00737 
00745 struct subscription * subscription_start(struct upnp_wps_device_sm *sm,
00746                                          const char *callback_urls)
00747 {
00748         struct subscription *s;
00749         time_t now = time(NULL);
00750         time_t expire = now + UPNP_SUBSCRIBE_SEC;
00751 
00752         /* Get rid of expired subscriptions so we have room */
00753         subscription_list_age(sm, now);
00754 
00755         /* If too many subscriptions, remove oldest */
00756         if (sm->n_subscriptions >= MAX_SUBSCRIPTIONS) {
00757                 s = sm->subscriptions;
00758                 wpa_printf(MSG_INFO, "WPS UPnP: Too many subscriptions, "
00759                            "trashing oldest");
00760                 subscription_unlink(s);
00761                 subscription_destroy(s);
00762         }
00763 
00764         s = os_zalloc(sizeof(*s));
00765         if (s == NULL)
00766                 return NULL;
00767 
00768         s->sm = sm;
00769         s->timeout_time = expire;
00770         uuid_make(s->uuid);
00771         subscr_addr_list_create(s, callback_urls);
00772         /* Add to end of list, since it has the highest expiration time */
00773         subscription_link_to_end(s);
00774         /* Queue up immediate event message (our last event)
00775          * as required by UPnP spec.
00776          */
00777         if (subscription_first_event(s)) {
00778                 wpa_printf(MSG_INFO, "WPS UPnP: Dropping subscriber due to "
00779                            "event backlog");
00780                 subscription_unlink(s);
00781                 subscription_destroy(s);
00782                 return NULL;
00783         }
00784         wpa_printf(MSG_DEBUG, "WPS UPnP: Subscription %p started with %s",
00785                    s, callback_urls);
00786         /* Schedule sending this */
00787         event_send_all_later(sm);
00788         return s;
00789 }
00790 
00791 
00792 /* subscription_renew -- find subscription and reset timeout */
00793 struct subscription * subscription_renew(struct upnp_wps_device_sm *sm,
00794                                          const u8 uuid[UUID_LEN])
00795 {
00796         time_t now = time(NULL);
00797         time_t expire = now + UPNP_SUBSCRIBE_SEC;
00798         struct subscription *s = subscription_find(sm, uuid);
00799         if (s == NULL)
00800                 return NULL;
00801         wpa_printf(MSG_DEBUG, "WPS UPnP: Subscription renewed");
00802         subscription_unlink(s);
00803         s->timeout_time = expire;
00804         /* add back to end of list, since it now has highest expiry */
00805         subscription_link_to_end(s);
00806         return s;
00807 }
00808 
00809 
00823 int upnp_wps_device_send_wlan_event(struct upnp_wps_device_sm *sm,
00824                                     const u8 from_mac_addr[ETH_ALEN],
00825                                     enum upnp_wps_wlanevent_type ev_type,
00826                                     const struct wpabuf *msg)
00827 {
00828         int ret = -1;
00829         char type[2];
00830         const u8 *mac = from_mac_addr;
00831         char mac_text[18];
00832         u8 *raw = NULL;
00833         size_t raw_len;
00834         char *val;
00835         size_t val_len;
00836         int pos = 0;
00837 
00838         if (!sm)
00839                 goto fail;
00840 
00841         os_snprintf(type, sizeof(type), "%1u", ev_type);
00842 
00843         raw_len = 1 + 17 + (msg ? wpabuf_len(msg) : 0);
00844         raw = os_zalloc(raw_len);
00845         if (!raw)
00846                 goto fail;
00847 
00848         *(raw + pos) = (u8) ev_type;
00849         pos += 1;
00850         os_snprintf(mac_text, sizeof(mac_text), MACSTR, MAC2STR(mac));
00851         wpa_printf(MSG_DEBUG, "WPS UPnP: Proxying WLANEvent from %s",
00852                    mac_text);
00853         os_memcpy(raw + pos, mac_text, 17);
00854         pos += 17;
00855         if (msg) {
00856                 os_memcpy(raw + pos, wpabuf_head(msg), wpabuf_len(msg));
00857                 pos += wpabuf_len(msg);
00858         }
00859         raw_len = pos;
00860 
00861         val = (char *) base64_encode(raw, raw_len, &val_len);
00862         if (val == NULL)
00863                 goto fail;
00864 
00865         os_free(sm->wlanevent);
00866         sm->wlanevent = val;
00867         upnp_wps_device_send_event(sm);
00868 
00869         ret = 0;
00870 
00871 fail:
00872         os_free(raw);
00873 
00874         return ret;
00875 }
00876 
00877 
00878 #ifdef __FreeBSD__
00879 #include <sys/sysctl.h>
00880 #include <net/route.h>
00881 #include <net/if_dl.h>
00882 
00883 static int eth_get(const char *device, u8 ea[ETH_ALEN])
00884 {
00885         struct if_msghdr *ifm;
00886         struct sockaddr_dl *sdl;
00887         u_char *p, *buf;
00888         size_t len;
00889         int mib[] = { CTL_NET, AF_ROUTE, 0, AF_LINK, NET_RT_IFLIST, 0 };
00890 
00891         if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0)
00892                 return -1;
00893         if ((buf = os_malloc(len)) == NULL)
00894                 return -1;
00895         if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
00896                 os_free(buf);
00897                 return -1;
00898         }
00899         for (p = buf; p < buf + len; p += ifm->ifm_msglen) {
00900                 ifm = (struct if_msghdr *)p;
00901                 sdl = (struct sockaddr_dl *)(ifm + 1);
00902                 if (ifm->ifm_type != RTM_IFINFO ||
00903                     (ifm->ifm_addrs & RTA_IFP) == 0)
00904                         continue;
00905                 if (sdl->sdl_family != AF_LINK || sdl->sdl_nlen == 0 ||
00906                     os_memcmp(sdl->sdl_data, device, sdl->sdl_nlen) != 0)
00907                         continue;
00908                 os_memcpy(ea, LLADDR(sdl), sdl->sdl_alen);
00909                 break;
00910         }
00911         os_free(buf);
00912 
00913         if (p >= buf + len) {
00914                 errno = ESRCH;
00915                 return -1;
00916         }
00917         return 0;
00918 }
00919 #endif /* __FreeBSD__ */
00920 
00921 
00932 int get_netif_info(const char *net_if, unsigned *ip_addr, char **ip_addr_text,
00933                    u8 mac[ETH_ALEN], char **mac_addr_text)
00934 {
00935         struct ifreq req;
00936         int sock = -1;
00937         struct sockaddr_in *addr;
00938         struct in_addr in_addr;
00939 
00940         *ip_addr_text = os_zalloc(16);
00941         *mac_addr_text = os_zalloc(18);
00942         if (*ip_addr_text == NULL || *mac_addr_text == NULL)
00943                 goto fail;
00944 
00945         sock = socket(AF_INET, SOCK_DGRAM, 0);
00946         if (sock < 0)
00947                 goto fail;
00948 
00949         os_strlcpy(req.ifr_name, net_if, sizeof(req.ifr_name));
00950         if (ioctl(sock, SIOCGIFADDR, &req) < 0) {
00951                 wpa_printf(MSG_ERROR, "WPS UPnP: SIOCGIFADDR failed: %d (%s)",
00952                            errno, strerror(errno));
00953                 goto fail;
00954         }
00955         addr = (void *) &req.ifr_addr;
00956         *ip_addr = addr->sin_addr.s_addr;
00957         in_addr.s_addr = *ip_addr;
00958         os_snprintf(*ip_addr_text, 16, "%s", inet_ntoa(in_addr));
00959 
00960 #ifdef __linux__
00961         os_strlcpy(req.ifr_name, net_if, sizeof(req.ifr_name));
00962         if (ioctl(sock, SIOCGIFHWADDR, &req) < 0) {
00963                 wpa_printf(MSG_ERROR, "WPS UPnP: SIOCGIFHWADDR failed: "
00964                            "%d (%s)", errno, strerror(errno));
00965                 goto fail;
00966         }
00967         os_memcpy(mac, req.ifr_addr.sa_data, 6);
00968 #elif defined(__FreeBSD__)
00969         if (eth_get(net_if, mac) < 0) {
00970                 wpa_printf(MSG_ERROR, "WPS UPnP: Failed to get MAC address");
00971                 goto fail;
00972         }
00973 #else
00974 #error MAC address fetch not implemented
00975 #endif
00976         os_snprintf(*mac_addr_text, 18, MACSTR, MAC2STR(mac));
00977 
00978         close(sock);
00979         return 0;
00980 
00981 fail:
00982         if (sock >= 0)
00983                 close(sock);
00984         os_free(*ip_addr_text);
00985         *ip_addr_text = NULL;
00986         os_free(*mac_addr_text);
00987         *mac_addr_text = NULL;
00988         return -1;
00989 }
00990 
00991 
00997 void upnp_wps_device_stop(struct upnp_wps_device_sm *sm)
00998 {
00999         if (!sm || !sm->started)
01000                 return;
01001 
01002         wpa_printf(MSG_DEBUG, "WPS UPnP: Stop device");
01003         web_listener_stop(sm);
01004         while (sm->msearch_replies)
01005                 msearchreply_state_machine_stop(sm->msearch_replies);
01006         while (sm->subscriptions)  {
01007                 struct subscription *s = sm->subscriptions;
01008                 subscription_unlink(s);
01009                 subscription_destroy(s);
01010         }
01011 
01012         advertisement_state_machine_stop(sm, 1);
01013 
01014         event_send_stop_all(sm);
01015         os_free(sm->wlanevent);
01016         sm->wlanevent = NULL;
01017         os_free(sm->net_if);
01018         sm->net_if = NULL;
01019         os_free(sm->mac_addr_text);
01020         sm->mac_addr_text = NULL;
01021         os_free(sm->ip_addr_text);
01022         sm->ip_addr_text = NULL;
01023         if (sm->multicast_sd >= 0)
01024                 close(sm->multicast_sd);
01025         sm->multicast_sd = -1;
01026         ssdp_listener_stop(sm);
01027 
01028         sm->started = 0;
01029 }
01030 
01031 
01039 int upnp_wps_device_start(struct upnp_wps_device_sm *sm, char *net_if)
01040 {
01041         if (!sm || !net_if)
01042                 return -1;
01043 
01044         if (sm->started)
01045                 upnp_wps_device_stop(sm);
01046 
01047         sm->net_if = strdup(net_if);
01048         sm->multicast_sd = -1;
01049         sm->ssdp_sd = -1;
01050         sm->started = 1;
01051         sm->advertise_count = 0;
01052 
01053         /* Fix up linux multicast handling */
01054         if (add_ssdp_network(net_if))
01055                 goto fail;
01056 
01057         /* Determine which IP and mac address we're using */
01058         if (get_netif_info(net_if,
01059                            &sm->ip_addr, &sm->ip_addr_text,
01060                            sm->mac_addr, &sm->mac_addr_text)) {
01061                 wpa_printf(MSG_INFO, "WPS UPnP: Could not get IP/MAC address "
01062                            "for %s. Does it have IP address?", net_if);
01063                 goto fail;
01064         }
01065 
01066         /* Listen for incoming TCP connections so that others
01067          * can fetch our "xml files" from us.
01068          */
01069         if (web_listener_start(sm))
01070                 goto fail;
01071 
01072         /* Set up for receiving discovery (UDP) packets */
01073         if (ssdp_listener_start(sm))
01074                 goto fail;
01075 
01076         /* Set up for sending multicast */
01077         if (ssdp_open_multicast(sm) < 0)
01078                 goto fail;
01079 
01080         /*
01081          * Broadcast NOTIFY messages to let the world know we exist.
01082          * This is done via a state machine since the messages should not be
01083          * all sent out at once.
01084          */
01085         if (advertisement_state_machine_start(sm))
01086                 goto fail;
01087 
01088         return 0;
01089 
01090 fail:
01091         upnp_wps_device_stop(sm);
01092         return -1;
01093 }
01094 
01095 
01101 void upnp_wps_device_deinit(struct upnp_wps_device_sm *sm)
01102 {
01103         if (!sm)
01104                 return;
01105 
01106         upnp_wps_device_stop(sm);
01107 
01108         if (sm->peer.wps)
01109                 wps_deinit(sm->peer.wps);
01110         os_free(sm->root_dir);
01111         os_free(sm->desc_url);
01112         os_free(sm->ctx);
01113         os_free(sm);
01114 }
01115 
01116 
01125 struct upnp_wps_device_sm *
01126 upnp_wps_device_init(struct upnp_wps_device_ctx *ctx, struct wps_context *wps,
01127                      void *priv)
01128 {
01129         struct upnp_wps_device_sm *sm;
01130 
01131         sm = os_zalloc(sizeof(*sm));
01132         if (!sm) {
01133                 wpa_printf(MSG_ERROR, "WPS UPnP: upnp_wps_device_init failed");
01134                 return NULL;
01135         }
01136 
01137         sm->ctx = ctx;
01138         sm->wps = wps;
01139         sm->priv = priv;
01140 
01141         return sm;
01142 }
01143 
01144 
01151 int upnp_wps_subscribers(struct upnp_wps_device_sm *sm)
01152 {
01153         return sm->subscriptions != NULL;
01154 }
01155 
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Defines

Generated on Sat Nov 21 23:16:55 2009 for hostapd by  doxygen 1.6.1