LCOV - code coverage report
Current view: top level - src/wps - wps_upnp.c (source / functions) Hit Total Coverage
Test: wpa_supplicant/hostapd combined for hwsim test run 1422976643 Lines: 361 443 81.5 %
Date: 2015-02-03 Functions: 26 26 100.0 %

          Line data    Source code
       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 no one 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 <time.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             : 
     216             : static struct upnp_wps_device_sm *shared_upnp_device = NULL;
     217             : 
     218             : 
     219             : /* Write the current date/time per RFC */
     220         643 : void format_date(struct wpabuf *buf)
     221             : {
     222         643 :         const char *weekday_str = "Sun\0Mon\0Tue\0Wed\0Thu\0Fri\0Sat";
     223         643 :         const char *month_str = "Jan\0Feb\0Mar\0Apr\0May\0Jun\0"
     224             :                 "Jul\0Aug\0Sep\0Oct\0Nov\0Dec";
     225             :         struct tm *date;
     226             :         time_t t;
     227             : 
     228         643 :         t = time(NULL);
     229         643 :         date = gmtime(&t);
     230         643 :         if (date == NULL)
     231         643 :                 return;
     232        2572 :         wpabuf_printf(buf, "%s, %02d %s %d %02d:%02d:%02d GMT",
     233         643 :                       &weekday_str[date->tm_wday * 4], date->tm_mday,
     234        1286 :                       &month_str[date->tm_mon * 4], date->tm_year + 1900,
     235             :                       date->tm_hour, date->tm_min, date->tm_sec);
     236             : }
     237             : 
     238             : 
     239             : /***************************************************************************
     240             :  * UUIDs (unique identifiers)
     241             :  *
     242             :  * These are supposed to be unique in all the world.
     243             :  * Sometimes permanent ones are used, sometimes temporary ones
     244             :  * based on random numbers... there are different rules for valid content
     245             :  * of different types.
     246             :  * Each uuid is 16 bytes long.
     247             :  **************************************************************************/
     248             : 
     249             : /* uuid_make -- construct a random UUID
     250             :  * The UPnP documents don't seem to offer any guidelines as to which method to
     251             :  * use for constructing UUIDs for subscriptions. Presumably any method from
     252             :  * rfc4122 is good enough; I've chosen random number method.
     253             :  */
     254          12 : static int uuid_make(u8 uuid[UUID_LEN])
     255             : {
     256          12 :         if (os_get_random(uuid, UUID_LEN) < 0)
     257           0 :                 return -1;
     258             : 
     259             :         /* Replace certain bits as specified in rfc4122 or X.667 */
     260          12 :         uuid[6] &= 0x0f; uuid[6] |= (4 << 4);   /* version 4 == random gen */
     261          12 :         uuid[8] &= 0x3f; uuid[8] |= 0x80;
     262             : 
     263          12 :         return 0;
     264             : }
     265             : 
     266             : 
     267             : /*
     268             :  * Subscriber address handling.
     269             :  * Since a subscriber may have an arbitrary number of addresses, we have to
     270             :  * add a bunch of code to handle them.
     271             :  *
     272             :  * Addresses are passed in text, and MAY be domain names instead of the (usual
     273             :  * and expected) dotted IP addresses. Resolving domain names consumes a lot of
     274             :  * resources. Worse, we are currently using the standard Linux getaddrinfo()
     275             :  * which will block the entire program until complete or timeout! The proper
     276             :  * solution would be to use the "ares" library or similar with more state
     277             :  * machine steps etc. or just disable domain name resolution by setting
     278             :  * NO_DOMAIN_NAME_RESOLUTION to 1 at top of this file.
     279             :  */
     280             : 
     281             : /* subscr_addr_delete -- delete single unlinked subscriber address
     282             :  * (be sure to unlink first if need be)
     283             :  */
     284          19 : void subscr_addr_delete(struct subscr_addr *a)
     285             : {
     286             :         /*
     287             :          * Note: do NOT free domain_and_port or path because they point to
     288             :          * memory within the allocation of "a".
     289             :          */
     290          19 :         os_free(a);
     291          19 : }
     292             : 
     293             : 
     294             : /* subscr_addr_free_all -- unlink and delete list of subscriber addresses. */
     295          12 : static void subscr_addr_free_all(struct subscription *s)
     296             : {
     297             :         struct subscr_addr *a, *tmp;
     298          31 :         dl_list_for_each_safe(a, tmp, &s->addr_list, struct subscr_addr, list)
     299             :         {
     300          19 :                 dl_list_del(&a->list);
     301          19 :                 subscr_addr_delete(a);
     302             :         }
     303          12 : }
     304             : 
     305             : 
     306             : /* subscr_addr_add_url -- add address(es) for one url to subscription */
     307          35 : static void subscr_addr_add_url(struct subscription *s, const char *url,
     308             :                                 size_t url_len)
     309             : {
     310             :         int alloc_len;
     311          35 :         char *scratch_mem = NULL;
     312             :         char *mem;
     313             :         char *host;
     314             :         char *delim;
     315             :         char *path;
     316          35 :         int port = 80;  /* port to send to (default is port 80) */
     317             :         struct addrinfo hints;
     318          35 :         struct addrinfo *result = NULL;
     319             :         struct addrinfo *rp;
     320             :         int rerr;
     321             :         size_t host_len, path_len;
     322             : 
     323             :         /* url MUST begin with http: */
     324          35 :         if (url_len < 7 || os_strncasecmp(url, "http://", 7))
     325             :                 goto fail;
     326          35 :         url += 7;
     327          35 :         url_len -= 7;
     328             : 
     329             :         /* Make a copy of the string to allow modification during parsing */
     330          35 :         scratch_mem = dup_binstr(url, url_len);
     331          35 :         if (scratch_mem == NULL)
     332           0 :                 goto fail;
     333          35 :         wpa_printf(MSG_DEBUG, "WPS UPnP: Adding URL '%s'", scratch_mem);
     334          35 :         host = scratch_mem;
     335          35 :         path = os_strchr(host, '/');
     336          35 :         if (path)
     337          35 :                 *path++ = '\0'; /* null terminate host */
     338             : 
     339             :         /* Process and remove optional port component */
     340          35 :         delim = os_strchr(host, ':');
     341          35 :         if (delim) {
     342          35 :                 *delim = '\0'; /* null terminate host name for now */
     343          35 :                 if (isdigit(delim[1]))
     344          35 :                         port = atol(delim + 1);
     345             :         }
     346             : 
     347             :         /*
     348             :          * getaddrinfo does the right thing with dotted decimal notations, or
     349             :          * will resolve domain names. Resolving domain names will unfortunately
     350             :          * hang the entire program until it is resolved or it times out
     351             :          * internal to getaddrinfo; fortunately we think that the use of actual
     352             :          * domain names (vs. dotted decimal notations) should be uncommon.
     353             :          */
     354          35 :         os_memset(&hints, 0, sizeof(struct addrinfo));
     355          35 :         hints.ai_family = AF_INET;      /* IPv4 */
     356          35 :         hints.ai_socktype = SOCK_STREAM;
     357             : #if NO_DOMAIN_NAME_RESOLUTION
     358             :         /* Suppress domain name resolutions that would halt
     359             :          * the program for periods of time
     360             :          */
     361          35 :         hints.ai_flags = AI_NUMERICHOST;
     362             : #else
     363             :         /* Allow domain name resolution. */
     364             :         hints.ai_flags = 0;
     365             : #endif
     366          35 :         hints.ai_protocol = 0;          /* Any protocol? */
     367          35 :         rerr = getaddrinfo(host, NULL /* fill in port ourselves */,
     368             :                            &hints, &result);
     369          35 :         if (rerr) {
     370           0 :                 wpa_printf(MSG_INFO, "WPS UPnP: Resolve error %d (%s) on: %s",
     371             :                            rerr, gai_strerror(rerr), host);
     372           0 :                 goto fail;
     373             :         }
     374             : 
     375          35 :         if (delim)
     376          35 :                 *delim = ':'; /* Restore port */
     377             : 
     378          35 :         host_len = os_strlen(host);
     379          35 :         path_len = path ? os_strlen(path) : 0;
     380          35 :         alloc_len = host_len + 1 + 1 + path_len + 1;
     381             : 
     382          54 :         for (rp = result; rp; rp = rp->ai_next) {
     383             :                 struct subscr_addr *a;
     384             : 
     385             :                 /* Limit no. of address to avoid denial of service attack */
     386          35 :                 if (dl_list_len(&s->addr_list) >= MAX_ADDR_PER_SUBSCRIPTION) {
     387          16 :                         wpa_printf(MSG_INFO, "WPS UPnP: subscr_addr_add_url: "
     388             :                                    "Ignoring excessive addresses");
     389          16 :                         break;
     390             :                 }
     391             : 
     392          19 :                 a = os_zalloc(sizeof(*a) + alloc_len);
     393          19 :                 if (a == NULL)
     394           0 :                         break;
     395          19 :                 mem = (char *) (a + 1);
     396          19 :                 a->domain_and_port = mem;
     397          19 :                 os_memcpy(mem, host, host_len);
     398          19 :                 mem += host_len + 1;
     399          19 :                 a->path = mem;
     400          19 :                 if (path == NULL || path[0] != '/')
     401          19 :                         *mem++ = '/';
     402          19 :                 if (path)
     403          19 :                         os_memcpy(mem, path, path_len);
     404          19 :                 os_memcpy(&a->saddr, rp->ai_addr, sizeof(a->saddr));
     405          19 :                 a->saddr.sin_port = htons(port);
     406             : 
     407          19 :                 dl_list_add(&s->addr_list, &a->list);
     408             :         }
     409             : 
     410             : fail:
     411          35 :         if (result)
     412          35 :                 freeaddrinfo(result);
     413          35 :         os_free(scratch_mem);
     414          35 : }
     415             : 
     416             : 
     417             : /* subscr_addr_list_create -- create list from urls in string.
     418             :  *      Each url is enclosed by angle brackets.
     419             :  */
     420          12 : static void subscr_addr_list_create(struct subscription *s,
     421             :                                     const char *url_list)
     422             : {
     423             :         const char *end;
     424          12 :         wpa_printf(MSG_DEBUG, "WPS UPnP: Parsing URL list '%s'", url_list);
     425             :         for (;;) {
     426          96 :                 while (*url_list == ' ' || *url_list == '\t')
     427           2 :                         url_list++;
     428          47 :                 if (*url_list != '<')
     429          12 :                         break;
     430          35 :                 url_list++;
     431          35 :                 end = os_strchr(url_list, '>');
     432          35 :                 if (end == NULL)
     433           0 :                         break;
     434          35 :                 subscr_addr_add_url(s, url_list, end - url_list);
     435          35 :                 url_list = end + 1;
     436          35 :         }
     437          12 : }
     438             : 
     439             : 
     440          81 : static void wpabuf_put_property(struct wpabuf *buf, const char *name,
     441             :                                 const char *value)
     442             : {
     443          81 :         wpabuf_put_str(buf, "<e:property>");
     444          81 :         wpabuf_printf(buf, "<%s>", name);
     445          81 :         if (value)
     446          81 :                 wpabuf_put_str(buf, value);
     447          81 :         wpabuf_printf(buf, "</%s>", name);
     448          81 :         wpabuf_put_str(buf, "</e:property>\n");
     449          81 : }
     450             : 
     451             : 
     452             : /**
     453             :  * upnp_wps_device_send_event - Queue event messages for subscribers
     454             :  * @sm: WPS UPnP state machine from upnp_wps_device_init()
     455             :  *
     456             :  * This function queues the last WLANEvent to be sent for all currently
     457             :  * subscribed UPnP control points. sm->wlanevent must have been set with the
     458             :  * encoded data before calling this function.
     459             :  */
     460          73 : static void upnp_wps_device_send_event(struct upnp_wps_device_sm *sm)
     461             : {
     462             :         /* Enqueue event message for all subscribers */
     463             :         struct wpabuf *buf; /* holds event message */
     464          73 :         int buf_size = 0;
     465             :         struct subscription *s, *tmp;
     466             :         /* Actually, utf-8 is the default, but it doesn't hurt to specify it */
     467          73 :         const char *format_head =
     468             :                 "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
     469             :                 "<e:propertyset xmlns:e=\"urn:schemas-upnp-org:event-1-0\">\n";
     470          73 :         const char *format_tail = "</e:propertyset>\n";
     471             :         struct os_reltime now;
     472             : 
     473          73 :         if (dl_list_empty(&sm->subscriptions)) {
     474             :                 /* optimize */
     475          55 :                 return;
     476             :         }
     477             : 
     478          46 :         if (os_get_reltime(&now) == 0) {
     479          46 :                 if (now.sec != sm->last_event_sec) {
     480          17 :                         sm->last_event_sec = now.sec;
     481          17 :                         sm->num_events_in_sec = 1;
     482             :                 } else {
     483          29 :                         sm->num_events_in_sec++;
     484             :                         /*
     485             :                          * In theory, this should apply to all WLANEvent
     486             :                          * notifications, but EAP messages are of much higher
     487             :                          * priority and Probe Request notifications should not
     488             :                          * be allowed to drop EAP messages, so only throttle
     489             :                          * Probe Request notifications.
     490             :                          */
     491          37 :                         if (sm->num_events_in_sec > MAX_EVENTS_PER_SEC &&
     492           8 :                             sm->wlanevent_type ==
     493             :                             UPNP_WPS_WLANEVENT_TYPE_PROBE) {
     494           1 :                                 wpa_printf(MSG_DEBUG, "WPS UPnP: Throttle "
     495             :                                            "event notifications (%u seen "
     496             :                                            "during one second)",
     497             :                                            sm->num_events_in_sec);
     498           1 :                                 return;
     499             :                         }
     500             :                 }
     501             :         }
     502             : 
     503             :         /* Determine buffer size needed first */
     504          45 :         buf_size += os_strlen(format_head);
     505          45 :         buf_size += 50 + 2 * os_strlen("WLANEvent");
     506          45 :         if (sm->wlanevent)
     507          45 :                 buf_size += os_strlen(sm->wlanevent);
     508          45 :         buf_size += os_strlen(format_tail);
     509             : 
     510          45 :         buf = wpabuf_alloc(buf_size);
     511          45 :         if (buf == NULL)
     512           0 :                 return;
     513          45 :         wpabuf_put_str(buf, format_head);
     514          45 :         wpabuf_put_property(buf, "WLANEvent", sm->wlanevent);
     515          45 :         wpabuf_put_str(buf, format_tail);
     516             : 
     517          45 :         wpa_printf(MSG_MSGDUMP, "WPS UPnP: WLANEvent message:\n%s",
     518          45 :                    (char *) wpabuf_head(buf));
     519             : 
     520          90 :         dl_list_for_each_safe(s, tmp, &sm->subscriptions, struct subscription,
     521             :                               list) {
     522          45 :                 event_add(s, buf,
     523          45 :                           sm->wlanevent_type == UPNP_WPS_WLANEVENT_TYPE_PROBE);
     524             :         }
     525             : 
     526          45 :         wpabuf_free(buf);
     527             : }
     528             : 
     529             : 
     530             : /*
     531             :  * Event subscription (subscriber machines register with us to receive event
     532             :  * messages).
     533             :  * This is the result of an incoming HTTP over TCP SUBSCRIBE request.
     534             :  */
     535             : 
     536             : /* subscription_destroy -- destroy an unlinked subscription
     537             :  * Be sure to unlink first if necessary.
     538             :  */
     539          12 : void subscription_destroy(struct subscription *s)
     540             : {
     541             :         struct upnp_wps_device_interface *iface;
     542          12 :         wpa_printf(MSG_DEBUG, "WPS UPnP: Destroy subscription %p", s);
     543          12 :         subscr_addr_free_all(s);
     544          12 :         event_delete_all(s);
     545          24 :         dl_list_for_each(iface, &s->sm->interfaces,
     546             :                          struct upnp_wps_device_interface, list)
     547          12 :                 upnp_er_remove_notification(iface->wps->registrar, s);
     548          12 :         os_free(s);
     549          12 : }
     550             : 
     551             : 
     552             : /* subscription_list_age -- remove expired subscriptions */
     553          12 : static void subscription_list_age(struct upnp_wps_device_sm *sm, time_t now)
     554             : {
     555             :         struct subscription *s, *tmp;
     556          12 :         dl_list_for_each_safe(s, tmp, &sm->subscriptions,
     557             :                               struct subscription, list) {
     558           0 :                 if (s->timeout_time > now)
     559           0 :                         break;
     560           0 :                 wpa_printf(MSG_DEBUG, "WPS UPnP: Removing aged subscription");
     561           0 :                 dl_list_del(&s->list);
     562           0 :                 subscription_destroy(s);
     563             :         }
     564          12 : }
     565             : 
     566             : 
     567             : /* subscription_find -- return existing subscription matching uuid, if any
     568             :  * returns NULL if not found
     569             :  */
     570          15 : struct subscription * subscription_find(struct upnp_wps_device_sm *sm,
     571             :                                         const u8 uuid[UUID_LEN])
     572             : {
     573             :         struct subscription *s;
     574          16 :         dl_list_for_each(s, &sm->subscriptions, struct subscription, list) {
     575          14 :                 if (os_memcmp(s->uuid, uuid, UUID_LEN) == 0)
     576          13 :                         return s; /* Found match */
     577             :         }
     578           2 :         return NULL;
     579             : }
     580             : 
     581             : 
     582           1 : static struct wpabuf * build_fake_wsc_ack(void)
     583             : {
     584           1 :         struct wpabuf *msg = wpabuf_alloc(100);
     585           1 :         if (msg == NULL)
     586           0 :                 return NULL;
     587           1 :         wpabuf_put_u8(msg, UPNP_WPS_WLANEVENT_TYPE_EAP);
     588           1 :         wpabuf_put_str(msg, "00:00:00:00:00:00");
     589           2 :         if (wps_build_version(msg) ||
     590           1 :             wps_build_msg_type(msg, WPS_WSC_ACK)) {
     591           0 :                 wpabuf_free(msg);
     592           0 :                 return NULL;
     593             :         }
     594             :         /* Enrollee Nonce */
     595           1 :         wpabuf_put_be16(msg, ATTR_ENROLLEE_NONCE);
     596           1 :         wpabuf_put_be16(msg, WPS_NONCE_LEN);
     597           1 :         wpabuf_put(msg, WPS_NONCE_LEN);
     598             :         /* Registrar Nonce */
     599           1 :         wpabuf_put_be16(msg, ATTR_REGISTRAR_NONCE);
     600           1 :         wpabuf_put_be16(msg, WPS_NONCE_LEN);
     601           1 :         wpabuf_put(msg, WPS_NONCE_LEN);
     602           1 :         if (wps_build_wfa_ext(msg, 0, NULL, 0)) {
     603           0 :                 wpabuf_free(msg);
     604           0 :                 return NULL;
     605             :         }
     606           1 :         return msg;
     607             : }
     608             : 
     609             : 
     610             : /* subscription_first_event -- send format/queue event that is automatically
     611             :  * sent on a new subscription.
     612             :  */
     613          12 : static int subscription_first_event(struct subscription *s)
     614             : {
     615             :         /*
     616             :          * Actually, utf-8 is the default, but it doesn't hurt to specify it.
     617             :          *
     618             :          * APStatus is apparently a bit set,
     619             :          * 0x1 = configuration change (but is always set?)
     620             :          * 0x10 = ap is locked
     621             :          *
     622             :          * Per UPnP spec, we send out the last value of each variable, even
     623             :          * for WLANEvent, whatever it was.
     624             :          */
     625             :         char *wlan_event;
     626             :         struct wpabuf *buf;
     627          12 :         int ap_status = 1;      /* TODO: add 0x10 if access point is locked */
     628          12 :         const char *head =
     629             :                 "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
     630             :                 "<e:propertyset xmlns:e=\"urn:schemas-upnp-org:event-1-0\">\n";
     631          12 :         const char *tail = "</e:propertyset>\n";
     632             :         char txt[10];
     633             :         int ret;
     634             : 
     635          12 :         if (s->sm->wlanevent == NULL) {
     636             :                 /*
     637             :                  * There has been no events before the subscription. However,
     638             :                  * UPnP device architecture specification requires all the
     639             :                  * evented variables to be included, so generate a dummy event
     640             :                  * for this particular case using a WSC_ACK and all-zeros
     641             :                  * nonces. The ER (UPnP control point) will ignore this, but at
     642             :                  * least it will learn that WLANEvent variable will be used in
     643             :                  * event notifications in the future.
     644             :                  */
     645             :                 struct wpabuf *msg;
     646           1 :                 wpa_printf(MSG_DEBUG, "WPS UPnP: Use a fake WSC_ACK as the "
     647             :                            "initial WLANEvent");
     648           1 :                 msg = build_fake_wsc_ack();
     649           1 :                 if (msg) {
     650           2 :                         s->sm->wlanevent = (char *)
     651           1 :                                 base64_encode(wpabuf_head(msg),
     652             :                                               wpabuf_len(msg), NULL);
     653           1 :                         wpabuf_free(msg);
     654             :                 }
     655             :         }
     656             : 
     657          12 :         wlan_event = s->sm->wlanevent;
     658          12 :         if (wlan_event == NULL || *wlan_event == '\0') {
     659           0 :                 wpa_printf(MSG_DEBUG, "WPS UPnP: WLANEvent not known for "
     660             :                            "initial event message");
     661           0 :                 wlan_event = "";
     662             :         }
     663          12 :         buf = wpabuf_alloc(500 + os_strlen(wlan_event));
     664          12 :         if (buf == NULL)
     665           0 :                 return -1;
     666             : 
     667          12 :         wpabuf_put_str(buf, head);
     668          12 :         wpabuf_put_property(buf, "STAStatus", "1");
     669          12 :         os_snprintf(txt, sizeof(txt), "%d", ap_status);
     670          12 :         wpabuf_put_property(buf, "APStatus", txt);
     671          12 :         if (*wlan_event)
     672          12 :                 wpabuf_put_property(buf, "WLANEvent", wlan_event);
     673          12 :         wpabuf_put_str(buf, tail);
     674             : 
     675          12 :         ret = event_add(s, buf, 0);
     676          12 :         if (ret) {
     677           0 :                 wpabuf_free(buf);
     678           0 :                 return ret;
     679             :         }
     680          12 :         wpabuf_free(buf);
     681             : 
     682          12 :         return 0;
     683             : }
     684             : 
     685             : 
     686             : /**
     687             :  * subscription_start - Remember a UPnP control point to send events to.
     688             :  * @sm: WPS UPnP state machine from upnp_wps_device_init()
     689             :  * @callback_urls: Callback URLs
     690             :  * Returns: %NULL on error, or pointer to new subscription structure.
     691             :  */
     692          12 : struct subscription * subscription_start(struct upnp_wps_device_sm *sm,
     693             :                                          const char *callback_urls)
     694             : {
     695             :         struct subscription *s;
     696          12 :         time_t now = time(NULL);
     697          12 :         time_t expire = now + UPNP_SUBSCRIBE_SEC;
     698             : 
     699             :         /* Get rid of expired subscriptions so we have room */
     700          12 :         subscription_list_age(sm, now);
     701             : 
     702             :         /* If too many subscriptions, remove oldest */
     703          12 :         if (dl_list_len(&sm->subscriptions) >= MAX_SUBSCRIPTIONS) {
     704           0 :                 s = dl_list_first(&sm->subscriptions, struct subscription,
     705             :                                   list);
     706           0 :                 if (s) {
     707           0 :                         wpa_printf(MSG_INFO,
     708             :                                    "WPS UPnP: Too many subscriptions, trashing oldest");
     709           0 :                         dl_list_del(&s->list);
     710           0 :                         subscription_destroy(s);
     711             :                 }
     712             :         }
     713             : 
     714          12 :         s = os_zalloc(sizeof(*s));
     715          12 :         if (s == NULL)
     716           0 :                 return NULL;
     717          12 :         dl_list_init(&s->addr_list);
     718          12 :         dl_list_init(&s->event_queue);
     719             : 
     720          12 :         s->sm = sm;
     721          12 :         s->timeout_time = expire;
     722          12 :         if (uuid_make(s->uuid) < 0) {
     723           0 :                 subscription_destroy(s);
     724           0 :                 return NULL;
     725             :         }
     726          12 :         subscr_addr_list_create(s, callback_urls);
     727          12 :         if (dl_list_empty(&s->addr_list)) {
     728           0 :                 wpa_printf(MSG_DEBUG, "WPS UPnP: No valid callback URLs in "
     729             :                            "'%s' - drop subscription", callback_urls);
     730           0 :                 subscription_destroy(s);
     731           0 :                 return NULL;
     732             :         }
     733             : 
     734             :         /* Add to end of list, since it has the highest expiration time */
     735          12 :         dl_list_add_tail(&sm->subscriptions, &s->list);
     736             :         /* Queue up immediate event message (our last event)
     737             :          * as required by UPnP spec.
     738             :          */
     739          12 :         if (subscription_first_event(s)) {
     740           0 :                 wpa_printf(MSG_INFO, "WPS UPnP: Dropping subscriber due to "
     741             :                            "event backlog");
     742           0 :                 dl_list_del(&s->list);
     743           0 :                 subscription_destroy(s);
     744           0 :                 return NULL;
     745             :         }
     746          12 :         wpa_printf(MSG_DEBUG, "WPS UPnP: Subscription %p started with %s",
     747             :                    s, callback_urls);
     748             :         /* Schedule sending this */
     749          12 :         event_send_all_later(sm);
     750          12 :         return s;
     751             : }
     752             : 
     753             : 
     754             : /* subscription_renew -- find subscription and reset timeout */
     755           3 : struct subscription * subscription_renew(struct upnp_wps_device_sm *sm,
     756             :                                          const u8 uuid[UUID_LEN])
     757             : {
     758           3 :         time_t now = time(NULL);
     759           3 :         time_t expire = now + UPNP_SUBSCRIBE_SEC;
     760           3 :         struct subscription *s = subscription_find(sm, uuid);
     761           3 :         if (s == NULL)
     762           1 :                 return NULL;
     763           2 :         wpa_printf(MSG_DEBUG, "WPS UPnP: Subscription renewed");
     764           2 :         dl_list_del(&s->list);
     765           2 :         s->timeout_time = expire;
     766             :         /* add back to end of list, since it now has highest expiry */
     767           2 :         dl_list_add_tail(&sm->subscriptions, &s->list);
     768           2 :         return s;
     769             : }
     770             : 
     771             : 
     772             : /**
     773             :  * upnp_wps_device_send_wlan_event - Event notification
     774             :  * @sm: WPS UPnP state machine from upnp_wps_device_init()
     775             :  * @from_mac_addr: Source (Enrollee) MAC address for the event
     776             :  * @ev_type: Event type
     777             :  * @msg: Event data
     778             :  * Returns: 0 on success, -1 on failure
     779             :  *
     780             :  * Tell external Registrars (UPnP control points) that something happened. In
     781             :  * particular, events include WPS messages from clients that are proxied to
     782             :  * external Registrars.
     783             :  */
     784         517 : int upnp_wps_device_send_wlan_event(struct upnp_wps_device_sm *sm,
     785             :                                     const u8 from_mac_addr[ETH_ALEN],
     786             :                                     enum upnp_wps_wlanevent_type ev_type,
     787             :                                     const struct wpabuf *msg)
     788             : {
     789         517 :         int ret = -1;
     790             :         char type[2];
     791         517 :         const u8 *mac = from_mac_addr;
     792             :         char mac_text[18];
     793         517 :         u8 *raw = NULL;
     794             :         size_t raw_len;
     795             :         char *val;
     796             :         size_t val_len;
     797         517 :         int pos = 0;
     798             : 
     799         517 :         if (!sm)
     800         444 :                 goto fail;
     801             : 
     802          73 :         os_snprintf(type, sizeof(type), "%1u", ev_type);
     803             : 
     804          73 :         raw_len = 1 + 17 + (msg ? wpabuf_len(msg) : 0);
     805          73 :         raw = os_zalloc(raw_len);
     806          73 :         if (!raw)
     807           0 :                 goto fail;
     808             : 
     809          73 :         *(raw + pos) = (u8) ev_type;
     810          73 :         pos += 1;
     811          73 :         os_snprintf(mac_text, sizeof(mac_text), MACSTR, MAC2STR(mac));
     812          73 :         wpa_printf(MSG_DEBUG, "WPS UPnP: Proxying WLANEvent from %s",
     813             :                    mac_text);
     814          73 :         os_memcpy(raw + pos, mac_text, 17);
     815          73 :         pos += 17;
     816          73 :         if (msg) {
     817          73 :                 os_memcpy(raw + pos, wpabuf_head(msg), wpabuf_len(msg));
     818          73 :                 pos += wpabuf_len(msg);
     819             :         }
     820          73 :         raw_len = pos;
     821             : 
     822          73 :         val = (char *) base64_encode(raw, raw_len, &val_len);
     823          73 :         if (val == NULL)
     824           0 :                 goto fail;
     825             : 
     826          73 :         os_free(sm->wlanevent);
     827          73 :         sm->wlanevent = val;
     828          73 :         sm->wlanevent_type = ev_type;
     829          73 :         upnp_wps_device_send_event(sm);
     830             : 
     831          73 :         ret = 0;
     832             : 
     833             : fail:
     834         517 :         os_free(raw);
     835             : 
     836         517 :         return ret;
     837             : }
     838             : 
     839             : 
     840             : #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
     841             : #include <sys/sysctl.h>
     842             : #include <net/route.h>
     843             : #include <net/if_dl.h>
     844             : 
     845             : static int eth_get(const char *device, u8 ea[ETH_ALEN])
     846             : {
     847             :         struct if_msghdr *ifm;
     848             :         struct sockaddr_dl *sdl;
     849             :         u_char *p, *buf;
     850             :         size_t len;
     851             :         int mib[] = { CTL_NET, AF_ROUTE, 0, AF_LINK, NET_RT_IFLIST, 0 };
     852             : 
     853             :         if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0)
     854             :                 return -1;
     855             :         if ((buf = os_malloc(len)) == NULL)
     856             :                 return -1;
     857             :         if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
     858             :                 os_free(buf);
     859             :                 return -1;
     860             :         }
     861             :         for (p = buf; p < buf + len; p += ifm->ifm_msglen) {
     862             :                 ifm = (struct if_msghdr *)p;
     863             :                 sdl = (struct sockaddr_dl *)(ifm + 1);
     864             :                 if (ifm->ifm_type != RTM_IFINFO ||
     865             :                     (ifm->ifm_addrs & RTA_IFP) == 0)
     866             :                         continue;
     867             :                 if (sdl->sdl_family != AF_LINK || sdl->sdl_nlen == 0 ||
     868             :                     os_memcmp(sdl->sdl_data, device, sdl->sdl_nlen) != 0)
     869             :                         continue;
     870             :                 os_memcpy(ea, LLADDR(sdl), sdl->sdl_alen);
     871             :                 break;
     872             :         }
     873             :         os_free(buf);
     874             : 
     875             :         if (p >= buf + len) {
     876             :                 errno = ESRCH;
     877             :                 return -1;
     878             :         }
     879             :         return 0;
     880             : }
     881             : #endif /* __FreeBSD__ */
     882             : 
     883             : 
     884             : /**
     885             :  * get_netif_info - Get hw and IP addresses for network device
     886             :  * @net_if: Selected network interface name
     887             :  * @ip_addr: Buffer for returning IP address in network byte order
     888             :  * @ip_addr_text: Buffer for returning a pointer to allocated IP address text
     889             :  * @mac: Buffer for returning MAC address
     890             :  * Returns: 0 on success, -1 on failure
     891             :  */
     892          26 : int get_netif_info(const char *net_if, unsigned *ip_addr, char **ip_addr_text,
     893             :                    u8 mac[ETH_ALEN])
     894             : {
     895             :         struct ifreq req;
     896          26 :         int sock = -1;
     897             :         struct sockaddr_in *addr;
     898             :         struct in_addr in_addr;
     899             : 
     900          26 :         *ip_addr_text = os_zalloc(16);
     901          26 :         if (*ip_addr_text == NULL)
     902           0 :                 goto fail;
     903             : 
     904          26 :         sock = socket(AF_INET, SOCK_DGRAM, 0);
     905          26 :         if (sock < 0)
     906           0 :                 goto fail;
     907             : 
     908          26 :         os_strlcpy(req.ifr_name, net_if, sizeof(req.ifr_name));
     909          26 :         if (ioctl(sock, SIOCGIFADDR, &req) < 0) {
     910           0 :                 wpa_printf(MSG_ERROR, "WPS UPnP: SIOCGIFADDR failed: %d (%s)",
     911           0 :                            errno, strerror(errno));
     912           0 :                 goto fail;
     913             :         }
     914          26 :         addr = (void *) &req.ifr_addr;
     915          26 :         *ip_addr = addr->sin_addr.s_addr;
     916          26 :         in_addr.s_addr = *ip_addr;
     917          26 :         os_snprintf(*ip_addr_text, 16, "%s", inet_ntoa(in_addr));
     918             : 
     919             : #ifdef __linux__
     920          26 :         os_strlcpy(req.ifr_name, net_if, sizeof(req.ifr_name));
     921          26 :         if (ioctl(sock, SIOCGIFHWADDR, &req) < 0) {
     922           0 :                 wpa_printf(MSG_ERROR, "WPS UPnP: SIOCGIFHWADDR failed: "
     923           0 :                            "%d (%s)", errno, strerror(errno));
     924           0 :                 goto fail;
     925             :         }
     926          26 :         os_memcpy(mac, req.ifr_addr.sa_data, 6);
     927             : #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
     928             :         if (eth_get(net_if, mac) < 0) {
     929             :                 wpa_printf(MSG_ERROR, "WPS UPnP: Failed to get MAC address");
     930             :                 goto fail;
     931             :         }
     932             : #else
     933             : #error MAC address fetch not implemented
     934             : #endif
     935             : 
     936          26 :         close(sock);
     937          26 :         return 0;
     938             : 
     939             : fail:
     940           0 :         if (sock >= 0)
     941           0 :                 close(sock);
     942           0 :         os_free(*ip_addr_text);
     943           0 :         *ip_addr_text = NULL;
     944           0 :         return -1;
     945             : }
     946             : 
     947             : 
     948          16 : static void upnp_wps_free_msearchreply(struct dl_list *head)
     949             : {
     950             :         struct advertisement_state_machine *a, *tmp;
     951          17 :         dl_list_for_each_safe(a, tmp, head, struct advertisement_state_machine,
     952             :                               list)
     953           1 :                 msearchreply_state_machine_stop(a);
     954          16 : }
     955             : 
     956             : 
     957          16 : static void upnp_wps_free_subscriptions(struct dl_list *head,
     958             :                                         struct wps_registrar *reg)
     959             : {
     960             :         struct subscription *s, *tmp;
     961          17 :         dl_list_for_each_safe(s, tmp, head, struct subscription, list) {
     962           1 :                 if (reg && s->reg != reg)
     963           0 :                         continue;
     964           1 :                 dl_list_del(&s->list);
     965           1 :                 subscription_destroy(s);
     966             :         }
     967          16 : }
     968             : 
     969             : 
     970             : /**
     971             :  * upnp_wps_device_stop - Stop WPS UPnP operations on an interface
     972             :  * @sm: WPS UPnP state machine from upnp_wps_device_init()
     973             :  */
     974          16 : static void upnp_wps_device_stop(struct upnp_wps_device_sm *sm)
     975             : {
     976          16 :         if (!sm || !sm->started)
     977          16 :                 return;
     978             : 
     979          16 :         wpa_printf(MSG_DEBUG, "WPS UPnP: Stop device");
     980          16 :         web_listener_stop(sm);
     981          16 :         ssdp_listener_stop(sm);
     982          16 :         upnp_wps_free_msearchreply(&sm->msearch_replies);
     983          16 :         upnp_wps_free_subscriptions(&sm->subscriptions, NULL);
     984             : 
     985          16 :         advertisement_state_machine_stop(sm, 1);
     986             : 
     987          16 :         event_send_stop_all(sm);
     988          16 :         os_free(sm->wlanevent);
     989          16 :         sm->wlanevent = NULL;
     990          16 :         os_free(sm->ip_addr_text);
     991          16 :         sm->ip_addr_text = NULL;
     992          16 :         if (sm->multicast_sd >= 0)
     993          16 :                 close(sm->multicast_sd);
     994          16 :         sm->multicast_sd = -1;
     995             : 
     996          16 :         sm->started = 0;
     997             : }
     998             : 
     999             : 
    1000             : /**
    1001             :  * upnp_wps_device_start - Start WPS UPnP operations on an interface
    1002             :  * @sm: WPS UPnP state machine from upnp_wps_device_init()
    1003             :  * @net_if: Selected network interface name
    1004             :  * Returns: 0 on success, -1 on failure
    1005             :  */
    1006          16 : static int upnp_wps_device_start(struct upnp_wps_device_sm *sm, char *net_if)
    1007             : {
    1008          16 :         if (!sm || !net_if)
    1009           0 :                 return -1;
    1010             : 
    1011          16 :         if (sm->started)
    1012           0 :                 upnp_wps_device_stop(sm);
    1013             : 
    1014          16 :         sm->multicast_sd = -1;
    1015          16 :         sm->ssdp_sd = -1;
    1016          16 :         sm->started = 1;
    1017          16 :         sm->advertise_count = 0;
    1018             : 
    1019             :         /* Fix up linux multicast handling */
    1020          16 :         if (add_ssdp_network(net_if))
    1021           0 :                 goto fail;
    1022             : 
    1023             :         /* Determine which IP and mac address we're using */
    1024          16 :         if (get_netif_info(net_if, &sm->ip_addr, &sm->ip_addr_text,
    1025          16 :                            sm->mac_addr)) {
    1026           0 :                 wpa_printf(MSG_INFO, "WPS UPnP: Could not get IP/MAC address "
    1027             :                            "for %s. Does it have IP address?", net_if);
    1028           0 :                 goto fail;
    1029             :         }
    1030             : 
    1031             :         /* Listen for incoming TCP connections so that others
    1032             :          * can fetch our "xml files" from us.
    1033             :          */
    1034          16 :         if (web_listener_start(sm))
    1035           0 :                 goto fail;
    1036             : 
    1037             :         /* Set up for receiving discovery (UDP) packets */
    1038          16 :         if (ssdp_listener_start(sm))
    1039           0 :                 goto fail;
    1040             : 
    1041             :         /* Set up for sending multicast */
    1042          16 :         if (ssdp_open_multicast(sm) < 0)
    1043           0 :                 goto fail;
    1044             : 
    1045             :         /*
    1046             :          * Broadcast NOTIFY messages to let the world know we exist.
    1047             :          * This is done via a state machine since the messages should not be
    1048             :          * all sent out at once.
    1049             :          */
    1050          16 :         if (advertisement_state_machine_start(sm))
    1051           0 :                 goto fail;
    1052             : 
    1053          16 :         return 0;
    1054             : 
    1055             : fail:
    1056           0 :         upnp_wps_device_stop(sm);
    1057           0 :         return -1;
    1058             : }
    1059             : 
    1060             : 
    1061             : static struct upnp_wps_device_interface *
    1062          16 : upnp_wps_get_iface(struct upnp_wps_device_sm *sm, void *priv)
    1063             : {
    1064             :         struct upnp_wps_device_interface *iface;
    1065          16 :         dl_list_for_each(iface, &sm->interfaces,
    1066             :                          struct upnp_wps_device_interface, list) {
    1067          16 :                 if (iface->priv == priv)
    1068          16 :                         return iface;
    1069             :         }
    1070           0 :         return NULL;
    1071             : }
    1072             : 
    1073             : 
    1074             : /**
    1075             :  * upnp_wps_device_deinit - Deinitialize WPS UPnP
    1076             :  * @sm: WPS UPnP state machine from upnp_wps_device_init()
    1077             :  * @priv: External context data that was used in upnp_wps_device_init() call
    1078             :  */
    1079         320 : void upnp_wps_device_deinit(struct upnp_wps_device_sm *sm, void *priv)
    1080             : {
    1081             :         struct upnp_wps_device_interface *iface;
    1082             : 
    1083         320 :         if (!sm)
    1084         304 :                 return;
    1085             : 
    1086          16 :         iface = upnp_wps_get_iface(sm, priv);
    1087          16 :         if (iface == NULL) {
    1088           0 :                 wpa_printf(MSG_ERROR, "WPS UPnP: Could not find the interface "
    1089             :                            "instance to deinit");
    1090           0 :                 return;
    1091             :         }
    1092          16 :         wpa_printf(MSG_DEBUG, "WPS UPnP: Deinit interface instance %p", iface);
    1093          16 :         if (dl_list_len(&sm->interfaces) == 1) {
    1094          16 :                 wpa_printf(MSG_DEBUG, "WPS UPnP: Deinitializing last instance "
    1095             :                            "- free global device instance");
    1096          16 :                 upnp_wps_device_stop(sm);
    1097             :         } else
    1098           0 :                 upnp_wps_free_subscriptions(&sm->subscriptions,
    1099           0 :                                             iface->wps->registrar);
    1100          16 :         dl_list_del(&iface->list);
    1101             : 
    1102          16 :         if (iface->peer.wps)
    1103          11 :                 wps_deinit(iface->peer.wps);
    1104          16 :         os_free(iface->ctx->ap_pin);
    1105          16 :         os_free(iface->ctx);
    1106          16 :         os_free(iface);
    1107             : 
    1108          16 :         if (dl_list_empty(&sm->interfaces)) {
    1109          16 :                 os_free(sm->root_dir);
    1110          16 :                 os_free(sm->desc_url);
    1111          16 :                 os_free(sm);
    1112          16 :                 shared_upnp_device = NULL;
    1113             :         }
    1114             : }
    1115             : 
    1116             : 
    1117             : /**
    1118             :  * upnp_wps_device_init - Initialize WPS UPnP
    1119             :  * @ctx: callback table; we must eventually free it
    1120             :  * @wps: Pointer to longterm WPS context
    1121             :  * @priv: External context data that will be used in callbacks
    1122             :  * @net_if: Selected network interface name
    1123             :  * Returns: WPS UPnP state or %NULL on failure
    1124             :  */
    1125             : struct upnp_wps_device_sm *
    1126          16 : upnp_wps_device_init(struct upnp_wps_device_ctx *ctx, struct wps_context *wps,
    1127             :                      void *priv, char *net_if)
    1128             : {
    1129             :         struct upnp_wps_device_sm *sm;
    1130             :         struct upnp_wps_device_interface *iface;
    1131          16 :         int start = 0;
    1132             : 
    1133          16 :         iface = os_zalloc(sizeof(*iface));
    1134          16 :         if (iface == NULL) {
    1135           0 :                 os_free(ctx->ap_pin);
    1136           0 :                 os_free(ctx);
    1137           0 :                 return NULL;
    1138             :         }
    1139          16 :         wpa_printf(MSG_DEBUG, "WPS UPnP: Init interface instance %p", iface);
    1140             : 
    1141          16 :         iface->ctx = ctx;
    1142          16 :         iface->wps = wps;
    1143          16 :         iface->priv = priv;
    1144             : 
    1145          16 :         if (shared_upnp_device) {
    1146           0 :                 wpa_printf(MSG_DEBUG, "WPS UPnP: Share existing device "
    1147             :                            "context");
    1148           0 :                 sm = shared_upnp_device;
    1149             :         } else {
    1150          16 :                 wpa_printf(MSG_DEBUG, "WPS UPnP: Initialize device context");
    1151          16 :                 sm = os_zalloc(sizeof(*sm));
    1152          16 :                 if (!sm) {
    1153           0 :                         wpa_printf(MSG_ERROR, "WPS UPnP: upnp_wps_device_init "
    1154             :                                    "failed");
    1155           0 :                         os_free(iface);
    1156           0 :                         os_free(ctx->ap_pin);
    1157           0 :                         os_free(ctx);
    1158           0 :                         return NULL;
    1159             :                 }
    1160          16 :                 shared_upnp_device = sm;
    1161             : 
    1162          16 :                 dl_list_init(&sm->msearch_replies);
    1163          16 :                 dl_list_init(&sm->subscriptions);
    1164          16 :                 dl_list_init(&sm->interfaces);
    1165          16 :                 start = 1;
    1166             :         }
    1167             : 
    1168          16 :         dl_list_add(&sm->interfaces, &iface->list);
    1169             : 
    1170          16 :         if (start && upnp_wps_device_start(sm, net_if)) {
    1171           0 :                 upnp_wps_device_deinit(sm, priv);
    1172           0 :                 return NULL;
    1173             :         }
    1174             : 
    1175             : 
    1176          16 :         return sm;
    1177             : }
    1178             : 
    1179             : 
    1180             : /**
    1181             :  * upnp_wps_subscribers - Check whether there are any event subscribers
    1182             :  * @sm: WPS UPnP state machine from upnp_wps_device_init()
    1183             :  * Returns: 0 if no subscribers, 1 if subscribers
    1184             :  */
    1185          17 : int upnp_wps_subscribers(struct upnp_wps_device_sm *sm)
    1186             : {
    1187          17 :         return !dl_list_empty(&sm->subscriptions);
    1188             : }
    1189             : 
    1190             : 
    1191          10 : int upnp_wps_set_ap_pin(struct upnp_wps_device_sm *sm, const char *ap_pin)
    1192             : {
    1193             :         struct upnp_wps_device_interface *iface;
    1194          10 :         if (sm == NULL)
    1195           1 :                 return 0;
    1196             : 
    1197          18 :         dl_list_for_each(iface, &sm->interfaces,
    1198             :                          struct upnp_wps_device_interface, list) {
    1199           9 :                 os_free(iface->ctx->ap_pin);
    1200           9 :                 if (ap_pin) {
    1201           4 :                         iface->ctx->ap_pin = os_strdup(ap_pin);
    1202           4 :                         if (iface->ctx->ap_pin == NULL)
    1203           0 :                                 return -1;
    1204             :                 } else
    1205           5 :                         iface->ctx->ap_pin = NULL;
    1206             :         }
    1207             : 
    1208           9 :         return 0;
    1209             : }

Generated by: LCOV version 1.10