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