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