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