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