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