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