LCOV - code coverage report
Current view: top level - src/wps - wps_upnp_ssdp.c (source / functions) Hit Total Coverage
Test: wpa_supplicant/hostapd combined for hwsim test run 1475438200 Lines: 357 394 90.6 %
Date: 2016-10-02 Functions: 19 19 100.0 %

          Line data    Source code
       1             : /*
       2             :  * UPnP SSDP for WPS
       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-2013, Jouni Malinen <j@w1.fi>
       7             :  *
       8             :  * See wps_upnp.c for more details on licensing and code history.
       9             :  */
      10             : 
      11             : #include "includes.h"
      12             : 
      13             : #include <fcntl.h>
      14             : #include <sys/ioctl.h>
      15             : #include <net/route.h>
      16             : #ifdef __linux__
      17             : #include <net/if.h>
      18             : #endif /* __linux__ */
      19             : 
      20             : #include "common.h"
      21             : #include "uuid.h"
      22             : #include "eloop.h"
      23             : #include "wps.h"
      24             : #include "wps_upnp.h"
      25             : #include "wps_upnp_i.h"
      26             : 
      27             : #define UPNP_CACHE_SEC (UPNP_CACHE_SEC_MIN + 1) /* cache time we use */
      28             : #define UPNP_CACHE_SEC_MIN 1800 /* min cachable time per UPnP standard */
      29             : #define UPNP_ADVERTISE_REPEAT 2 /* no more than 3 */
      30             : #define MAX_MSEARCH 20          /* max simultaneous M-SEARCH replies ongoing */
      31             : #define SSDP_TARGET  "239.0.0.0"
      32             : #define SSDP_NETMASK "255.0.0.0"
      33             : 
      34             : 
      35             : /* Check tokens for equality, where tokens consist of letters, digits,
      36             :  * underscore and hyphen, and are matched case insensitive.
      37             :  */
      38        1454 : static int token_eq(const char *s1, const char *s2)
      39             : {
      40             :         int c1;
      41             :         int c2;
      42        1454 :         int end1 = 0;
      43        1454 :         int end2 = 0;
      44             :         for (;;) {
      45        2700 :                 c1 = *s1++;
      46        2700 :                 c2 = *s2++;
      47        2700 :                 if (isalpha(c1) && isupper(c1))
      48        1843 :                         c1 = tolower(c1);
      49        2700 :                 if (isalpha(c2) && isupper(c2))
      50           0 :                         c2 = tolower(c2);
      51        2700 :                 end1 = !(isalnum(c1) || c1 == '_' || c1 == '-');
      52        2700 :                 end2 = !(isalnum(c2) || c2 == '_' || c2 == '-');
      53        2700 :                 if (end1 || end2 || c1 != c2)
      54             :                         break;
      55        1246 :         }
      56        1454 :         return end1 && end2; /* reached end of both words? */
      57             : }
      58             : 
      59             : 
      60             : /* Return length of token (see above for definition of token) */
      61         311 : static int token_length(const char *s)
      62             : {
      63         311 :         const char *begin = s;
      64         726 :         for (;; s++) {
      65        1037 :                 int c = *s;
      66        1037 :                 int end = !(isalnum(c) || c == '_' || c == '-');
      67        1037 :                 if (end)
      68         311 :                         break;
      69         726 :         }
      70         311 :         return s - begin;
      71             : }
      72             : 
      73             : 
      74             : /* return length of interword separation.
      75             :  * This accepts only spaces/tabs and thus will not traverse a line
      76             :  * or buffer ending.
      77             :  */
      78         619 : static int word_separation_length(const char *s)
      79             : {
      80         619 :         const char *begin = s;
      81         313 :         for (;; s++) {
      82         932 :                 int c = *s;
      83         932 :                 if (c == ' ' || c == '\t')
      84         313 :                         continue;
      85         619 :                 break;
      86         313 :         }
      87         619 :         return s - begin;
      88             : }
      89             : 
      90             : 
      91             : /* No. of chars through (including) end of line */
      92         624 : static int line_length(const char *l)
      93             : {
      94         624 :         const char *lp = l;
      95       12955 :         while (*lp && *lp != '\n')
      96       11707 :                 lp++;
      97         624 :         if (*lp == '\n')
      98         623 :                 lp++;
      99         624 :         return lp - l;
     100             : }
     101             : 
     102             : 
     103             : /***************************************************************************
     104             :  * Advertisements.
     105             :  * These are multicast to the world to tell them we are here.
     106             :  * The individual packets are spread out in time to limit loss,
     107             :  * and then after a much longer period of time the whole sequence
     108             :  * is repeated again (for NOTIFYs only).
     109             :  **************************************************************************/
     110             : 
     111             : /**
     112             :  * next_advertisement - Build next message and advance the state machine
     113             :  * @a: Advertisement state
     114             :  * @islast: Buffer for indicating whether this is the last message (= 1)
     115             :  * Returns: The new message (caller is responsible for freeing this)
     116             :  *
     117             :  * Note: next_advertisement is shared code with msearchreply_* functions
     118             :  */
     119             : static struct wpabuf *
     120        1459 : next_advertisement(struct upnp_wps_device_sm *sm,
     121             :                    struct advertisement_state_machine *a, int *islast)
     122             : {
     123             :         struct wpabuf *msg;
     124        1459 :         char *NTString = "";
     125             :         char uuid_string[80];
     126             :         struct upnp_wps_device_interface *iface;
     127             : 
     128        1459 :         *islast = 0;
     129        1459 :         iface = dl_list_first(&sm->interfaces,
     130             :                               struct upnp_wps_device_interface, list);
     131        1459 :         if (!iface)
     132           0 :                 return NULL;
     133        1459 :         uuid_bin2str(iface->wps->uuid, uuid_string, sizeof(uuid_string));
     134        1459 :         msg = wpabuf_alloc(800); /* more than big enough */
     135        1459 :         if (msg == NULL)
     136           1 :                 return NULL;
     137        1458 :         switch (a->type) {
     138             :         case ADVERTISE_UP:
     139             :         case ADVERTISE_DOWN:
     140         856 :                 NTString = "NT";
     141         856 :                 wpabuf_put_str(msg, "NOTIFY * HTTP/1.1\r\n");
     142         856 :                 wpabuf_printf(msg, "HOST: %s:%d\r\n",
     143             :                               UPNP_MULTICAST_ADDRESS, UPNP_MULTICAST_PORT);
     144         856 :                 wpabuf_printf(msg, "CACHE-CONTROL: max-age=%d\r\n",
     145             :                               UPNP_CACHE_SEC);
     146         856 :                 wpabuf_printf(msg, "NTS: %s\r\n",
     147         856 :                               (a->type == ADVERTISE_UP ?
     148             :                                "ssdp:alive" : "ssdp:byebye"));
     149         856 :                 break;
     150             :         case MSEARCH_REPLY:
     151         602 :                 NTString = "ST";
     152         602 :                 wpabuf_put_str(msg, "HTTP/1.1 200 OK\r\n");
     153         602 :                 wpabuf_printf(msg, "CACHE-CONTROL: max-age=%d\r\n",
     154             :                               UPNP_CACHE_SEC);
     155             : 
     156         602 :                 wpabuf_put_str(msg, "DATE: ");
     157         602 :                 format_date(msg);
     158         602 :                 wpabuf_put_str(msg, "\r\n");
     159             : 
     160         602 :                 wpabuf_put_str(msg, "EXT:\r\n");
     161         602 :                 break;
     162             :         }
     163             : 
     164        1458 :         if (a->type != ADVERTISE_DOWN) {
     165             :                 /* Where others may get our XML files from */
     166         890 :                 wpabuf_printf(msg, "LOCATION: http://%s:%d/%s\r\n",
     167             :                               sm->ip_addr_text, sm->web_port,
     168             :                               UPNP_WPS_DEVICE_XML_FILE);
     169             :         }
     170             : 
     171             :         /* The SERVER line has three comma-separated fields:
     172             :          *      operating system / version
     173             :          *      upnp version
     174             :          *      software package / version
     175             :          * However, only the UPnP version is really required, the
     176             :          * others can be place holders... for security reasons
     177             :          * it is better to NOT provide extra information.
     178             :          */
     179        1458 :         wpabuf_put_str(msg, "SERVER: Unspecified, UPnP/1.0, Unspecified\r\n");
     180             : 
     181        1458 :         switch (a->state / UPNP_ADVERTISE_REPEAT) {
     182             :         case 0:
     183         372 :                 wpabuf_printf(msg, "%s: upnp:rootdevice\r\n", NTString);
     184         372 :                 wpabuf_printf(msg, "USN: uuid:%s::upnp:rootdevice\r\n",
     185             :                               uuid_string);
     186         372 :                 break;
     187             :         case 1:
     188         372 :                 wpabuf_printf(msg, "%s: uuid:%s\r\n", NTString, uuid_string);
     189         372 :                 wpabuf_printf(msg, "USN: uuid:%s\r\n", uuid_string);
     190         372 :                 break;
     191             :         case 2:
     192         369 :                 wpabuf_printf(msg, "%s: urn:schemas-wifialliance-org:device:"
     193             :                               "WFADevice:1\r\n", NTString);
     194         369 :                 wpabuf_printf(msg, "USN: uuid:%s::urn:schemas-wifialliance-"
     195             :                               "org:device:WFADevice:1\r\n", uuid_string);
     196         369 :                 break;
     197             :         case 3:
     198         345 :                 wpabuf_printf(msg, "%s: urn:schemas-wifialliance-org:service:"
     199             :                               "WFAWLANConfig:1\r\n", NTString);
     200         345 :                 wpabuf_printf(msg, "USN: uuid:%s::urn:schemas-wifialliance-"
     201             :                               "org:service:WFAWLANConfig:1\r\n", uuid_string);
     202         345 :                 break;
     203             :         }
     204        1458 :         wpabuf_put_str(msg, "\r\n");
     205             : 
     206        1458 :         if (a->state + 1 >= 4 * UPNP_ADVERTISE_REPEAT)
     207         170 :                 *islast = 1;
     208             : 
     209        1458 :         return msg;
     210             : }
     211             : 
     212             : 
     213             : static void advertisement_state_machine_handler(void *eloop_data,
     214             :                                                 void *user_ctx);
     215             : 
     216             : 
     217             : /**
     218             :  * advertisement_state_machine_stop - Stop SSDP advertisements
     219             :  * @sm: WPS UPnP state machine from upnp_wps_device_init()
     220             :  * @send_byebye: Send byebye advertisement messages immediately
     221             :  */
     222          74 : void advertisement_state_machine_stop(struct upnp_wps_device_sm *sm,
     223             :                                       int send_byebye)
     224             : {
     225          74 :         struct advertisement_state_machine *a = &sm->advertisement;
     226          74 :         int islast = 0;
     227             :         struct wpabuf *msg;
     228             :         struct sockaddr_in dest;
     229             : 
     230          74 :         eloop_cancel_timeout(advertisement_state_machine_handler, NULL, sm);
     231          74 :         if (!send_byebye || sm->multicast_sd < 0)
     232         112 :                 return;
     233             : 
     234          36 :         a->type = ADVERTISE_DOWN;
     235          36 :         a->state = 0;
     236             : 
     237          36 :         os_memset(&dest, 0, sizeof(dest));
     238          36 :         dest.sin_family = AF_INET;
     239          36 :         dest.sin_addr.s_addr = inet_addr(UPNP_MULTICAST_ADDRESS);
     240          36 :         dest.sin_port = htons(UPNP_MULTICAST_PORT);
     241             : 
     242         352 :         while (!islast) {
     243         281 :                 msg = next_advertisement(sm, a, &islast);
     244         281 :                 if (msg == NULL)
     245           1 :                         break;
     246         280 :                 if (sendto(sm->multicast_sd, wpabuf_head(msg), wpabuf_len(msg),
     247             :                            0, (struct sockaddr *) &dest, sizeof(dest)) < 0) {
     248           0 :                         wpa_printf(MSG_INFO, "WPS UPnP: Advertisement sendto "
     249           0 :                                    "failed: %d (%s)", errno, strerror(errno));
     250             :                 }
     251         280 :                 wpabuf_free(msg);
     252         280 :                 a->state++;
     253             :         }
     254             : }
     255             : 
     256             : 
     257         576 : static void advertisement_state_machine_handler(void *eloop_data,
     258             :                                                 void *user_ctx)
     259             : {
     260         576 :         struct upnp_wps_device_sm *sm = user_ctx;
     261         576 :         struct advertisement_state_machine *a = &sm->advertisement;
     262             :         struct wpabuf *msg;
     263         576 :         int next_timeout_msec = 100;
     264         576 :         int next_timeout_sec = 0;
     265             :         struct sockaddr_in dest;
     266         576 :         int islast = 0;
     267             : 
     268             :         /*
     269             :          * Each is sent twice (in case lost) w/ 100 msec delay between;
     270             :          * spec says no more than 3 times.
     271             :          * One pair for rootdevice, one pair for uuid, and a pair each for
     272             :          * each of the two urns.
     273             :          * The entire sequence must be repeated before cache control timeout
     274             :          * (which  is min  1800 seconds),
     275             :          * recommend random portion of half of the advertised cache control age
     276             :          * to ensure against loss... perhaps 1800/4 + rand*1800/4 ?
     277             :          * Delay random interval < 100 msec prior to initial sending.
     278             :          * TTL of 4
     279             :          */
     280             : 
     281         576 :         wpa_printf(MSG_MSGDUMP, "WPS UPnP: Advertisement state=%d", a->state);
     282         576 :         msg = next_advertisement(sm, a, &islast);
     283         576 :         if (msg == NULL)
     284         576 :                 return;
     285             : 
     286         576 :         os_memset(&dest, 0, sizeof(dest));
     287         576 :         dest.sin_family = AF_INET;
     288         576 :         dest.sin_addr.s_addr = inet_addr(UPNP_MULTICAST_ADDRESS);
     289         576 :         dest.sin_port = htons(UPNP_MULTICAST_PORT);
     290             : 
     291         576 :         if (sendto(sm->multicast_sd, wpabuf_head(msg), wpabuf_len(msg), 0,
     292             :                    (struct sockaddr *) &dest, sizeof(dest)) == -1) {
     293           0 :                 wpa_printf(MSG_ERROR, "WPS UPnP: Advertisement sendto failed:"
     294           0 :                            "%d (%s)", errno, strerror(errno));
     295           0 :                 next_timeout_msec = 0;
     296           0 :                 next_timeout_sec = 10; /* ... later */
     297         576 :         } else if (islast) {
     298          72 :                 a->state = 0; /* wrap around */
     299          72 :                 if (a->type == ADVERTISE_DOWN) {
     300          36 :                         wpa_printf(MSG_DEBUG, "WPS UPnP: ADVERTISE_DOWN->UP");
     301          36 :                         a->type = ADVERTISE_UP;
     302             :                         /* do it all over again right away */
     303             :                 } else {
     304             :                         u16 r;
     305             :                         /*
     306             :                          * Start over again after a long timeout
     307             :                          * (see notes above)
     308             :                          */
     309          36 :                         next_timeout_msec = 0;
     310          36 :                         if (os_get_random((void *) &r, sizeof(r)) < 0)
     311           0 :                                 r = 32768;
     312          36 :                         next_timeout_sec = UPNP_CACHE_SEC / 4 +
     313          36 :                                 (((UPNP_CACHE_SEC / 4) * r) >> 16);
     314          36 :                         sm->advertise_count++;
     315          36 :                         wpa_printf(MSG_DEBUG, "WPS UPnP: ADVERTISE_UP (#%u); "
     316             :                                    "next in %d sec",
     317             :                                    sm->advertise_count, next_timeout_sec);
     318             :                 }
     319             :         } else {
     320         504 :                 a->state++;
     321             :         }
     322             : 
     323         576 :         wpabuf_free(msg);
     324             : 
     325         576 :         eloop_register_timeout(next_timeout_sec, next_timeout_msec,
     326             :                                advertisement_state_machine_handler, NULL, sm);
     327             : }
     328             : 
     329             : 
     330             : /**
     331             :  * advertisement_state_machine_start - Start SSDP advertisements
     332             :  * @sm: WPS UPnP state machine from upnp_wps_device_init()
     333             :  * Returns: 0 on success, -1 on failure
     334             :  */
     335          36 : int advertisement_state_machine_start(struct upnp_wps_device_sm *sm)
     336             : {
     337          36 :         struct advertisement_state_machine *a = &sm->advertisement;
     338             :         int next_timeout_msec;
     339             : 
     340          36 :         advertisement_state_machine_stop(sm, 0);
     341             : 
     342             :         /*
     343             :          * Start out advertising down, this automatically switches
     344             :          * to advertising up which signals our restart.
     345             :          */
     346          36 :         a->type = ADVERTISE_DOWN;
     347          36 :         a->state = 0;
     348             :         /* (other fields not used here) */
     349             : 
     350             :         /* First timeout should be random interval < 100 msec */
     351          36 :         next_timeout_msec = (100 * (os_random() & 0xFF)) >> 8;
     352          36 :         return eloop_register_timeout(0, next_timeout_msec,
     353             :                                       advertisement_state_machine_handler,
     354             :                                       NULL, sm);
     355             : }
     356             : 
     357             : 
     358             : /***************************************************************************
     359             :  * M-SEARCH replies
     360             :  * These are very similar to the multicast advertisements, with some
     361             :  * small changes in data content; and they are sent (UDP) to a specific
     362             :  * unicast address instead of multicast.
     363             :  * They are sent in response to a UDP M-SEARCH packet.
     364             :  **************************************************************************/
     365             : 
     366             : /**
     367             :  * msearchreply_state_machine_stop - Stop M-SEARCH reply state machine
     368             :  * @a: Selected advertisement/reply state
     369             :  */
     370          81 : void msearchreply_state_machine_stop(struct advertisement_state_machine *a)
     371             : {
     372          81 :         wpa_printf(MSG_DEBUG, "WPS UPnP: M-SEARCH stop");
     373          81 :         dl_list_del(&a->list);
     374          81 :         os_free(a);
     375          81 : }
     376             : 
     377             : 
     378         602 : static void msearchreply_state_machine_handler(void *eloop_data,
     379             :                                                void *user_ctx)
     380             : {
     381         602 :         struct advertisement_state_machine *a = user_ctx;
     382         602 :         struct upnp_wps_device_sm *sm = eloop_data;
     383             :         struct wpabuf *msg;
     384         602 :         int next_timeout_msec = 100;
     385         602 :         int next_timeout_sec = 0;
     386         602 :         int islast = 0;
     387             : 
     388             :         /*
     389             :          * Each response is sent twice (in case lost) w/ 100 msec delay
     390             :          * between; spec says no more than 3 times.
     391             :          * One pair for rootdevice, one pair for uuid, and a pair each for
     392             :          * each of the two urns.
     393             :          */
     394             : 
     395             :         /* TODO: should only send the requested response types */
     396             : 
     397         602 :         wpa_printf(MSG_MSGDUMP, "WPS UPnP: M-SEARCH reply state=%d (%s:%d)",
     398             :                    a->state, inet_ntoa(a->client.sin_addr),
     399         602 :                    ntohs(a->client.sin_port));
     400         602 :         msg = next_advertisement(sm, a, &islast);
     401         602 :         if (msg == NULL)
     402          63 :                 return;
     403             : 
     404             :         /*
     405             :          * Send it on the multicast socket to avoid having to set up another
     406             :          * socket.
     407             :          */
     408         602 :         if (sendto(sm->multicast_sd, wpabuf_head(msg), wpabuf_len(msg), 0,
     409         602 :                    (struct sockaddr *) &a->client, sizeof(a->client)) < 0) {
     410           0 :                 wpa_printf(MSG_DEBUG, "WPS UPnP: M-SEARCH reply sendto "
     411             :                            "errno %d (%s) for %s:%d",
     412           0 :                            errno, strerror(errno),
     413             :                            inet_ntoa(a->client.sin_addr),
     414           0 :                            ntohs(a->client.sin_port));
     415             :                 /* Ignore error and hope for the best */
     416             :         }
     417         602 :         wpabuf_free(msg);
     418         602 :         if (islast) {
     419          63 :                 wpa_printf(MSG_DEBUG, "WPS UPnP: M-SEARCH reply done");
     420          63 :                 msearchreply_state_machine_stop(a);
     421          63 :                 return;
     422             :         }
     423         539 :         a->state++;
     424             : 
     425         539 :         wpa_printf(MSG_MSGDUMP, "WPS UPnP: M-SEARCH reply in %d.%03d sec",
     426             :                    next_timeout_sec, next_timeout_msec);
     427         539 :         eloop_register_timeout(next_timeout_sec, next_timeout_msec,
     428             :                                msearchreply_state_machine_handler, sm, a);
     429             : }
     430             : 
     431             : 
     432             : /**
     433             :  * msearchreply_state_machine_start - Reply to M-SEARCH discovery request
     434             :  * @sm: WPS UPnP state machine from upnp_wps_device_init()
     435             :  * @client: Client address
     436             :  * @mx: Maximum delay in seconds
     437             :  *
     438             :  * Use TTL of 4 (this was done when socket set up).
     439             :  * A response should be given in randomized portion of min(MX,120) seconds
     440             :  *
     441             :  * UPnP-arch-DeviceArchitecture, 1.2.3:
     442             :  * To be found, a device must send a UDP response to the source IP address and
     443             :  * port that sent the request to the multicast channel. Devices respond if the
     444             :  * ST header of the M-SEARCH request is "ssdp:all", "upnp:rootdevice", "uuid:"
     445             :  * followed by a UUID that exactly matches one advertised by the device.
     446             :  */
     447          93 : static void msearchreply_state_machine_start(struct upnp_wps_device_sm *sm,
     448             :                                              struct sockaddr_in *client,
     449             :                                              int mx)
     450             : {
     451             :         struct advertisement_state_machine *a;
     452             :         int next_timeout_sec;
     453             :         int next_timeout_msec;
     454             :         int replies;
     455             : 
     456          93 :         replies = dl_list_len(&sm->msearch_replies);
     457          93 :         wpa_printf(MSG_DEBUG, "WPS UPnP: M-SEARCH reply start (%d "
     458             :                    "outstanding)", replies);
     459          93 :         if (replies >= MAX_MSEARCH) {
     460          10 :                 wpa_printf(MSG_INFO, "WPS UPnP: Too many outstanding "
     461             :                            "M-SEARCH replies");
     462          10 :                 return;
     463             :         }
     464             : 
     465          83 :         a = os_zalloc(sizeof(*a));
     466          83 :         if (a == NULL)
     467           1 :                 return;
     468          82 :         a->type = MSEARCH_REPLY;
     469          82 :         a->state = 0;
     470          82 :         os_memcpy(&a->client, client, sizeof(*client));
     471             :         /* Wait time depending on MX value */
     472          82 :         next_timeout_msec = (1000 * mx * (os_random() & 0xFF)) >> 8;
     473          82 :         next_timeout_sec = next_timeout_msec / 1000;
     474          82 :         next_timeout_msec = next_timeout_msec % 1000;
     475          82 :         if (eloop_register_timeout(next_timeout_sec, next_timeout_msec,
     476             :                                    msearchreply_state_machine_handler, sm,
     477             :                                    a)) {
     478             :                 /* No way to recover (from malloc failure) */
     479           1 :                 goto fail;
     480             :         }
     481             :         /* Remember for future cleanup */
     482          81 :         dl_list_add(&sm->msearch_replies, &a->list);
     483          81 :         return;
     484             : 
     485             : fail:
     486           1 :         wpa_printf(MSG_INFO, "WPS UPnP: M-SEARCH reply failure!");
     487           1 :         eloop_cancel_timeout(msearchreply_state_machine_handler, sm, a);
     488           1 :         os_free(a);
     489             : }
     490             : 
     491             : 
     492             : /**
     493             :  * ssdp_parse_msearch - Process a received M-SEARCH
     494             :  * @sm: WPS UPnP state machine from upnp_wps_device_init()
     495             :  * @client: Client address
     496             :  * @data: NULL terminated M-SEARCH message
     497             :  *
     498             :  * Given that we have received a header w/ M-SEARCH, act upon it
     499             :  *
     500             :  * Format of M-SEARCH (case insensitive!):
     501             :  *
     502             :  * First line must be:
     503             :  *      M-SEARCH * HTTP/1.1
     504             :  * Other lines in arbitrary order:
     505             :  *      HOST:239.255.255.250:1900
     506             :  *      ST:<varies -- must match>
     507             :  *      MAN:"ssdp:discover"
     508             :  *      MX:<varies>
     509             :  *
     510             :  * It should be noted that when Microsoft Vista is still learning its IP
     511             :  * address, it sends out host lines like: HOST:[FF02::C]:1900
     512             :  */
     513         106 : static void ssdp_parse_msearch(struct upnp_wps_device_sm *sm,
     514             :                                struct sockaddr_in *client, const char *data)
     515             : {
     516             : #ifndef CONFIG_NO_STDOUT_DEBUG
     517         106 :         const char *start = data;
     518             : #endif /* CONFIG_NO_STDOUT_DEBUG */
     519         106 :         int got_host = 0;
     520         106 :         int got_st = 0, st_match = 0;
     521         106 :         int got_man = 0;
     522         106 :         int got_mx = 0;
     523         106 :         int mx = 0;
     524             : 
     525             :         /*
     526             :          * Skip first line M-SEARCH * HTTP/1.1
     527             :          * (perhaps we should check remainder of the line for syntax)
     528             :          */
     529         106 :         data += line_length(data);
     530             : 
     531             :         /* Parse remaining lines */
     532         624 :         for (; *data != '\0'; data += line_length(data)) {
     533         519 :                 if (token_eq(data, "host")) {
     534             :                         /* The host line indicates who the packet
     535             :                          * is addressed to... but do we really care?
     536             :                          * Note that Microsoft sometimes does funny
     537             :                          * stuff with the HOST: line.
     538             :                          */
     539             : #if 0   /* could be */
     540             :                         data += token_length(data);
     541             :                         data += word_separation_length(data);
     542             :                         if (*data != ':')
     543             :                                 goto bad;
     544             :                         data++;
     545             :                         data += word_separation_length(data);
     546             :                         /* UPNP_MULTICAST_ADDRESS */
     547             :                         if (!str_starts(data, "239.255.255.250"))
     548             :                                 goto bad;
     549             :                         data += os_strlen("239.255.255.250");
     550             :                         if (*data == ':') {
     551             :                                 if (!str_starts(data, ":1900"))
     552             :                                         goto bad;
     553             :                         }
     554             : #endif  /* could be */
     555         104 :                         got_host = 1;
     556         104 :                         continue;
     557         415 :                 } else if (token_eq(data, "st")) {
     558             :                         /* There are a number of forms; we look
     559             :                          * for one that matches our case.
     560             :                          */
     561         103 :                         got_st = 1;
     562         103 :                         data += token_length(data);
     563         103 :                         data += word_separation_length(data);
     564         103 :                         if (*data != ':')
     565           1 :                                 continue;
     566         102 :                         data++;
     567         102 :                         data += word_separation_length(data);
     568         102 :                         if (str_starts(data, "ssdp:all")) {
     569           1 :                                 st_match = 1;
     570           1 :                                 continue;
     571             :                         }
     572         101 :                         if (str_starts(data, "upnp:rootdevice")) {
     573           1 :                                 st_match = 1;
     574           1 :                                 continue;
     575             :                         }
     576         100 :                         if (str_starts(data, "uuid:")) {
     577             :                                 char uuid_string[80];
     578             :                                 struct upnp_wps_device_interface *iface;
     579          11 :                                 iface = dl_list_first(
     580             :                                         &sm->interfaces,
     581             :                                         struct upnp_wps_device_interface,
     582             :                                         list);
     583          11 :                                 if (!iface)
     584           0 :                                         continue;
     585          11 :                                 data += os_strlen("uuid:");
     586          11 :                                 uuid_bin2str(iface->wps->uuid, uuid_string,
     587             :                                              sizeof(uuid_string));
     588          11 :                                 if (str_starts(data, uuid_string))
     589          10 :                                         st_match = 1;
     590          11 :                                 continue;
     591             :                         }
     592             : #if 0
     593             :                         /* FIX: should we really reply to IGD string? */
     594             :                         if (str_starts(data, "urn:schemas-upnp-org:device:"
     595             :                                        "InternetGatewayDevice:1")) {
     596             :                                 st_match = 1;
     597             :                                 continue;
     598             :                         }
     599             : #endif
     600          89 :                         if (str_starts(data, "urn:schemas-wifialliance-org:"
     601             :                                        "service:WFAWLANConfig:1")) {
     602           3 :                                 st_match = 1;
     603           3 :                                 continue;
     604             :                         }
     605          86 :                         if (str_starts(data, "urn:schemas-wifialliance-org:"
     606             :                                        "device:WFADevice:1")) {
     607          84 :                                 st_match = 1;
     608          84 :                                 continue;
     609             :                         }
     610           2 :                         continue;
     611         312 :                 } else if (token_eq(data, "man")) {
     612         104 :                         data += token_length(data);
     613         104 :                         data += word_separation_length(data);
     614         104 :                         if (*data != ':')
     615           1 :                                 continue;
     616         103 :                         data++;
     617         103 :                         data += word_separation_length(data);
     618         103 :                         if (!str_starts(data, "\"ssdp:discover\"")) {
     619           1 :                                 wpa_printf(MSG_DEBUG, "WPS UPnP: Unexpected "
     620             :                                            "M-SEARCH man-field");
     621           1 :                                 goto bad;
     622             :                         }
     623         102 :                         got_man = 1;
     624         102 :                         continue;
     625         208 :                 } else if (token_eq(data, "mx")) {
     626         104 :                         data += token_length(data);
     627         104 :                         data += word_separation_length(data);
     628         104 :                         if (*data != ':')
     629           1 :                                 continue;
     630         103 :                         data++;
     631         103 :                         data += word_separation_length(data);
     632         103 :                         mx = atol(data);
     633         103 :                         got_mx = 1;
     634         103 :                         continue;
     635             :                 }
     636             :                 /* ignore anything else */
     637             :         }
     638         105 :         if (!got_host || !got_st || !got_man || !got_mx || mx < 0) {
     639           8 :                 wpa_printf(MSG_DEBUG, "WPS UPnP: Invalid M-SEARCH: %d %d %d "
     640             :                            "%d mx=%d", got_host, got_st, got_man, got_mx, mx);
     641           8 :                 goto bad;
     642             :         }
     643          97 :         if (!st_match) {
     644           4 :                 wpa_printf(MSG_DEBUG, "WPS UPnP: Ignored M-SEARCH (no ST "
     645             :                            "match)");
     646           4 :                 return;
     647             :         }
     648          93 :         if (mx > 120)
     649           1 :                 mx = 120; /* UPnP-arch-DeviceArchitecture, 1.2.3 */
     650          93 :         msearchreply_state_machine_start(sm, client, mx);
     651          93 :         return;
     652             : 
     653             : bad:
     654           9 :         wpa_printf(MSG_INFO, "WPS UPnP: Failed to parse M-SEARCH");
     655           9 :         wpa_printf(MSG_MSGDUMP, "WPS UPnP: M-SEARCH data:\n%s", start);
     656             : }
     657             : 
     658             : 
     659             : /* Listening for (UDP) discovery (M-SEARCH) packets */
     660             : 
     661             : /**
     662             :  * ssdp_listener_stop - Stop SSDP listered
     663             :  * @sm: WPS UPnP state machine from upnp_wps_device_init()
     664             :  *
     665             :  * This function stops the SSDP listener that was started by calling
     666             :  * ssdp_listener_start().
     667             :  */
     668          39 : void ssdp_listener_stop(struct upnp_wps_device_sm *sm)
     669             : {
     670          39 :         if (sm->ssdp_sd_registered) {
     671          36 :                 eloop_unregister_sock(sm->ssdp_sd, EVENT_TYPE_READ);
     672          36 :                 sm->ssdp_sd_registered = 0;
     673             :         }
     674             : 
     675          39 :         if (sm->ssdp_sd != -1) {
     676          37 :                 close(sm->ssdp_sd);
     677          37 :                 sm->ssdp_sd = -1;
     678             :         }
     679             : 
     680          39 :         eloop_cancel_timeout(msearchreply_state_machine_handler, sm,
     681             :                              ELOOP_ALL_CTX);
     682          39 : }
     683             : 
     684             : 
     685         685 : static void ssdp_listener_handler(int sd, void *eloop_ctx, void *sock_ctx)
     686             : {
     687         685 :         struct upnp_wps_device_sm *sm = sock_ctx;
     688             :         struct sockaddr_in addr; /* client address */
     689             :         socklen_t addr_len;
     690             :         int nread;
     691             :         char buf[MULTICAST_MAX_READ], *pos;
     692             : 
     693         685 :         addr_len = sizeof(addr);
     694         685 :         nread = recvfrom(sm->ssdp_sd, buf, sizeof(buf) - 1, 0,
     695             :                          (struct sockaddr *) &addr, &addr_len);
     696         685 :         if (nread <= 0)
     697         683 :                 return;
     698         685 :         buf[nread] = '\0'; /* need null termination for algorithm */
     699             : 
     700         685 :         if (str_starts(buf, "NOTIFY ")) {
     701             :                 /*
     702             :                  * Silently ignore NOTIFYs to avoid filling debug log with
     703             :                  * unwanted messages.
     704             :                  */
     705         577 :                 return;
     706             :         }
     707             : 
     708         108 :         pos = os_strchr(buf, '\n');
     709         108 :         if (pos)
     710         107 :                 *pos = '\0';
     711         108 :         wpa_printf(MSG_MSGDUMP, "WPS UPnP: Received SSDP packet from %s:%d: "
     712         108 :                    "%s", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port), buf);
     713         108 :         if (pos)
     714         107 :                 *pos = '\n';
     715             : 
     716             :         /* Parse first line */
     717         215 :         if (os_strncasecmp(buf, "M-SEARCH", os_strlen("M-SEARCH")) == 0 &&
     718         107 :             !isgraph(buf[strlen("M-SEARCH")])) {
     719         106 :                 ssdp_parse_msearch(sm, &addr, buf);
     720         106 :                 return;
     721             :         }
     722             : 
     723             :         /* Ignore anything else */
     724             : }
     725             : 
     726             : 
     727          89 : int ssdp_listener_open(void)
     728             : {
     729             :         struct sockaddr_in addr;
     730             :         struct ip_mreq mcast_addr;
     731          89 :         int on = 1;
     732             :         /* per UPnP spec, keep IP packet time to live (TTL) small */
     733          89 :         unsigned char ttl = 4;
     734             :         int sd;
     735             : 
     736          89 :         sd = socket(AF_INET, SOCK_DGRAM, 0);
     737         178 :         if (sd < 0 ||
     738         178 :             fcntl(sd, F_SETFL, O_NONBLOCK) != 0 ||
     739          89 :             setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)))
     740             :                 goto fail;
     741          89 :         os_memset(&addr, 0, sizeof(addr));
     742          89 :         addr.sin_family = AF_INET;
     743          89 :         addr.sin_addr.s_addr = htonl(INADDR_ANY);
     744          89 :         addr.sin_port = htons(UPNP_MULTICAST_PORT);
     745          89 :         if (bind(sd, (struct sockaddr *) &addr, sizeof(addr)))
     746           0 :                 goto fail;
     747          89 :         os_memset(&mcast_addr, 0, sizeof(mcast_addr));
     748          89 :         mcast_addr.imr_interface.s_addr = htonl(INADDR_ANY);
     749          89 :         mcast_addr.imr_multiaddr.s_addr = inet_addr(UPNP_MULTICAST_ADDRESS);
     750          89 :         if (setsockopt(sd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
     751          89 :                        (char *) &mcast_addr, sizeof(mcast_addr)) ||
     752          89 :             setsockopt(sd, IPPROTO_IP, IP_MULTICAST_TTL,
     753             :                        &ttl, sizeof(ttl)))
     754             :                 goto fail;
     755             : 
     756          89 :         return sd;
     757             : 
     758             : fail:
     759           0 :         if (sd >= 0)
     760           0 :                 close(sd);
     761           0 :         return -1;
     762             : }
     763             : 
     764             : 
     765             : /**
     766             :  * ssdp_listener_start - Set up for receiving discovery (UDP) packets
     767             :  * @sm: WPS UPnP state machine from upnp_wps_device_init()
     768             :  * Returns: 0 on success, -1 on failure
     769             :  *
     770             :  * The SSDP listener is stopped by calling ssdp_listener_stop().
     771             :  */
     772          37 : int ssdp_listener_start(struct upnp_wps_device_sm *sm)
     773             : {
     774          37 :         sm->ssdp_sd = ssdp_listener_open();
     775             : 
     776          37 :         if (eloop_register_sock(sm->ssdp_sd, EVENT_TYPE_READ,
     777             :                                 ssdp_listener_handler, NULL, sm))
     778           1 :                 goto fail;
     779          36 :         sm->ssdp_sd_registered = 1;
     780          36 :         return 0;
     781             : 
     782             : fail:
     783             :         /* Error */
     784           1 :         wpa_printf(MSG_ERROR, "WPS UPnP: ssdp_listener_start failed");
     785           1 :         ssdp_listener_stop(sm);
     786           1 :         return -1;
     787             : }
     788             : 
     789             : 
     790             : /**
     791             :  * add_ssdp_network - Add routing entry for SSDP
     792             :  * @net_if: Selected network interface name
     793             :  * Returns: 0 on success, -1 on failure
     794             :  *
     795             :  * This function assures that the multicast address will be properly
     796             :  * handled by Linux networking code (by a modification to routing tables).
     797             :  * This must be done per network interface. It really only needs to be done
     798             :  * once after booting up, but it does not hurt to call this more frequently
     799             :  * "to be safe".
     800             :  */
     801          90 : int add_ssdp_network(const char *net_if)
     802             : {
     803             : #ifdef __linux__
     804          90 :         int ret = -1;
     805          90 :         int sock = -1;
     806             :         struct rtentry rt;
     807             :         struct sockaddr_in *sin;
     808             : 
     809          90 :         if (!net_if)
     810           0 :                 goto fail;
     811             : 
     812          90 :         os_memset(&rt, 0, sizeof(rt));
     813          90 :         sock = socket(AF_INET, SOCK_DGRAM, 0);
     814          90 :         if (sock < 0)
     815           0 :                 goto fail;
     816             : 
     817          90 :         rt.rt_dev = (char *) net_if;
     818          90 :         sin = aliasing_hide_typecast(&rt.rt_dst, struct sockaddr_in);
     819          90 :         sin->sin_family = AF_INET;
     820          90 :         sin->sin_port = 0;
     821          90 :         sin->sin_addr.s_addr = inet_addr(SSDP_TARGET);
     822          90 :         sin = aliasing_hide_typecast(&rt.rt_genmask, struct sockaddr_in);
     823          90 :         sin->sin_family = AF_INET;
     824          90 :         sin->sin_port = 0;
     825          90 :         sin->sin_addr.s_addr = inet_addr(SSDP_NETMASK);
     826          90 :         rt.rt_flags = RTF_UP;
     827          90 :         if (ioctl(sock, SIOCADDRT, &rt) < 0) {
     828          84 :                 if (errno == EPERM) {
     829           0 :                         wpa_printf(MSG_DEBUG, "add_ssdp_network: No "
     830             :                                    "permissions to add routing table entry");
     831             :                         /* Continue to allow testing as non-root */
     832          84 :                 } else if (errno != EEXIST) {
     833           0 :                         wpa_printf(MSG_INFO, "add_ssdp_network() ioctl errno "
     834           0 :                                    "%d (%s)", errno, strerror(errno));
     835           0 :                         goto fail;
     836             :                 }
     837             :         }
     838             : 
     839          90 :         ret = 0;
     840             : 
     841             : fail:
     842          90 :         if (sock >= 0)
     843          90 :                 close(sock);
     844             : 
     845          90 :         return ret;
     846             : #else /* __linux__ */
     847             :         return 0;
     848             : #endif /* __linux__ */
     849             : }
     850             : 
     851             : 
     852          88 : int ssdp_open_multicast_sock(u32 ip_addr, const char *forced_ifname)
     853             : {
     854             :         int sd;
     855             :          /* per UPnP-arch-DeviceArchitecture, 1. Discovery, keep IP packet
     856             :           * time to live (TTL) small */
     857          88 :         unsigned char ttl = 4;
     858             : 
     859          88 :         sd = socket(AF_INET, SOCK_DGRAM, 0);
     860          88 :         if (sd < 0)
     861           0 :                 return -1;
     862             : 
     863          88 :         if (forced_ifname) {
     864             : #ifdef __linux__
     865             :                 struct ifreq req;
     866          52 :                 os_memset(&req, 0, sizeof(req));
     867          52 :                 os_strlcpy(req.ifr_name, forced_ifname, sizeof(req.ifr_name));
     868          52 :                 if (setsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, &req,
     869             :                                sizeof(req)) < 0) {
     870           0 :                         wpa_printf(MSG_INFO, "WPS UPnP: Failed to bind "
     871             :                                    "multicast socket to ifname %s: %s",
     872           0 :                                    forced_ifname, strerror(errno));
     873           0 :                         close(sd);
     874           0 :                         return -1;
     875             :                 }
     876             : #endif /* __linux__ */
     877             :         }
     878             : 
     879             : #if 0   /* maybe ok if we sometimes block on writes */
     880             :         if (fcntl(sd, F_SETFL, O_NONBLOCK) != 0) {
     881             :                 close(sd);
     882             :                 return -1;
     883             :         }
     884             : #endif
     885             : 
     886          88 :         if (setsockopt(sd, IPPROTO_IP, IP_MULTICAST_IF,
     887             :                        &ip_addr, sizeof(ip_addr))) {
     888           0 :                 wpa_printf(MSG_DEBUG, "WPS: setsockopt(IP_MULTICAST_IF) %x: "
     889           0 :                            "%d (%s)", ip_addr, errno, strerror(errno));
     890           0 :                 close(sd);
     891           0 :                 return -1;
     892             :         }
     893          88 :         if (setsockopt(sd, IPPROTO_IP, IP_MULTICAST_TTL,
     894             :                        &ttl, sizeof(ttl))) {
     895           0 :                 wpa_printf(MSG_DEBUG, "WPS: setsockopt(IP_MULTICAST_TTL): "
     896           0 :                            "%d (%s)", errno, strerror(errno));
     897           0 :                 close(sd);
     898           0 :                 return -1;
     899             :         }
     900             : 
     901             : #if 0   /* not needed, because we don't receive using multicast_sd */
     902             :         {
     903             :                 struct ip_mreq mreq;
     904             :                 mreq.imr_multiaddr.s_addr = inet_addr(UPNP_MULTICAST_ADDRESS);
     905             :                 mreq.imr_interface.s_addr = ip_addr;
     906             :                 wpa_printf(MSG_DEBUG, "WPS UPnP: Multicast addr 0x%x if addr "
     907             :                            "0x%x",
     908             :                            mreq.imr_multiaddr.s_addr,
     909             :                            mreq.imr_interface.s_addr);
     910             :                 if (setsockopt(sd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq,
     911             :                                 sizeof(mreq))) {
     912             :                         wpa_printf(MSG_ERROR,
     913             :                                    "WPS UPnP: setsockopt "
     914             :                                    "IP_ADD_MEMBERSHIP errno %d (%s)",
     915             :                                    errno, strerror(errno));
     916             :                         close(sd);
     917             :                         return -1;
     918             :                 }
     919             :         }
     920             : #endif  /* not needed */
     921             : 
     922             :         /*
     923             :          * TODO: What about IP_MULTICAST_LOOP? It seems to be on by default?
     924             :          * which aids debugging I suppose but isn't really necessary?
     925             :          */
     926             : 
     927          88 :         return sd;
     928             : }
     929             : 
     930             : 
     931             : /**
     932             :  * ssdp_open_multicast - Open socket for sending multicast SSDP messages
     933             :  * @sm: WPS UPnP state machine from upnp_wps_device_init()
     934             :  * Returns: 0 on success, -1 on failure
     935             :  */
     936          36 : int ssdp_open_multicast(struct upnp_wps_device_sm *sm)
     937             : {
     938          36 :         sm->multicast_sd = ssdp_open_multicast_sock(sm->ip_addr, NULL);
     939          36 :         if (sm->multicast_sd < 0)
     940           0 :                 return -1;
     941          36 :         return 0;
     942             : }

Generated by: LCOV version 1.10