Sat Jul 12 2014 17:18:36

Asterisk developer's documentation


res_calendar_caldav.c
Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 2008 - 2009, Digium, Inc.
00005  *
00006  * Terry Wilson <twilson@digium.com>
00007  *
00008  * See http://www.asterisk.org for more information about
00009  * the Asterisk project. Please do not directly contact
00010  * any of the maintainers of this project for assistance;
00011  * the project provides a web site, mailing lists and IRC
00012  * channels for your use.
00013  *
00014  * This program is free software, distributed under the terms of
00015  * the GNU General Public License Version 2. See the LICENSE file
00016  * at the top of the source tree.
00017  */
00018 
00019 /*! \file
00020  * \brief Resource for handling CalDAV calendars
00021  */
00022 
00023 /*** MODULEINFO
00024    <depend>neon</depend>
00025    <depend>ical</depend>
00026    <depend>libxml2</depend>
00027    <support_level>core</support_level>
00028 ***/
00029 
00030 #include "asterisk.h"
00031 
00032 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 413587 $")
00033 
00034 #include <libical/ical.h>
00035 #include <ne_session.h>
00036 #include <ne_uri.h>
00037 #include <ne_request.h>
00038 #include <ne_auth.h>
00039 #include <ne_redirect.h>
00040 #include <libxml/xmlmemory.h>
00041 #include <libxml/parser.h>
00042 
00043 #include "asterisk/module.h"
00044 #include "asterisk/calendar.h"
00045 #include "asterisk/lock.h"
00046 #include "asterisk/config.h"
00047 #include "asterisk/astobj2.h"
00048 
00049 static void *caldav_load_calendar(void *data);
00050 static void *unref_caldav(void *obj);
00051 static int caldav_write_event(struct ast_calendar_event *event);
00052 
00053 static struct ast_calendar_tech caldav_tech = {
00054    .type = "caldav",
00055    .description = "CalDAV calendars",
00056    .module = AST_MODULE,
00057    .load_calendar = caldav_load_calendar,
00058    .unref_calendar = unref_caldav,
00059    .write_event = caldav_write_event,
00060 };
00061 
00062 struct caldav_pvt {
00063    AST_DECLARE_STRING_FIELDS(
00064       AST_STRING_FIELD(url);
00065       AST_STRING_FIELD(user);
00066       AST_STRING_FIELD(secret);
00067    );
00068    struct ast_calendar *owner;
00069    ne_uri uri;
00070    ne_session *session;
00071    struct ao2_container *events;
00072 };
00073 
00074 static void caldav_destructor(void *obj)
00075 {
00076    struct caldav_pvt *pvt = obj;
00077 
00078    ast_debug(1, "Destroying pvt for CalDAV calendar %s\n", pvt->owner->name);
00079    if (pvt->session) {
00080       ne_session_destroy(pvt->session);
00081    }
00082    ast_string_field_free_memory(pvt);
00083 
00084    ao2_callback(pvt->events, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL);
00085 
00086    ao2_ref(pvt->events, -1);
00087 }
00088 
00089 static void *unref_caldav(void *obj)
00090 {
00091    struct caldav_pvt *pvt = obj;
00092 
00093    ao2_ref(pvt, -1);
00094    return NULL;
00095 }
00096 
00097 static int fetch_response_reader(void *data, const char *block, size_t len)
00098 {
00099    struct ast_str **response = data;
00100    unsigned char *tmp;
00101 
00102    if (!(tmp = ast_malloc(len + 1))) {
00103       return -1;
00104    }
00105    memcpy(tmp, block, len);
00106    tmp[len] = '\0';
00107    ast_str_append(response, 0, "%s", tmp);
00108    ast_free(tmp);
00109 
00110    return 0;
00111 }
00112 
00113 static int auth_credentials(void *userdata, const char *realm, int attempts, char *username, char *secret)
00114 {
00115    struct caldav_pvt *pvt = userdata;
00116 
00117    if (attempts > 1) {
00118       ast_log(LOG_WARNING, "Invalid username or password for CalDAV calendar '%s'\n", pvt->owner->name);
00119       return -1;
00120    }
00121 
00122    ne_strnzcpy(username, pvt->user, NE_ABUFSIZ);
00123    ne_strnzcpy(secret, pvt->secret, NE_ABUFSIZ);
00124 
00125    return 0;
00126 }
00127 
00128 static int debug_response_handler(void *userdata, ne_request *req, const ne_status *st)
00129 {
00130    if (st->code < 200 || st->code > 299) {
00131       ast_debug(1, "Unexpected response from server, %d: %s\n", st->code, st->reason_phrase);
00132       return 0;
00133    }
00134    return 1;
00135 }
00136 
00137 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)
00138 {
00139    struct ast_str *response;
00140    ne_request *req;
00141    int ret;
00142    char buf[1000];
00143 
00144    if (!pvt) {
00145       ast_log(LOG_ERROR, "There is no private!\n");
00146       return NULL;
00147    }
00148 
00149    if (!(response = ast_str_create(512))) {
00150       ast_log(LOG_ERROR, "Could not allocate memory for response.\n");
00151       return NULL;
00152    }
00153 
00154    snprintf(buf, sizeof(buf), "%s%s", pvt->uri.path, subdir ? ast_str_buffer(subdir) : "");
00155 
00156    req = ne_request_create(pvt->session, method, buf);
00157    ne_add_response_body_reader(req, debug_response_handler, fetch_response_reader, &response);
00158    ne_set_request_body_buffer(req, ast_str_buffer(req_body), ast_str_strlen(req_body));
00159    ne_add_request_header(req, "Content-type", ast_strlen_zero(content_type) ? "text/xml" : content_type);
00160 
00161    ret = ne_request_dispatch(req);
00162    ne_request_destroy(req);
00163 
00164    if (ret != NE_OK) {
00165       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));
00166       ast_free(response);
00167       return NULL;
00168    }
00169 
00170    return response;
00171 }
00172 
00173 static int caldav_write_event(struct ast_calendar_event *event)
00174 {
00175    struct caldav_pvt *pvt;
00176    struct ast_str *body = NULL, *response = NULL, *subdir = NULL;
00177    icalcomponent *calendar, *icalevent;
00178    icaltimezone *utc = icaltimezone_get_utc_timezone();
00179    int ret = -1;
00180 
00181    if (!event) {
00182       ast_log(LOG_WARNING, "No event passed!\n");
00183       return -1;
00184    }
00185 
00186    if (!(event->start && event->end)) {
00187       ast_log(LOG_WARNING, "The event must contain a start and an end\n");
00188       return -1;
00189    }
00190    if (!(body = ast_str_create(512)) ||
00191       !(subdir = ast_str_create(32))) {
00192       ast_log(LOG_ERROR, "Could not allocate memory for request!\n");
00193       goto write_cleanup;
00194    }
00195 
00196    pvt = event->owner->tech_pvt;
00197 
00198    if (ast_strlen_zero(event->uid)) {
00199       unsigned short val[8];
00200       int x;
00201       for (x = 0; x < 8; x++) {
00202          val[x] = ast_random();
00203       }
00204       ast_string_field_build(event, uid, "%04x%04x-%04x-%04x-%04x-%04x%04x%04x",
00205          (unsigned)val[0], (unsigned)val[1], (unsigned)val[2],
00206          (unsigned)val[3], (unsigned)val[4], (unsigned)val[5],
00207          (unsigned)val[6], (unsigned)val[7]);
00208    }
00209 
00210    calendar = icalcomponent_new(ICAL_VCALENDAR_COMPONENT);
00211    icalcomponent_add_property(calendar, icalproperty_new_version("2.0"));
00212    icalcomponent_add_property(calendar, icalproperty_new_prodid("-//Digium, Inc.//res_caldav//EN"));
00213 
00214    icalevent = icalcomponent_new(ICAL_VEVENT_COMPONENT);
00215    icalcomponent_add_property(icalevent, icalproperty_new_dtstamp(icaltime_current_time_with_zone(utc)));
00216    icalcomponent_add_property(icalevent, icalproperty_new_uid(event->uid));
00217    icalcomponent_add_property(icalevent, icalproperty_new_dtstart(icaltime_from_timet_with_zone(event->start, 0, utc)));
00218    icalcomponent_add_property(icalevent, icalproperty_new_dtend(icaltime_from_timet_with_zone(event->end, 0, utc)));
00219    if (!ast_strlen_zero(event->organizer)) {
00220       icalcomponent_add_property(icalevent, icalproperty_new_organizer(event->organizer));
00221    }
00222    if (!ast_strlen_zero(event->summary)) {
00223       icalcomponent_add_property(icalevent, icalproperty_new_summary(event->summary));
00224    }
00225    if (!ast_strlen_zero(event->description)) {
00226       icalcomponent_add_property(icalevent, icalproperty_new_description(event->description));
00227    }
00228    if (!ast_strlen_zero(event->location)) {
00229       icalcomponent_add_property(icalevent, icalproperty_new_location(event->location));
00230    }
00231    if (!ast_strlen_zero(event->categories)) {
00232       icalcomponent_add_property(icalevent, icalproperty_new_categories(event->categories));
00233    }
00234    if (event->priority > 0) {
00235       icalcomponent_add_property(icalevent, icalproperty_new_priority(event->priority));
00236    }
00237 
00238    switch (event->busy_state) {
00239    case AST_CALENDAR_BS_BUSY:
00240       icalcomponent_add_property(icalevent, icalproperty_new_status(ICAL_STATUS_CONFIRMED));
00241       break;
00242 
00243    case AST_CALENDAR_BS_BUSY_TENTATIVE:
00244       icalcomponent_add_property(icalevent, icalproperty_new_status(ICAL_STATUS_TENTATIVE));
00245       break;
00246 
00247    default:
00248       icalcomponent_add_property(icalevent, icalproperty_new_status(ICAL_STATUS_NONE));
00249    }
00250 
00251    icalcomponent_add_component(calendar, icalevent);
00252 
00253    ast_str_append(&body, 0, "%s", icalcomponent_as_ical_string(calendar));
00254    ast_str_set(&subdir, 0, "%s%s.ics", pvt->url[strlen(pvt->url) - 1] == '/' ? "" : "/", event->uid);
00255 
00256    if ((response = caldav_request(pvt, "PUT", body, subdir, "text/calendar"))) {
00257       ret = 0;
00258    }
00259 
00260 write_cleanup:
00261    if (body) {
00262       ast_free(body);
00263    }
00264    if (response) {
00265       ast_free(response);
00266    }
00267    if (subdir) {
00268       ast_free(subdir);
00269    }
00270 
00271    return ret;
00272 }
00273 
00274 static struct ast_str *caldav_get_events_between(struct caldav_pvt *pvt, time_t start_time, time_t end_time)
00275 {
00276    struct ast_str *body, *response;
00277    icaltimezone *utc = icaltimezone_get_utc_timezone();
00278    icaltimetype start, end;
00279    const char *start_str, *end_str;
00280 
00281    if (!(body = ast_str_create(512))) {
00282       ast_log(LOG_ERROR, "Could not allocate memory for body of request!\n");
00283       return NULL;
00284    }
00285 
00286    start = icaltime_from_timet_with_zone(start_time, 0, utc);
00287    end = icaltime_from_timet_with_zone(end_time, 0, utc);
00288    start_str = icaltime_as_ical_string(start);
00289    end_str = icaltime_as_ical_string(end);
00290 
00291    /* If I was really being efficient, I would store a collection of event URIs and etags,
00292     * first doing a query of just the etag and seeing if anything had changed.  If it had,
00293     * then I would do a request for each of the events that had changed, and only bother
00294     * updating those.  Oh well. */
00295    ast_str_append(&body, 0,
00296       "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n"
00297       "<C:calendar-query xmlns:D=\"DAV:\" xmlns:C=\"urn:ietf:params:xml:ns:caldav\">\n"
00298       "  <D:prop>\n"
00299       "    <C:calendar-data>\n"
00300       "      <C:expand start=\"%s\" end=\"%s\"/>\n"
00301       "    </C:calendar-data>\n"
00302       "  </D:prop>\n"
00303       "  <C:filter>\n"
00304       "    <C:comp-filter name=\"VCALENDAR\">\n"
00305       "      <C:comp-filter name=\"VEVENT\">\n"
00306       "        <C:time-range start=\"%s\" end=\"%s\"/>\n"
00307       "      </C:comp-filter>\n"
00308       "    </C:comp-filter>\n"
00309       "  </C:filter>\n"
00310       "</C:calendar-query>\n", start_str, end_str, start_str, end_str);
00311 
00312    response = caldav_request(pvt, "REPORT", body, NULL, NULL);
00313    ast_free(body);
00314    if (response && !ast_str_strlen(response)) {
00315       ast_free(response);
00316       return NULL;
00317    }
00318 
00319    return response;
00320 }
00321 
00322 static time_t icalfloat_to_timet(icaltimetype time) 
00323 {
00324    struct ast_tm tm = {0,};
00325    struct timeval tv;
00326 
00327    tm.tm_mday = time.day;
00328    tm.tm_mon = time.month - 1;
00329    tm.tm_year = time.year - 1900;
00330    tm.tm_hour = time.hour;
00331    tm.tm_min = time.minute;
00332    tm.tm_sec = time.second;
00333    tm.tm_isdst = -1;
00334    tv = ast_mktime(&tm, NULL);
00335 
00336    return tv.tv_sec;
00337 }
00338 
00339 /* span->start & span->end may be dates or floating times which have no timezone,
00340  * which would mean that they should apply to the local timezone for all recepients.
00341  * For example, if a meeting was set for 1PM-2PM floating time, people in different time
00342  * zones would not be scheduled at the same local times.  Dates are often treated as
00343  * floating times, so all day events will need to be converted--so we can trust the
00344  * span here, and instead will grab the start and end from the component, which will
00345  * allow us to test for floating times or dates.
00346  */
00347 static void caldav_add_event(icalcomponent *comp, struct icaltime_span *span, void *data)
00348 {
00349    struct caldav_pvt *pvt = data;
00350    struct ast_calendar_event *event;
00351    icaltimezone *utc = icaltimezone_get_utc_timezone();
00352    icaltimetype start, end, tmp;
00353    icalcomponent *valarm;
00354    icalproperty *prop;
00355    struct icaltriggertype trigger;
00356 
00357    if (!(pvt && pvt->owner)) {
00358       ast_log(LOG_ERROR, "Require a private structure with an owner\n");
00359       return;
00360    }
00361 
00362    if (!(event = ast_calendar_event_alloc(pvt->owner))) {
00363       ast_log(LOG_ERROR, "Could not allocate an event!\n");
00364       return;
00365    }
00366 
00367    start = icalcomponent_get_dtstart(comp);
00368    end = icalcomponent_get_dtend(comp);
00369 
00370    event->start = icaltime_get_tzid(start) ? span->start : icalfloat_to_timet(start);
00371    event->end = icaltime_get_tzid(end) ? span->end : icalfloat_to_timet(end);
00372    event->busy_state = span->is_busy ? AST_CALENDAR_BS_BUSY : AST_CALENDAR_BS_FREE;
00373 
00374    if ((prop = icalcomponent_get_first_property(comp, ICAL_SUMMARY_PROPERTY))) {
00375       ast_string_field_set(event, summary, icalproperty_get_value_as_string(prop));
00376    }
00377 
00378    if ((prop = icalcomponent_get_first_property(comp, ICAL_DESCRIPTION_PROPERTY))) {
00379       ast_string_field_set(event, description, icalproperty_get_value_as_string(prop));
00380    }
00381 
00382    if ((prop = icalcomponent_get_first_property(comp, ICAL_ORGANIZER_PROPERTY))) {
00383       ast_string_field_set(event, organizer, icalproperty_get_value_as_string(prop));
00384    }
00385 
00386    if ((prop = icalcomponent_get_first_property(comp, ICAL_LOCATION_PROPERTY))) {
00387       ast_string_field_set(event, location, icalproperty_get_value_as_string(prop));
00388    }
00389 
00390    if ((prop = icalcomponent_get_first_property(comp, ICAL_CATEGORIES_PROPERTY))) {
00391       ast_string_field_set(event, categories, icalproperty_get_value_as_string(prop));
00392    }
00393 
00394    if ((prop = icalcomponent_get_first_property(comp, ICAL_PRIORITY_PROPERTY))) {
00395       event->priority = icalvalue_get_integer(icalproperty_get_value(prop));
00396    }
00397 
00398    if ((prop = icalcomponent_get_first_property(comp, ICAL_UID_PROPERTY))) {
00399       ast_string_field_set(event, uid, icalproperty_get_value_as_string(prop));
00400    } else {
00401       ast_log(LOG_WARNING, "No UID found, but one is required. Generating, but updates may not be acurate\n");
00402       if (!ast_strlen_zero(event->summary)) {
00403          ast_string_field_set(event, uid, event->summary);
00404       } else {
00405          char tmp[100];
00406          snprintf(tmp, sizeof(tmp), "%ld", event->start);
00407          ast_string_field_set(event, uid, tmp);
00408       }
00409    }
00410 
00411    /* Get the attendees */
00412    for (prop = icalcomponent_get_first_property(comp, ICAL_ATTENDEE_PROPERTY);
00413          prop; prop = icalcomponent_get_next_property(comp, ICAL_ATTENDEE_PROPERTY)) {
00414       struct ast_calendar_attendee *attendee;
00415       const char *data;
00416 
00417       if (!(attendee = ast_calloc(1, sizeof(*attendee)))) {
00418          event = ast_calendar_unref_event(event);
00419          return;
00420       }
00421       data = icalproperty_get_attendee(prop);
00422       if (ast_strlen_zero(data)) {
00423          ast_free(attendee);
00424          continue;
00425       }
00426       attendee->data = ast_strdup(data);
00427       AST_LIST_INSERT_TAIL(&event->attendees, attendee, next);
00428    }
00429 
00430 
00431    /* Only set values for alarm based on VALARM.  Can be overriden in main/calendar.c by autoreminder
00432     * therefore, go ahead and add events even if their is no VALARM or it is malformed
00433     * Currently we are only getting the first VALARM and are handling repitition in main/calendar.c from calendar.conf */
00434    if (!(valarm = icalcomponent_get_first_component(comp, ICAL_VALARM_COMPONENT))) {
00435       ao2_link(pvt->events, event);
00436       event = ast_calendar_unref_event(event);
00437       return;
00438    }
00439 
00440    if (!(prop = icalcomponent_get_first_property(valarm, ICAL_TRIGGER_PROPERTY))) {
00441       ast_log(LOG_WARNING, "VALARM has no TRIGGER, skipping!\n");
00442       ao2_link(pvt->events, event);
00443       event = ast_calendar_unref_event(event);
00444       return;
00445    }
00446 
00447    trigger = icalproperty_get_trigger(prop);
00448 
00449    if (icaltriggertype_is_null_trigger(trigger)) {
00450       ast_log(LOG_WARNING, "Bad TRIGGER for VALARM, skipping!\n");
00451       ao2_link(pvt->events, event);
00452       event = ast_calendar_unref_event(event);
00453       return;
00454    }
00455 
00456    if (!icaltime_is_null_time(trigger.time)) { /* This is an absolute time */
00457       tmp = icaltime_convert_to_zone(trigger.time, utc);
00458       event->alarm = icaltime_as_timet_with_zone(tmp, utc);
00459    } else { /* Offset from either dtstart or dtend */
00460       /* XXX Technically you can check RELATED to see if the event fires from the END of the event
00461        * But, I'm not sure I've ever seen anyone implement it in calendaring software, so I'm ignoring for now */
00462       tmp = icaltime_add(start, trigger.duration);
00463       event->alarm = icaltime_as_timet_with_zone(tmp, icaltime_get_timezone(start));
00464    }
00465 
00466    ao2_link(pvt->events, event);
00467    event = ast_calendar_unref_event(event);
00468 
00469    return;
00470 }
00471 
00472 struct xmlstate {
00473    int in_caldata;
00474    struct caldav_pvt *pvt;
00475    struct ast_str *cdata;
00476    time_t start;
00477    time_t end;
00478 };
00479 
00480 static void handle_start_element(void *data, const xmlChar *fullname, const xmlChar **atts)
00481 {
00482    struct xmlstate *state = data;
00483 
00484    if (!xmlStrcasecmp(fullname, BAD_CAST "C:calendar-data")) {
00485       state->in_caldata = 1;
00486       ast_str_reset(state->cdata);
00487    }
00488 }
00489 
00490 static void handle_end_element(void *data, const xmlChar *name)
00491 {
00492    struct xmlstate *state = data;
00493    struct icaltimetype start, end;
00494    icaltimezone *utc = icaltimezone_get_utc_timezone();
00495    icalcomponent *iter;
00496    icalcomponent *comp;
00497 
00498    if (xmlStrcasecmp(name, BAD_CAST "C:calendar-data")) {
00499       return;
00500    }
00501 
00502    state->in_caldata = 0;
00503    if (!(state->cdata && ast_str_strlen(state->cdata))) {
00504       return;
00505    }
00506    /* XXX Parse the calendar blurb for recurrence events in the time range,
00507     * create an event, and add it to pvt->events */
00508    start = icaltime_from_timet_with_zone(state->start, 0, utc);
00509    end = icaltime_from_timet_with_zone(state->end, 0, utc);
00510    comp = icalparser_parse_string(ast_str_buffer(state->cdata));
00511 
00512    for (iter = icalcomponent_get_first_component(comp, ICAL_VEVENT_COMPONENT);
00513         iter;
00514         iter = icalcomponent_get_next_component(comp, ICAL_VEVENT_COMPONENT))
00515    {
00516       icalcomponent_foreach_recurrence(iter, start, end, caldav_add_event, state->pvt);
00517    }
00518 
00519    icalcomponent_free(comp);
00520 }
00521 
00522 static void handle_characters(void *data, const xmlChar *ch, int len)
00523 {
00524    struct xmlstate *state = data;
00525    xmlChar *tmp;
00526 
00527    if (!state->in_caldata) {
00528       return;
00529    }
00530 
00531    tmp = xmlStrndup(ch, len);
00532    ast_str_append(&state->cdata, 0, "%s", (char *)tmp);
00533    xmlFree(tmp);
00534 }
00535 
00536 static int update_caldav(struct caldav_pvt *pvt)
00537 {
00538    struct timeval now = ast_tvnow();
00539    time_t start, end;
00540    struct ast_str *response;
00541    xmlSAXHandler saxHandler;
00542    struct xmlstate state = {
00543       .in_caldata = 0,
00544       .pvt = pvt
00545    };
00546 
00547    start = now.tv_sec;
00548    end = now.tv_sec + 60 * pvt->owner->timeframe;
00549    if (!(response = caldav_get_events_between(pvt, start, end))) {
00550       return -1;
00551    }
00552 
00553    if (!(state.cdata = ast_str_create(512))) {
00554       ast_free(response);
00555       return -1;
00556    }
00557 
00558    state.start = start;
00559    state.end = end;
00560 
00561    memset(&saxHandler, 0, sizeof(saxHandler));
00562    saxHandler.startElement = handle_start_element;
00563    saxHandler.endElement = handle_end_element;
00564    saxHandler.characters = handle_characters;
00565 
00566    xmlSAXUserParseMemory(&saxHandler, &state, ast_str_buffer(response), ast_str_strlen(response));
00567 
00568    ast_calendar_merge_events(pvt->owner, pvt->events);
00569 
00570    ast_free(response);
00571    ast_free(state.cdata);
00572 
00573    return 0;
00574 }
00575 
00576 static int verify_cert(void *userdata, int failures, const ne_ssl_certificate *cert)
00577 {
00578    /* Verify all certs */
00579    return 0;
00580 }
00581 
00582 static void *caldav_load_calendar(void *void_data)
00583 {
00584    struct caldav_pvt *pvt;
00585    const struct ast_config *cfg;
00586    struct ast_variable *v;
00587    struct ast_calendar *cal = void_data;
00588    ast_mutex_t refreshlock;
00589 
00590    if (!(cal && (cfg = ast_calendar_config_acquire()))) {
00591       ast_log(LOG_ERROR, "You must enable calendar support for res_caldav to load\n");
00592       return NULL;
00593    }
00594 
00595    if (ao2_trylock(cal)) {
00596       if (cal->unloading) {
00597          ast_log(LOG_WARNING, "Unloading module, load_calendar cancelled.\n");
00598       } else {
00599          ast_log(LOG_WARNING, "Could not lock calendar, aborting!\n");
00600       }
00601       ast_calendar_config_release();
00602       return NULL;
00603    }
00604 
00605    if (!(pvt = ao2_alloc(sizeof(*pvt), caldav_destructor))) {
00606       ast_log(LOG_ERROR, "Could not allocate caldav_pvt structure for calendar: %s\n", cal->name);
00607       ast_calendar_config_release();
00608       return NULL;
00609    }
00610 
00611    pvt->owner = cal;
00612 
00613    if (!(pvt->events = ast_calendar_event_container_alloc())) {
00614       ast_log(LOG_ERROR, "Could not allocate space for fetching events for calendar: %s\n", cal->name);
00615       pvt = unref_caldav(pvt);
00616       ao2_unlock(cal);
00617       ast_calendar_config_release();
00618       return NULL;
00619    }
00620 
00621    if (ast_string_field_init(pvt, 32)) {
00622       ast_log(LOG_ERROR, "Couldn't allocate string field space for calendar: %s\n", cal->name);
00623       pvt = unref_caldav(pvt);
00624       ao2_unlock(cal);
00625       ast_calendar_config_release();
00626       return NULL;
00627    }
00628 
00629    for (v = ast_variable_browse(cfg, cal->name); v; v = v->next) {
00630       if (!strcasecmp(v->name, "url")) {
00631          ast_string_field_set(pvt, url, v->value);
00632       } else if (!strcasecmp(v->name, "user")) {
00633          ast_string_field_set(pvt, user, v->value);
00634       } else if (!strcasecmp(v->name, "secret")) {
00635          ast_string_field_set(pvt, secret, v->value);
00636       }
00637    }
00638 
00639    ast_calendar_config_release();
00640 
00641    if (ast_strlen_zero(pvt->url)) {
00642       ast_log(LOG_WARNING, "No URL was specified for CalDAV calendar '%s' - skipping.\n", cal->name);
00643       pvt = unref_caldav(pvt);
00644       ao2_unlock(cal);
00645       return NULL;
00646    }
00647 
00648    if (ne_uri_parse(pvt->url, &pvt->uri) || pvt->uri.host == NULL || pvt->uri.path == NULL) {
00649       ast_log(LOG_WARNING, "Could not parse url '%s' for CalDAV calendar '%s' - skipping.\n", pvt->url, cal->name);
00650       pvt = unref_caldav(pvt);
00651       ao2_unlock(cal);
00652       return NULL;
00653    }
00654 
00655    if (pvt->uri.scheme == NULL) {
00656       pvt->uri.scheme = "http";
00657    }
00658 
00659    if (pvt->uri.port == 0) {
00660       pvt->uri.port = ne_uri_defaultport(pvt->uri.scheme);
00661    }
00662 
00663    pvt->session = ne_session_create(pvt->uri.scheme, pvt->uri.host, pvt->uri.port);
00664    ne_redirect_register(pvt->session);
00665    ne_set_server_auth(pvt->session, auth_credentials, pvt);
00666    if (!strcasecmp(pvt->uri.scheme, "https")) {
00667       ne_ssl_trust_default_ca(pvt->session);
00668       ne_ssl_set_verify(pvt->session, verify_cert, NULL);
00669    }
00670 
00671    cal->tech_pvt = pvt;
00672 
00673    ast_mutex_init(&refreshlock);
00674 
00675    /* Load it the first time */
00676    update_caldav(pvt);
00677 
00678    ao2_unlock(cal);
00679 
00680    /* The only writing from another thread will be if unload is true */
00681    for (;;) {
00682       struct timeval tv = ast_tvnow();
00683       struct timespec ts = {0,};
00684 
00685       ts.tv_sec = tv.tv_sec + (60 * pvt->owner->refresh);
00686 
00687       ast_mutex_lock(&refreshlock);
00688       while (!pvt->owner->unloading) {
00689          if (ast_cond_timedwait(&pvt->owner->unload, &refreshlock, &ts) == ETIMEDOUT) {
00690             break;
00691          }
00692       }
00693       ast_mutex_unlock(&refreshlock);
00694 
00695       if (pvt->owner->unloading) {
00696          ast_debug(10, "Skipping refresh since we got a shutdown signal\n");
00697          return NULL;
00698       }
00699 
00700       ast_debug(10, "Refreshing after %d minute timeout\n", pvt->owner->refresh);
00701 
00702       update_caldav(pvt);
00703    }
00704 
00705    return NULL;
00706 }
00707 
00708 static int load_module(void)
00709 {
00710    ne_sock_init();
00711    if (ast_calendar_register(&caldav_tech)) {
00712       ne_sock_exit();
00713       return AST_MODULE_LOAD_DECLINE;
00714    }
00715 
00716    return AST_MODULE_LOAD_SUCCESS;
00717 }
00718 
00719 static int unload_module(void)
00720 {
00721    ast_calendar_unregister(&caldav_tech);
00722    ne_sock_exit();
00723    return 0;
00724 }
00725 
00726 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Asterisk CalDAV Calendar Integration",
00727       .load = load_module,
00728       .unload = unload_module,
00729       .load_pri = AST_MODPRI_DEVSTATE_PLUGIN,
00730    );