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