WPS: Add support for external Registrars using UPnP transport
[mech_eap.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 #include <fcntl.h>
14
15 #include "common.h"
16 #include "eloop.h"
17 #include "uuid.h"
18 #include "httpread.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 EVENT_TIMEOUT_SEC 30   /* Drop sending event after timeout */
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 wps_event_ *next;
50         struct wps_event_ *prev;        /* double linked list */
51         struct subscription *s;         /* parent */
52         unsigned subscriber_sequence;   /* which event for this subscription*/
53         int retry;                      /* which retry */
54         struct subscr_addr *addr;       /* address to connect to */
55         struct wpabuf *data;            /* event data to send */
56         /* The following apply while we are sending an event message. */
57         int sd;            /* -1 or socket descriptor for open connection */
58         int sd_registered;        /* nonzero if we must cancel registration */
59         struct httpread *hread; /* NULL or open connection for event msg */
60 };
61
62
63 static void event_timeout_handler(void *eloop_data, void *user_ctx);
64
65 /* event_clean -- clean sockets etc. of event
66  * Leaves data, retry count etc. alone.
67  */
68 static void event_clean(struct wps_event_ *e)
69 {
70         if (e->s->current_event == e) {
71                 eloop_cancel_timeout(event_timeout_handler, NULL, e);
72                 e->s->current_event = NULL;
73         }
74         if (e->sd_registered) {
75                 eloop_unregister_sock(e->sd, EVENT_TYPE_WRITE);
76                 e->sd_registered = 0;
77         }
78         if (e->sd != -1) {
79                 close(e->sd);
80                 e->sd = -1;
81         }
82         if (e->hread)
83                 httpread_destroy(e->hread);
84         e->hread = NULL;
85 }
86
87
88 /* event_delete -- delete single unqueued event
89  * (be sure to dequeue first if need be)
90  */
91 void event_delete(struct wps_event_ *e)
92 {
93         event_clean(e);
94         wpabuf_free(e->data);
95         os_free(e);
96 }
97
98
99 /* event_dequeue -- get next event from the queue
100  * Returns NULL if empty.
101  */
102 static struct wps_event_ *event_dequeue(struct subscription *s)
103 {
104         struct wps_event_ **event_head = &s->event_queue;
105         struct wps_event_ *e = *event_head;
106         if (e == NULL)
107                 return NULL;
108         e->next->prev = e->prev;
109         e->prev->next = e->next;
110         if (*event_head == e) {
111                 if (e == e->next) {
112                         /* last in queue */
113                         *event_head = NULL;
114                 } else {
115                         *event_head = e->next;
116                 }
117         }
118         s->n_queue--;
119         e->next = e->prev = NULL;
120         /* but parent "s" is still valid */
121         return e;
122 }
123
124
125 /* event_enqueue_at_end -- add event to end of queue */
126 static void event_enqueue_at_end(struct subscription *s, struct wps_event_ *e)
127 {
128         struct wps_event_ **event_head = &s->event_queue;
129         if (*event_head == NULL) {
130                 *event_head = e->next = e->prev = e;
131         } else {
132                 e->next = *event_head;
133                 e->prev = e->next->prev;
134                 e->prev->next = e;
135                 e->next->prev = e;
136         }
137         s->n_queue++;
138 }
139
140
141 /* event_enqueue_at_begin -- add event to begin of queue
142  * (appropriate for retrying event only)
143  */
144 static void event_enqueue_at_begin(struct subscription *s,
145                                    struct wps_event_ *e)
146 {
147         struct wps_event_ **event_head = &s->event_queue;
148         if (*event_head == NULL) {
149                 *event_head = e->next = e->prev = e;
150         } else {
151                 e->prev = *event_head;
152                 e->next = e->prev->next;
153                 e->prev->next = e;
154                 e->next->prev = e;
155                 *event_head = e;
156         }
157         s->n_queue++;
158 }
159
160
161 /* event_delete_all -- delete entire event queue and current event */
162 void event_delete_all(struct subscription *s)
163 {
164         struct wps_event_ *e;
165         while ((e = event_dequeue(s)) != NULL)
166                 event_delete(e);
167         if (s->current_event) {
168                 event_delete(s->current_event);
169                 /* will set: s->current_event = NULL;  */
170         }
171 }
172
173
174 /**
175  * event_retry - Called when we had a failure delivering event msg
176  * @e: Event
177  * @do_next_address: skip address e.g. on connect fail
178  */
179 static void event_retry(struct wps_event_ *e, int do_next_address)
180 {
181         struct subscription *s = e->s;
182         struct upnp_wps_device_sm *sm = s->sm;
183
184         event_clean(e);
185         /* will set: s->current_event = NULL; */
186
187         if (do_next_address)
188                 e->retry++;
189         if (e->retry >= s->n_addr) {
190                 wpa_printf(MSG_DEBUG, "WPS UPnP: Giving up on sending event");
191                 return;
192         }
193         event_enqueue_at_begin(s, e);
194         event_send_all_later(sm);
195 }
196
197
198 /* called if the overall event-sending process takes too long */
199 static void event_timeout_handler(void *eloop_data, void *user_ctx)
200 {
201         struct wps_event_ *e = user_ctx;
202         struct subscription *s = e->s;
203
204         assert(e == s->current_event);
205
206         wpa_printf(MSG_DEBUG, "WPS UPnP: Event send timeout");
207         event_retry(e, 1);
208 }
209
210
211 /* event_got_response_handler -- called back when http response is received. */
212 static void event_got_response_handler(struct httpread *handle, void *cookie,
213                                        enum httpread_event en)
214 {
215         struct wps_event_ *e = cookie;
216         struct subscription *s = e->s;
217         struct upnp_wps_device_sm *sm = s->sm;
218         struct httpread *hread = e->hread;
219         int reply_code = 0;
220
221         assert(e == s->current_event);
222         eloop_cancel_timeout(event_timeout_handler, NULL, e);
223
224         if (en == HTTPREAD_EVENT_FILE_READY) {
225                 if (httpread_hdr_type_get(hread) == HTTPREAD_HDR_TYPE_REPLY) {
226                         reply_code = httpread_reply_code_get(hread);
227                         if (reply_code == HTTP_OK) {
228                                 wpa_printf(MSG_DEBUG,
229                                            "WPS UPnP: Got event reply OK");
230                                 event_delete(e);
231                                 goto send_more;
232                         } else {
233                                 wpa_printf(MSG_DEBUG, "WPS UPnP: Got event "
234                                            "error reply code %d", reply_code);
235                                 goto bad;
236                         }
237                 } else {
238                         wpa_printf(MSG_DEBUG, "WPS UPnP: Got bogus event "
239                                    "response %d", en);
240                 }
241         } else {
242                 wpa_printf(MSG_DEBUG, "WPS UPnP: Event response timeout/fail");
243                 goto bad;
244         }
245         event_retry(e, 1);
246         goto send_more;
247
248 send_more:
249         /* Schedule sending more if there is more to send */
250         if (s->event_queue)
251                 event_send_all_later(sm);
252         return;
253
254 bad:
255         /*
256          * If other side doesn't like what we say, forget about them.
257          * (There is no way to tell other side that we are dropping
258          * them...).
259          * Alternately, we could just do event_delete(e)
260          */
261         wpa_printf(MSG_DEBUG, "WPS UPnP: Deleting subscription due to errors");
262         subscription_unlink(s);
263         subscription_destroy(s);
264 }
265
266
267 /* event_send_tx_ready -- actually write event message
268  *
269  * Prequisite: subscription socket descriptor has become ready to
270  * write (because connection to subscriber has been made).
271  *
272  * It is also possible that we are called because the connect has failed;
273  * it is possible to test for this, or we can just go ahead and then
274  * the write will fail.
275  */
276 static void event_send_tx_ready(int sock, void *eloop_ctx, void *sock_ctx)
277 {
278         struct wps_event_ *e = sock_ctx;
279         struct subscription *s = e->s;
280         struct wpabuf *buf;
281         char *b;
282
283         assert(e == s->current_event);
284         assert(e->sd == sock);
285
286         buf = wpabuf_alloc(1000 + wpabuf_len(e->data));
287         if (buf == NULL) {
288                 event_retry(e, 0);
289                 goto bad;
290         }
291         wpabuf_printf(buf, "NOTIFY %s HTTP/1.1\r\n", e->addr->path);
292         wpabuf_put_str(buf, "SERVER: Unspecified, UPnP/1.0, Unspecified\r\n");
293         wpabuf_printf(buf, "HOST: %s\r\n", e->addr->domain_and_port);
294         wpabuf_put_str(buf, "CONTENT-TYPE: text/xml; charset=\"utf-8\"\r\n"
295                        "NT: upnp:event\r\n"
296                        "NTS: upnp:propchange\r\n");
297         wpabuf_put_str(buf, "SID: uuid:");
298         b = wpabuf_put(buf, 0);
299         uuid_bin2str(s->uuid, b, 80);
300         wpabuf_put(buf, os_strlen(b));
301         wpabuf_put_str(buf, "\r\n");
302         wpabuf_printf(buf, "SEQ: %u\r\n", e->subscriber_sequence);
303         wpabuf_printf(buf, "CONTENT-LENGTH: %d\r\n",
304                       (int) wpabuf_len(e->data));
305         wpabuf_put_str(buf, "\r\n"); /* terminating empty line */
306         wpabuf_put_buf(buf, e->data);
307
308         /* Since the message size is pretty small, we should be
309          * able to get the operating system to buffer what we give it
310          * and not have to come back again later to write more...
311          */
312 #if 0
313         /* we could: Turn blocking back on? */
314         fcntl(e->sd, F_SETFL, 0);
315 #endif
316         if (send_wpabuf(e->sd, buf) < 0) {
317                 event_retry(e, 1);
318                 goto bad;
319         }
320         wpabuf_free(buf);
321         buf = NULL;
322
323         if (e->sd_registered) {
324                 e->sd_registered = 0;
325                 eloop_unregister_sock(e->sd, EVENT_TYPE_WRITE);
326         }
327         /* Set up to read the reply */
328         e->hread = httpread_create(e->sd, event_got_response_handler,
329                                    e /* cookie */,
330                                    0 /* no data expected */,
331                                    EVENT_TIMEOUT_SEC);
332         if (e->hread == NULL) {
333                 wpa_printf(MSG_ERROR, "WPS UPnP: httpread_create failed");
334                 event_retry(e, 0);
335                 goto bad;
336         }
337         return;
338
339 bad:
340         /* Schedule sending more if there is more to send */
341         if (s->event_queue)
342                 event_send_all_later(s->sm);
343         wpabuf_free(buf);
344 }
345
346
347 /* event_send_start -- prepare to send a event message to subscriber
348  *
349  * This gets complicated because:
350  * -- The message is sent via TCP and we have to keep the stream open
351  *      for 30 seconds to get a response... then close it.
352  * -- But we might have other event happen in the meantime...
353  *      we have to queue them, if we lose them then the subscriber will
354  *      be forced to unsubscribe and subscribe again.
355  * -- If multiple URLs are provided then we are supposed to try successive
356  *      ones after 30 second timeout.
357  * -- The URLs might use domain names instead of dotted decimal addresses,
358  *      and resolution of those may cause unwanted sleeping.
359  * -- Doing the initial TCP connect can take a while, so we have to come
360  *      back after connection and then send the data.
361  *
362  * Returns nonzero on error;
363  *
364  * Prerequisite: No current event send (s->current_event == NULL)
365  *      and non-empty queue.
366  */
367 static int event_send_start(struct subscription *s)
368 {
369         struct wps_event_ *e;
370         int itry;
371
372         /*
373          * Assume we are called ONLY with no current event and ONLY with
374          * nonempty event queue and ONLY with at least one address to send to.
375          */
376         assert(s->addr_list != NULL);
377         assert(s->current_event == NULL);
378         assert(s->event_queue != NULL);
379
380         s->current_event = e = event_dequeue(s);
381
382         /* Use address acc. to no. of retries */
383         e->addr = s->addr_list;
384         for (itry = 0; itry < e->retry; itry++)
385                 e->addr = e->addr->next;
386
387         e->sd = socket(AF_INET, SOCK_STREAM, 0);
388         if (e->sd < 0) {
389                 event_retry(e, 0);
390                 return -1;
391         }
392         /* set non-blocking so we don't sleep waiting for connection */
393         if (fcntl(e->sd, F_SETFL, O_NONBLOCK) != 0) {
394                 event_retry(e, 0);
395                 return -1;
396         }
397         /*
398          * Start the connect. It might succeed immediately but more likely will
399          * return errno EINPROGRESS.
400          */
401         if (connect(e->sd, (struct sockaddr *) &e->addr->saddr,
402                     sizeof(e->addr->saddr))) {
403                 if (errno == EINPROGRESS) {
404                 } else {
405                         event_retry(e, 1);
406                         return -1;
407                 }
408         }
409         /* Call back when ready for writing (or on failure...). */
410         if (eloop_register_sock(e->sd, EVENT_TYPE_WRITE, event_send_tx_ready,
411                                 NULL, e)) {
412                 event_retry(e, 0);
413                 return -1;
414         }
415         e->sd_registered = 1;
416         /* Don't wait forever! */
417         if (eloop_register_timeout(EVENT_TIMEOUT_SEC, 0, event_timeout_handler,
418                                    NULL, e)) {
419                 event_retry(e, 0);
420                 return -1;
421         }
422         return 0;
423 }
424
425
426 /* event_send_all_later_handler -- actually send events as needed */
427 void event_send_all_later_handler(void *eloop_data, void *user_ctx)
428 {
429         struct upnp_wps_device_sm *sm = user_ctx;
430         struct subscription *s;
431         struct subscription *s_old;
432         int nerrors = 0;
433
434         sm->event_send_all_queued = 0;
435         if ((s = sm->subscriptions) == NULL)
436                 return;
437         do {
438                 if (s->addr_list == NULL) {
439                         /* if we've given up on all addresses */
440                         wpa_printf(MSG_DEBUG, "WPS UPnP: Removing "
441                                    "subscription with no addresses");
442                         s_old = s;
443                         s = s_old->next;
444                         subscription_unlink(s_old);
445                         subscription_destroy(s_old);
446                 } else {
447                         if (s->current_event == NULL /* not busy */ &&
448                             s->event_queue != NULL /* more to do */) {
449                                 if (event_send_start(s))
450                                         nerrors++;
451                         }
452                         s = s->next;
453                 }
454         } while (sm->subscriptions != NULL && s != sm->subscriptions);
455
456         if (nerrors) {
457                 /* Try again later */
458                 event_send_all_later(sm);
459         }
460 }
461
462
463 /* event_send_all_later -- schedule sending events to all subscribers
464  * that need it.
465  * This avoids two problems:
466  * -- After getting a subscription, we should not send the first event
467  *      until after our reply is fully queued to be sent back,
468  * -- Possible stack depth or infinite recursion issues.
469  */
470 void event_send_all_later(struct upnp_wps_device_sm *sm)
471 {
472         /*
473          * The exact time in the future isn't too important. Waiting a bit
474          * might let us do several together.
475          */
476         if (sm->event_send_all_queued)
477                 return;
478         sm->event_send_all_queued = 1;
479         eloop_register_timeout(EVENT_DELAY_SECONDS, EVENT_DELAY_MSEC,
480                                event_send_all_later_handler, NULL, sm);
481 }
482
483
484 /* event_send_stop_all -- cleanup */
485 void event_send_stop_all(struct upnp_wps_device_sm *sm)
486 {
487         if (sm->event_send_all_queued)
488                 eloop_cancel_timeout(event_send_all_later_handler, NULL, sm);
489         sm->event_send_all_queued = 0;
490 }
491
492
493 /**
494  * event_add - Add a new event to a queue
495  * @s: Subscription
496  * @data: Event data (is copied; caller retains ownership)
497  * Returns: 0 on success, 1 on error
498  */
499 int event_add(struct subscription *s, const struct wpabuf *data)
500 {
501         struct wps_event_ *e;
502
503         if (s->n_queue >= MAX_EVENTS_QUEUED) {
504                 wpa_printf(MSG_DEBUG, "WPS UPnP: Too many events queued for "
505                            "subscriber");
506                 return 1;
507         }
508
509         e = os_zalloc(sizeof(*e));
510         if (e == NULL)
511                 return 1;
512         e->s = s;
513         e->sd = -1;
514         e->data = wpabuf_dup(data);
515         if (e->data == NULL) {
516                 os_free(e);
517                 return 1;
518         }
519         e->subscriber_sequence = s->next_subscriber_sequence++;
520         if (s->next_subscriber_sequence == 0)
521                 s->next_subscriber_sequence++;
522         event_enqueue_at_end(s, e);
523         event_send_all_later(s->sm);
524         return 0;
525 }