Fri Aug 17 00:17:18 2018

Asterisk developer's documentation


res_calendar_icalendar.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 iCalendar calendars
00021  */
00022 
00023 /*** MODULEINFO
00024    <depend>neon</depend>
00025    <depend>ical</depend>
00026    <support_level>core</support_level>
00027 ***/
00028 
00029 #include "asterisk.h"
00030 
00031 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 413586 $")
00032 
00033 #include <libical/ical.h>
00034 #include <ne_session.h>
00035 #include <ne_uri.h>
00036 #include <ne_request.h>
00037 #include <ne_auth.h>
00038 #include <ne_redirect.h>
00039 
00040 #include "asterisk/module.h"
00041 #include "asterisk/calendar.h"
00042 #include "asterisk/lock.h"
00043 #include "asterisk/config.h"
00044 #include "asterisk/astobj2.h"
00045 
00046 static void *ical_load_calendar(void *data);
00047 static void *unref_icalendar(void *obj);
00048 
00049 static struct ast_calendar_tech ical_tech = {
00050    .type = "ical",
00051    .module = AST_MODULE,
00052    .description = "iCalendar .ics calendars",
00053    .load_calendar = ical_load_calendar,
00054    .unref_calendar = unref_icalendar,
00055 };
00056 
00057 struct icalendar_pvt {
00058    AST_DECLARE_STRING_FIELDS(
00059       AST_STRING_FIELD(url);
00060       AST_STRING_FIELD(user);
00061       AST_STRING_FIELD(secret);
00062    );
00063    struct ast_calendar *owner;
00064    ne_uri uri;
00065    ne_session *session;
00066    icalcomponent *data;
00067    struct ao2_container *events;
00068 };
00069 
00070 static void icalendar_destructor(void *obj)
00071 {
00072    struct icalendar_pvt *pvt = obj;
00073 
00074    ast_debug(1, "Destroying pvt for iCalendar %s\n", pvt->owner->name);
00075    if (pvt->session) {
00076       ne_session_destroy(pvt->session);
00077    }
00078    if (pvt->data) {
00079       icalcomponent_free(pvt->data);
00080    }
00081    ast_string_field_free_memory(pvt);
00082 
00083    ao2_callback(pvt->events, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL);
00084 
00085    ao2_ref(pvt->events, -1);
00086 }
00087 
00088 static void *unref_icalendar(void *obj)
00089 {
00090    struct icalendar_pvt *pvt = obj;
00091 
00092    ao2_ref(pvt, -1);
00093    return NULL;
00094 }
00095 
00096 static int fetch_response_reader(void *data, const char *block, size_t len)
00097 {
00098    struct ast_str **response = data;
00099    unsigned char *tmp;
00100 
00101    if (!(tmp = ast_malloc(len + 1))) {
00102       return -1;
00103    }
00104    memcpy(tmp, block, len);
00105    tmp[len] = '\0';
00106    ast_str_append(response, 0, "%s", tmp);
00107    ast_free(tmp);
00108 
00109    return 0;
00110 }
00111 
00112 static int auth_credentials(void *userdata, const char *realm, int attempts, char *username, char *secret)
00113 {
00114    struct icalendar_pvt *pvt = userdata;
00115 
00116    if (attempts > 1) {
00117       ast_log(LOG_WARNING, "Invalid username or password for iCalendar '%s'\n", pvt->owner->name);
00118       return -1;
00119    }
00120 
00121    ne_strnzcpy(username, pvt->user, NE_ABUFSIZ);
00122    ne_strnzcpy(secret, pvt->secret, NE_ABUFSIZ);
00123 
00124    return 0;
00125 }
00126 
00127 static icalcomponent *fetch_icalendar(struct icalendar_pvt *pvt)
00128 {
00129    int ret;
00130    struct ast_str *response;
00131    ne_request *req;
00132    icalcomponent *comp = NULL;
00133 
00134    if (!pvt) {
00135       ast_log(LOG_ERROR, "There is no private!\n");
00136       return NULL;
00137    }
00138 
00139    if (!(response = ast_str_create(512))) {
00140       ast_log(LOG_ERROR, "Could not allocate memory for response.\n");
00141       return NULL;
00142    }
00143 
00144    req = ne_request_create(pvt->session, "GET", pvt->uri.path);
00145    ne_add_response_body_reader(req, ne_accept_2xx, fetch_response_reader, &response);
00146 
00147    ret = ne_request_dispatch(req);
00148    ne_request_destroy(req);
00149    if (ret != NE_OK || !ast_str_strlen(response)) {
00150       ast_log(LOG_WARNING, "Unable to retrieve iCalendar '%s' from '%s': %s\n", pvt->owner->name, pvt->url, ne_get_error(pvt->session));
00151       ast_free(response);
00152       return NULL;
00153    }
00154 
00155    if (!ast_strlen_zero(ast_str_buffer(response))) {
00156       comp = icalparser_parse_string(ast_str_buffer(response));
00157    }
00158    ast_free(response);
00159 
00160    return comp;
00161 }
00162 
00163 static time_t icalfloat_to_timet(icaltimetype time) 
00164 {
00165    struct ast_tm tm = {0,};
00166    struct timeval tv;
00167 
00168    tm.tm_mday = time.day;
00169    tm.tm_mon = time.month - 1;
00170    tm.tm_year = time.year - 1900;
00171    tm.tm_hour = time.hour;
00172    tm.tm_min = time.minute;
00173    tm.tm_sec = time.second;
00174    tm.tm_isdst = -1;
00175    tv = ast_mktime(&tm, NULL);
00176 
00177    return tv.tv_sec;
00178 }
00179 
00180 /* span->start & span->end may be dates or floating times which have no timezone,
00181  * which would mean that they should apply to the local timezone for all recepients.
00182  * For example, if a meeting was set for 1PM-2PM floating time, people in different time
00183  * zones would not be scheduled at the same local times.  Dates are often treated as
00184  * floating times, so all day events will need to be converted--so we can trust the
00185  * span here, and instead will grab the start and end from the component, which will
00186  * allow us to test for floating times or dates.
00187  */
00188 
00189 static void icalendar_add_event(icalcomponent *comp, struct icaltime_span *span, void *data)
00190 {
00191    struct icalendar_pvt *pvt = data;
00192    struct ast_calendar_event *event;
00193    icaltimezone *utc = icaltimezone_get_utc_timezone();
00194    icaltimetype start, end, tmp;
00195    icalcomponent *valarm;
00196    icalproperty *prop;
00197    struct icaltriggertype trigger;
00198 
00199    if (!(pvt && pvt->owner)) {
00200       ast_log(LOG_ERROR, "Require a private structure with an ownenr\n");
00201       return;
00202    }
00203 
00204    if (!(event = ast_calendar_event_alloc(pvt->owner))) {
00205       ast_log(LOG_ERROR, "Could not allocate an event!\n");
00206       return;
00207    }
00208 
00209    start = icalcomponent_get_dtstart(comp);
00210    end = icalcomponent_get_dtend(comp);
00211 
00212    event->start = icaltime_get_tzid(start) ? span->start : icalfloat_to_timet(start);
00213    event->end = icaltime_get_tzid(end) ? span->end : icalfloat_to_timet(end);
00214    event->busy_state = span->is_busy ? AST_CALENDAR_BS_BUSY : AST_CALENDAR_BS_FREE;
00215 
00216    if ((prop = icalcomponent_get_first_property(comp, ICAL_SUMMARY_PROPERTY))) {
00217       ast_string_field_set(event, summary, icalproperty_get_value_as_string(prop));
00218    }
00219 
00220    if ((prop = icalcomponent_get_first_property(comp, ICAL_DESCRIPTION_PROPERTY))) {
00221       ast_string_field_set(event, description, icalproperty_get_value_as_string(prop));
00222    }
00223 
00224    if ((prop = icalcomponent_get_first_property(comp, ICAL_ORGANIZER_PROPERTY))) {
00225       ast_string_field_set(event, organizer, icalproperty_get_value_as_string(prop));
00226    }
00227 
00228    if ((prop = icalcomponent_get_first_property(comp, ICAL_LOCATION_PROPERTY))) {
00229       ast_string_field_set(event, location, icalproperty_get_value_as_string(prop));
00230    }
00231 
00232    if ((prop = icalcomponent_get_first_property(comp, ICAL_CATEGORIES_PROPERTY))) {
00233       ast_string_field_set(event, categories, icalproperty_get_value_as_string(prop));
00234    }
00235 
00236    if ((prop = icalcomponent_get_first_property(comp, ICAL_PRIORITY_PROPERTY))) {
00237       event->priority = icalvalue_get_integer(icalproperty_get_value(prop));
00238    }
00239 
00240    if ((prop = icalcomponent_get_first_property(comp, ICAL_UID_PROPERTY))) {
00241       ast_string_field_set(event, uid, icalproperty_get_value_as_string(prop));
00242    } else {
00243       ast_log(LOG_WARNING, "No UID found, but one is required. Generating, but updates may not be acurate\n");
00244       if (!ast_strlen_zero(event->summary)) {
00245          ast_string_field_set(event, uid, event->summary);
00246       } else {
00247          char tmp[100];
00248          snprintf(tmp, sizeof(tmp), "%ld", event->start);
00249          ast_string_field_set(event, uid, tmp);
00250       }
00251    }
00252 
00253    /* Get the attendees */
00254    for (prop = icalcomponent_get_first_property(comp, ICAL_ATTENDEE_PROPERTY);
00255          prop; prop = icalcomponent_get_next_property(comp, ICAL_ATTENDEE_PROPERTY)) {
00256       struct ast_calendar_attendee *attendee;
00257       const char *data;
00258 
00259       if (!(attendee = ast_calloc(1, sizeof(*attendee)))) {
00260          event = ast_calendar_unref_event(event);
00261          return;
00262       }
00263       data = icalproperty_get_attendee(prop);
00264       if (ast_strlen_zero(data)) {
00265          ast_free(attendee);
00266          continue;
00267       }
00268       attendee->data = ast_strdup(data);;
00269       AST_LIST_INSERT_TAIL(&event->attendees, attendee, next);
00270    }
00271 
00272 
00273    /* Only set values for alarm based on VALARM.  Can be overriden in main/calendar.c by autoreminder
00274     * therefore, go ahead and add events even if their is no VALARM or it is malformed
00275     * Currently we are only getting the first VALARM and are handling repitition in main/calendar.c from calendar.conf */
00276    if (!(valarm = icalcomponent_get_first_component(comp, ICAL_VALARM_COMPONENT))) {
00277       ao2_link(pvt->events, event);
00278       event = ast_calendar_unref_event(event);
00279       return;
00280    }
00281 
00282    if (!(prop = icalcomponent_get_first_property(valarm, ICAL_TRIGGER_PROPERTY))) {
00283       ast_log(LOG_WARNING, "VALARM has no TRIGGER, skipping!\n");
00284       ao2_link(pvt->events, event);
00285       event = ast_calendar_unref_event(event);
00286       return;
00287    }
00288 
00289    trigger = icalproperty_get_trigger(prop);
00290 
00291    if (icaltriggertype_is_null_trigger(trigger)) {
00292       ast_log(LOG_WARNING, "Bad TRIGGER for VALARM, skipping!\n");
00293       ao2_link(pvt->events, event);
00294       event = ast_calendar_unref_event(event);
00295       return;
00296    }
00297 
00298    if (!icaltime_is_null_time(trigger.time)) { /* This is an absolute time */
00299       tmp = icaltime_convert_to_zone(trigger.time, utc);
00300       event->alarm = icaltime_as_timet_with_zone(tmp, utc);
00301    } else { /* Offset from either dtstart or dtend */
00302       /* XXX Technically you can check RELATED to see if the event fires from the END of the event
00303        * But, I'm not sure I've ever seen anyone implement it in calendaring software, so I'm ignoring for now */
00304       tmp = icaltime_add(start, trigger.duration);
00305       event->alarm = icaltime_as_timet_with_zone(tmp, utc);
00306    }
00307 
00308    ao2_link(pvt->events, event);
00309    event = ast_calendar_unref_event(event);
00310 
00311    return;
00312 }
00313 
00314  static void icalendar_update_events(struct icalendar_pvt *pvt)
00315 {
00316    struct icaltimetype start_time, end_time;
00317    icalcomponent *iter;
00318 
00319    if (!pvt) {
00320       ast_log(LOG_ERROR, "iCalendar is NULL\n");
00321       return;
00322    }
00323 
00324    if (!pvt->owner) {
00325       ast_log(LOG_ERROR, "iCalendar is an orphan!\n");
00326       return;
00327    }
00328 
00329    if (!pvt->data) {
00330       ast_log(LOG_ERROR, "The iCalendar has not been parsed!\n");
00331       return;
00332    }
00333 
00334    start_time = icaltime_current_time_with_zone(icaltimezone_get_utc_timezone());
00335    end_time = icaltime_current_time_with_zone(icaltimezone_get_utc_timezone());
00336    end_time.second += pvt->owner->timeframe * 60;
00337    icaltime_normalize(end_time);
00338 
00339    for (iter = icalcomponent_get_first_component(pvt->data, ICAL_VEVENT_COMPONENT);
00340         iter;
00341        iter = icalcomponent_get_next_component(pvt->data, ICAL_VEVENT_COMPONENT))
00342    {
00343       icalcomponent_foreach_recurrence(iter, start_time, end_time, icalendar_add_event, pvt);
00344    }
00345 
00346    ast_calendar_merge_events(pvt->owner, pvt->events);
00347 }
00348 
00349 static void *ical_load_calendar(void *void_data)
00350 {
00351    struct icalendar_pvt *pvt;
00352    const struct ast_config *cfg;
00353    struct ast_variable *v;
00354    struct ast_calendar *cal = void_data;
00355    ast_mutex_t refreshlock;
00356 
00357    if (!(cal && (cfg = ast_calendar_config_acquire()))) {
00358       ast_log(LOG_ERROR, "You must enable calendar support for res_icalendar to load\n");
00359       return NULL;
00360    }
00361    if (ao2_trylock(cal)) {
00362       if (cal->unloading) {
00363          ast_log(LOG_WARNING, "Unloading module, load_calendar cancelled.\n");
00364       } else {
00365          ast_log(LOG_WARNING, "Could not lock calendar, aborting!\n");
00366       }
00367       ast_calendar_config_release();
00368       return NULL;
00369    }
00370 
00371    if (!(pvt = ao2_alloc(sizeof(*pvt), icalendar_destructor))) {
00372       ast_log(LOG_ERROR, "Could not allocate icalendar_pvt structure for calendar: %s\n", cal->name);
00373       ast_calendar_config_release();
00374       return NULL;
00375    }
00376 
00377    pvt->owner = cal;
00378 
00379    if (!(pvt->events = ast_calendar_event_container_alloc())) {
00380       ast_log(LOG_ERROR, "Could not allocate space for fetching events for calendar: %s\n", cal->name);
00381       pvt = unref_icalendar(pvt);
00382       ao2_unlock(cal);
00383       ast_calendar_config_release();
00384       return NULL;
00385    }
00386 
00387    if (ast_string_field_init(pvt, 32)) {
00388       ast_log(LOG_ERROR, "Couldn't allocate string field space for calendar: %s\n", cal->name);
00389       pvt = unref_icalendar(pvt);
00390       ao2_unlock(cal);
00391       ast_calendar_config_release();
00392       return NULL;
00393    }
00394 
00395    for (v = ast_variable_browse(cfg, cal->name); v; v = v->next) {
00396       if (!strcasecmp(v->name, "url")) {
00397          ast_string_field_set(pvt, url, v->value);
00398       } else if (!strcasecmp(v->name, "user")) {
00399          ast_string_field_set(pvt, user, v->value);
00400       } else if (!strcasecmp(v->name, "secret")) {
00401          ast_string_field_set(pvt, secret, v->value);
00402       }
00403    }
00404 
00405    ast_calendar_config_release();
00406 
00407    if (ast_strlen_zero(pvt->url)) {
00408       ast_log(LOG_WARNING, "No URL was specified for iCalendar '%s' - skipping.\n", cal->name);
00409       pvt = unref_icalendar(pvt);
00410       ao2_unlock(cal);
00411       return NULL;
00412    }
00413 
00414    if (ne_uri_parse(pvt->url, &pvt->uri) || pvt->uri.host == NULL || pvt->uri.path == NULL) {
00415       ast_log(LOG_WARNING, "Could not parse url '%s' for iCalendar '%s' - skipping.\n", pvt->url, cal->name);
00416       pvt = unref_icalendar(pvt);
00417       ao2_unlock(cal);
00418       return NULL;
00419    }
00420 
00421    if (pvt->uri.scheme == NULL) {
00422       pvt->uri.scheme = "http";
00423    }
00424 
00425    if (pvt->uri.port == 0) {
00426       pvt->uri.port = ne_uri_defaultport(pvt->uri.scheme);
00427    }
00428 
00429    pvt->session = ne_session_create(pvt->uri.scheme, pvt->uri.host, pvt->uri.port);
00430    ne_redirect_register(pvt->session);
00431    ne_set_server_auth(pvt->session, auth_credentials, pvt);
00432    if (!strcasecmp(pvt->uri.scheme, "https")) {
00433       ne_ssl_trust_default_ca(pvt->session);
00434    }
00435 
00436    cal->tech_pvt = pvt;
00437 
00438    ast_mutex_init(&refreshlock);
00439 
00440    /* Load it the first time */
00441    if (!(pvt->data = fetch_icalendar(pvt))) {
00442       ast_log(LOG_WARNING, "Unable to parse iCalendar '%s'\n", cal->name);
00443    }
00444 
00445    icalendar_update_events(pvt);
00446 
00447    ao2_unlock(cal);
00448 
00449    /* The only writing from another thread will be if unload is true */
00450    for(;;) {
00451       struct timeval tv = ast_tvnow();
00452       struct timespec ts = {0,};
00453 
00454       ts.tv_sec = tv.tv_sec + (60 * pvt->owner->refresh);
00455 
00456       ast_mutex_lock(&refreshlock);
00457       while (!pvt->owner->unloading) {
00458          if (ast_cond_timedwait(&pvt->owner->unload, &refreshlock, &ts) == ETIMEDOUT) {
00459             break;
00460          }
00461       }
00462       ast_mutex_unlock(&refreshlock);
00463 
00464       if (pvt->owner->unloading) {
00465          ast_debug(10, "Skipping refresh since we got a shutdown signal\n");
00466          return NULL;
00467       }
00468 
00469       ast_debug(10, "Refreshing after %d minute timeout\n", pvt->owner->refresh);
00470 
00471       /* Free the old calendar data */
00472       if (pvt->data) {
00473          icalcomponent_free(pvt->data);
00474          pvt->data = NULL;
00475       }
00476       if (!(pvt->data = fetch_icalendar(pvt))) {
00477          ast_log(LOG_WARNING, "Unable to parse iCalendar '%s'\n", pvt->owner->name);
00478          continue;
00479       }
00480 
00481       icalendar_update_events(pvt);
00482    }
00483 
00484    return NULL;
00485 }
00486 
00487 static int load_module(void)
00488 {
00489    ne_sock_init();
00490    if (ast_calendar_register(&ical_tech)) {
00491       ne_sock_exit();
00492       return AST_MODULE_LOAD_DECLINE;
00493    }
00494 
00495    return AST_MODULE_LOAD_SUCCESS;
00496 }
00497 
00498 static int unload_module(void)
00499 {
00500    ast_calendar_unregister(&ical_tech);
00501    ne_sock_exit();
00502    return 0;
00503 }
00504 
00505 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Asterisk iCalendar .ics file integration",
00506       .load = load_module,
00507       .unload = unload_module,
00508       .load_pri = AST_MODPRI_DEVSTATE_PLUGIN,
00509    );

Generated on 17 Aug 2018 for Asterisk - The Open Source Telephony Project by  doxygen 1.6.1