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