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