1189251Ssam/*
2189251Ssam * UPnP WPS Device - Event processing
3189251Ssam * Copyright (c) 2000-2003 Intel Corporation
4189251Ssam * Copyright (c) 2006-2007 Sony Corporation
5189251Ssam * Copyright (c) 2008-2009 Atheros Communications
6252726Srpaulo * Copyright (c) 2009-2010, 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#include <assert.h>
13189251Ssam
14189251Ssam#include "common.h"
15189251Ssam#include "eloop.h"
16189251Ssam#include "uuid.h"
17214734Srpaulo#include "http_client.h"
18189251Ssam#include "wps_defs.h"
19189251Ssam#include "wps_upnp.h"
20189251Ssam#include "wps_upnp_i.h"
21189251Ssam
22189251Ssam/*
23189251Ssam * Event message generation (to subscribers)
24189251Ssam *
25189251Ssam * We make a separate copy for each message for each subscriber. This memory
26189251Ssam * wasted could be limited (adding code complexity) by sharing copies, keeping
27189251Ssam * a usage count and freeing when zero.
28189251Ssam *
29189251Ssam * Sending a message requires using a HTTP over TCP NOTIFY
30189251Ssam * (like a PUT) which requires a number of states..
31189251Ssam */
32189251Ssam
33189251Ssam#define MAX_EVENTS_QUEUED 20   /* How far behind queued events */
34252726Srpaulo#define MAX_FAILURES 10 /* Drop subscription after this many failures */
35189251Ssam
36189251Ssam/* How long to wait before sending event */
37189251Ssam#define EVENT_DELAY_SECONDS 0
38189251Ssam#define EVENT_DELAY_MSEC 0
39189251Ssam
40189251Ssam/*
41189251Ssam * Event information that we send to each subscriber is remembered in this
42189251Ssam * struct. The event cannot be sent by simple UDP; it has to be sent by a HTTP
43189251Ssam * over TCP transaction which requires various states.. It may also need to be
44189251Ssam * retried at a different address (if more than one is available).
45189251Ssam *
46189251Ssam * TODO: As an optimization we could share data between subscribers.
47189251Ssam */
48189251Ssamstruct wps_event_ {
49214734Srpaulo	struct dl_list list;
50189251Ssam	struct subscription *s;         /* parent */
51189251Ssam	unsigned subscriber_sequence;   /* which event for this subscription*/
52214734Srpaulo	unsigned int retry;             /* which retry */
53189251Ssam	struct subscr_addr *addr;       /* address to connect to */
54189251Ssam	struct wpabuf *data;            /* event data to send */
55214734Srpaulo	struct http_client *http_event;
56189251Ssam};
57189251Ssam
58189251Ssam
59189251Ssam/* event_clean -- clean sockets etc. of event
60189251Ssam * Leaves data, retry count etc. alone.
61189251Ssam */
62189251Ssamstatic void event_clean(struct wps_event_ *e)
63189251Ssam{
64214734Srpaulo	if (e->s->current_event == e)
65189251Ssam		e->s->current_event = NULL;
66214734Srpaulo	http_client_free(e->http_event);
67214734Srpaulo	e->http_event = NULL;
68189251Ssam}
69189251Ssam
70189251Ssam
71189251Ssam/* event_delete -- delete single unqueued event
72189251Ssam * (be sure to dequeue first if need be)
73189251Ssam */
74209158Srpaulostatic void event_delete(struct wps_event_ *e)
75189251Ssam{
76252726Srpaulo	wpa_printf(MSG_DEBUG, "WPS UPnP: Delete event %p", e);
77189251Ssam	event_clean(e);
78189251Ssam	wpabuf_free(e->data);
79189251Ssam	os_free(e);
80189251Ssam}
81189251Ssam
82189251Ssam
83189251Ssam/* event_dequeue -- get next event from the queue
84189251Ssam * Returns NULL if empty.
85189251Ssam */
86189251Ssamstatic struct wps_event_ *event_dequeue(struct subscription *s)
87189251Ssam{
88214734Srpaulo	struct wps_event_ *e;
89214734Srpaulo	e = dl_list_first(&s->event_queue, struct wps_event_, list);
90252726Srpaulo	if (e) {
91252726Srpaulo		wpa_printf(MSG_DEBUG, "WPS UPnP: Dequeue event %p for "
92252726Srpaulo			   "subscription %p", e, s);
93214734Srpaulo		dl_list_del(&e->list);
94252726Srpaulo	}
95189251Ssam	return e;
96189251Ssam}
97189251Ssam
98189251Ssam
99189251Ssam/* event_delete_all -- delete entire event queue and current event */
100189251Ssamvoid event_delete_all(struct subscription *s)
101189251Ssam{
102189251Ssam	struct wps_event_ *e;
103189251Ssam	while ((e = event_dequeue(s)) != NULL)
104189251Ssam		event_delete(e);
105189251Ssam	if (s->current_event) {
106189251Ssam		event_delete(s->current_event);
107189251Ssam		/* will set: s->current_event = NULL;  */
108189251Ssam	}
109189251Ssam}
110189251Ssam
111189251Ssam
112189251Ssam/**
113189251Ssam * event_retry - Called when we had a failure delivering event msg
114189251Ssam * @e: Event
115189251Ssam * @do_next_address: skip address e.g. on connect fail
116189251Ssam */
117189251Ssamstatic void event_retry(struct wps_event_ *e, int do_next_address)
118189251Ssam{
119189251Ssam	struct subscription *s = e->s;
120189251Ssam	struct upnp_wps_device_sm *sm = s->sm;
121189251Ssam
122252726Srpaulo	wpa_printf(MSG_DEBUG, "WPS UPnP: Retry event %p for subscription %p",
123252726Srpaulo		   e, s);
124189251Ssam	event_clean(e);
125189251Ssam	/* will set: s->current_event = NULL; */
126189251Ssam
127252726Srpaulo	if (do_next_address) {
128189251Ssam		e->retry++;
129252726Srpaulo		wpa_printf(MSG_DEBUG, "WPS UPnP: Try address %d", e->retry);
130252726Srpaulo	}
131214734Srpaulo	if (e->retry >= dl_list_len(&s->addr_list)) {
132189251Ssam		wpa_printf(MSG_DEBUG, "WPS UPnP: Giving up on sending event "
133189251Ssam			   "for %s", e->addr->domain_and_port);
134252726Srpaulo		event_delete(e);
135252726Srpaulo		s->last_event_failed = 1;
136252726Srpaulo		if (!dl_list_empty(&s->event_queue))
137252726Srpaulo			event_send_all_later(s->sm);
138189251Ssam		return;
139189251Ssam	}
140214734Srpaulo	dl_list_add(&s->event_queue, &e->list);
141189251Ssam	event_send_all_later(sm);
142189251Ssam}
143189251Ssam
144189251Ssam
145214734Srpaulostatic struct wpabuf * event_build_message(struct wps_event_ *e)
146189251Ssam{
147189251Ssam	struct wpabuf *buf;
148189251Ssam	char *b;
149189251Ssam
150189251Ssam	buf = wpabuf_alloc(1000 + wpabuf_len(e->data));
151214734Srpaulo	if (buf == NULL)
152214734Srpaulo		return NULL;
153189251Ssam	wpabuf_printf(buf, "NOTIFY %s HTTP/1.1\r\n", e->addr->path);
154189251Ssam	wpabuf_put_str(buf, "SERVER: Unspecified, UPnP/1.0, Unspecified\r\n");
155189251Ssam	wpabuf_printf(buf, "HOST: %s\r\n", e->addr->domain_and_port);
156189251Ssam	wpabuf_put_str(buf, "CONTENT-TYPE: text/xml; charset=\"utf-8\"\r\n"
157189251Ssam		       "NT: upnp:event\r\n"
158189251Ssam		       "NTS: upnp:propchange\r\n");
159189251Ssam	wpabuf_put_str(buf, "SID: uuid:");
160189251Ssam	b = wpabuf_put(buf, 0);
161214734Srpaulo	uuid_bin2str(e->s->uuid, b, 80);
162189251Ssam	wpabuf_put(buf, os_strlen(b));
163189251Ssam	wpabuf_put_str(buf, "\r\n");
164189251Ssam	wpabuf_printf(buf, "SEQ: %u\r\n", e->subscriber_sequence);
165189251Ssam	wpabuf_printf(buf, "CONTENT-LENGTH: %d\r\n",
166189251Ssam		      (int) wpabuf_len(e->data));
167189251Ssam	wpabuf_put_str(buf, "\r\n"); /* terminating empty line */
168189251Ssam	wpabuf_put_buf(buf, e->data);
169214734Srpaulo	return buf;
170214734Srpaulo}
171189251Ssam
172214734Srpaulo
173252726Srpaulostatic void event_addr_failure(struct wps_event_ *e)
174252726Srpaulo{
175252726Srpaulo	struct subscription *s = e->s;
176252726Srpaulo
177252726Srpaulo	e->addr->num_failures++;
178252726Srpaulo	wpa_printf(MSG_DEBUG, "WPS UPnP: Failed to send event %p to %s "
179252726Srpaulo		   "(num_failures=%u)",
180252726Srpaulo		   e, e->addr->domain_and_port, e->addr->num_failures);
181252726Srpaulo
182252726Srpaulo	if (e->addr->num_failures < MAX_FAILURES) {
183252726Srpaulo		/* Try other addresses, if available */
184252726Srpaulo		event_retry(e, 1);
185252726Srpaulo		return;
186252726Srpaulo	}
187252726Srpaulo
188252726Srpaulo	/*
189252726Srpaulo	 * If other side doesn't like what we say, forget about them.
190252726Srpaulo	 * (There is no way to tell other side that we are dropping them...).
191252726Srpaulo	 */
192252726Srpaulo	wpa_printf(MSG_DEBUG, "WPS UPnP: Deleting subscription %p "
193252726Srpaulo		   "address %s due to errors", s, e->addr->domain_and_port);
194252726Srpaulo	dl_list_del(&e->addr->list);
195252726Srpaulo	subscr_addr_delete(e->addr);
196252726Srpaulo	e->addr = NULL;
197252726Srpaulo
198252726Srpaulo	if (dl_list_empty(&s->addr_list)) {
199252726Srpaulo		/* if we've given up on all addresses */
200252726Srpaulo		wpa_printf(MSG_DEBUG, "WPS UPnP: Removing subscription %p "
201252726Srpaulo			   "with no addresses", s);
202252726Srpaulo		dl_list_del(&s->list);
203252726Srpaulo		subscription_destroy(s);
204252726Srpaulo		return;
205252726Srpaulo	}
206252726Srpaulo
207252726Srpaulo	/* Try other addresses, if available */
208252726Srpaulo	event_retry(e, 0);
209252726Srpaulo}
210252726Srpaulo
211252726Srpaulo
212214734Srpaulostatic void event_http_cb(void *ctx, struct http_client *c,
213214734Srpaulo			  enum http_client_event event)
214214734Srpaulo{
215214734Srpaulo	struct wps_event_ *e = ctx;
216214734Srpaulo	struct subscription *s = e->s;
217214734Srpaulo
218252726Srpaulo	wpa_printf(MSG_DEBUG, "WPS UPnP: HTTP client callback: e=%p c=%p "
219252726Srpaulo		   "event=%d", e, c, event);
220214734Srpaulo	switch (event) {
221214734Srpaulo	case HTTP_CLIENT_OK:
222214734Srpaulo		wpa_printf(MSG_DEBUG,
223252726Srpaulo			   "WPS UPnP: Got event %p reply OK from %s",
224252726Srpaulo			   e, e->addr->domain_and_port);
225252726Srpaulo		e->addr->num_failures = 0;
226252726Srpaulo		s->last_event_failed = 0;
227214734Srpaulo		event_delete(e);
228214734Srpaulo
229214734Srpaulo		/* Schedule sending more if there is more to send */
230214734Srpaulo		if (!dl_list_empty(&s->event_queue))
231214734Srpaulo			event_send_all_later(s->sm);
232214734Srpaulo		break;
233214734Srpaulo	case HTTP_CLIENT_FAILED:
234252726Srpaulo		wpa_printf(MSG_DEBUG, "WPS UPnP: Event send failure");
235252726Srpaulo		event_addr_failure(e);
236252726Srpaulo		break;
237214734Srpaulo	case HTTP_CLIENT_INVALID_REPLY:
238252726Srpaulo		wpa_printf(MSG_DEBUG, "WPS UPnP: Invalid reply");
239252726Srpaulo		event_addr_failure(e);
240214734Srpaulo		break;
241214734Srpaulo	case HTTP_CLIENT_TIMEOUT:
242214734Srpaulo		wpa_printf(MSG_DEBUG, "WPS UPnP: Event send timeout");
243252726Srpaulo		event_addr_failure(e);
244252726Srpaulo		break;
245189251Ssam	}
246189251Ssam}
247189251Ssam
248189251Ssam
249189251Ssam/* event_send_start -- prepare to send a event message to subscriber
250189251Ssam *
251189251Ssam * This gets complicated because:
252189251Ssam * -- The message is sent via TCP and we have to keep the stream open
253189251Ssam *      for 30 seconds to get a response... then close it.
254189251Ssam * -- But we might have other event happen in the meantime...
255189251Ssam *      we have to queue them, if we lose them then the subscriber will
256189251Ssam *      be forced to unsubscribe and subscribe again.
257189251Ssam * -- If multiple URLs are provided then we are supposed to try successive
258189251Ssam *      ones after 30 second timeout.
259189251Ssam * -- The URLs might use domain names instead of dotted decimal addresses,
260189251Ssam *      and resolution of those may cause unwanted sleeping.
261189251Ssam * -- Doing the initial TCP connect can take a while, so we have to come
262189251Ssam *      back after connection and then send the data.
263189251Ssam *
264189251Ssam * Returns nonzero on error;
265189251Ssam *
266189251Ssam * Prerequisite: No current event send (s->current_event == NULL)
267189251Ssam *      and non-empty queue.
268189251Ssam */
269189251Ssamstatic int event_send_start(struct subscription *s)
270189251Ssam{
271189251Ssam	struct wps_event_ *e;
272214734Srpaulo	unsigned int itry;
273214734Srpaulo	struct wpabuf *buf;
274189251Ssam
275189251Ssam	/*
276189251Ssam	 * Assume we are called ONLY with no current event and ONLY with
277189251Ssam	 * nonempty event queue and ONLY with at least one address to send to.
278189251Ssam	 */
279252726Srpaulo	if (dl_list_empty(&s->addr_list))
280252726Srpaulo		return -1;
281252726Srpaulo	if (s->current_event)
282252726Srpaulo		return -1;
283252726Srpaulo	if (dl_list_empty(&s->event_queue))
284252726Srpaulo		return -1;
285189251Ssam
286189251Ssam	s->current_event = e = event_dequeue(s);
287189251Ssam
288214734Srpaulo	/* Use address according to number of retries */
289214734Srpaulo	itry = 0;
290214734Srpaulo	dl_list_for_each(e->addr, &s->addr_list, struct subscr_addr, list)
291214734Srpaulo		if (itry++ == e->retry)
292214734Srpaulo			break;
293214734Srpaulo	if (itry < e->retry)
294214734Srpaulo		return -1;
295189251Ssam
296214734Srpaulo	buf = event_build_message(e);
297214734Srpaulo	if (buf == NULL) {
298189251Ssam		event_retry(e, 0);
299189251Ssam		return -1;
300189251Ssam	}
301214734Srpaulo
302214734Srpaulo	e->http_event = http_client_addr(&e->addr->saddr, buf, 0,
303214734Srpaulo					 event_http_cb, e);
304214734Srpaulo	if (e->http_event == NULL) {
305214734Srpaulo		wpabuf_free(buf);
306189251Ssam		event_retry(e, 0);
307189251Ssam		return -1;
308189251Ssam	}
309214734Srpaulo
310189251Ssam	return 0;
311189251Ssam}
312189251Ssam
313189251Ssam
314189251Ssam/* event_send_all_later_handler -- actually send events as needed */
315209158Srpaulostatic void event_send_all_later_handler(void *eloop_data, void *user_ctx)
316189251Ssam{
317189251Ssam	struct upnp_wps_device_sm *sm = user_ctx;
318214734Srpaulo	struct subscription *s, *tmp;
319189251Ssam	int nerrors = 0;
320189251Ssam
321189251Ssam	sm->event_send_all_queued = 0;
322214734Srpaulo	dl_list_for_each_safe(s, tmp, &sm->subscriptions, struct subscription,
323214734Srpaulo			      list) {
324252726Srpaulo		if (s->current_event == NULL /* not busy */ &&
325252726Srpaulo		    !dl_list_empty(&s->event_queue) /* more to do */) {
326252726Srpaulo			if (event_send_start(s))
327252726Srpaulo				nerrors++;
328189251Ssam		}
329214734Srpaulo	}
330189251Ssam
331189251Ssam	if (nerrors) {
332189251Ssam		/* Try again later */
333189251Ssam		event_send_all_later(sm);
334189251Ssam	}
335189251Ssam}
336189251Ssam
337189251Ssam
338189251Ssam/* event_send_all_later -- schedule sending events to all subscribers
339189251Ssam * that need it.
340189251Ssam * This avoids two problems:
341189251Ssam * -- After getting a subscription, we should not send the first event
342189251Ssam *      until after our reply is fully queued to be sent back,
343189251Ssam * -- Possible stack depth or infinite recursion issues.
344189251Ssam */
345189251Ssamvoid event_send_all_later(struct upnp_wps_device_sm *sm)
346189251Ssam{
347189251Ssam	/*
348189251Ssam	 * The exact time in the future isn't too important. Waiting a bit
349189251Ssam	 * might let us do several together.
350189251Ssam	 */
351189251Ssam	if (sm->event_send_all_queued)
352189251Ssam		return;
353189251Ssam	sm->event_send_all_queued = 1;
354189251Ssam	eloop_register_timeout(EVENT_DELAY_SECONDS, EVENT_DELAY_MSEC,
355189251Ssam			       event_send_all_later_handler, NULL, sm);
356189251Ssam}
357189251Ssam
358189251Ssam
359189251Ssam/* event_send_stop_all -- cleanup */
360189251Ssamvoid event_send_stop_all(struct upnp_wps_device_sm *sm)
361189251Ssam{
362189251Ssam	if (sm->event_send_all_queued)
363189251Ssam		eloop_cancel_timeout(event_send_all_later_handler, NULL, sm);
364189251Ssam	sm->event_send_all_queued = 0;
365189251Ssam}
366189251Ssam
367189251Ssam
368189251Ssam/**
369189251Ssam * event_add - Add a new event to a queue
370189251Ssam * @s: Subscription
371189251Ssam * @data: Event data (is copied; caller retains ownership)
372252726Srpaulo * @probereq: Whether this is a Probe Request event
373252726Srpaulo * Returns: 0 on success, -1 on error, 1 on max event queue limit reached
374189251Ssam */
375252726Srpauloint event_add(struct subscription *s, const struct wpabuf *data, int probereq)
376189251Ssam{
377189251Ssam	struct wps_event_ *e;
378252726Srpaulo	unsigned int len;
379189251Ssam
380252726Srpaulo	len = dl_list_len(&s->event_queue);
381252726Srpaulo	if (len >= MAX_EVENTS_QUEUED) {
382189251Ssam		wpa_printf(MSG_DEBUG, "WPS UPnP: Too many events queued for "
383252726Srpaulo			   "subscriber %p", s);
384252726Srpaulo		if (probereq)
385252726Srpaulo			return 1;
386252726Srpaulo
387252726Srpaulo		/* Drop oldest entry to allow EAP event to be stored. */
388252726Srpaulo		e = event_dequeue(s);
389252726Srpaulo		if (!e)
390252726Srpaulo			return 1;
391252726Srpaulo		event_delete(e);
392189251Ssam	}
393189251Ssam
394252726Srpaulo	if (s->last_event_failed && probereq && len > 0) {
395252726Srpaulo		/*
396252726Srpaulo		 * Avoid queuing frames for subscribers that may have left
397252726Srpaulo		 * without unsubscribing.
398252726Srpaulo		 */
399252726Srpaulo		wpa_printf(MSG_DEBUG, "WPS UPnP: Do not queue more Probe "
400252726Srpaulo			   "Request frames for subscription %p since last "
401252726Srpaulo			   "delivery failed", s);
402252726Srpaulo		return -1;
403252726Srpaulo	}
404252726Srpaulo
405189251Ssam	e = os_zalloc(sizeof(*e));
406189251Ssam	if (e == NULL)
407252726Srpaulo		return -1;
408214734Srpaulo	dl_list_init(&e->list);
409189251Ssam	e->s = s;
410189251Ssam	e->data = wpabuf_dup(data);
411189251Ssam	if (e->data == NULL) {
412189251Ssam		os_free(e);
413252726Srpaulo		return -1;
414189251Ssam	}
415189251Ssam	e->subscriber_sequence = s->next_subscriber_sequence++;
416189251Ssam	if (s->next_subscriber_sequence == 0)
417189251Ssam		s->next_subscriber_sequence++;
418252726Srpaulo	wpa_printf(MSG_DEBUG, "WPS UPnP: Queue event %p for subscriber %p "
419252726Srpaulo		   "(queue len %u)", e, s, len + 1);
420214734Srpaulo	dl_list_add_tail(&s->event_queue, &e->list);
421189251Ssam	event_send_all_later(s->sm);
422189251Ssam	return 0;
423189251Ssam}
424