WPS: Convert assert() to error return
[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         if (dl_list_empty(&s->addr_list))
242                 return -1;
243         if (s->current_event)
244                 return -1;
245         if (dl_list_empty(&s->event_queue))
246                 return -1;
247
248         s->current_event = e = event_dequeue(s);
249
250         /* Use address according to number of retries */
251         itry = 0;
252         dl_list_for_each(e->addr, &s->addr_list, struct subscr_addr, list)
253                 if (itry++ == e->retry)
254                         break;
255         if (itry < e->retry)
256                 return -1;
257
258         buf = event_build_message(e);
259         if (buf == NULL) {
260                 event_retry(e, 0);
261                 return -1;
262         }
263
264         e->http_event = http_client_addr(&e->addr->saddr, buf, 0,
265                                          event_http_cb, e);
266         if (e->http_event == NULL) {
267                 wpabuf_free(buf);
268                 event_retry(e, 0);
269                 return -1;
270         }
271
272         return 0;
273 }
274
275
276 /* event_send_all_later_handler -- actually send events as needed */
277 static void event_send_all_later_handler(void *eloop_data, void *user_ctx)
278 {
279         struct upnp_wps_device_sm *sm = user_ctx;
280         struct subscription *s, *tmp;
281         int nerrors = 0;
282
283         sm->event_send_all_queued = 0;
284         dl_list_for_each_safe(s, tmp, &sm->subscriptions, struct subscription,
285                               list) {
286                 if (dl_list_empty(&s->addr_list)) {
287                         /* if we've given up on all addresses */
288                         wpa_printf(MSG_DEBUG, "WPS UPnP: Removing "
289                                    "subscription with no addresses");
290                         dl_list_del(&s->list);
291                         subscription_destroy(s);
292                 } else {
293                         if (s->current_event == NULL /* not busy */ &&
294                             !dl_list_empty(&s->event_queue) /* more to do */) {
295                                 if (event_send_start(s))
296                                         nerrors++;
297                         }
298                 }
299         }
300
301         if (nerrors) {
302                 /* Try again later */
303                 event_send_all_later(sm);
304         }
305 }
306
307
308 /* event_send_all_later -- schedule sending events to all subscribers
309  * that need it.
310  * This avoids two problems:
311  * -- After getting a subscription, we should not send the first event
312  *      until after our reply is fully queued to be sent back,
313  * -- Possible stack depth or infinite recursion issues.
314  */
315 void event_send_all_later(struct upnp_wps_device_sm *sm)
316 {
317         /*
318          * The exact time in the future isn't too important. Waiting a bit
319          * might let us do several together.
320          */
321         if (sm->event_send_all_queued)
322                 return;
323         sm->event_send_all_queued = 1;
324         eloop_register_timeout(EVENT_DELAY_SECONDS, EVENT_DELAY_MSEC,
325                                event_send_all_later_handler, NULL, sm);
326 }
327
328
329 /* event_send_stop_all -- cleanup */
330 void event_send_stop_all(struct upnp_wps_device_sm *sm)
331 {
332         if (sm->event_send_all_queued)
333                 eloop_cancel_timeout(event_send_all_later_handler, NULL, sm);
334         sm->event_send_all_queued = 0;
335 }
336
337
338 /**
339  * event_add - Add a new event to a queue
340  * @s: Subscription
341  * @data: Event data (is copied; caller retains ownership)
342  * Returns: 0 on success, 1 on error
343  */
344 int event_add(struct subscription *s, const struct wpabuf *data)
345 {
346         struct wps_event_ *e;
347         unsigned int len;
348
349         len = dl_list_len(&s->event_queue);
350         if (len >= MAX_EVENTS_QUEUED) {
351                 wpa_printf(MSG_DEBUG, "WPS UPnP: Too many events queued for "
352                            "subscriber %p", s);
353                 return 1;
354         }
355
356         e = os_zalloc(sizeof(*e));
357         if (e == NULL)
358                 return 1;
359         dl_list_init(&e->list);
360         e->s = s;
361         e->data = wpabuf_dup(data);
362         if (e->data == NULL) {
363                 os_free(e);
364                 return 1;
365         }
366         e->subscriber_sequence = s->next_subscriber_sequence++;
367         if (s->next_subscriber_sequence == 0)
368                 s->next_subscriber_sequence++;
369         wpa_printf(MSG_DEBUG, "WPS UPnP: Queue event %p for subscriber %p "
370                    "(queue len %u)", e, s, len + 1);
371         dl_list_add_tail(&s->event_queue, &e->list);
372         event_send_all_later(s->sm);
373         return 0;
374 }