WPS UPnP: Add IP address and port details into debug messages
[mech_eap.orig] / 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                            "for %s", e->addr->domain_and_port);
192                 return;
193         }
194         event_enqueue_at_begin(s, e);
195         event_send_all_later(sm);
196 }
197
198
199 /* called if the overall event-sending process takes too long */
200 static void event_timeout_handler(void *eloop_data, void *user_ctx)
201 {
202         struct wps_event_ *e = user_ctx;
203         struct subscription *s = e->s;
204
205         assert(e == s->current_event);
206
207         wpa_printf(MSG_DEBUG, "WPS UPnP: Event send timeout");
208         event_retry(e, 1);
209 }
210
211
212 /* event_got_response_handler -- called back when http response is received. */
213 static void event_got_response_handler(struct httpread *handle, void *cookie,
214                                        enum httpread_event en)
215 {
216         struct wps_event_ *e = cookie;
217         struct subscription *s = e->s;
218         struct upnp_wps_device_sm *sm = s->sm;
219         struct httpread *hread = e->hread;
220         int reply_code = 0;
221
222         assert(e == s->current_event);
223         eloop_cancel_timeout(event_timeout_handler, NULL, e);
224
225         if (en == HTTPREAD_EVENT_FILE_READY) {
226                 if (httpread_hdr_type_get(hread) == HTTPREAD_HDR_TYPE_REPLY) {
227                         reply_code = httpread_reply_code_get(hread);
228                         if (reply_code == HTTP_OK) {
229                                 wpa_printf(MSG_DEBUG,
230                                            "WPS UPnP: Got event reply OK from "
231                                            "%s", e->addr->domain_and_port);
232                                 event_delete(e);
233                                 goto send_more;
234                         } else {
235                                 wpa_printf(MSG_DEBUG, "WPS UPnP: Got event "
236                                            "error reply code %d from %s",
237                                            reply_code,
238                                            e->addr->domain_and_port);
239                                 goto bad;
240                         }
241                 } else {
242                         wpa_printf(MSG_DEBUG, "WPS UPnP: Got bogus event "
243                                    "response %d from %s", en,
244                                    e->addr->domain_and_port);
245                 }
246         } else {
247                 wpa_printf(MSG_DEBUG, "WPS UPnP: Event response timeout/fail "
248                            "for %s", e->addr->domain_and_port);
249                 goto bad;
250         }
251         event_retry(e, 1);
252         goto send_more;
253
254 send_more:
255         /* Schedule sending more if there is more to send */
256         if (s->event_queue)
257                 event_send_all_later(sm);
258         return;
259
260 bad:
261         /*
262          * If other side doesn't like what we say, forget about them.
263          * (There is no way to tell other side that we are dropping
264          * them...).
265          * Alternately, we could just do event_delete(e)
266          */
267         wpa_printf(MSG_DEBUG, "WPS UPnP: Deleting subscription due to errors");
268         subscription_unlink(s);
269         subscription_destroy(s);
270 }
271
272
273 /* event_send_tx_ready -- actually write event message
274  *
275  * Prequisite: subscription socket descriptor has become ready to
276  * write (because connection to subscriber has been made).
277  *
278  * It is also possible that we are called because the connect has failed;
279  * it is possible to test for this, or we can just go ahead and then
280  * the write will fail.
281  */
282 static void event_send_tx_ready(int sock, void *eloop_ctx, void *sock_ctx)
283 {
284         struct wps_event_ *e = sock_ctx;
285         struct subscription *s = e->s;
286         struct wpabuf *buf;
287         char *b;
288
289         assert(e == s->current_event);
290         assert(e->sd == sock);
291
292         buf = wpabuf_alloc(1000 + wpabuf_len(e->data));
293         if (buf == NULL) {
294                 event_retry(e, 0);
295                 goto bad;
296         }
297         wpabuf_printf(buf, "NOTIFY %s HTTP/1.1\r\n", e->addr->path);
298         wpabuf_put_str(buf, "SERVER: Unspecified, UPnP/1.0, Unspecified\r\n");
299         wpabuf_printf(buf, "HOST: %s\r\n", e->addr->domain_and_port);
300         wpabuf_put_str(buf, "CONTENT-TYPE: text/xml; charset=\"utf-8\"\r\n"
301                        "NT: upnp:event\r\n"
302                        "NTS: upnp:propchange\r\n");
303         wpabuf_put_str(buf, "SID: uuid:");
304         b = wpabuf_put(buf, 0);
305         uuid_bin2str(s->uuid, b, 80);
306         wpabuf_put(buf, os_strlen(b));
307         wpabuf_put_str(buf, "\r\n");
308         wpabuf_printf(buf, "SEQ: %u\r\n", e->subscriber_sequence);
309         wpabuf_printf(buf, "CONTENT-LENGTH: %d\r\n",
310                       (int) wpabuf_len(e->data));
311         wpabuf_put_str(buf, "\r\n"); /* terminating empty line */
312         wpabuf_put_buf(buf, e->data);
313
314         /* Since the message size is pretty small, we should be
315          * able to get the operating system to buffer what we give it
316          * and not have to come back again later to write more...
317          */
318 #if 0
319         /* we could: Turn blocking back on? */
320         fcntl(e->sd, F_SETFL, 0);
321 #endif
322         wpa_printf(MSG_DEBUG, "WPS UPnP: Sending event to %s",
323                    e->addr->domain_and_port);
324         if (send_wpabuf(e->sd, buf) < 0) {
325                 event_retry(e, 1);
326                 goto bad;
327         }
328         wpabuf_free(buf);
329         buf = NULL;
330
331         if (e->sd_registered) {
332                 e->sd_registered = 0;
333                 eloop_unregister_sock(e->sd, EVENT_TYPE_WRITE);
334         }
335         /* Set up to read the reply */
336         e->hread = httpread_create(e->sd, event_got_response_handler,
337                                    e /* cookie */,
338                                    0 /* no data expected */,
339                                    EVENT_TIMEOUT_SEC);
340         if (e->hread == NULL) {
341                 wpa_printf(MSG_ERROR, "WPS UPnP: httpread_create failed");
342                 event_retry(e, 0);
343                 goto bad;
344         }
345         return;
346
347 bad:
348         /* Schedule sending more if there is more to send */
349         if (s->event_queue)
350                 event_send_all_later(s->sm);
351         wpabuf_free(buf);
352 }
353
354
355 /* event_send_start -- prepare to send a event message to subscriber
356  *
357  * This gets complicated because:
358  * -- The message is sent via TCP and we have to keep the stream open
359  *      for 30 seconds to get a response... then close it.
360  * -- But we might have other event happen in the meantime...
361  *      we have to queue them, if we lose them then the subscriber will
362  *      be forced to unsubscribe and subscribe again.
363  * -- If multiple URLs are provided then we are supposed to try successive
364  *      ones after 30 second timeout.
365  * -- The URLs might use domain names instead of dotted decimal addresses,
366  *      and resolution of those may cause unwanted sleeping.
367  * -- Doing the initial TCP connect can take a while, so we have to come
368  *      back after connection and then send the data.
369  *
370  * Returns nonzero on error;
371  *
372  * Prerequisite: No current event send (s->current_event == NULL)
373  *      and non-empty queue.
374  */
375 static int event_send_start(struct subscription *s)
376 {
377         struct wps_event_ *e;
378         int itry;
379
380         /*
381          * Assume we are called ONLY with no current event and ONLY with
382          * nonempty event queue and ONLY with at least one address to send to.
383          */
384         assert(s->addr_list != NULL);
385         assert(s->current_event == NULL);
386         assert(s->event_queue != NULL);
387
388         s->current_event = e = event_dequeue(s);
389
390         /* Use address acc. to no. of retries */
391         e->addr = s->addr_list;
392         for (itry = 0; itry < e->retry; itry++)
393                 e->addr = e->addr->next;
394
395         e->sd = socket(AF_INET, SOCK_STREAM, 0);
396         if (e->sd < 0) {
397                 event_retry(e, 0);
398                 return -1;
399         }
400         /* set non-blocking so we don't sleep waiting for connection */
401         if (fcntl(e->sd, F_SETFL, O_NONBLOCK) != 0) {
402                 event_retry(e, 0);
403                 return -1;
404         }
405         /*
406          * Start the connect. It might succeed immediately but more likely will
407          * return errno EINPROGRESS.
408          */
409         if (connect(e->sd, (struct sockaddr *) &e->addr->saddr,
410                     sizeof(e->addr->saddr))) {
411                 if (errno != EINPROGRESS) {
412                         event_retry(e, 1);
413                         return -1;
414                 }
415         }
416         /* Call back when ready for writing (or on failure...). */
417         if (eloop_register_sock(e->sd, EVENT_TYPE_WRITE, event_send_tx_ready,
418                                 NULL, e)) {
419                 event_retry(e, 0);
420                 return -1;
421         }
422         e->sd_registered = 1;
423         /* Don't wait forever! */
424         if (eloop_register_timeout(EVENT_TIMEOUT_SEC, 0, event_timeout_handler,
425                                    NULL, e)) {
426                 event_retry(e, 0);
427                 return -1;
428         }
429         return 0;
430 }
431
432
433 /* event_send_all_later_handler -- actually send events as needed */
434 void event_send_all_later_handler(void *eloop_data, void *user_ctx)
435 {
436         struct upnp_wps_device_sm *sm = user_ctx;
437         struct subscription *s;
438         struct subscription *s_old;
439         int nerrors = 0;
440
441         sm->event_send_all_queued = 0;
442         s = sm->subscriptions;
443         if (s == NULL)
444                 return;
445         do {
446                 if (s->addr_list == NULL) {
447                         /* if we've given up on all addresses */
448                         wpa_printf(MSG_DEBUG, "WPS UPnP: Removing "
449                                    "subscription with no addresses");
450                         s_old = s;
451                         s = s_old->next;
452                         subscription_unlink(s_old);
453                         subscription_destroy(s_old);
454                 } else {
455                         if (s->current_event == NULL /* not busy */ &&
456                             s->event_queue != NULL /* more to do */) {
457                                 if (event_send_start(s))
458                                         nerrors++;
459                         }
460                         s = s->next;
461                 }
462         } while (sm->subscriptions != NULL && s != sm->subscriptions);
463
464         if (nerrors) {
465                 /* Try again later */
466                 event_send_all_later(sm);
467         }
468 }
469
470
471 /* event_send_all_later -- schedule sending events to all subscribers
472  * that need it.
473  * This avoids two problems:
474  * -- After getting a subscription, we should not send the first event
475  *      until after our reply is fully queued to be sent back,
476  * -- Possible stack depth or infinite recursion issues.
477  */
478 void event_send_all_later(struct upnp_wps_device_sm *sm)
479 {
480         /*
481          * The exact time in the future isn't too important. Waiting a bit
482          * might let us do several together.
483          */
484         if (sm->event_send_all_queued)
485                 return;
486         sm->event_send_all_queued = 1;
487         eloop_register_timeout(EVENT_DELAY_SECONDS, EVENT_DELAY_MSEC,
488                                event_send_all_later_handler, NULL, sm);
489 }
490
491
492 /* event_send_stop_all -- cleanup */
493 void event_send_stop_all(struct upnp_wps_device_sm *sm)
494 {
495         if (sm->event_send_all_queued)
496                 eloop_cancel_timeout(event_send_all_later_handler, NULL, sm);
497         sm->event_send_all_queued = 0;
498 }
499
500
501 /**
502  * event_add - Add a new event to a queue
503  * @s: Subscription
504  * @data: Event data (is copied; caller retains ownership)
505  * Returns: 0 on success, 1 on error
506  */
507 int event_add(struct subscription *s, const struct wpabuf *data)
508 {
509         struct wps_event_ *e;
510
511         if (s->n_queue >= MAX_EVENTS_QUEUED) {
512                 wpa_printf(MSG_DEBUG, "WPS UPnP: Too many events queued for "
513                            "subscriber");
514                 return 1;
515         }
516
517         e = os_zalloc(sizeof(*e));
518         if (e == NULL)
519                 return 1;
520         e->s = s;
521         e->sd = -1;
522         e->data = wpabuf_dup(data);
523         if (e->data == NULL) {
524                 os_free(e);
525                 return 1;
526         }
527         e->subscriber_sequence = s->next_subscriber_sequence++;
528         if (s->next_subscriber_sequence == 0)
529                 s->next_subscriber_sequence++;
530         event_enqueue_at_end(s, e);
531         event_send_all_later(s->sm);
532         return 0;
533 }