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

Generated by: LCOV version 1.10