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