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