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