6ef29091401c0958bea29e9586d21ee40335e7ce
[libeap.git] / src / wps / wps_upnp_event.c
1 /*
2  * UPnP WPS Device - Event processing
3  * Copyright (c) 2000-2003 Intel Corporation
4  * Copyright (c) 2006-2007 Sony Corporation
5  * Copyright (c) 2008-2009 Atheros Communications
6  * Copyright (c) 2009, Jouni Malinen <j@w1.fi>
7  *
8  * See wps_upnp.c for more details on licensing and code history.
9  */
10
11 #include "includes.h"
12 #include <assert.h>
13
14 #include "common.h"
15 #include "eloop.h"
16 #include "uuid.h"
17 #include "http_client.h"
18 #include "wps_defs.h"
19 #include "wps_upnp.h"
20 #include "wps_upnp_i.h"
21
22 /*
23  * Event message generation (to subscribers)
24  *
25  * We make a separate copy for each message for each subscriber. This memory
26  * wasted could be limited (adding code complexity) by sharing copies, keeping
27  * a usage count and freeing when zero.
28  *
29  * Sending a message requires using a HTTP over TCP NOTIFY
30  * (like a PUT) which requires a number of states..
31  */
32
33 #define MAX_EVENTS_QUEUED 20   /* How far behind queued events */
34
35 /* How long to wait before sending event */
36 #define EVENT_DELAY_SECONDS 0
37 #define EVENT_DELAY_MSEC 0
38
39 /*
40  * Event information that we send to each subscriber is remembered in this
41  * struct. The event cannot be sent by simple UDP; it has to be sent by a HTTP
42  * over TCP transaction which requires various states.. It may also need to be
43  * retried at a different address (if more than one is available).
44  *
45  * TODO: As an optimization we could share data between subscribers.
46  */
47 struct wps_event_ {
48         struct dl_list list;
49         struct subscription *s;         /* parent */
50         unsigned subscriber_sequence;   /* which event for this subscription*/
51         unsigned int retry;             /* which retry */
52         struct subscr_addr *addr;       /* address to connect to */
53         struct wpabuf *data;            /* event data to send */
54         struct http_client *http_event;
55 };
56
57
58 /* event_clean -- clean sockets etc. of event
59  * Leaves data, retry count etc. alone.
60  */
61 static void event_clean(struct wps_event_ *e)
62 {
63         if (e->s->current_event == e)
64                 e->s->current_event = NULL;
65         http_client_free(e->http_event);
66         e->http_event = NULL;
67 }
68
69
70 /* event_delete -- delete single unqueued event
71  * (be sure to dequeue first if need be)
72  */
73 static void event_delete(struct wps_event_ *e)
74 {
75         event_clean(e);
76         wpabuf_free(e->data);
77         os_free(e);
78 }
79
80
81 /* event_dequeue -- get next event from the queue
82  * Returns NULL if empty.
83  */
84 static struct wps_event_ *event_dequeue(struct subscription *s)
85 {
86         struct wps_event_ *e;
87         e = dl_list_first(&s->event_queue, struct wps_event_, list);
88         if (e)
89                 dl_list_del(&e->list);
90         return e;
91 }
92
93
94 /* event_delete_all -- delete entire event queue and current event */
95 void event_delete_all(struct subscription *s)
96 {
97         struct wps_event_ *e;
98         while ((e = event_dequeue(s)) != NULL)
99                 event_delete(e);
100         if (s->current_event) {
101                 event_delete(s->current_event);
102                 /* will set: s->current_event = NULL;  */
103         }
104 }
105
106
107 /**
108  * event_retry - Called when we had a failure delivering event msg
109  * @e: Event
110  * @do_next_address: skip address e.g. on connect fail
111  */
112 static void event_retry(struct wps_event_ *e, int do_next_address)
113 {
114         struct subscription *s = e->s;
115         struct upnp_wps_device_sm *sm = s->sm;
116
117         event_clean(e);
118         /* will set: s->current_event = NULL; */
119
120         if (do_next_address)
121                 e->retry++;
122         if (e->retry >= dl_list_len(&s->addr_list)) {
123                 wpa_printf(MSG_DEBUG, "WPS UPnP: Giving up on sending event "
124                            "for %s", e->addr->domain_and_port);
125                 return;
126         }
127         dl_list_add(&s->event_queue, &e->list);
128         event_send_all_later(sm);
129 }
130
131
132 static struct wpabuf * event_build_message(struct wps_event_ *e)
133 {
134         struct wpabuf *buf;
135         char *b;
136
137         buf = wpabuf_alloc(1000 + wpabuf_len(e->data));
138         if (buf == NULL)
139                 return NULL;
140         wpabuf_printf(buf, "NOTIFY %s HTTP/1.1\r\n", e->addr->path);
141         wpabuf_put_str(buf, "SERVER: Unspecified, UPnP/1.0, Unspecified\r\n");
142         wpabuf_printf(buf, "HOST: %s\r\n", e->addr->domain_and_port);
143         wpabuf_put_str(buf, "CONTENT-TYPE: text/xml; charset=\"utf-8\"\r\n"
144                        "NT: upnp:event\r\n"
145                        "NTS: upnp:propchange\r\n");
146         wpabuf_put_str(buf, "SID: uuid:");
147         b = wpabuf_put(buf, 0);
148         uuid_bin2str(e->s->uuid, b, 80);
149         wpabuf_put(buf, os_strlen(b));
150         wpabuf_put_str(buf, "\r\n");
151         wpabuf_printf(buf, "SEQ: %u\r\n", e->subscriber_sequence);
152         wpabuf_printf(buf, "CONTENT-LENGTH: %d\r\n",
153                       (int) wpabuf_len(e->data));
154         wpabuf_put_str(buf, "\r\n"); /* terminating empty line */
155         wpabuf_put_buf(buf, e->data);
156         return buf;
157 }
158
159
160 static void event_http_cb(void *ctx, struct http_client *c,
161                           enum http_client_event event)
162 {
163         struct wps_event_ *e = ctx;
164         struct subscription *s = e->s;
165
166         switch (event) {
167         case HTTP_CLIENT_OK:
168                 wpa_printf(MSG_DEBUG,
169                            "WPS UPnP: Got event reply OK from "
170                            "%s", e->addr->domain_and_port);
171                 event_delete(e);
172
173                 /* Schedule sending more if there is more to send */
174                 if (!dl_list_empty(&s->event_queue))
175                         event_send_all_later(s->sm);
176                 break;
177         case HTTP_CLIENT_FAILED:
178         case HTTP_CLIENT_INVALID_REPLY:
179                 wpa_printf(MSG_DEBUG, "WPS UPnP: Failed to send event to %s",
180                            e->addr->domain_and_port);
181
182                 /*
183                  * If other side doesn't like what we say, forget about them.
184                  * (There is no way to tell other side that we are dropping
185                  * them...).
186                  * Alternately, we could just do event_delete(e)
187                  */
188                 wpa_printf(MSG_DEBUG, "WPS UPnP: Deleting subscription due to "
189                            "errors");
190                 dl_list_del(&s->list);
191                 subscription_destroy(s);
192                 break;
193         case HTTP_CLIENT_TIMEOUT:
194                 wpa_printf(MSG_DEBUG, "WPS UPnP: Event send timeout");
195                 event_retry(e, 1);
196         }
197 }
198
199
200 /* event_send_start -- prepare to send a event message to subscriber
201  *
202  * This gets complicated because:
203  * -- The message is sent via TCP and we have to keep the stream open
204  *      for 30 seconds to get a response... then close it.
205  * -- But we might have other event happen in the meantime...
206  *      we have to queue them, if we lose them then the subscriber will
207  *      be forced to unsubscribe and subscribe again.
208  * -- If multiple URLs are provided then we are supposed to try successive
209  *      ones after 30 second timeout.
210  * -- The URLs might use domain names instead of dotted decimal addresses,
211  *      and resolution of those may cause unwanted sleeping.
212  * -- Doing the initial TCP connect can take a while, so we have to come
213  *      back after connection and then send the data.
214  *
215  * Returns nonzero on error;
216  *
217  * Prerequisite: No current event send (s->current_event == NULL)
218  *      and non-empty queue.
219  */
220 static int event_send_start(struct subscription *s)
221 {
222         struct wps_event_ *e;
223         unsigned int itry;
224         struct wpabuf *buf;
225
226         /*
227          * Assume we are called ONLY with no current event and ONLY with
228          * nonempty event queue and ONLY with at least one address to send to.
229          */
230         assert(!dl_list_empty(&s->addr_list));
231         assert(s->current_event == NULL);
232         assert(!dl_list_empty(&s->event_queue));
233
234         s->current_event = e = event_dequeue(s);
235
236         /* Use address according to number of retries */
237         itry = 0;
238         dl_list_for_each(e->addr, &s->addr_list, struct subscr_addr, list)
239                 if (itry++ == e->retry)
240                         break;
241         if (itry < e->retry)
242                 return -1;
243
244         buf = event_build_message(e);
245         if (buf == NULL) {
246                 event_retry(e, 0);
247                 return -1;
248         }
249
250         e->http_event = http_client_addr(&e->addr->saddr, buf, 0,
251                                          event_http_cb, e);
252         if (e->http_event == NULL) {
253                 wpabuf_free(buf);
254                 event_retry(e, 0);
255                 return -1;
256         }
257
258         return 0;
259 }
260
261
262 /* event_send_all_later_handler -- actually send events as needed */
263 static void event_send_all_later_handler(void *eloop_data, void *user_ctx)
264 {
265         struct upnp_wps_device_sm *sm = user_ctx;
266         struct subscription *s, *tmp;
267         int nerrors = 0;
268
269         sm->event_send_all_queued = 0;
270         dl_list_for_each_safe(s, tmp, &sm->subscriptions, struct subscription,
271                               list) {
272                 if (dl_list_empty(&s->addr_list)) {
273                         /* if we've given up on all addresses */
274                         wpa_printf(MSG_DEBUG, "WPS UPnP: Removing "
275                                    "subscription with no addresses");
276                         dl_list_del(&s->list);
277                         subscription_destroy(s);
278                 } else {
279                         if (s->current_event == NULL /* not busy */ &&
280                             !dl_list_empty(&s->event_queue) /* more to do */) {
281                                 if (event_send_start(s))
282                                         nerrors++;
283                         }
284                 }
285         }
286
287         if (nerrors) {
288                 /* Try again later */
289                 event_send_all_later(sm);
290         }
291 }
292
293
294 /* event_send_all_later -- schedule sending events to all subscribers
295  * that need it.
296  * This avoids two problems:
297  * -- After getting a subscription, we should not send the first event
298  *      until after our reply is fully queued to be sent back,
299  * -- Possible stack depth or infinite recursion issues.
300  */
301 void event_send_all_later(struct upnp_wps_device_sm *sm)
302 {
303         /*
304          * The exact time in the future isn't too important. Waiting a bit
305          * might let us do several together.
306          */
307         if (sm->event_send_all_queued)
308                 return;
309         sm->event_send_all_queued = 1;
310         eloop_register_timeout(EVENT_DELAY_SECONDS, EVENT_DELAY_MSEC,
311                                event_send_all_later_handler, NULL, sm);
312 }
313
314
315 /* event_send_stop_all -- cleanup */
316 void event_send_stop_all(struct upnp_wps_device_sm *sm)
317 {
318         if (sm->event_send_all_queued)
319                 eloop_cancel_timeout(event_send_all_later_handler, NULL, sm);
320         sm->event_send_all_queued = 0;
321 }
322
323
324 /**
325  * event_add - Add a new event to a queue
326  * @s: Subscription
327  * @data: Event data (is copied; caller retains ownership)
328  * Returns: 0 on success, 1 on error
329  */
330 int event_add(struct subscription *s, const struct wpabuf *data)
331 {
332         struct wps_event_ *e;
333
334         if (dl_list_len(&s->event_queue) >= MAX_EVENTS_QUEUED) {
335                 wpa_printf(MSG_DEBUG, "WPS UPnP: Too many events queued for "
336                            "subscriber");
337                 return 1;
338         }
339
340         e = os_zalloc(sizeof(*e));
341         if (e == NULL)
342                 return 1;
343         dl_list_init(&e->list);
344         e->s = s;
345         e->data = wpabuf_dup(data);
346         if (e->data == NULL) {
347                 os_free(e);
348                 return 1;
349         }
350         e->subscriber_sequence = s->next_subscriber_sequence++;
351         if (s->next_subscriber_sequence == 0)
352                 s->next_subscriber_sequence++;
353         dl_list_add_tail(&s->event_queue, &e->list);
354         event_send_all_later(s->sm);
355         return 0;
356 }