1189251Ssam/*
2189251Ssam * UPnP SSDP for WPS
3189251Ssam * Copyright (c) 2000-2003 Intel Corporation
4189251Ssam * Copyright (c) 2006-2007 Sony Corporation
5189251Ssam * Copyright (c) 2008-2009 Atheros Communications
6281806Srpaulo * Copyright (c) 2009-2013, Jouni Malinen <j@w1.fi>
7189251Ssam *
8189251Ssam * See wps_upnp.c for more details on licensing and code history.
9189251Ssam */
10189251Ssam
11189251Ssam#include "includes.h"
12189251Ssam
13189251Ssam#include <fcntl.h>
14189251Ssam#include <sys/ioctl.h>
15189251Ssam#include <net/route.h>
16281806Srpaulo#ifdef __linux__
17281806Srpaulo#include <net/if.h>
18281806Srpaulo#endif /* __linux__ */
19189251Ssam
20189251Ssam#include "common.h"
21189251Ssam#include "uuid.h"
22189251Ssam#include "eloop.h"
23189251Ssam#include "wps.h"
24189251Ssam#include "wps_upnp.h"
25189251Ssam#include "wps_upnp_i.h"
26189251Ssam
27189251Ssam#define UPNP_CACHE_SEC (UPNP_CACHE_SEC_MIN + 1) /* cache time we use */
28189251Ssam#define UPNP_CACHE_SEC_MIN 1800 /* min cachable time per UPnP standard */
29189251Ssam#define UPNP_ADVERTISE_REPEAT 2 /* no more than 3 */
30189251Ssam#define MAX_MSEARCH 20          /* max simultaneous M-SEARCH replies ongoing */
31189251Ssam#define SSDP_TARGET  "239.0.0.0"
32189251Ssam#define SSDP_NETMASK "255.0.0.0"
33189251Ssam
34189251Ssam
35189251Ssam/* Check tokens for equality, where tokens consist of letters, digits,
36189251Ssam * underscore and hyphen, and are matched case insensitive.
37189251Ssam */
38189251Ssamstatic int token_eq(const char *s1, const char *s2)
39189251Ssam{
40189251Ssam	int c1;
41189251Ssam	int c2;
42189251Ssam	int end1 = 0;
43189251Ssam	int end2 = 0;
44189251Ssam	for (;;) {
45189251Ssam		c1 = *s1++;
46189251Ssam		c2 = *s2++;
47189251Ssam		if (isalpha(c1) && isupper(c1))
48189251Ssam			c1 = tolower(c1);
49189251Ssam		if (isalpha(c2) && isupper(c2))
50189251Ssam			c2 = tolower(c2);
51189251Ssam		end1 = !(isalnum(c1) || c1 == '_' || c1 == '-');
52189251Ssam		end2 = !(isalnum(c2) || c2 == '_' || c2 == '-');
53189251Ssam		if (end1 || end2 || c1 != c2)
54189251Ssam			break;
55189251Ssam	}
56189251Ssam	return end1 && end2; /* reached end of both words? */
57189251Ssam}
58189251Ssam
59189251Ssam
60189251Ssam/* Return length of token (see above for definition of token) */
61189251Ssamstatic int token_length(const char *s)
62189251Ssam{
63189251Ssam	const char *begin = s;
64189251Ssam	for (;; s++) {
65189251Ssam		int c = *s;
66189251Ssam		int end = !(isalnum(c) || c == '_' || c == '-');
67189251Ssam		if (end)
68189251Ssam			break;
69189251Ssam	}
70189251Ssam	return s - begin;
71189251Ssam}
72189251Ssam
73189251Ssam
74189251Ssam/* return length of interword separation.
75189251Ssam * This accepts only spaces/tabs and thus will not traverse a line
76189251Ssam * or buffer ending.
77189251Ssam */
78189251Ssamstatic int word_separation_length(const char *s)
79189251Ssam{
80189251Ssam	const char *begin = s;
81189251Ssam	for (;; s++) {
82189251Ssam		int c = *s;
83189251Ssam		if (c == ' ' || c == '\t')
84189251Ssam			continue;
85189251Ssam		break;
86189251Ssam	}
87189251Ssam	return s - begin;
88189251Ssam}
89189251Ssam
90189251Ssam
91189251Ssam/* No. of chars through (including) end of line */
92189251Ssamstatic int line_length(const char *l)
93189251Ssam{
94189251Ssam	const char *lp = l;
95189251Ssam	while (*lp && *lp != '\n')
96189251Ssam		lp++;
97189251Ssam	if (*lp == '\n')
98189251Ssam		lp++;
99189251Ssam	return lp - l;
100189251Ssam}
101189251Ssam
102189251Ssam
103189251Ssam/***************************************************************************
104189251Ssam * Advertisements.
105189251Ssam * These are multicast to the world to tell them we are here.
106189251Ssam * The individual packets are spread out in time to limit loss,
107189251Ssam * and then after a much longer period of time the whole sequence
108189251Ssam * is repeated again (for NOTIFYs only).
109189251Ssam **************************************************************************/
110189251Ssam
111189251Ssam/**
112189251Ssam * next_advertisement - Build next message and advance the state machine
113189251Ssam * @a: Advertisement state
114189251Ssam * @islast: Buffer for indicating whether this is the last message (= 1)
115189251Ssam * Returns: The new message (caller is responsible for freeing this)
116189251Ssam *
117189251Ssam * Note: next_advertisement is shared code with msearchreply_* functions
118189251Ssam */
119189251Ssamstatic struct wpabuf *
120214734Srpaulonext_advertisement(struct upnp_wps_device_sm *sm,
121214734Srpaulo		   struct advertisement_state_machine *a, int *islast)
122189251Ssam{
123189251Ssam	struct wpabuf *msg;
124189251Ssam	char *NTString = "";
125189251Ssam	char uuid_string[80];
126252726Srpaulo	struct upnp_wps_device_interface *iface;
127189251Ssam
128189251Ssam	*islast = 0;
129252726Srpaulo	iface = dl_list_first(&sm->interfaces,
130252726Srpaulo			      struct upnp_wps_device_interface, list);
131281806Srpaulo	if (!iface)
132281806Srpaulo		return NULL;
133252726Srpaulo	uuid_bin2str(iface->wps->uuid, uuid_string, sizeof(uuid_string));
134189251Ssam	msg = wpabuf_alloc(800); /* more than big enough */
135189251Ssam	if (msg == NULL)
136289549Srpaulo		return NULL;
137189251Ssam	switch (a->type) {
138189251Ssam	case ADVERTISE_UP:
139189251Ssam	case ADVERTISE_DOWN:
140189251Ssam		NTString = "NT";
141189251Ssam		wpabuf_put_str(msg, "NOTIFY * HTTP/1.1\r\n");
142189251Ssam		wpabuf_printf(msg, "HOST: %s:%d\r\n",
143189251Ssam			      UPNP_MULTICAST_ADDRESS, UPNP_MULTICAST_PORT);
144189251Ssam		wpabuf_printf(msg, "CACHE-CONTROL: max-age=%d\r\n",
145189251Ssam			      UPNP_CACHE_SEC);
146189251Ssam		wpabuf_printf(msg, "NTS: %s\r\n",
147189251Ssam			      (a->type == ADVERTISE_UP ?
148189251Ssam			       "ssdp:alive" : "ssdp:byebye"));
149189251Ssam		break;
150189251Ssam	case MSEARCH_REPLY:
151189251Ssam		NTString = "ST";
152189251Ssam		wpabuf_put_str(msg, "HTTP/1.1 200 OK\r\n");
153189251Ssam		wpabuf_printf(msg, "CACHE-CONTROL: max-age=%d\r\n",
154189251Ssam			      UPNP_CACHE_SEC);
155189251Ssam
156189251Ssam		wpabuf_put_str(msg, "DATE: ");
157189251Ssam		format_date(msg);
158189251Ssam		wpabuf_put_str(msg, "\r\n");
159189251Ssam
160189251Ssam		wpabuf_put_str(msg, "EXT:\r\n");
161189251Ssam		break;
162189251Ssam	}
163189251Ssam
164189251Ssam	if (a->type != ADVERTISE_DOWN) {
165189251Ssam		/* Where others may get our XML files from */
166189251Ssam		wpabuf_printf(msg, "LOCATION: http://%s:%d/%s\r\n",
167214734Srpaulo			      sm->ip_addr_text, sm->web_port,
168189251Ssam			      UPNP_WPS_DEVICE_XML_FILE);
169189251Ssam	}
170189251Ssam
171189251Ssam	/* The SERVER line has three comma-separated fields:
172189251Ssam	 *      operating system / version
173189251Ssam	 *      upnp version
174189251Ssam	 *      software package / version
175189251Ssam	 * However, only the UPnP version is really required, the
176189251Ssam	 * others can be place holders... for security reasons
177189251Ssam	 * it is better to NOT provide extra information.
178189251Ssam	 */
179189251Ssam	wpabuf_put_str(msg, "SERVER: Unspecified, UPnP/1.0, Unspecified\r\n");
180189251Ssam
181189251Ssam	switch (a->state / UPNP_ADVERTISE_REPEAT) {
182189251Ssam	case 0:
183189251Ssam		wpabuf_printf(msg, "%s: upnp:rootdevice\r\n", NTString);
184189251Ssam		wpabuf_printf(msg, "USN: uuid:%s::upnp:rootdevice\r\n",
185189251Ssam			      uuid_string);
186189251Ssam		break;
187189251Ssam	case 1:
188189251Ssam		wpabuf_printf(msg, "%s: uuid:%s\r\n", NTString, uuid_string);
189189251Ssam		wpabuf_printf(msg, "USN: uuid:%s\r\n", uuid_string);
190189251Ssam		break;
191189251Ssam	case 2:
192189251Ssam		wpabuf_printf(msg, "%s: urn:schemas-wifialliance-org:device:"
193189251Ssam			      "WFADevice:1\r\n", NTString);
194189251Ssam		wpabuf_printf(msg, "USN: uuid:%s::urn:schemas-wifialliance-"
195189251Ssam			      "org:device:WFADevice:1\r\n", uuid_string);
196189251Ssam		break;
197189251Ssam	case 3:
198189251Ssam		wpabuf_printf(msg, "%s: urn:schemas-wifialliance-org:service:"
199189251Ssam			      "WFAWLANConfig:1\r\n", NTString);
200189251Ssam		wpabuf_printf(msg, "USN: uuid:%s::urn:schemas-wifialliance-"
201189251Ssam			      "org:service:WFAWLANConfig:1\r\n", uuid_string);
202189251Ssam		break;
203189251Ssam	}
204189251Ssam	wpabuf_put_str(msg, "\r\n");
205189251Ssam
206189251Ssam	if (a->state + 1 >= 4 * UPNP_ADVERTISE_REPEAT)
207189251Ssam		*islast = 1;
208189251Ssam
209189251Ssam	return msg;
210189251Ssam}
211189251Ssam
212189251Ssam
213189251Ssamstatic void advertisement_state_machine_handler(void *eloop_data,
214189251Ssam						void *user_ctx);
215189251Ssam
216189251Ssam
217189251Ssam/**
218189251Ssam * advertisement_state_machine_stop - Stop SSDP advertisements
219189251Ssam * @sm: WPS UPnP state machine from upnp_wps_device_init()
220209158Srpaulo * @send_byebye: Send byebye advertisement messages immediately
221189251Ssam */
222209158Srpaulovoid advertisement_state_machine_stop(struct upnp_wps_device_sm *sm,
223209158Srpaulo				      int send_byebye)
224189251Ssam{
225209158Srpaulo	struct advertisement_state_machine *a = &sm->advertisement;
226209158Srpaulo	int islast = 0;
227209158Srpaulo	struct wpabuf *msg;
228209158Srpaulo	struct sockaddr_in dest;
229209158Srpaulo
230189251Ssam	eloop_cancel_timeout(advertisement_state_machine_handler, NULL, sm);
231209158Srpaulo	if (!send_byebye || sm->multicast_sd < 0)
232209158Srpaulo		return;
233209158Srpaulo
234209158Srpaulo	a->type = ADVERTISE_DOWN;
235209158Srpaulo	a->state = 0;
236209158Srpaulo
237209158Srpaulo	os_memset(&dest, 0, sizeof(dest));
238209158Srpaulo	dest.sin_family = AF_INET;
239209158Srpaulo	dest.sin_addr.s_addr = inet_addr(UPNP_MULTICAST_ADDRESS);
240209158Srpaulo	dest.sin_port = htons(UPNP_MULTICAST_PORT);
241209158Srpaulo
242209158Srpaulo	while (!islast) {
243214734Srpaulo		msg = next_advertisement(sm, a, &islast);
244209158Srpaulo		if (msg == NULL)
245209158Srpaulo			break;
246209158Srpaulo		if (sendto(sm->multicast_sd, wpabuf_head(msg), wpabuf_len(msg),
247209158Srpaulo			   0, (struct sockaddr *) &dest, sizeof(dest)) < 0) {
248209158Srpaulo			wpa_printf(MSG_INFO, "WPS UPnP: Advertisement sendto "
249209158Srpaulo				   "failed: %d (%s)", errno, strerror(errno));
250209158Srpaulo		}
251209158Srpaulo		wpabuf_free(msg);
252209158Srpaulo		a->state++;
253209158Srpaulo	}
254189251Ssam}
255189251Ssam
256189251Ssam
257189251Ssamstatic void advertisement_state_machine_handler(void *eloop_data,
258189251Ssam						void *user_ctx)
259189251Ssam{
260189251Ssam	struct upnp_wps_device_sm *sm = user_ctx;
261189251Ssam	struct advertisement_state_machine *a = &sm->advertisement;
262189251Ssam	struct wpabuf *msg;
263189251Ssam	int next_timeout_msec = 100;
264189251Ssam	int next_timeout_sec = 0;
265189251Ssam	struct sockaddr_in dest;
266189251Ssam	int islast = 0;
267189251Ssam
268189251Ssam	/*
269189251Ssam	 * Each is sent twice (in case lost) w/ 100 msec delay between;
270189251Ssam	 * spec says no more than 3 times.
271189251Ssam	 * One pair for rootdevice, one pair for uuid, and a pair each for
272189251Ssam	 * each of the two urns.
273189251Ssam	 * The entire sequence must be repeated before cache control timeout
274189251Ssam	 * (which  is min  1800 seconds),
275189251Ssam	 * recommend random portion of half of the advertised cache control age
276189251Ssam	 * to ensure against loss... perhaps 1800/4 + rand*1800/4 ?
277189251Ssam	 * Delay random interval < 100 msec prior to initial sending.
278189251Ssam	 * TTL of 4
279189251Ssam	 */
280189251Ssam
281189251Ssam	wpa_printf(MSG_MSGDUMP, "WPS UPnP: Advertisement state=%d", a->state);
282214734Srpaulo	msg = next_advertisement(sm, a, &islast);
283189251Ssam	if (msg == NULL)
284189251Ssam		return;
285189251Ssam
286189251Ssam	os_memset(&dest, 0, sizeof(dest));
287189251Ssam	dest.sin_family = AF_INET;
288189251Ssam	dest.sin_addr.s_addr = inet_addr(UPNP_MULTICAST_ADDRESS);
289189251Ssam	dest.sin_port = htons(UPNP_MULTICAST_PORT);
290189251Ssam
291189251Ssam	if (sendto(sm->multicast_sd, wpabuf_head(msg), wpabuf_len(msg), 0,
292189251Ssam		   (struct sockaddr *) &dest, sizeof(dest)) == -1) {
293189251Ssam		wpa_printf(MSG_ERROR, "WPS UPnP: Advertisement sendto failed:"
294189251Ssam			   "%d (%s)", errno, strerror(errno));
295189251Ssam		next_timeout_msec = 0;
296189251Ssam		next_timeout_sec = 10; /* ... later */
297189251Ssam	} else if (islast) {
298189251Ssam		a->state = 0; /* wrap around */
299189251Ssam		if (a->type == ADVERTISE_DOWN) {
300189251Ssam			wpa_printf(MSG_DEBUG, "WPS UPnP: ADVERTISE_DOWN->UP");
301189251Ssam			a->type = ADVERTISE_UP;
302189251Ssam			/* do it all over again right away */
303189251Ssam		} else {
304189251Ssam			u16 r;
305189251Ssam			/*
306189251Ssam			 * Start over again after a long timeout
307189251Ssam			 * (see notes above)
308189251Ssam			 */
309189251Ssam			next_timeout_msec = 0;
310281806Srpaulo			if (os_get_random((void *) &r, sizeof(r)) < 0)
311281806Srpaulo				r = 32768;
312189251Ssam			next_timeout_sec = UPNP_CACHE_SEC / 4 +
313189251Ssam				(((UPNP_CACHE_SEC / 4) * r) >> 16);
314189251Ssam			sm->advertise_count++;
315189251Ssam			wpa_printf(MSG_DEBUG, "WPS UPnP: ADVERTISE_UP (#%u); "
316189251Ssam				   "next in %d sec",
317189251Ssam				   sm->advertise_count, next_timeout_sec);
318189251Ssam		}
319189251Ssam	} else {
320189251Ssam		a->state++;
321189251Ssam	}
322189251Ssam
323189251Ssam	wpabuf_free(msg);
324189251Ssam
325189251Ssam	eloop_register_timeout(next_timeout_sec, next_timeout_msec,
326189251Ssam			       advertisement_state_machine_handler, NULL, sm);
327189251Ssam}
328189251Ssam
329189251Ssam
330189251Ssam/**
331189251Ssam * advertisement_state_machine_start - Start SSDP advertisements
332189251Ssam * @sm: WPS UPnP state machine from upnp_wps_device_init()
333189251Ssam * Returns: 0 on success, -1 on failure
334189251Ssam */
335189251Ssamint advertisement_state_machine_start(struct upnp_wps_device_sm *sm)
336189251Ssam{
337189251Ssam	struct advertisement_state_machine *a = &sm->advertisement;
338189251Ssam	int next_timeout_msec;
339189251Ssam
340209158Srpaulo	advertisement_state_machine_stop(sm, 0);
341189251Ssam
342189251Ssam	/*
343189251Ssam	 * Start out advertising down, this automatically switches
344189251Ssam	 * to advertising up which signals our restart.
345189251Ssam	 */
346189251Ssam	a->type = ADVERTISE_DOWN;
347189251Ssam	a->state = 0;
348189251Ssam	/* (other fields not used here) */
349189251Ssam
350189251Ssam	/* First timeout should be random interval < 100 msec */
351189251Ssam	next_timeout_msec = (100 * (os_random() & 0xFF)) >> 8;
352189251Ssam	return eloop_register_timeout(0, next_timeout_msec,
353189251Ssam				      advertisement_state_machine_handler,
354189251Ssam				      NULL, sm);
355189251Ssam}
356189251Ssam
357189251Ssam
358189251Ssam/***************************************************************************
359189251Ssam * M-SEARCH replies
360189251Ssam * These are very similar to the multicast advertisements, with some
361189251Ssam * small changes in data content; and they are sent (UDP) to a specific
362189251Ssam * unicast address instead of multicast.
363189251Ssam * They are sent in response to a UDP M-SEARCH packet.
364189251Ssam **************************************************************************/
365189251Ssam
366189251Ssam/**
367189251Ssam * msearchreply_state_machine_stop - Stop M-SEARCH reply state machine
368189251Ssam * @a: Selected advertisement/reply state
369189251Ssam */
370189251Ssamvoid msearchreply_state_machine_stop(struct advertisement_state_machine *a)
371189251Ssam{
372189251Ssam	wpa_printf(MSG_DEBUG, "WPS UPnP: M-SEARCH stop");
373214734Srpaulo	dl_list_del(&a->list);
374189251Ssam	os_free(a);
375189251Ssam}
376189251Ssam
377189251Ssam
378189251Ssamstatic void msearchreply_state_machine_handler(void *eloop_data,
379189251Ssam					       void *user_ctx)
380189251Ssam{
381189251Ssam	struct advertisement_state_machine *a = user_ctx;
382214734Srpaulo	struct upnp_wps_device_sm *sm = eloop_data;
383189251Ssam	struct wpabuf *msg;
384189251Ssam	int next_timeout_msec = 100;
385189251Ssam	int next_timeout_sec = 0;
386189251Ssam	int islast = 0;
387189251Ssam
388189251Ssam	/*
389189251Ssam	 * Each response is sent twice (in case lost) w/ 100 msec delay
390189251Ssam	 * between; spec says no more than 3 times.
391189251Ssam	 * One pair for rootdevice, one pair for uuid, and a pair each for
392189251Ssam	 * each of the two urns.
393189251Ssam	 */
394189251Ssam
395189251Ssam	/* TODO: should only send the requested response types */
396189251Ssam
397189251Ssam	wpa_printf(MSG_MSGDUMP, "WPS UPnP: M-SEARCH reply state=%d (%s:%d)",
398189251Ssam		   a->state, inet_ntoa(a->client.sin_addr),
399189251Ssam		   ntohs(a->client.sin_port));
400214734Srpaulo	msg = next_advertisement(sm, a, &islast);
401189251Ssam	if (msg == NULL)
402189251Ssam		return;
403189251Ssam
404189251Ssam	/*
405189251Ssam	 * Send it on the multicast socket to avoid having to set up another
406189251Ssam	 * socket.
407189251Ssam	 */
408189251Ssam	if (sendto(sm->multicast_sd, wpabuf_head(msg), wpabuf_len(msg), 0,
409189251Ssam		   (struct sockaddr *) &a->client, sizeof(a->client)) < 0) {
410189251Ssam		wpa_printf(MSG_DEBUG, "WPS UPnP: M-SEARCH reply sendto "
411189251Ssam			   "errno %d (%s) for %s:%d",
412189251Ssam			   errno, strerror(errno),
413189251Ssam			   inet_ntoa(a->client.sin_addr),
414189251Ssam			   ntohs(a->client.sin_port));
415189251Ssam		/* Ignore error and hope for the best */
416189251Ssam	}
417189251Ssam	wpabuf_free(msg);
418189251Ssam	if (islast) {
419189251Ssam		wpa_printf(MSG_DEBUG, "WPS UPnP: M-SEARCH reply done");
420189251Ssam		msearchreply_state_machine_stop(a);
421189251Ssam		return;
422189251Ssam	}
423189251Ssam	a->state++;
424189251Ssam
425189251Ssam	wpa_printf(MSG_MSGDUMP, "WPS UPnP: M-SEARCH reply in %d.%03d sec",
426189251Ssam		   next_timeout_sec, next_timeout_msec);
427189251Ssam	eloop_register_timeout(next_timeout_sec, next_timeout_msec,
428189251Ssam			       msearchreply_state_machine_handler, sm, a);
429189251Ssam}
430189251Ssam
431189251Ssam
432189251Ssam/**
433189251Ssam * msearchreply_state_machine_start - Reply to M-SEARCH discovery request
434189251Ssam * @sm: WPS UPnP state machine from upnp_wps_device_init()
435189251Ssam * @client: Client address
436189251Ssam * @mx: Maximum delay in seconds
437189251Ssam *
438189251Ssam * Use TTL of 4 (this was done when socket set up).
439189251Ssam * A response should be given in randomized portion of min(MX,120) seconds
440189251Ssam *
441189251Ssam * UPnP-arch-DeviceArchitecture, 1.2.3:
442189251Ssam * To be found, a device must send a UDP response to the source IP address and
443189251Ssam * port that sent the request to the multicast channel. Devices respond if the
444189251Ssam * ST header of the M-SEARCH request is "ssdp:all", "upnp:rootdevice", "uuid:"
445189251Ssam * followed by a UUID that exactly matches one advertised by the device.
446189251Ssam */
447189251Ssamstatic void msearchreply_state_machine_start(struct upnp_wps_device_sm *sm,
448189251Ssam					     struct sockaddr_in *client,
449189251Ssam					     int mx)
450189251Ssam{
451189251Ssam	struct advertisement_state_machine *a;
452189251Ssam	int next_timeout_sec;
453189251Ssam	int next_timeout_msec;
454214734Srpaulo	int replies;
455189251Ssam
456214734Srpaulo	replies = dl_list_len(&sm->msearch_replies);
457189251Ssam	wpa_printf(MSG_DEBUG, "WPS UPnP: M-SEARCH reply start (%d "
458214734Srpaulo		   "outstanding)", replies);
459214734Srpaulo	if (replies >= MAX_MSEARCH) {
460189251Ssam		wpa_printf(MSG_INFO, "WPS UPnP: Too many outstanding "
461189251Ssam			   "M-SEARCH replies");
462189251Ssam		return;
463189251Ssam	}
464189251Ssam
465189251Ssam	a = os_zalloc(sizeof(*a));
466189251Ssam	if (a == NULL)
467189251Ssam		return;
468189251Ssam	a->type = MSEARCH_REPLY;
469189251Ssam	a->state = 0;
470209158Srpaulo	os_memcpy(&a->client, client, sizeof(*client));
471189251Ssam	/* Wait time depending on MX value */
472189251Ssam	next_timeout_msec = (1000 * mx * (os_random() & 0xFF)) >> 8;
473189251Ssam	next_timeout_sec = next_timeout_msec / 1000;
474189251Ssam	next_timeout_msec = next_timeout_msec % 1000;
475189251Ssam	if (eloop_register_timeout(next_timeout_sec, next_timeout_msec,
476189251Ssam				   msearchreply_state_machine_handler, sm,
477189251Ssam				   a)) {
478189251Ssam		/* No way to recover (from malloc failure) */
479189251Ssam		goto fail;
480189251Ssam	}
481189251Ssam	/* Remember for future cleanup */
482214734Srpaulo	dl_list_add(&sm->msearch_replies, &a->list);
483189251Ssam	return;
484189251Ssam
485189251Ssamfail:
486189251Ssam	wpa_printf(MSG_INFO, "WPS UPnP: M-SEARCH reply failure!");
487189251Ssam	eloop_cancel_timeout(msearchreply_state_machine_handler, sm, a);
488189251Ssam	os_free(a);
489189251Ssam}
490189251Ssam
491189251Ssam
492189251Ssam/**
493189251Ssam * ssdp_parse_msearch - Process a received M-SEARCH
494189251Ssam * @sm: WPS UPnP state machine from upnp_wps_device_init()
495189251Ssam * @client: Client address
496189251Ssam * @data: NULL terminated M-SEARCH message
497189251Ssam *
498189251Ssam * Given that we have received a header w/ M-SEARCH, act upon it
499189251Ssam *
500189251Ssam * Format of M-SEARCH (case insensitive!):
501189251Ssam *
502189251Ssam * First line must be:
503189251Ssam *      M-SEARCH * HTTP/1.1
504189251Ssam * Other lines in arbitrary order:
505189251Ssam *      HOST:239.255.255.250:1900
506189251Ssam *      ST:<varies -- must match>
507189251Ssam *      MAN:"ssdp:discover"
508189251Ssam *      MX:<varies>
509189251Ssam *
510189251Ssam * It should be noted that when Microsoft Vista is still learning its IP
511189251Ssam * address, it sends out host lines like: HOST:[FF02::C]:1900
512189251Ssam */
513189251Ssamstatic void ssdp_parse_msearch(struct upnp_wps_device_sm *sm,
514189251Ssam			       struct sockaddr_in *client, const char *data)
515189251Ssam{
516214734Srpaulo#ifndef CONFIG_NO_STDOUT_DEBUG
517189251Ssam	const char *start = data;
518214734Srpaulo#endif /* CONFIG_NO_STDOUT_DEBUG */
519189251Ssam	int got_host = 0;
520189251Ssam	int got_st = 0, st_match = 0;
521189251Ssam	int got_man = 0;
522189251Ssam	int got_mx = 0;
523189251Ssam	int mx = 0;
524189251Ssam
525189251Ssam	/*
526189251Ssam	 * Skip first line M-SEARCH * HTTP/1.1
527189251Ssam	 * (perhaps we should check remainder of the line for syntax)
528189251Ssam	 */
529189251Ssam	data += line_length(data);
530189251Ssam
531189251Ssam	/* Parse remaining lines */
532189251Ssam	for (; *data != '\0'; data += line_length(data)) {
533189251Ssam		if (token_eq(data, "host")) {
534189251Ssam			/* The host line indicates who the packet
535189251Ssam			 * is addressed to... but do we really care?
536189251Ssam			 * Note that Microsoft sometimes does funny
537189251Ssam			 * stuff with the HOST: line.
538189251Ssam			 */
539189251Ssam#if 0   /* could be */
540189251Ssam			data += token_length(data);
541189251Ssam			data += word_separation_length(data);
542189251Ssam			if (*data != ':')
543189251Ssam				goto bad;
544189251Ssam			data++;
545189251Ssam			data += word_separation_length(data);
546189251Ssam			/* UPNP_MULTICAST_ADDRESS */
547189251Ssam			if (!str_starts(data, "239.255.255.250"))
548189251Ssam				goto bad;
549189251Ssam			data += os_strlen("239.255.255.250");
550189251Ssam			if (*data == ':') {
551189251Ssam				if (!str_starts(data, ":1900"))
552189251Ssam					goto bad;
553189251Ssam			}
554189251Ssam#endif  /* could be */
555189251Ssam			got_host = 1;
556189251Ssam			continue;
557189251Ssam		} else if (token_eq(data, "st")) {
558189251Ssam			/* There are a number of forms; we look
559189251Ssam			 * for one that matches our case.
560189251Ssam			 */
561189251Ssam			got_st = 1;
562189251Ssam			data += token_length(data);
563189251Ssam			data += word_separation_length(data);
564189251Ssam			if (*data != ':')
565189251Ssam				continue;
566189251Ssam			data++;
567189251Ssam			data += word_separation_length(data);
568189251Ssam			if (str_starts(data, "ssdp:all")) {
569189251Ssam				st_match = 1;
570189251Ssam				continue;
571189251Ssam			}
572189251Ssam			if (str_starts(data, "upnp:rootdevice")) {
573189251Ssam				st_match = 1;
574189251Ssam				continue;
575189251Ssam			}
576189251Ssam			if (str_starts(data, "uuid:")) {
577189251Ssam				char uuid_string[80];
578252726Srpaulo				struct upnp_wps_device_interface *iface;
579252726Srpaulo				iface = dl_list_first(
580252726Srpaulo					&sm->interfaces,
581252726Srpaulo					struct upnp_wps_device_interface,
582252726Srpaulo					list);
583281806Srpaulo				if (!iface)
584281806Srpaulo					continue;
585189251Ssam				data += os_strlen("uuid:");
586252726Srpaulo				uuid_bin2str(iface->wps->uuid, uuid_string,
587189251Ssam					     sizeof(uuid_string));
588189251Ssam				if (str_starts(data, uuid_string))
589189251Ssam					st_match = 1;
590189251Ssam				continue;
591189251Ssam			}
592189251Ssam#if 0
593189251Ssam			/* FIX: should we really reply to IGD string? */
594189251Ssam			if (str_starts(data, "urn:schemas-upnp-org:device:"
595189251Ssam				       "InternetGatewayDevice:1")) {
596189251Ssam				st_match = 1;
597189251Ssam				continue;
598189251Ssam			}
599189251Ssam#endif
600189251Ssam			if (str_starts(data, "urn:schemas-wifialliance-org:"
601189251Ssam				       "service:WFAWLANConfig:1")) {
602189251Ssam				st_match = 1;
603189251Ssam				continue;
604189251Ssam			}
605189251Ssam			if (str_starts(data, "urn:schemas-wifialliance-org:"
606189251Ssam				       "device:WFADevice:1")) {
607189251Ssam				st_match = 1;
608189251Ssam				continue;
609189251Ssam			}
610189251Ssam			continue;
611189251Ssam		} else if (token_eq(data, "man")) {
612189251Ssam			data += token_length(data);
613189251Ssam			data += word_separation_length(data);
614189251Ssam			if (*data != ':')
615189251Ssam				continue;
616189251Ssam			data++;
617189251Ssam			data += word_separation_length(data);
618189251Ssam			if (!str_starts(data, "\"ssdp:discover\"")) {
619189251Ssam				wpa_printf(MSG_DEBUG, "WPS UPnP: Unexpected "
620189251Ssam					   "M-SEARCH man-field");
621189251Ssam				goto bad;
622189251Ssam			}
623189251Ssam			got_man = 1;
624189251Ssam			continue;
625189251Ssam		} else if (token_eq(data, "mx")) {
626189251Ssam			data += token_length(data);
627189251Ssam			data += word_separation_length(data);
628189251Ssam			if (*data != ':')
629189251Ssam				continue;
630189251Ssam			data++;
631189251Ssam			data += word_separation_length(data);
632189251Ssam			mx = atol(data);
633189251Ssam			got_mx = 1;
634189251Ssam			continue;
635189251Ssam		}
636189251Ssam		/* ignore anything else */
637189251Ssam	}
638189251Ssam	if (!got_host || !got_st || !got_man || !got_mx || mx < 0) {
639189251Ssam		wpa_printf(MSG_DEBUG, "WPS UPnP: Invalid M-SEARCH: %d %d %d "
640189251Ssam			   "%d mx=%d", got_host, got_st, got_man, got_mx, mx);
641189251Ssam		goto bad;
642189251Ssam	}
643189251Ssam	if (!st_match) {
644189251Ssam		wpa_printf(MSG_DEBUG, "WPS UPnP: Ignored M-SEARCH (no ST "
645189251Ssam			   "match)");
646189251Ssam		return;
647189251Ssam	}
648189251Ssam	if (mx > 120)
649189251Ssam		mx = 120; /* UPnP-arch-DeviceArchitecture, 1.2.3 */
650189251Ssam	msearchreply_state_machine_start(sm, client, mx);
651189251Ssam	return;
652189251Ssam
653189251Ssambad:
654189251Ssam	wpa_printf(MSG_INFO, "WPS UPnP: Failed to parse M-SEARCH");
655189251Ssam	wpa_printf(MSG_MSGDUMP, "WPS UPnP: M-SEARCH data:\n%s", start);
656189251Ssam}
657189251Ssam
658189251Ssam
659189251Ssam/* Listening for (UDP) discovery (M-SEARCH) packets */
660189251Ssam
661189251Ssam/**
662189251Ssam * ssdp_listener_stop - Stop SSDP listered
663189251Ssam * @sm: WPS UPnP state machine from upnp_wps_device_init()
664189251Ssam *
665214734Srpaulo * This function stops the SSDP listener that was started by calling
666189251Ssam * ssdp_listener_start().
667189251Ssam */
668189251Ssamvoid ssdp_listener_stop(struct upnp_wps_device_sm *sm)
669189251Ssam{
670189251Ssam	if (sm->ssdp_sd_registered) {
671189251Ssam		eloop_unregister_sock(sm->ssdp_sd, EVENT_TYPE_READ);
672189251Ssam		sm->ssdp_sd_registered = 0;
673189251Ssam	}
674189251Ssam
675189251Ssam	if (sm->ssdp_sd != -1) {
676189251Ssam		close(sm->ssdp_sd);
677189251Ssam		sm->ssdp_sd = -1;
678189251Ssam	}
679189251Ssam
680189251Ssam	eloop_cancel_timeout(msearchreply_state_machine_handler, sm,
681189251Ssam			     ELOOP_ALL_CTX);
682189251Ssam}
683189251Ssam
684189251Ssam
685189251Ssamstatic void ssdp_listener_handler(int sd, void *eloop_ctx, void *sock_ctx)
686189251Ssam{
687189251Ssam	struct upnp_wps_device_sm *sm = sock_ctx;
688189251Ssam	struct sockaddr_in addr; /* client address */
689189251Ssam	socklen_t addr_len;
690189251Ssam	int nread;
691189251Ssam	char buf[MULTICAST_MAX_READ], *pos;
692189251Ssam
693189251Ssam	addr_len = sizeof(addr);
694189251Ssam	nread = recvfrom(sm->ssdp_sd, buf, sizeof(buf) - 1, 0,
695189251Ssam			 (struct sockaddr *) &addr, &addr_len);
696189251Ssam	if (nread <= 0)
697189251Ssam		return;
698189251Ssam	buf[nread] = '\0'; /* need null termination for algorithm */
699189251Ssam
700189251Ssam	if (str_starts(buf, "NOTIFY ")) {
701189251Ssam		/*
702189251Ssam		 * Silently ignore NOTIFYs to avoid filling debug log with
703189251Ssam		 * unwanted messages.
704189251Ssam		 */
705189251Ssam		return;
706189251Ssam	}
707189251Ssam
708189251Ssam	pos = os_strchr(buf, '\n');
709189251Ssam	if (pos)
710189251Ssam		*pos = '\0';
711189251Ssam	wpa_printf(MSG_MSGDUMP, "WPS UPnP: Received SSDP packet from %s:%d: "
712189251Ssam		   "%s", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port), buf);
713189251Ssam	if (pos)
714189251Ssam		*pos = '\n';
715189251Ssam
716189251Ssam	/* Parse first line */
717189251Ssam	if (os_strncasecmp(buf, "M-SEARCH", os_strlen("M-SEARCH")) == 0 &&
718189251Ssam	    !isgraph(buf[strlen("M-SEARCH")])) {
719189251Ssam		ssdp_parse_msearch(sm, &addr, buf);
720189251Ssam		return;
721189251Ssam	}
722189251Ssam
723189251Ssam	/* Ignore anything else */
724189251Ssam}
725189251Ssam
726189251Ssam
727214734Srpauloint ssdp_listener_open(void)
728189251Ssam{
729189251Ssam	struct sockaddr_in addr;
730189251Ssam	struct ip_mreq mcast_addr;
731189251Ssam	int on = 1;
732189251Ssam	/* per UPnP spec, keep IP packet time to live (TTL) small */
733189251Ssam	unsigned char ttl = 4;
734214734Srpaulo	int sd;
735189251Ssam
736214734Srpaulo	sd = socket(AF_INET, SOCK_DGRAM, 0);
737289549Srpaulo	if (sd < 0 ||
738289549Srpaulo	    fcntl(sd, F_SETFL, O_NONBLOCK) != 0 ||
739289549Srpaulo	    setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)))
740189251Ssam		goto fail;
741189251Ssam	os_memset(&addr, 0, sizeof(addr));
742189251Ssam	addr.sin_family = AF_INET;
743189251Ssam	addr.sin_addr.s_addr = htonl(INADDR_ANY);
744189251Ssam	addr.sin_port = htons(UPNP_MULTICAST_PORT);
745189251Ssam	if (bind(sd, (struct sockaddr *) &addr, sizeof(addr)))
746189251Ssam		goto fail;
747189251Ssam	os_memset(&mcast_addr, 0, sizeof(mcast_addr));
748189251Ssam	mcast_addr.imr_interface.s_addr = htonl(INADDR_ANY);
749189251Ssam	mcast_addr.imr_multiaddr.s_addr = inet_addr(UPNP_MULTICAST_ADDRESS);
750189251Ssam	if (setsockopt(sd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
751289549Srpaulo		       (char *) &mcast_addr, sizeof(mcast_addr)) ||
752289549Srpaulo	    setsockopt(sd, IPPROTO_IP, IP_MULTICAST_TTL,
753189251Ssam		       &ttl, sizeof(ttl)))
754189251Ssam		goto fail;
755214734Srpaulo
756214734Srpaulo	return sd;
757214734Srpaulo
758214734Srpaulofail:
759214734Srpaulo	if (sd >= 0)
760214734Srpaulo		close(sd);
761214734Srpaulo	return -1;
762214734Srpaulo}
763214734Srpaulo
764214734Srpaulo
765214734Srpaulo/**
766214734Srpaulo * ssdp_listener_start - Set up for receiving discovery (UDP) packets
767214734Srpaulo * @sm: WPS UPnP state machine from upnp_wps_device_init()
768214734Srpaulo * Returns: 0 on success, -1 on failure
769214734Srpaulo *
770214734Srpaulo * The SSDP listener is stopped by calling ssdp_listener_stop().
771214734Srpaulo */
772214734Srpauloint ssdp_listener_start(struct upnp_wps_device_sm *sm)
773214734Srpaulo{
774214734Srpaulo	sm->ssdp_sd = ssdp_listener_open();
775214734Srpaulo
776214734Srpaulo	if (eloop_register_sock(sm->ssdp_sd, EVENT_TYPE_READ,
777214734Srpaulo				ssdp_listener_handler, NULL, sm))
778189251Ssam		goto fail;
779189251Ssam	sm->ssdp_sd_registered = 1;
780189251Ssam	return 0;
781189251Ssam
782189251Ssamfail:
783189251Ssam	/* Error */
784189251Ssam	wpa_printf(MSG_ERROR, "WPS UPnP: ssdp_listener_start failed");
785189251Ssam	ssdp_listener_stop(sm);
786189251Ssam	return -1;
787189251Ssam}
788189251Ssam
789189251Ssam
790189251Ssam/**
791189251Ssam * add_ssdp_network - Add routing entry for SSDP
792189251Ssam * @net_if: Selected network interface name
793189251Ssam * Returns: 0 on success, -1 on failure
794189251Ssam *
795189251Ssam * This function assures that the multicast address will be properly
796189251Ssam * handled by Linux networking code (by a modification to routing tables).
797189251Ssam * This must be done per network interface. It really only needs to be done
798189251Ssam * once after booting up, but it does not hurt to call this more frequently
799189251Ssam * "to be safe".
800189251Ssam */
801214734Srpauloint add_ssdp_network(const char *net_if)
802189251Ssam{
803209158Srpaulo#ifdef __linux__
804189251Ssam	int ret = -1;
805189251Ssam	int sock = -1;
806189251Ssam	struct rtentry rt;
807189251Ssam	struct sockaddr_in *sin;
808189251Ssam
809189251Ssam	if (!net_if)
810189251Ssam		goto fail;
811189251Ssam
812189251Ssam	os_memset(&rt, 0, sizeof(rt));
813189251Ssam	sock = socket(AF_INET, SOCK_DGRAM, 0);
814189251Ssam	if (sock < 0)
815189251Ssam		goto fail;
816189251Ssam
817214734Srpaulo	rt.rt_dev = (char *) net_if;
818209158Srpaulo	sin = aliasing_hide_typecast(&rt.rt_dst, struct sockaddr_in);
819189251Ssam	sin->sin_family = AF_INET;
820189251Ssam	sin->sin_port = 0;
821189251Ssam	sin->sin_addr.s_addr = inet_addr(SSDP_TARGET);
822209158Srpaulo	sin = aliasing_hide_typecast(&rt.rt_genmask, struct sockaddr_in);
823189251Ssam	sin->sin_family = AF_INET;
824189251Ssam	sin->sin_port = 0;
825189251Ssam	sin->sin_addr.s_addr = inet_addr(SSDP_NETMASK);
826189251Ssam	rt.rt_flags = RTF_UP;
827189251Ssam	if (ioctl(sock, SIOCADDRT, &rt) < 0) {
828189251Ssam		if (errno == EPERM) {
829189251Ssam			wpa_printf(MSG_DEBUG, "add_ssdp_network: No "
830189251Ssam				   "permissions to add routing table entry");
831189251Ssam			/* Continue to allow testing as non-root */
832189251Ssam		} else if (errno != EEXIST) {
833189251Ssam			wpa_printf(MSG_INFO, "add_ssdp_network() ioctl errno "
834189251Ssam				   "%d (%s)", errno, strerror(errno));
835189251Ssam			goto fail;
836189251Ssam		}
837189251Ssam	}
838189251Ssam
839189251Ssam	ret = 0;
840189251Ssam
841189251Ssamfail:
842189251Ssam	if (sock >= 0)
843189251Ssam		close(sock);
844189251Ssam
845189251Ssam	return ret;
846209158Srpaulo#else /* __linux__ */
847209158Srpaulo	return 0;
848209158Srpaulo#endif /* __linux__ */
849189251Ssam}
850189251Ssam
851189251Ssam
852281806Srpauloint ssdp_open_multicast_sock(u32 ip_addr, const char *forced_ifname)
853189251Ssam{
854214734Srpaulo	int sd;
855189251Ssam	 /* per UPnP-arch-DeviceArchitecture, 1. Discovery, keep IP packet
856189251Ssam	  * time to live (TTL) small */
857189251Ssam	unsigned char ttl = 4;
858189251Ssam
859214734Srpaulo	sd = socket(AF_INET, SOCK_DGRAM, 0);
860189251Ssam	if (sd < 0)
861189251Ssam		return -1;
862189251Ssam
863281806Srpaulo	if (forced_ifname) {
864281806Srpaulo#ifdef __linux__
865281806Srpaulo		struct ifreq req;
866281806Srpaulo		os_memset(&req, 0, sizeof(req));
867281806Srpaulo		os_strlcpy(req.ifr_name, forced_ifname, sizeof(req.ifr_name));
868281806Srpaulo		if (setsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, &req,
869281806Srpaulo			       sizeof(req)) < 0) {
870281806Srpaulo			wpa_printf(MSG_INFO, "WPS UPnP: Failed to bind "
871281806Srpaulo				   "multicast socket to ifname %s: %s",
872281806Srpaulo				   forced_ifname, strerror(errno));
873281806Srpaulo			close(sd);
874281806Srpaulo			return -1;
875281806Srpaulo		}
876281806Srpaulo#endif /* __linux__ */
877281806Srpaulo	}
878281806Srpaulo
879189251Ssam#if 0   /* maybe ok if we sometimes block on writes */
880252726Srpaulo	if (fcntl(sd, F_SETFL, O_NONBLOCK) != 0) {
881252726Srpaulo		close(sd);
882189251Ssam		return -1;
883252726Srpaulo	}
884189251Ssam#endif
885189251Ssam
886189251Ssam	if (setsockopt(sd, IPPROTO_IP, IP_MULTICAST_IF,
887252726Srpaulo		       &ip_addr, sizeof(ip_addr))) {
888252726Srpaulo		wpa_printf(MSG_DEBUG, "WPS: setsockopt(IP_MULTICAST_IF) %x: "
889252726Srpaulo			   "%d (%s)", ip_addr, errno, strerror(errno));
890252726Srpaulo		close(sd);
891189251Ssam		return -1;
892252726Srpaulo	}
893189251Ssam	if (setsockopt(sd, IPPROTO_IP, IP_MULTICAST_TTL,
894252726Srpaulo		       &ttl, sizeof(ttl))) {
895252726Srpaulo		wpa_printf(MSG_DEBUG, "WPS: setsockopt(IP_MULTICAST_TTL): "
896252726Srpaulo			   "%d (%s)", errno, strerror(errno));
897252726Srpaulo		close(sd);
898189251Ssam		return -1;
899252726Srpaulo	}
900189251Ssam
901189251Ssam#if 0   /* not needed, because we don't receive using multicast_sd */
902189251Ssam	{
903189251Ssam		struct ip_mreq mreq;
904189251Ssam		mreq.imr_multiaddr.s_addr = inet_addr(UPNP_MULTICAST_ADDRESS);
905214734Srpaulo		mreq.imr_interface.s_addr = ip_addr;
906189251Ssam		wpa_printf(MSG_DEBUG, "WPS UPnP: Multicast addr 0x%x if addr "
907189251Ssam			   "0x%x",
908189251Ssam			   mreq.imr_multiaddr.s_addr,
909189251Ssam			   mreq.imr_interface.s_addr);
910189251Ssam		if (setsockopt(sd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq,
911189251Ssam				sizeof(mreq))) {
912189251Ssam			wpa_printf(MSG_ERROR,
913189251Ssam				   "WPS UPnP: setsockopt "
914189251Ssam				   "IP_ADD_MEMBERSHIP errno %d (%s)",
915189251Ssam				   errno, strerror(errno));
916252726Srpaulo			close(sd);
917189251Ssam			return -1;
918189251Ssam		}
919189251Ssam	}
920189251Ssam#endif  /* not needed */
921189251Ssam
922189251Ssam	/*
923189251Ssam	 * TODO: What about IP_MULTICAST_LOOP? It seems to be on by default?
924189251Ssam	 * which aids debugging I suppose but isn't really necessary?
925189251Ssam	 */
926189251Ssam
927214734Srpaulo	return sd;
928214734Srpaulo}
929214734Srpaulo
930214734Srpaulo
931214734Srpaulo/**
932214734Srpaulo * ssdp_open_multicast - Open socket for sending multicast SSDP messages
933214734Srpaulo * @sm: WPS UPnP state machine from upnp_wps_device_init()
934214734Srpaulo * Returns: 0 on success, -1 on failure
935214734Srpaulo */
936214734Srpauloint ssdp_open_multicast(struct upnp_wps_device_sm *sm)
937214734Srpaulo{
938281806Srpaulo	sm->multicast_sd = ssdp_open_multicast_sock(sm->ip_addr, NULL);
939214734Srpaulo	if (sm->multicast_sd < 0)
940214734Srpaulo		return -1;
941189251Ssam	return 0;
942189251Ssam}
943