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