More 'static' qualifiers on module global variables.
[asterisk/asterisk.git] / res / res_calendar_caldav.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2008 - 2009, Digium, Inc.
5  *
6  * Terry Wilson <twilson@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  * \brief Resource for handling iCalnedar calendars
21  */
22
23 /*** MODULEINFO
24         <depend>neon</depend>
25         <depend>ical</depend>
26         <depend>libxml2</depend>
27 ***/
28 #include "asterisk.h"
29
30 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
31
32 #include <libical/ical.h>
33 #include <neon/ne_session.h>
34 #include <neon/ne_uri.h>
35 #include <neon/ne_request.h>
36 #include <neon/ne_auth.h>
37 #include <libxml/xmlmemory.h>
38 #include <libxml/parser.h>
39
40 #include "asterisk/module.h"
41 #include "asterisk/calendar.h"
42 #include "asterisk/lock.h"
43 #include "asterisk/config.h"
44 #include "asterisk/astobj2.h"
45
46 static void *caldav_load_calendar(void *data);
47 static void *unref_caldav(void *obj);
48 static int caldav_write_event(struct ast_calendar_event *event);
49
50 static struct ast_calendar_tech caldav_tech = {
51         .type = "caldav",
52         .description = "CalDAV calendars",
53         .module = AST_MODULE,
54         .load_calendar = caldav_load_calendar,
55         .unref_calendar = unref_caldav,
56         .write_event = caldav_write_event,
57 };
58
59 struct caldav_pvt {
60         AST_DECLARE_STRING_FIELDS(
61                 AST_STRING_FIELD(url);
62                 AST_STRING_FIELD(user);
63                 AST_STRING_FIELD(secret);
64         );
65         struct ast_calendar *owner;
66         ne_uri uri;
67         ne_session *session;
68         struct ao2_container *events;
69 };
70
71 static int cb_true(void *user_data, void *arg, int flags)
72 {
73         return CMP_MATCH;
74 }
75
76 static void caldav_destructor(void *obj)
77 {
78         struct caldav_pvt *pvt = obj;
79
80         ast_debug(1, "Destroying pvt for CalDAV calendar %s\n", pvt->owner->name);
81         if (pvt->session) {
82                 ne_session_destroy(pvt->session);
83         }
84         ast_string_field_free_memory(pvt);
85
86         ao2_callback(pvt->events, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, cb_true, NULL);
87
88         ao2_ref(pvt->events, -1);
89 }
90
91 static void *unref_caldav(void *obj)
92 {
93         struct caldav_pvt *pvt = obj;
94
95         ao2_ref(pvt, -1);
96         return NULL;
97 }
98
99 static int fetch_response_reader(void *data, const char *block, size_t len)
100 {
101         struct ast_str **response = data;
102         unsigned char *tmp;
103
104         if (!(tmp = ast_malloc(len + 1))) {
105                 return -1;
106         }
107         memcpy(tmp, block, len);
108         tmp[len] = '\0';
109         ast_str_append(response, 0, "%s", tmp);
110         ast_free(tmp);
111
112         return 0;
113 }
114
115 static int auth_credentials(void *userdata, const char *realm, int attempts, char *username, char *secret)
116 {
117         struct caldav_pvt *pvt = userdata;
118
119         if (attempts > 1) {
120                 ast_log(LOG_WARNING, "Invalid username or password for CalDAV calendar '%s'\n", pvt->owner->name);
121                 return -1;
122         }
123
124         ne_strnzcpy(username, pvt->user, NE_ABUFSIZ);
125         ne_strnzcpy(secret, pvt->secret, NE_ABUFSIZ);
126
127         return 0;
128 }
129
130 static struct ast_str *caldav_request(struct caldav_pvt *pvt, const char *method, struct ast_str *req_body, struct ast_str *subdir, const char *content_type)
131 {
132         struct ast_str *response;
133         ne_request *req;
134         int ret;
135         char buf[1000];
136
137         if (!pvt) {
138                 ast_log(LOG_ERROR, "There is no private!\n");
139                 return NULL;
140         }
141
142         if (!(response = ast_str_create(512))) {
143                 ast_log(LOG_ERROR, "Could not allocate memory for response.\n");
144                 return NULL;
145         }
146
147         snprintf(buf, sizeof(buf), "%s%s", pvt->uri.path, subdir ? ast_str_buffer(subdir) : "");
148
149         req = ne_request_create(pvt->session, method, buf);
150         ne_add_response_body_reader(req, ne_accept_2xx, fetch_response_reader, &response);
151         ne_set_request_body_buffer(req, ast_str_buffer(req_body), ast_str_strlen(req_body));
152         ne_add_request_header(req, "Content-type", ast_strlen_zero(content_type) ? "text/xml" : content_type);
153
154         ret = ne_request_dispatch(req);
155         ne_request_destroy(req);
156
157         if (ret != NE_OK || !ast_str_strlen(response)) {
158                 ast_log(LOG_WARNING, "Unknown response to CalDAV calendar %s, request %s to %s: %s\n", pvt->owner->name, method, pvt->url, ne_get_error(pvt->session));
159                 ast_free(response);
160                 return NULL;
161         }
162
163         return response;
164 }
165
166 static int caldav_write_event(struct ast_calendar_event *event)
167 {
168         struct ast_str *body = NULL, *response = NULL, *subdir = NULL;
169         icalcomponent *calendar, *icalevent;
170         icaltimezone *utc = icaltimezone_get_utc_timezone();
171         int ret = -1;
172
173         if (!event) {
174                 ast_log(LOG_WARNING, "No event passed!\n");
175                 return -1;
176         }
177
178         if (!(event->start && event->end)) {
179                 ast_log(LOG_WARNING, "The event must contain a start and an end\n");
180                 return -1;
181         }
182         if (!(body = ast_str_create(512)) ||
183                 !(subdir = ast_str_create(32)) ||
184                 !(response = ast_str_create(512))) {
185                 ast_log(LOG_ERROR, "Could not allocate memory for request and response!\n");
186                 goto write_cleanup;
187         }
188
189         if (ast_strlen_zero(event->uid)) {
190                 unsigned short val[8];
191                 int x;
192                 for (x = 0; x < 8; x++) {
193                         val[x] = ast_random();
194                 }
195                 ast_string_field_build(event, uid, "%04x%04x-%04x-%04x-%04x-%04x%04x%04x", val[0], val[1], val[2], val[3], val[4], val[5], val[6], val[7]);
196         }
197
198         calendar = icalcomponent_new(ICAL_VCALENDAR_COMPONENT);
199         icalcomponent_add_property(calendar, icalproperty_new_version("2.0"));
200         icalcomponent_add_property(calendar, icalproperty_new_prodid("-//Digium, Inc.//res_caldav//EN"));
201
202         icalevent = icalcomponent_new(ICAL_VEVENT_COMPONENT);
203         icalcomponent_add_property(icalevent, icalproperty_new_dtstamp(icaltime_current_time_with_zone(utc)));
204         icalcomponent_add_property(icalevent, icalproperty_new_uid(event->uid));
205         icalcomponent_add_property(icalevent, icalproperty_new_dtstart(icaltime_from_timet_with_zone(event->start, 0, utc)));
206         icalcomponent_add_property(icalevent, icalproperty_new_dtend(icaltime_from_timet_with_zone(event->end, 0, utc)));
207         if (!ast_strlen_zero(event->organizer)) {
208                 icalcomponent_add_property(icalevent, icalproperty_new_organizer(event->organizer));
209         }
210         if (!ast_strlen_zero(event->summary)) {
211                 icalcomponent_add_property(icalevent, icalproperty_new_summary(event->summary));
212         }
213         if (!ast_strlen_zero(event->description)) {
214                 icalcomponent_add_property(icalevent, icalproperty_new_description(event->description));
215         }
216         if (!ast_strlen_zero(event->location)) {
217                 icalcomponent_add_property(icalevent, icalproperty_new_location(event->location));
218         }
219
220         switch (event->busy_state) {
221         case AST_CALENDAR_BS_BUSY:
222                 icalcomponent_add_property(icalevent, icalproperty_new_status(ICAL_STATUS_CONFIRMED));
223                 break;
224
225         case AST_CALENDAR_BS_BUSY_TENTATIVE:
226                 icalcomponent_add_property(icalevent, icalproperty_new_status(ICAL_STATUS_TENTATIVE));
227                 break;
228
229         default:
230                 icalcomponent_add_property(icalevent, icalproperty_new_status(ICAL_STATUS_NONE));
231         }
232
233         icalcomponent_add_component(calendar, icalevent);
234
235         ast_str_append(&body, 0, "%s", icalcomponent_as_ical_string(calendar));
236         ast_str_set(&subdir, 0, "%s%s.ics", ast_str_buffer(body)[ast_str_strlen(body)] == '/' ? "" : "/", event->uid);
237
238         response = caldav_request(event->owner->tech_pvt, "PUT", body, subdir, "text/calendar");
239
240         ret = 0;
241
242 write_cleanup:
243         if (body) {
244                 ast_free(body);
245         }
246         if (response) {
247                 ast_free(response);
248         }
249         if (subdir) {
250                 ast_free(subdir);
251         }
252
253         return ret;
254 }
255
256 static struct ast_str *caldav_get_events_between(struct caldav_pvt *pvt, time_t start_time, time_t end_time)
257 {
258         struct ast_str *body, *response;
259         icaltimezone *utc = icaltimezone_get_utc_timezone();
260         icaltimetype start, end;
261         const char *start_str, *end_str;
262
263         if (!(body = ast_str_create(512))) {
264                 ast_log(LOG_ERROR, "Could not allocate memory for body of request!\n");
265                 return NULL;
266         }
267
268         start = icaltime_from_timet_with_zone(start_time, 0, utc);
269         end = icaltime_from_timet_with_zone(end_time, 0, utc);
270         start_str = icaltime_as_ical_string(start);
271         end_str = icaltime_as_ical_string(end);
272
273         /* If I was really being efficient, I would store a collection of event URIs and etags,
274          * first doing a query of just the etag and seeing if anything had changed.  If it had,
275          * then I would do a request for each of the events that had changed, and only bother
276          * updating those.  Oh well. */
277         ast_str_append(&body, 0,
278                 "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n"
279                 "<C:calendar-query xmlns:D=\"DAV:\" xmlns:C=\"urn:ietf:params:xml:ns:caldav\">\n"
280                 "  <D:prop>\n"
281                 "    <C:calendar-data>\n"
282                 "      <C:expand start=\"%s\" end=\"%s\"/>\n"
283                 "    </C:calendar-data>\n"
284                 "  </D:prop>\n"
285                 "  <C:filter>\n"
286                 "    <C:comp-filter name=\"VCALENDAR\">\n"
287                 "      <C:comp-filter name=\"VEVENT\">\n"
288                 "        <C:time-range start=\"%s\" end=\"%s\"/>\n"
289                 "      </C:comp-filter>\n"
290                 "    </C:comp-filter>\n"
291                 "  </C:filter>\n"
292                 "</C:calendar-query>\n", start_str, end_str, start_str, end_str);
293
294         response = caldav_request(pvt, "REPORT", body, NULL, NULL);
295         ast_free(body);
296
297         return response;
298 }
299
300 static void caldav_add_event(icalcomponent *comp, struct icaltime_span *span, void *data)
301 {
302         struct caldav_pvt *pvt = data;
303         struct ast_calendar_event *event;
304         icaltimezone *utc = icaltimezone_get_utc_timezone();
305         icaltimetype start, end, tmp;
306         icalcomponent *valarm;
307         icalproperty *prop;
308         struct icaltriggertype trigger;
309
310         if (!(pvt && pvt->owner)) {
311                 ast_log(LOG_ERROR, "Require a private structure with an owner\n");
312                 return;
313         }
314
315         if (!(event = ast_calendar_event_alloc(pvt->owner))) {
316                 ast_log(LOG_ERROR, "Could not allocate an event!\n");
317                 return;
318         }
319
320         start = icaltime_from_timet_with_zone(span->start, 0, utc);
321         end = icaltime_from_timet_with_zone(span->end, 0, utc);
322         event->start = span->start;
323         event->end = span->end;
324
325         switch(icalcomponent_get_status(comp)) {
326         case ICAL_STATUS_CONFIRMED:
327                 event->busy_state = AST_CALENDAR_BS_BUSY;
328                 break;
329
330         case ICAL_STATUS_TENTATIVE:
331                 event->busy_state = AST_CALENDAR_BS_BUSY_TENTATIVE;
332                 break;
333
334         default:
335                 event->busy_state = AST_CALENDAR_BS_FREE;
336         }
337
338         if ((prop = icalcomponent_get_first_property(comp, ICAL_SUMMARY_PROPERTY))) {
339                 ast_string_field_set(event, summary, icalproperty_get_value_as_string(prop));
340         }
341
342         if ((prop = icalcomponent_get_first_property(comp, ICAL_DESCRIPTION_PROPERTY))) {
343                 ast_string_field_set(event, description, icalproperty_get_value_as_string(prop));
344         }
345
346         if ((prop = icalcomponent_get_first_property(comp, ICAL_ORGANIZER_PROPERTY))) {
347                 ast_string_field_set(event, organizer, icalproperty_get_value_as_string(prop));
348         }
349
350         if ((prop = icalcomponent_get_first_property(comp, ICAL_LOCATION_PROPERTY))) {
351                 ast_string_field_set(event, location, icalproperty_get_value_as_string(prop));
352         }
353
354         if ((prop = icalcomponent_get_first_property(comp, ICAL_UID_PROPERTY))) {
355                 ast_string_field_set(event, uid, icalproperty_get_value_as_string(prop));
356         } else {
357                 ast_log(LOG_WARNING, "No UID found, but one is required. Generating, but updates may not be acurate\n");
358                 if (!ast_strlen_zero(event->summary)) {
359                         ast_string_field_set(event, uid, event->summary);
360                 } else {
361                         char tmp[100];
362                         snprintf(tmp, sizeof(tmp), "%lu", event->start);
363                         ast_string_field_set(event, uid, tmp);
364                 }
365         }
366
367         /* Get the attendees */
368         for (prop = icalcomponent_get_first_property(comp, ICAL_ATTENDEE_PROPERTY);
369                         prop; prop = icalcomponent_get_next_property(comp, ICAL_ATTENDEE_PROPERTY)) {
370                 struct ast_calendar_attendee *attendee;
371                 const char *data;
372
373                 if (!(attendee = ast_calloc(1, sizeof(*attendee)))) {
374                         event = ast_calendar_unref_event(event);
375                         return;
376                 }
377                 data = icalproperty_get_attendee(prop);
378                 if (!ast_strlen_zero(data)) {
379                         attendee->data = ast_strdup(data);;
380                         AST_LIST_INSERT_TAIL(&event->attendees, attendee, next);
381                 }
382         }
383
384
385         /* Only set values for alarm based on VALARM.  Can be overriden in main/calendar.c by autoreminder
386          * therefore, go ahead and add events even if their is no VALARM or it is malformed
387          * Currently we are only getting the first VALARM and are handling repitition in main/calendar.c from calendar.conf */
388         if (!(valarm = icalcomponent_get_first_component(comp, ICAL_VALARM_COMPONENT))) {
389                 ao2_link(pvt->events, event);
390                 event = ast_calendar_unref_event(event);
391                 return;
392         }
393
394         if (!(prop = icalcomponent_get_first_property(valarm, ICAL_TRIGGER_PROPERTY))) {
395                 ast_log(LOG_WARNING, "VALARM has no TRIGGER, skipping!\n");
396                 ao2_link(pvt->events, event);
397                 event = ast_calendar_unref_event(event);
398                 return;
399         }
400
401         trigger = icalproperty_get_trigger(prop);
402
403         if (icaltriggertype_is_null_trigger(trigger)) {
404                 ast_log(LOG_WARNING, "Bad TRIGGER for VALARM, skipping!\n");
405                 ao2_link(pvt->events, event);
406                 event = ast_calendar_unref_event(event);
407                 return;
408         }
409
410         if (!icaltime_is_null_time(trigger.time)) { /* This is an absolute time */
411                 tmp = icaltime_convert_to_zone(trigger.time, utc);
412                 event->alarm = icaltime_as_timet_with_zone(tmp, utc);
413         } else { /* Offset from either dtstart or dtend */
414                 /* XXX Technically you can check RELATED to see if the event fires from the END of the event
415                  * But, I'm not sure I've ever seen anyone implement it in calendaring software, so I'm ignoring for now */
416                 tmp = icaltime_add(start, trigger.duration);
417                 event->alarm = icaltime_as_timet_with_zone(tmp, utc);
418         }
419
420         ao2_link(pvt->events, event);
421         event = ast_calendar_unref_event(event);
422
423         return;
424 }
425
426 struct xmlstate {
427         int in_caldata;
428         struct caldav_pvt *pvt;
429         struct ast_str *cdata;
430         time_t start;
431         time_t end;
432 };
433
434 static void handle_start_element(void *data, const xmlChar *fullname, const xmlChar **atts)
435 {
436         struct xmlstate *state = data;
437
438         if (!xmlStrcasecmp(fullname, BAD_CAST "C:calendar-data")) {
439                 state->in_caldata = 1;
440                 ast_str_reset(state->cdata);
441         }
442 }
443
444 static void handle_end_element(void *data, const xmlChar *name)
445 {
446         struct xmlstate *state = data;
447         struct icaltimetype start, end;
448         icaltimezone *utc = icaltimezone_get_utc_timezone();
449         icalcomponent *iter;
450         icalcomponent *comp;
451
452         if (xmlStrcasecmp(name, BAD_CAST "C:calendar-data")) {
453                 return;
454         }
455
456         state->in_caldata = 0;
457         if (!(state->cdata && ast_str_strlen(state->cdata))) {
458                 return;
459         }
460         /* XXX Parse the calendar blurb for recurrence events in the time range,
461          * create an event, and add it to pvt->events */
462         start = icaltime_from_timet_with_zone(state->start, 0, utc);
463         end = icaltime_from_timet_with_zone(state->end, 0, utc);
464         comp = icalparser_parse_string(ast_str_buffer(state->cdata));
465
466         for (iter = icalcomponent_get_first_component(comp, ICAL_VEVENT_COMPONENT);
467              iter;
468              iter = icalcomponent_get_next_component(comp, ICAL_VEVENT_COMPONENT))
469         {
470                 icalcomponent_foreach_recurrence(iter, start, end, caldav_add_event, state->pvt);
471         }
472
473         icalcomponent_free(comp);
474 }
475
476 static void handle_characters(void *data, const xmlChar *ch, int len)
477 {
478         struct xmlstate *state = data;
479         xmlChar *tmp;
480
481         if (!state->in_caldata) {
482                 return;
483         }
484
485         tmp = xmlStrndup(ch, len);
486         ast_str_append(&state->cdata, 0, "%s", (char *)tmp);
487         xmlFree(tmp);
488 }
489
490 static int update_caldav(struct caldav_pvt *pvt)
491 {
492         struct timeval now = ast_tvnow();
493         time_t start, end;
494         struct ast_str *response;
495         xmlSAXHandler saxHandler;
496         struct xmlstate state = {
497                 .in_caldata = 0,
498                 .pvt = pvt
499         };
500
501         start = now.tv_sec;
502         end = now.tv_sec + 60 * pvt->owner->timeframe;
503         if (!(response = caldav_get_events_between(pvt, start, end))) {
504                 return -1;
505         }
506
507         if (!(state.cdata = ast_str_create(512))) {
508                 ast_free(response);
509                 return -1;
510         }
511
512         state.start = start;
513         state.end = end;
514
515         memset(&saxHandler, 0, sizeof(saxHandler));
516         saxHandler.startElement = handle_start_element;
517         saxHandler.endElement = handle_end_element;
518         saxHandler.characters = handle_characters;
519
520         xmlSAXUserParseMemory(&saxHandler, &state, ast_str_buffer(response), ast_str_strlen(response));
521
522         ast_calendar_merge_events(pvt->owner, pvt->events);
523
524         ast_free(response);
525         ast_free(state.cdata);
526
527         return 0;
528 }
529
530 static int verify_cert(void *userdata, int failures, const ne_ssl_certificate *cert)
531 {
532         /* Verify all certs */
533         return 0;
534 }
535
536 static void *caldav_load_calendar(void *void_data)
537 {
538         struct caldav_pvt *pvt;
539         struct ast_variable *v;
540         struct ast_calendar *cal = void_data;
541         ast_mutex_t refreshlock;
542
543         if (!(cal && ast_calendar_config)) {
544                 ast_log(LOG_ERROR, "You must enable calendar support for res_caldav to load\n");
545                 return NULL;
546         }
547
548         if (ao2_trylock(cal)) {
549                 if (cal->unloading) {
550                         ast_log(LOG_WARNING, "Unloading module, load_calendar cancelled.\n");
551                 } else {
552                         ast_log(LOG_WARNING, "Could not lock calendar, aborting!\n");
553                 }
554                 return NULL;
555         }
556
557         if (!(pvt = ao2_alloc(sizeof(*pvt), caldav_destructor))) {
558                 ast_log(LOG_ERROR, "Could not allocate caldav_pvt structure for calendar: %s\n", cal->name);
559                 return NULL;
560         }
561
562         pvt->owner = cal;
563
564         if (!(pvt->events = ast_calendar_event_container_alloc())) {
565                 ast_log(LOG_ERROR, "Could not allocate space for fetching events for calendar: %s\n", cal->name);
566                 pvt = unref_caldav(pvt);
567                 ao2_unlock(cal);
568                 return NULL;
569         }
570
571         if (ast_string_field_init(pvt, 32)) {
572                 ast_log(LOG_ERROR, "Couldn't allocate string field space for calendar: %s\n", cal->name);
573                 pvt = unref_caldav(pvt);
574                 ao2_unlock(cal);
575                 return NULL;
576         }
577
578         for (v = ast_variable_browse(ast_calendar_config, cal->name); v; v = v->next) {
579                 if (!strcasecmp(v->name, "url")) {
580                         ast_string_field_set(pvt, url, v->value);
581                 } else if (!strcasecmp(v->name, "user")) {
582                         ast_string_field_set(pvt, user, v->value);
583                 } else if (!strcasecmp(v->name, "secret")) {
584                         ast_string_field_set(pvt, secret, v->value);
585                 }
586         }
587
588         if (ast_strlen_zero(pvt->url)) {
589                 ast_log(LOG_WARNING, "No URL was specified for CalDAV calendar '%s' - skipping.\n", cal->name);
590                 pvt = unref_caldav(pvt);
591                 ao2_unlock(cal);
592                 return NULL;
593         }
594
595         if (ne_uri_parse(pvt->url, &pvt->uri) || pvt->uri.host == NULL || pvt->uri.path == NULL) {
596                 ast_log(LOG_WARNING, "Could not parse url '%s' for CalDAV calendar '%s' - skipping.\n", pvt->url, cal->name);
597                 pvt = unref_caldav(pvt);
598                 ao2_unlock(cal);
599                 return NULL;
600         }
601
602         if (pvt->uri.scheme == NULL) {
603                 pvt->uri.scheme = "http";
604         }
605
606         if (pvt->uri.port == 0) {
607                 pvt->uri.port = ne_uri_defaultport(pvt->uri.scheme);
608         }
609
610         pvt->session = ne_session_create(pvt->uri.scheme, pvt->uri.host, pvt->uri.port);
611         ne_set_server_auth(pvt->session, auth_credentials, pvt);
612         if (!strncasecmp(pvt->uri.scheme, "https", sizeof(pvt->uri.scheme))) {
613                 ne_ssl_trust_default_ca(pvt->session);
614                 ne_ssl_set_verify(pvt->session, verify_cert, NULL);
615         }
616
617         cal->tech_pvt = pvt;
618
619         ast_mutex_init(&refreshlock);
620
621         /* Load it the first time */
622         update_caldav(pvt);
623
624         ao2_unlock(cal);
625
626         /* The only writing from another thread will be if unload is true */
627         for (;;) {
628                 struct timeval tv = ast_tvnow();
629                 struct timespec ts = {0,};
630
631                 ts.tv_sec = tv.tv_sec + (60 * pvt->owner->refresh);
632
633                 ast_mutex_lock(&refreshlock);
634                 while (!pvt->owner->unloading) {
635                         if (ast_cond_timedwait(&pvt->owner->unload, &refreshlock, &ts) == ETIMEDOUT) {
636                                 break;
637                         }
638                 }
639                 ast_mutex_unlock(&refreshlock);
640
641                 if (pvt->owner->unloading) {
642                         ast_debug(10, "Skipping refresh since we got a shutdown signal\n");
643                         return NULL;
644                 }
645
646                 ast_debug(10, "Refreshing after %d minute timeout\n", pvt->owner->refresh);
647
648                 update_caldav(pvt);
649         }
650
651         return NULL;
652 }
653
654 static int load_module(void)
655 {
656         ne_sock_init();
657         if (ast_calendar_register(&caldav_tech)) {
658                 ne_sock_exit();
659                 return AST_MODULE_LOAD_DECLINE;
660         }
661
662         return AST_MODULE_LOAD_SUCCESS;
663 }
664
665 static int unload_module(void)
666 {
667         ast_calendar_unregister(&caldav_tech);
668         ne_sock_exit();
669         return 0;
670 }
671
672 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Asterisk CalDAV Calendar Integration",
673                 .load = load_module,
674                 .unload = unload_module,
675         );