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