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