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