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
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#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 */
34189251Ssam#define EVENT_TIMEOUT_SEC 30   /* Drop sending event after timeout */
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{
76189251Ssam	event_clean(e);
77189251Ssam	wpabuf_free(e->data);
78189251Ssam	os_free(e);
79189251Ssam}
80189251Ssam
81189251Ssam
82189251Ssam/* event_dequeue -- get next event from the queue
83189251Ssam * Returns NULL if empty.
84189251Ssam */
85189251Ssamstatic struct wps_event_ *event_dequeue(struct subscription *s)
86189251Ssam{
87214734Srpaulo	struct wps_event_ *e;
88214734Srpaulo	e = dl_list_first(&s->event_queue, struct wps_event_, list);
89214734Srpaulo	if (e)
90214734Srpaulo		dl_list_del(&e->list);
91189251Ssam	return e;
92189251Ssam}
93189251Ssam
94189251Ssam
95189251Ssam/* event_delete_all -- delete entire event queue and current event */
96189251Ssamvoid event_delete_all(struct subscription *s)
97189251Ssam{
98189251Ssam	struct wps_event_ *e;
99189251Ssam	while ((e = event_dequeue(s)) != NULL)
100189251Ssam		event_delete(e);
101189251Ssam	if (s->current_event) {
102189251Ssam		event_delete(s->current_event);
103189251Ssam		/* will set: s->current_event = NULL;  */
104189251Ssam	}
105189251Ssam}
106189251Ssam
107189251Ssam
108189251Ssam/**
109189251Ssam * event_retry - Called when we had a failure delivering event msg
110189251Ssam * @e: Event
111189251Ssam * @do_next_address: skip address e.g. on connect fail
112189251Ssam */
113189251Ssamstatic void event_retry(struct wps_event_ *e, int do_next_address)
114189251Ssam{
115189251Ssam	struct subscription *s = e->s;
116189251Ssam	struct upnp_wps_device_sm *sm = s->sm;
117189251Ssam
118189251Ssam	event_clean(e);
119189251Ssam	/* will set: s->current_event = NULL; */
120189251Ssam
121189251Ssam	if (do_next_address)
122189251Ssam		e->retry++;
123214734Srpaulo	if (e->retry >= dl_list_len(&s->addr_list)) {
124189251Ssam		wpa_printf(MSG_DEBUG, "WPS UPnP: Giving up on sending event "
125189251Ssam			   "for %s", e->addr->domain_and_port);
126189251Ssam		return;
127189251Ssam	}
128214734Srpaulo	dl_list_add(&s->event_queue, &e->list);
129189251Ssam	event_send_all_later(sm);
130189251Ssam}
131189251Ssam
132189251Ssam
133214734Srpaulostatic struct wpabuf * event_build_message(struct wps_event_ *e)
134189251Ssam{
135189251Ssam	struct wpabuf *buf;
136189251Ssam	char *b;
137189251Ssam
138189251Ssam	buf = wpabuf_alloc(1000 + wpabuf_len(e->data));
139214734Srpaulo	if (buf == NULL)
140214734Srpaulo		return NULL;
141189251Ssam	wpabuf_printf(buf, "NOTIFY %s HTTP/1.1\r\n", e->addr->path);
142189251Ssam	wpabuf_put_str(buf, "SERVER: Unspecified, UPnP/1.0, Unspecified\r\n");
143189251Ssam	wpabuf_printf(buf, "HOST: %s\r\n", e->addr->domain_and_port);
144189251Ssam	wpabuf_put_str(buf, "CONTENT-TYPE: text/xml; charset=\"utf-8\"\r\n"
145189251Ssam		       "NT: upnp:event\r\n"
146189251Ssam		       "NTS: upnp:propchange\r\n");
147189251Ssam	wpabuf_put_str(buf, "SID: uuid:");
148189251Ssam	b = wpabuf_put(buf, 0);
149214734Srpaulo	uuid_bin2str(e->s->uuid, b, 80);
150189251Ssam	wpabuf_put(buf, os_strlen(b));
151189251Ssam	wpabuf_put_str(buf, "\r\n");
152189251Ssam	wpabuf_printf(buf, "SEQ: %u\r\n", e->subscriber_sequence);
153189251Ssam	wpabuf_printf(buf, "CONTENT-LENGTH: %d\r\n",
154189251Ssam		      (int) wpabuf_len(e->data));
155189251Ssam	wpabuf_put_str(buf, "\r\n"); /* terminating empty line */
156189251Ssam	wpabuf_put_buf(buf, e->data);
157214734Srpaulo	return buf;
158214734Srpaulo}
159189251Ssam
160214734Srpaulo
161214734Srpaulostatic void event_http_cb(void *ctx, struct http_client *c,
162214734Srpaulo			  enum http_client_event event)
163214734Srpaulo{
164214734Srpaulo	struct wps_event_ *e = ctx;
165214734Srpaulo	struct subscription *s = e->s;
166214734Srpaulo
167214734Srpaulo	switch (event) {
168214734Srpaulo	case HTTP_CLIENT_OK:
169214734Srpaulo		wpa_printf(MSG_DEBUG,
170214734Srpaulo			   "WPS UPnP: Got event reply OK from "
171214734Srpaulo			   "%s", e->addr->domain_and_port);
172214734Srpaulo		event_delete(e);
173214734Srpaulo
174214734Srpaulo		/* Schedule sending more if there is more to send */
175214734Srpaulo		if (!dl_list_empty(&s->event_queue))
176214734Srpaulo			event_send_all_later(s->sm);
177214734Srpaulo		break;
178214734Srpaulo	case HTTP_CLIENT_FAILED:
179214734Srpaulo	case HTTP_CLIENT_INVALID_REPLY:
180214734Srpaulo		wpa_printf(MSG_DEBUG, "WPS UPnP: Failed to send event to %s",
181214734Srpaulo			   e->addr->domain_and_port);
182214734Srpaulo
183214734Srpaulo		/*
184214734Srpaulo		 * If other side doesn't like what we say, forget about them.
185214734Srpaulo		 * (There is no way to tell other side that we are dropping
186214734Srpaulo		 * them...).
187214734Srpaulo		 * Alternately, we could just do event_delete(e)
188214734Srpaulo		 */
189214734Srpaulo		wpa_printf(MSG_DEBUG, "WPS UPnP: Deleting subscription due to "
190214734Srpaulo			   "errors");
191214734Srpaulo		dl_list_del(&s->list);
192214734Srpaulo		subscription_destroy(s);
193214734Srpaulo		break;
194214734Srpaulo	case HTTP_CLIENT_TIMEOUT:
195214734Srpaulo		wpa_printf(MSG_DEBUG, "WPS UPnP: Event send timeout");
196189251Ssam		event_retry(e, 1);
197189251Ssam	}
198189251Ssam}
199189251Ssam
200189251Ssam
201189251Ssam/* event_send_start -- prepare to send a event message to subscriber
202189251Ssam *
203189251Ssam * This gets complicated because:
204189251Ssam * -- The message is sent via TCP and we have to keep the stream open
205189251Ssam *      for 30 seconds to get a response... then close it.
206189251Ssam * -- But we might have other event happen in the meantime...
207189251Ssam *      we have to queue them, if we lose them then the subscriber will
208189251Ssam *      be forced to unsubscribe and subscribe again.
209189251Ssam * -- If multiple URLs are provided then we are supposed to try successive
210189251Ssam *      ones after 30 second timeout.
211189251Ssam * -- The URLs might use domain names instead of dotted decimal addresses,
212189251Ssam *      and resolution of those may cause unwanted sleeping.
213189251Ssam * -- Doing the initial TCP connect can take a while, so we have to come
214189251Ssam *      back after connection and then send the data.
215189251Ssam *
216189251Ssam * Returns nonzero on error;
217189251Ssam *
218189251Ssam * Prerequisite: No current event send (s->current_event == NULL)
219189251Ssam *      and non-empty queue.
220189251Ssam */
221189251Ssamstatic int event_send_start(struct subscription *s)
222189251Ssam{
223189251Ssam	struct wps_event_ *e;
224214734Srpaulo	unsigned int itry;
225214734Srpaulo	struct wpabuf *buf;
226189251Ssam
227189251Ssam	/*
228189251Ssam	 * Assume we are called ONLY with no current event and ONLY with
229189251Ssam	 * nonempty event queue and ONLY with at least one address to send to.
230189251Ssam	 */
231214734Srpaulo	assert(!dl_list_empty(&s->addr_list));
232189251Ssam	assert(s->current_event == NULL);
233214734Srpaulo	assert(!dl_list_empty(&s->event_queue));
234189251Ssam
235189251Ssam	s->current_event = e = event_dequeue(s);
236189251Ssam
237214734Srpaulo	/* Use address according to number of retries */
238214734Srpaulo	itry = 0;
239214734Srpaulo	dl_list_for_each(e->addr, &s->addr_list, struct subscr_addr, list)
240214734Srpaulo		if (itry++ == e->retry)
241214734Srpaulo			break;
242214734Srpaulo	if (itry < e->retry)
243214734Srpaulo		return -1;
244189251Ssam
245214734Srpaulo	buf = event_build_message(e);
246214734Srpaulo	if (buf == NULL) {
247189251Ssam		event_retry(e, 0);
248189251Ssam		return -1;
249189251Ssam	}
250214734Srpaulo
251214734Srpaulo	e->http_event = http_client_addr(&e->addr->saddr, buf, 0,
252214734Srpaulo					 event_http_cb, e);
253214734Srpaulo	if (e->http_event == NULL) {
254214734Srpaulo		wpabuf_free(buf);
255189251Ssam		event_retry(e, 0);
256189251Ssam		return -1;
257189251Ssam	}
258214734Srpaulo
259189251Ssam	return 0;
260189251Ssam}
261189251Ssam
262189251Ssam
263189251Ssam/* event_send_all_later_handler -- actually send events as needed */
264209158Srpaulostatic void event_send_all_later_handler(void *eloop_data, void *user_ctx)
265189251Ssam{
266189251Ssam	struct upnp_wps_device_sm *sm = user_ctx;
267214734Srpaulo	struct subscription *s, *tmp;
268189251Ssam	int nerrors = 0;
269189251Ssam
270189251Ssam	sm->event_send_all_queued = 0;
271214734Srpaulo	dl_list_for_each_safe(s, tmp, &sm->subscriptions, struct subscription,
272214734Srpaulo			      list) {
273214734Srpaulo		if (dl_list_empty(&s->addr_list)) {
274189251Ssam			/* if we've given up on all addresses */
275189251Ssam			wpa_printf(MSG_DEBUG, "WPS UPnP: Removing "
276189251Ssam				   "subscription with no addresses");
277214734Srpaulo			dl_list_del(&s->list);
278214734Srpaulo			subscription_destroy(s);
279189251Ssam		} else {
280189251Ssam			if (s->current_event == NULL /* not busy */ &&
281214734Srpaulo			    !dl_list_empty(&s->event_queue) /* more to do */) {
282189251Ssam				if (event_send_start(s))
283189251Ssam					nerrors++;
284189251Ssam			}
285189251Ssam		}
286214734Srpaulo	}
287189251Ssam
288189251Ssam	if (nerrors) {
289189251Ssam		/* Try again later */
290189251Ssam		event_send_all_later(sm);
291189251Ssam	}
292189251Ssam}
293189251Ssam
294189251Ssam
295189251Ssam/* event_send_all_later -- schedule sending events to all subscribers
296189251Ssam * that need it.
297189251Ssam * This avoids two problems:
298189251Ssam * -- After getting a subscription, we should not send the first event
299189251Ssam *      until after our reply is fully queued to be sent back,
300189251Ssam * -- Possible stack depth or infinite recursion issues.
301189251Ssam */
302189251Ssamvoid event_send_all_later(struct upnp_wps_device_sm *sm)
303189251Ssam{
304189251Ssam	/*
305189251Ssam	 * The exact time in the future isn't too important. Waiting a bit
306189251Ssam	 * might let us do several together.
307189251Ssam	 */
308189251Ssam	if (sm->event_send_all_queued)
309189251Ssam		return;
310189251Ssam	sm->event_send_all_queued = 1;
311189251Ssam	eloop_register_timeout(EVENT_DELAY_SECONDS, EVENT_DELAY_MSEC,
312189251Ssam			       event_send_all_later_handler, NULL, sm);
313189251Ssam}
314189251Ssam
315189251Ssam
316189251Ssam/* event_send_stop_all -- cleanup */
317189251Ssamvoid event_send_stop_all(struct upnp_wps_device_sm *sm)
318189251Ssam{
319189251Ssam	if (sm->event_send_all_queued)
320189251Ssam		eloop_cancel_timeout(event_send_all_later_handler, NULL, sm);
321189251Ssam	sm->event_send_all_queued = 0;
322189251Ssam}
323189251Ssam
324189251Ssam
325189251Ssam/**
326189251Ssam * event_add - Add a new event to a queue
327189251Ssam * @s: Subscription
328189251Ssam * @data: Event data (is copied; caller retains ownership)
329189251Ssam * Returns: 0 on success, 1 on error
330189251Ssam */
331189251Ssamint event_add(struct subscription *s, const struct wpabuf *data)
332189251Ssam{
333189251Ssam	struct wps_event_ *e;
334189251Ssam
335214734Srpaulo	if (dl_list_len(&s->event_queue) >= MAX_EVENTS_QUEUED) {
336189251Ssam		wpa_printf(MSG_DEBUG, "WPS UPnP: Too many events queued for "
337189251Ssam			   "subscriber");
338189251Ssam		return 1;
339189251Ssam	}
340189251Ssam
341189251Ssam	e = os_zalloc(sizeof(*e));
342189251Ssam	if (e == NULL)
343189251Ssam		return 1;
344214734Srpaulo	dl_list_init(&e->list);
345189251Ssam	e->s = s;
346189251Ssam	e->data = wpabuf_dup(data);
347189251Ssam	if (e->data == NULL) {
348189251Ssam		os_free(e);
349189251Ssam		return 1;
350189251Ssam	}
351189251Ssam	e->subscriber_sequence = s->next_subscriber_sequence++;
352189251Ssam	if (s->next_subscriber_sequence == 0)
353189251Ssam		s->next_subscriber_sequence++;
354214734Srpaulo	dl_list_add_tail(&s->event_queue, &e->list);
355189251Ssam	event_send_all_later(s->sm);
356189251Ssam	return 0;
357189251Ssam}
358