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