aboutsummaryrefslogtreecommitdiffstats
path: root/res
diff options
context:
space:
mode:
Diffstat (limited to 'res')
-rw-r--r--res/res_calendar.c1604
-rw-r--r--res/res_calendar.exports7
-rw-r--r--res/res_calendar_caldav.c675
-rw-r--r--res/res_calendar_exchange.c757
-rw-r--r--res/res_calendar_icalendar.c470
5 files changed, 3513 insertions, 0 deletions
diff --git a/res/res_calendar.c b/res/res_calendar.c
new file mode 100644
index 000000000..f18aa18b1
--- /dev/null
+++ b/res/res_calendar.c
@@ -0,0 +1,1604 @@
+/*
+ * Asterisk -- An open source telephony toolkit.
+ *
+ * Copyright (C) 2008 - 2009, Digium, Inc.
+ *
+ * Terry Wilson <twilson@digium.com>
+ *
+ * See http://www.asterisk.org for more information about
+ * the Asterisk project. Please do not directly contact
+ * any of the maintainers of this project for assistance;
+ * the project provides a web site, mailing lists and IRC
+ * channels for your use.
+ *
+ * This program is free software, distributed under the terms of
+ * the GNU General Public License Version 2. See the LICENSE file
+ * at the top of the source tree.
+ */
+
+/*! \file
+ * \brief Calendaring API
+ */
+
+#include "asterisk.h"
+
+ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
+
+#include "asterisk/_private.h"
+#include "asterisk/calendar.h"
+#include "asterisk/utils.h"
+#include "asterisk/astobj2.h"
+#include "asterisk/module.h"
+#include "asterisk/config.h"
+#include "asterisk/channel.h"
+#include "asterisk/devicestate.h"
+#include "asterisk/linkedlists.h"
+#include "asterisk/sched.h"
+#include "asterisk/dial.h"
+#include "asterisk/cli.h"
+#include "asterisk/pbx.h"
+#include "asterisk/app.h"
+
+/*** DOCUMENTATION
+ <function name="CALENDAR_BUSY" language="en_US">
+ <synopsis>
+ Determine if the calendar is marked busy at this time.
+ </synopsis>
+ <syntax>
+ <parameter name="calendar" required="true" />
+ </syntax>
+ <description>
+ <para>Check the specified calendar's current busy status.</para>
+ </description>
+ </function>
+ <function name="CALENDAR_EVENT" language="en_US">
+ <synopsis>
+ Get calendar event notification data from a notification call.
+ </synopsis>
+ <syntax>
+ <parameter name="field" required="true">
+ <enumlist>
+ <enum name="summary"><para>The VEVENT SUMMARY property or Exchange event 'subject'</para></enum>
+ <enum name="description"><para>The text description of the event</para></enum>
+ <enum name="organizer"><para>The organizer of the event</para></enum>
+ <enum name="location"><para>The location of the eventt</para></enum>
+ <enum name="calendar"><para>The name of the calendar associated with the event</para></enum>
+ <enum name="uid"><para>The unique identifier for this event</para></enum>
+ <enum name="start"><para>The start time of the event</para></enum>
+ <enum name="end"><para>The end time of the event</para></enum>
+ <enum name="busystate"><para>The busy state of the event 0=FREE, 1=TENTATIVE, 2=BUSY</para></enum>
+ </enumlist>
+ </parameter>
+ </syntax>
+ <description>
+ <para>Whenever a calendar event notification call is made, the event data
+ may be accessed with this function.</para>
+ </description>
+ </function>
+ <function name="CALENDAR_QUERY" language="en_US">
+ <synopsis>Query a calendar server and store the data on a channel
+ </synopsis>
+ <syntax>
+ <parameter name="calendar" required="true">
+ <para>The calendar that should be queried</para>
+ </parameter>
+ <parameter name="start" required="false">
+ <para>The start time of the query (in seconds since epoch)</para>
+ </parameter>
+ <parameter name="end" required="false">
+ <para>The end time of the query (in seconds since epoch)</para>
+ </parameter>
+ </syntax>
+ <description>
+ <para>Get a list of events in the currently accessible timeframe of the <replaceable>calendar</replaceable>
+ The function returns the id for accessing the result with CALENDAR_QUERY_RESULT()</para>
+ </description>
+ </function>
+ <function name="CALENDAR_QUERY_RESULT" language="en_US">
+ <synopsis>
+ Retrieve data from a previously run CALENDAR_QUERY() call
+ </synopsis>
+ <syntax>
+ <parameter name="id" required="true">
+ <para>The query ID returned by <literal>CALENDAR_QUERY</literal></para>
+ </parameter>
+ <parameter name="field" required="true">
+ <enumlist>
+ <enum name="getnum"><para>number of events occurring during time range</para></enum>
+ <enum name="summary"><para>A summary of the event</para></enum>
+ <enum name="description"><para>The full event description</para></enum>
+ <enum name="organizer"><para>The event organizer</para></enum>
+ <enum name="location"><para>The event location</para></enum>
+ <enum name="calendar"><para>The name of the calendar associted with the event</para></enum>
+ <enum name="uid"><para>The unique identifier for the event</para></enum>
+ <enum name="start"><para>The start time of the event (in seconds since epoch)</para></enum>
+ <enum name="end"><para>The end time of the event (in seconds since epoch)</para></enum>
+ <enum name="busystate"><para>The busy status of the event 0=FREE, 1=TENTATIVE, 2=BUSY</para></enum>
+ </enumlist>
+ </parameter>
+ <parameter name="entry" required="false" default="1">
+ <para>Return data from a specific event returned by the query</para>
+ </parameter>
+ </syntax>
+ <description>
+ <para>After running CALENDAR_QUERY and getting a result <replaceable>id</replaceable>, calling
+ <literal>CALENDAR_QUERY</literal> with that <replaceable>id</replaceable> and a <replaceable>field</replaceable>
+ will return the data for that field. If multiple events matched the query, and <replaceable>entry</replaceable>
+ is provided, information from that event will be returned.</para>
+ </description>
+ </function>
+ <function name="CALENDAR_WRITE" language="en_US">
+ <synopsis>Write an event to a calendar</synopsis>
+ <syntax>
+ <parameter name="calendar" required="true">
+ <para>The calendar to write to</para>
+ </parameter>
+ <parameter name="field" multiple="true" required="true">
+ <enumlist>
+ <enum name="summary"><para>A summary of the event</para></enum>
+ <enum name="description"><para>The full event description</para></enum>
+ <enum name="organizer"><para>The event organizer</para></enum>
+ <enum name="location"><para>The event location</para></enum>
+ <enum name="uid"><para>The unique identifier for the event</para></enum>
+ <enum name="start"><para>The start time of the event (in seconds since epoch)</para></enum>
+ <enum name="end"><para>The end time of the event (in seconds since epoch)</para></enum>
+ <enum name="busystate"><para>The busy status of the event 0=FREE, 1=TENTATIVE, 2=BUSY</para></enum>
+ </enumlist>
+ </parameter>
+ </syntax>
+ <description>
+ <para>Example: CALENDAR_WRITE(calendar,field1,field2,field3)=val1,val2,val3</para>
+ <para>The field and value arguments can easily be set/passed using the HASHKEYS() and HASH() functions</para>
+ </description>
+ </function>
+
+***/
+#define CALENDAR_BUCKETS 19
+
+static struct ao2_container *calendars;
+static struct sched_context *sched;
+static pthread_t refresh_thread = AST_PTHREADT_NULL;
+static ast_mutex_t refreshlock;
+static ast_cond_t refresh_condition;
+static ast_mutex_t reloadlock;
+
+static void event_notification_destroy(void *data);
+static void *event_notification_duplicate(void *data);
+static void eventlist_destroy(void *data);
+static void *eventlist_duplicate(void *data);
+
+static const struct ast_datastore_info event_notification_datastore = {
+ .type = "EventNotification",
+ .destroy = event_notification_destroy,
+ .duplicate = event_notification_duplicate,
+};
+
+static const struct ast_datastore_info eventlist_datastore_info = {
+ .type = "CalendarEventList",
+ .destroy = eventlist_destroy,
+ .duplicate = eventlist_duplicate,
+};
+
+struct evententry {
+ struct ast_calendar_event *event;
+ AST_LIST_ENTRY(evententry) list;
+};
+
+AST_LIST_HEAD_STATIC(techs, ast_calendar_tech);
+AST_LIST_HEAD_NOLOCK(eventlist, evententry); /* define the type */
+
+struct ast_config *calendar_config = NULL;
+
+static struct ast_calendar *unref_calendar(struct ast_calendar *cal)
+{
+ ao2_ref(cal, -1);
+ return NULL;
+}
+
+static int calendar_hash_fn(const void *obj, const int flags)
+{
+ const struct ast_calendar *cal = obj;
+ return ast_str_case_hash(cal->name);
+}
+
+static int calendar_cmp_fn(void *obj, void *arg, int flags)
+{
+ const struct ast_calendar *one = obj, *two = arg;
+ return !strcasecmp(one->name, two->name) ? CMP_MATCH | CMP_STOP: 0;
+}
+
+static struct ast_calendar *find_calendar(const char *name)
+{
+ struct ast_calendar tmp = {
+ .name = name,
+ };
+ return ao2_find(calendars, &tmp, OBJ_POINTER);
+}
+
+static int event_hash_fn(const void *obj, const int flags)
+{
+ const struct ast_calendar_event *event = obj;
+ return ast_str_hash(event->uid);
+}
+
+static int event_cmp_fn(void *obj, void *arg, int flags)
+{
+ const struct ast_calendar_event *one = obj, *two = arg;
+ return !strcmp(one->uid, two->uid) ? CMP_MATCH | CMP_STOP : 0;
+}
+
+static struct ast_calendar_event *find_event(struct ao2_container *events, const char *uid)
+{
+ struct ast_calendar_event tmp = {
+ .uid = uid,
+ };
+ return ao2_find(events, &tmp, OBJ_POINTER);
+}
+
+struct ast_calendar_event *ast_calendar_unref_event(struct ast_calendar_event *event)
+{
+ ao2_ref(event, -1);
+ return NULL;
+}
+
+static void calendar_destructor(void *obj)
+{
+ struct ast_calendar *cal = obj;
+
+ ast_debug(3, "Destroying calendar %s\n", cal->name);
+
+ ao2_lock(cal);
+ cal->unloading = 1;
+ ast_cond_signal(&cal->unload);
+ pthread_join(cal->thread, NULL);
+ if (cal->tech_pvt) {
+ cal->tech_pvt = cal->tech->unref_calendar(cal->tech_pvt);
+ }
+ ast_calendar_clear_events(cal);
+ ast_string_field_free_memory(cal);
+ ao2_ref(cal->events, -1);
+ ao2_unlock(cal);
+}
+
+static void eventlist_destructor(void *obj)
+{
+ struct eventlist *events = obj;
+ struct evententry *entry;
+
+ while ((entry = AST_LIST_REMOVE_HEAD(events, list))) {
+ ao2_ref(entry->event, -1);
+ ast_free(entry);
+ }
+}
+
+static int calendar_busy_callback(void *obj, void *arg, int flags)
+{
+ struct ast_calendar_event *event = obj;
+ int *is_busy = arg;
+ struct timeval tv = ast_tvnow();
+
+ if (tv.tv_sec >= event->start && tv.tv_sec <= event->end && event->busy_state > AST_CALENDAR_BS_FREE) {
+ *is_busy = 1;
+ return CMP_STOP;
+ }
+
+ return 0;
+}
+
+static int calendar_is_busy(struct ast_calendar *cal)
+{
+ int is_busy = 0;
+
+ ao2_callback(cal->events, OBJ_NODATA, calendar_busy_callback, &is_busy);
+
+ return is_busy;
+}
+
+static enum ast_device_state calendarstate(const char *data)
+{
+ struct ast_calendar *cal;
+
+ if (ast_strlen_zero(data) || (!(cal = find_calendar(data)))) {
+ return AST_DEVICE_INVALID;
+ }
+
+ if (cal->tech->is_busy) {
+ return cal->tech->is_busy(cal) ? AST_DEVICE_INUSE : AST_DEVICE_NOT_INUSE;
+ }
+
+ return calendar_is_busy(cal) ? AST_DEVICE_INUSE : AST_DEVICE_NOT_INUSE;
+}
+
+static struct ast_calendar *build_calendar(struct ast_config *cfg, const char *cat, const struct ast_calendar_tech *tech)
+{
+ struct ast_calendar *cal;
+ struct ast_variable *v;
+ int new_calendar = 0;
+
+ if (!(cal = find_calendar(cat))) {
+ new_calendar = 1;
+ if (!(cal = ao2_alloc(sizeof(*cal), calendar_destructor))) {
+ ast_log(LOG_ERROR, "Could not allocate calendar structure. Stopping.\n");
+ return NULL;
+ }
+
+ if (!(cal->events = ao2_container_alloc(CALENDAR_BUCKETS, event_hash_fn, event_cmp_fn))) {
+ ast_log(LOG_ERROR, "Could not allocate events container for %s\n", cat);
+ cal = unref_calendar(cal);
+ return NULL;
+ }
+
+ if (ast_string_field_init(cal, 32)) {
+ ast_log(LOG_ERROR, "Couldn't create string fields for %s\n", cat);
+ cal = unref_calendar(cal);
+ return NULL;
+ }
+ } else {
+ cal->pending_deletion = 0;
+ }
+
+ ast_string_field_set(cal, name, cat);
+ cal->tech = tech;
+
+ cal->refresh = 3600;
+ cal->timeframe = 60;
+
+ for (v = ast_variable_browse(cfg, cat); v; v = v->next) {
+ if (!strcasecmp(v->name, "autoreminder")) {
+ cal->autoreminder = atoi(v->value);
+ } else if (!strcasecmp(v->name, "channel")) {
+ ast_string_field_set(cal, notify_channel, v->value);
+ } else if (!strcasecmp(v->name, "context")) {
+ ast_string_field_set(cal, notify_context, v->value);
+ } else if (!strcasecmp(v->name, "extension")) {
+ ast_string_field_set(cal, notify_extension, v->value);
+ } else if (!strcasecmp(v->name, "waittime")) {
+ cal->notify_waittime = atoi(v->value);
+ } else if (!strcasecmp(v->name, "app")) {
+ ast_string_field_set(cal, notify_app, v->value);
+ } else if (!strcasecmp(v->name, "appdata")) {
+ ast_string_field_set(cal, notify_appdata, v->value);
+ } else if (!strcasecmp(v->name, "refresh")) {
+ cal->refresh = atoi(v->value);
+ } else if (!strcasecmp(v->name, "timeframe")) {
+ cal->timeframe = atoi(v->value);
+ }
+ }
+
+ if (new_calendar) {
+ cal->thread = AST_PTHREADT_NULL;
+ ast_cond_init(&cal->unload, NULL);
+ ao2_link(calendars, cal);
+ if (ast_pthread_create(&cal->thread, NULL, cal->tech->load_calendar, cal)) {
+ /* If we start failing to create threads, go ahead and return NULL
+ * and the tech module will be unregistered
+ */
+ ao2_unlink(calendars, cal);
+ cal = unref_calendar(cal);
+ }
+ }
+
+ return cal;
+}
+
+static int load_tech_calendars(struct ast_calendar_tech *tech)
+{
+ struct ast_calendar *cal;
+ const char *cat = NULL;
+ const char *val;
+
+ if (!calendar_config) {
+ ast_log(LOG_WARNING, "Calendar support disabled, not loading %s calendar module\n", tech->type);
+ return -1;
+ }
+
+ while ((cat = ast_category_browse(calendar_config, cat))) {
+ if (!strcasecmp(cat, "general")) {
+ continue;
+ }
+
+ if (!(val = ast_variable_retrieve(calendar_config, cat, "type")) || strcasecmp(val, tech->type)) {
+ continue;
+ }
+
+ /* A serious error occurred loading calendars from this tech and it should be disabled */
+ if (!(cal = build_calendar(calendar_config, cat, tech))) {
+ ast_calendar_unregister(tech);
+ return -1;
+ }
+
+ cal = unref_calendar(cal);
+ }
+
+ return 0;
+}
+
+int ast_calendar_register(struct ast_calendar_tech *tech)
+{
+ struct ast_calendar_tech *iter;
+
+ AST_LIST_LOCK(&techs);
+ AST_LIST_TRAVERSE(&techs, iter, list) {
+ if(!strcasecmp(tech->type, iter->type)) {
+ ast_log(LOG_WARNING, "Already have a handler for calendar type '%s'\n", tech->type);
+ AST_LIST_UNLOCK(&techs);
+ return -1;
+ }
+ }
+ AST_LIST_INSERT_HEAD(&techs, tech, list);
+ AST_LIST_UNLOCK(&techs);
+
+ ast_verb(2, "Registered calendar type '%s' (%s)\n", tech->type, tech->description);
+
+ return load_tech_calendars(tech);
+}
+
+static int match_caltech_cb(void *user_data, void *arg, int flags)
+{
+ struct ast_calendar *cal = user_data;
+ struct ast_calendar_tech *tech = arg;
+
+ if (cal->tech == tech) {
+ return CMP_MATCH;
+ }
+
+ return 0;
+}
+
+void ast_calendar_unregister(struct ast_calendar_tech *tech)
+{
+ struct ast_calendar_tech *iter;
+
+ AST_LIST_LOCK(&techs);
+ AST_LIST_TRAVERSE_SAFE_BEGIN(&techs, iter, list) {
+ if (iter != tech) {
+ continue;
+ }
+
+ ao2_callback(calendars, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, match_caltech_cb, tech);
+
+ AST_LIST_REMOVE_CURRENT(list);
+ ast_verb(2, "Unregistered calendar type '%s'\n", tech->type);
+ break;
+ }
+ AST_LIST_TRAVERSE_SAFE_END;
+ AST_LIST_UNLOCK(&techs);
+
+}
+
+static void calendar_event_destructor(void *obj)
+{
+ struct ast_calendar_event *event = obj;
+ struct ast_calendar_attendee *attendee;
+
+ ast_debug(3, "Destroying event for calendar '%s'\n", event->owner->name);
+ ast_string_field_free_memory(event);
+ while ((attendee = AST_LIST_REMOVE_HEAD(&event->attendees, next))) {
+ if (attendee->data) {
+ ast_free(attendee->data);
+ }
+ ast_free(attendee);
+ }
+}
+
+/* This is only called from ao2_callbacks that are going to unref the event for us,
+ * so we don't unref the event here. */
+static struct ast_calendar_event *destroy_event(struct ast_calendar_event *event)
+{
+ if (event->notify_sched > -1 && ast_sched_del(sched, event->notify_sched)) {
+ ast_debug(3, "Notification running, can't delete sched entry\n");
+ }
+ if (event->bs_start_sched > -1 && ast_sched_del(sched, event->bs_start_sched)) {
+ ast_debug(3, "Devicestate update (start) running, can't delete sched entry\n");
+ }
+ if (event->bs_end_sched > -1 && ast_sched_del(sched, event->bs_end_sched)) {
+ ast_debug(3, "Devicestate update (end) running, can't delete sched entry\n");
+ }
+
+ /* If an event is being deleted and we've fired an event changing the status at the beginning,
+ * but haven't hit the end event yet, go ahead and set the devicestate to the current busy status */
+ if (event->bs_start_sched < 0 && event->bs_end_sched >= 0) {
+ if (!calendar_is_busy(event->owner)) {
+ ast_devstate_changed(AST_DEVICE_NOT_INUSE, "Calendar/%s", event->owner->name);
+ } else {
+ ast_devstate_changed(AST_DEVICE_BUSY, "Calendar/%s", event->owner->name);
+ }
+ }
+
+ return NULL;
+}
+
+static int clear_events_cb(void *user_data, void *arg, int flags)
+{
+ struct ast_calendar_event *event = user_data;
+
+ event = destroy_event(event);
+
+ return CMP_MATCH;
+}
+
+void ast_calendar_clear_events(struct ast_calendar *cal)
+{
+ ast_debug(3, "Clearing all events for calendar %s\n", cal->name);
+
+ ao2_callback(cal->events, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, clear_events_cb, NULL);
+}
+
+struct ast_calendar_event *ast_calendar_event_alloc(struct ast_calendar *cal)
+{
+ struct ast_calendar_event *event;
+ if (!(event = ao2_alloc(sizeof(*event), calendar_event_destructor))) {
+ return NULL;
+ }
+
+ if (ast_string_field_init(event, 32)) {
+ event = ast_calendar_unref_event(event);
+ return NULL;
+ }
+
+ event->owner = cal;
+ event->notify_sched = -1;
+ event->bs_start_sched = -1;
+ event->bs_end_sched = -1;
+
+ AST_LIST_HEAD_INIT_NOLOCK(&event->attendees);
+
+ return event;
+}
+
+struct ao2_container *ast_calendar_event_container_alloc(void)
+{
+ return ao2_container_alloc(CALENDAR_BUCKETS, event_hash_fn, event_cmp_fn);
+}
+
+static void event_notification_destroy(void *data)
+{
+ struct ast_calendar_event *event = data;
+
+ event = ast_calendar_unref_event(event);
+
+}
+
+static void *event_notification_duplicate(void *data)
+{
+ struct ast_calendar_event *event = data;
+
+ if (!event) {
+ return NULL;
+ }
+
+ ao2_ref(event, +1);
+
+ return event;
+}
+
+/*! \brief Generate 32 byte random string (stolen from chan_sip.c)*/
+static char *generate_random_string(char *buf, size_t size)
+{
+ long val[4];
+ int x;
+
+ for (x = 0; x < 4; x++) {
+ val[x] = ast_random();
+ }
+ snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
+
+ return buf;
+}
+
+static int calendar_event_notify(const void *data)
+{
+ struct ast_calendar_event *event = (void *)data;
+ char tech[256], dest[256], buf[8], *tmp;
+ struct ast_dial *dial = NULL;
+ struct ast_channel *chan = NULL;
+ struct ast_str *apptext = NULL;
+ int res = -1;
+ char start[12], end[12], busystate[2];
+ struct ast_datastore *datastore;
+
+ if (!(event && event->owner)) {
+ ast_log(LOG_ERROR, "Extremely low-cal...in fact cal is NULL!\n");
+ goto notify_cleanup;
+ }
+
+ ao2_ref(event, +1);
+ event->notify_sched = -1;
+
+ ast_copy_string(tech, event->owner->notify_channel, sizeof(tech));
+
+ if ((tmp = strchr(tech, '/'))) {
+ *tmp = '\0';
+ tmp++;
+ ast_copy_string(dest, tmp, sizeof(dest));
+ } else {
+ ast_log(LOG_WARNING, "Channel should be in form Tech/Dest\n");
+ goto notify_cleanup;
+ }
+
+ if (!(dial = ast_dial_create())) {
+ ast_log(LOG_ERROR, "Could not create dial structure\n");
+ goto notify_cleanup;
+ }
+
+ if (ast_dial_append(dial, tech, dest) < 0) {
+ ast_log(LOG_ERROR, "Could not append channel\n");
+ goto notify_cleanup;
+ }
+
+ ast_dial_set_global_timeout(dial, event->owner->notify_waittime);
+ generate_random_string(buf, sizeof(buf));
+ if (!(chan = ast_channel_alloc(1, AST_STATE_DOWN, 0, 0, 0, 0, 0, 0, "Calendar/%s-%s", event->owner->name, buf))) {
+ ast_log(LOG_ERROR, "Could not allocate notification channel\n");
+ goto notify_cleanup;
+ }
+
+ snprintf(busystate, sizeof(busystate), "%d", event->busy_state);
+ snprintf(start, sizeof(start), "%lu", event->start);
+ snprintf(end, sizeof(end), "%lu", event->end);
+
+ chan->nativeformats = AST_FORMAT_SLINEAR;
+
+ if (!(datastore = ast_datastore_alloc(&event_notification_datastore, NULL))) {
+ ast_log(LOG_ERROR, "Could not allocate datastore, notification not being sent!\n");
+ goto notify_cleanup;
+ }
+
+ datastore->data = event;
+ datastore->inheritance = DATASTORE_INHERIT_FOREVER;
+
+ ao2_ref(event, +1);
+ res = ast_channel_datastore_add(chan, datastore);
+
+ if (!(apptext = ast_str_create(32))) {
+ goto notify_cleanup;
+ }
+
+ if (!ast_strlen_zero(event->owner->notify_app)) {
+ ast_str_set(&apptext, 0, "%s,%s", event->owner->notify_app, event->owner->notify_appdata);
+ } else {
+ ast_str_set(&apptext, 0, "Dial,Local/%s@%s", event->owner->notify_extension, event->owner->notify_context);
+ }
+ ast_dial_option_global_enable(dial, AST_DIAL_OPTION_ANSWER_EXEC, ast_str_buffer(apptext));
+
+ ast_dial_run(dial, chan, 1);
+ res = 0;
+
+notify_cleanup:
+ event = ast_calendar_unref_event(event);
+ if (res == -1 && dial) {
+ ast_dial_destroy(dial);
+ }
+ if (apptext) {
+ ast_free(apptext);
+ }
+ if (chan) {
+ ast_channel_release(chan);
+ }
+
+ return res;
+}
+
+static int calendar_devstate_change(const void *data)
+{
+ struct ast_calendar_event *event = (struct ast_calendar_event *)data;
+ struct timeval now = ast_tvnow();
+ int is_end_event;
+
+ if (!event) {
+ ast_log(LOG_WARNING, "Event was NULL!\n");
+ return 0;
+ }
+
+ ao2_ref(event, +1);
+
+ is_end_event = event->end <= now.tv_sec;
+
+ if (is_end_event) {
+ event->bs_end_sched = -1;
+ } else {
+ event->bs_start_sched = -1;
+ }
+
+ /* We can have overlapping events, so ignore the event->busy_state and check busy state
+ * based on all events in the calendar */
+ if (!calendar_is_busy(event->owner)) {
+ ast_devstate_changed(AST_DEVICE_NOT_INUSE, "Calendar/%s", event->owner->name);
+ } else {
+ ast_devstate_changed(AST_DEVICE_BUSY, "Calendar/%s", event->owner->name);
+ }
+
+ event = ast_calendar_unref_event(event);
+
+ return 0;
+}
+
+static void copy_event_data(struct ast_calendar_event *dst, struct ast_calendar_event *src)
+{
+ struct ast_calendar_attendee *attendee;
+
+ ast_string_field_set(dst, summary, src->summary);
+ ast_string_field_set(dst, description, src->description);
+ ast_string_field_set(dst, organizer, src->organizer);
+ ast_string_field_set(dst, location, src->location);
+ ast_string_field_set(dst, uid, src->uid);
+ dst->owner = src->owner;
+ dst->start = src->start;
+ dst->end = src->end;
+ dst->alarm = src->alarm;
+ dst->busy_state = src->busy_state;
+
+ while ((attendee = AST_LIST_REMOVE_HEAD(&src->attendees, next))) {
+ AST_LIST_INSERT_TAIL(&dst->attendees, attendee, next);
+ }
+}
+
+static int schedule_calendar_event(struct ast_calendar *cal, struct ast_calendar_event *old_event, struct ast_calendar_event *cmp_event)
+{
+ struct timeval now = ast_tvnow();
+ struct ast_calendar_event *event;
+ time_t alarm_notify_sched = 0, devstate_sched_start, devstate_sched_end;
+ int changed = 0;
+
+ event = cmp_event ? cmp_event : old_event;
+
+ ao2_lock(event);
+ if (!cmp_event || old_event->alarm != event->alarm) {
+ changed = 1;
+ if (cal->autoreminder) {
+ alarm_notify_sched = (event->start - (60 * cal->autoreminder) - now.tv_sec) * 1000;
+ } else if (event->alarm) {
+ alarm_notify_sched = (event->alarm - now.tv_sec) * 1000;
+ }
+
+ /* For now, send the notification if we missed it, but the meeting hasn't happened yet */
+ if (event->start >= now.tv_sec) {
+ if (alarm_notify_sched <= 0) {
+ alarm_notify_sched = 1;
+ }
+ ast_mutex_lock(&refreshlock);
+ AST_SCHED_REPLACE(old_event->notify_sched, sched, alarm_notify_sched, calendar_event_notify, old_event);
+ ast_mutex_unlock(&refreshlock);
+ ast_debug(3, "Calendar alarm event notification scheduled to happen in %ld ms\n", alarm_notify_sched);
+ }
+ }
+
+ if (!cmp_event || old_event->start != event->start) {
+ changed = 1;
+ devstate_sched_start = (event->start - now.tv_sec) * 1000;
+
+ if (devstate_sched_start < 1) {
+ devstate_sched_start = 1;
+ }
+
+ ast_mutex_lock(&refreshlock);
+ AST_SCHED_REPLACE(old_event->bs_start_sched, sched, devstate_sched_start, calendar_devstate_change, old_event);
+ ast_mutex_unlock(&refreshlock);
+ ast_debug(3, "Calendar bs_start event notification scheduled to happen in %ld ms\n", devstate_sched_start);
+ }
+
+ if (!cmp_event || old_event->end != event->end) {
+ changed = 1;
+ devstate_sched_end = (event->end - now.tv_sec) * 1000;
+ ast_mutex_lock(&refreshlock);
+ AST_SCHED_REPLACE(old_event->bs_end_sched, sched, devstate_sched_end, calendar_devstate_change, old_event);
+ ast_mutex_unlock(&refreshlock);
+ ast_debug(3, "Calendar bs_end event notification scheduled to happen in %ld ms\n", devstate_sched_end);
+ }
+
+ if (changed) {
+ ast_cond_signal(&refresh_condition);
+ }
+
+ ao2_unlock(event);
+
+ return 0;
+}
+
+static int merge_events_cb(void *obj, void *arg, int flags)
+{
+ struct ast_calendar_event *old_event = obj, *new_event;
+ struct ao2_container *new_events = arg;
+
+ /* If we don't find the old_event in new_events, then we can safely delete the old_event */
+ if (!(new_event = find_event(new_events, old_event->uid))) {
+ old_event = destroy_event(old_event);
+ return CMP_MATCH;
+ }
+
+ /* We have events to merge. If any data that will affect a scheduler event has changed,
+ * then we need to replace the scheduler event */
+ schedule_calendar_event(old_event->owner, old_event, new_event);
+
+ /* Since we don't want to mess with cancelling sched events and adding new ones, just
+ * copy the internals of the new_event to the old_event */
+ copy_event_data(old_event, new_event);
+
+ /* Now we can go ahead and unlink the new_event from new_events and unref it so that only completely
+ * new events remain in the container */
+ ao2_unlink(new_events, new_event);
+ new_event = ast_calendar_unref_event(new_event);
+
+ return 0;
+}
+
+static int add_new_event_cb(void *obj, void *arg, int flags)
+{
+ struct ast_calendar_event *new_event = obj;
+ struct ao2_container *events = arg;
+
+ ao2_link(events, new_event);
+ schedule_calendar_event(new_event->owner, new_event, NULL);
+ return CMP_MATCH;
+}
+
+void ast_calendar_merge_events(struct ast_calendar *cal, struct ao2_container *new_events)
+{
+ /* Loop through all events attached to the calendar. If there is a matching new event
+ * merge its data over and handle any schedule changes that need to be made. Then remove
+ * the new_event from new_events so that we are left with only new_events that we can add later. */
+ ao2_callback(cal->events, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, merge_events_cb, new_events);
+
+ /* Now, we should only have completely new events in new_events. Loop through and add them */
+ ao2_callback(new_events, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, add_new_event_cb, cal->events);
+}
+
+
+static int load_config(void *data)
+{
+ struct ast_flags config_flags = { CONFIG_FLAG_FILEUNCHANGED };
+ struct ast_config *tmpcfg;
+
+ if (!(tmpcfg = ast_config_load2("calendar.conf", "calendar", config_flags)) ||
+ tmpcfg == CONFIG_STATUS_FILEINVALID) {
+ ast_log(LOG_ERROR, "Unable to load config calendar.conf\n");
+ return -1;
+ }
+
+ if (tmpcfg == CONFIG_STATUS_FILEUNCHANGED) {
+ return 0;
+ }
+
+ if (calendar_config) {
+ ast_config_destroy(calendar_config);
+ }
+
+ calendar_config = tmpcfg;
+
+ return 0;
+}
+
+/*! \brief A dialplan function that can be used to determine the busy status of a calendar */
+static int calendar_busy_exec(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
+{
+ struct ast_calendar *cal;
+
+ if (ast_strlen_zero(data)) {
+ ast_log(LOG_WARNING, "CALENDAR_BUSY requires an argument: CALENDAR_BUSY(<calendar_name>)\n");
+ return -1;
+ }
+
+ cal = find_calendar(data);
+
+ if (!cal) {
+ ast_log(LOG_WARNING, "Could not find calendar '%s'\n", data);
+ return -1;
+ }
+
+ strcpy(buf, calendar_is_busy(cal) ? "1" : "0");
+
+ return 0;
+}
+
+static struct ast_custom_function calendar_busy_function = {
+ .name = "CALENDAR_BUSY",
+ .read = calendar_busy_exec,
+};
+
+static int add_event_to_list(struct eventlist *events, struct ast_calendar_event *event, time_t start, time_t end)
+{
+ struct evententry *entry, *iter;
+ int event_startdiff = abs(start - event->start);
+ int event_enddiff = abs(end - event->end);
+ int i = 0;
+
+ if (!(entry = ast_calloc(1, sizeof(*entry)))) {
+ ast_log(LOG_ERROR, "Unable to allocate memory for event list\n");
+ return -1;
+ }
+
+ entry->event = event;
+ ao2_ref(event, +1);
+
+ if (start == end) {
+ AST_LIST_TRAVERSE_SAFE_BEGIN(events, iter, list) {
+ int startdiff = abs(iter->event->start - start);
+
+ ast_debug(10, "Comparing %s with startdiff %d to %s with startdiff %d\n", event->summary, event_startdiff, iter->event->summary, startdiff);
+ ++i;
+ if (startdiff > event_startdiff) {
+ AST_LIST_INSERT_BEFORE_CURRENT(entry, list);
+ return i;
+ }
+ if (startdiff == event_startdiff) {
+ int enddiff = abs(iter->event->end - end);
+
+ if (enddiff > event_enddiff) {
+ AST_LIST_INSERT_BEFORE_CURRENT(entry, list);
+ return i;
+ }
+ if (event_startdiff == enddiff) {
+ if (strcmp(event->uid, iter->event->uid) < 0) {
+ AST_LIST_INSERT_BEFORE_CURRENT(entry, list);
+ return i;
+ }
+ }
+ }
+ }
+ AST_LIST_TRAVERSE_SAFE_END;
+
+ AST_LIST_INSERT_TAIL(events, entry, list);
+
+ return i;
+ }
+
+ AST_LIST_TRAVERSE_SAFE_BEGIN(events, iter, list) {
+ ++i;
+ if (iter->event->start > event->start) {
+ AST_LIST_INSERT_BEFORE_CURRENT(entry, list);
+ return i;
+ }
+
+ if (iter->event->start == event->start) {
+ if ((iter->event->end - iter->event->start) == (event->end - event->start)) {
+ if (strcmp(event->uid, iter->event->uid) < 0) {
+ AST_LIST_INSERT_BEFORE_CURRENT(entry, list);
+ return i;
+ }
+ }
+ if ((iter->event->end - iter->event->start) < (event->end - event->start)) {
+ AST_LIST_INSERT_BEFORE_CURRENT(entry, list);
+ return i;
+ }
+ }
+ }
+ AST_LIST_TRAVERSE_SAFE_END;
+
+ AST_LIST_INSERT_TAIL(events, entry, list);
+
+ return i;
+}
+
+static void eventlist_destroy(void *data)
+{
+ struct eventlist *events = data;
+
+ ao2_ref(events, -1);
+}
+
+static void *eventlist_duplicate(void *data)
+{
+ struct eventlist *events = data;
+
+ if (!events) {
+ return NULL;
+ }
+
+ ao2_ref(events, +1);
+
+ return events;
+}
+
+static int calendar_query_exec(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
+{
+ struct ast_calendar *cal;
+ struct ao2_iterator i;
+ struct ast_calendar_event *event;
+ struct eventlist *events;
+ time_t start = INT_MIN, end = INT_MAX;
+ struct ast_datastore *eventlist_datastore;
+ AST_DECLARE_APP_ARGS(args,
+ AST_APP_ARG(calendar);
+ AST_APP_ARG(start);
+ AST_APP_ARG(end);
+ );
+
+ if (!chan) {
+ ast_log(LOG_WARNING, "%s requires a channel to store the data on\n", cmd);
+ return -1;
+ }
+
+ AST_STANDARD_APP_ARGS(args, data);
+
+ if (ast_strlen_zero(args.calendar)) {
+ ast_log(LOG_WARNING, "%s requires a calendar argument\n", cmd);
+ return -1;
+ }
+
+ if (!(cal = find_calendar(args.calendar))) {
+ ast_log(LOG_WARNING, "Unknown calendar '%s'\n", args.calendar);
+ return -1;
+ }
+
+ if (!(events = ao2_alloc(sizeof(*events), eventlist_destructor))) {
+ ast_log(LOG_ERROR, "Unable to allocate memory for event list\n");
+ cal = unref_calendar(cal);
+ return -1;
+ }
+
+ if (!ast_strlen_zero(args.start)) {
+ start = atoi(args.start);
+ }
+
+ if (!ast_strlen_zero(args.end)) {
+ end = atoi(args.end);
+ }
+
+ i = ao2_iterator_init(cal->events, 0);
+ while ((event = ao2_iterator_next(&i))) {
+ if (!(start > event->end || end < event->start)) {
+ ast_debug(10, "%s (%ld - %ld) overlapped with (%ld - %ld)\n", event->summary, event->start, event->end, start, end);
+ if (add_event_to_list(events, event, start, end) < 0) {
+ event = ast_calendar_unref_event(event);
+ return -1;
+ }
+ }
+
+ event = ast_calendar_unref_event(event);
+ }
+
+ ast_channel_lock(chan);
+ do {
+ generate_random_string(buf, len);
+ } while (ast_channel_datastore_find(chan, &eventlist_datastore_info, buf));
+ ast_channel_unlock(chan);
+
+ if (!(eventlist_datastore = ast_datastore_alloc(&eventlist_datastore_info, buf))) {
+ ast_log(LOG_ERROR, "Could not allocate datastore!\n");
+ return -1;
+ }
+
+ eventlist_datastore->inheritance = DATASTORE_INHERIT_FOREVER;
+ eventlist_datastore->data = events;
+
+ ast_channel_lock(chan);
+ ast_channel_datastore_add(chan, eventlist_datastore);
+ ast_channel_unlock(chan);
+
+ return 0;
+}
+
+static struct ast_custom_function calendar_query_function = {
+ .name = "CALENDAR_QUERY",
+ .read = calendar_query_exec,
+};
+
+static void calendar_join_attendees(struct ast_calendar_event *event, char *buf, size_t len)
+{
+ struct ast_str *tmp;
+ struct ast_calendar_attendee *attendee;
+
+ if (!(tmp = ast_str_create(32))) {
+ ast_log(LOG_ERROR, "Could not allocate memory for attendees!\n");
+ return;
+ }
+
+ AST_LIST_TRAVERSE(&event->attendees, attendee, next) {
+ ast_str_append(&tmp, 0, "%s%s", attendee == AST_LIST_FIRST(&event->attendees) ? "" : ",", attendee->data);
+ }
+
+ ast_copy_string(buf, ast_str_buffer(tmp), len);
+ ast_free(tmp);
+}
+
+static int calendar_query_result_exec(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
+{
+ struct ast_datastore *datastore;
+ struct eventlist *events;
+ struct evententry *entry;
+ int row = 1;
+ AST_DECLARE_APP_ARGS(args,
+ AST_APP_ARG(id);
+ AST_APP_ARG(field);
+ AST_APP_ARG(row);
+ );
+
+ if (!chan) {
+ ast_log(LOG_WARNING, "%s requires a channel\n", cmd);
+ return -1;
+ }
+
+ AST_STANDARD_APP_ARGS(args, data);
+
+ if (ast_strlen_zero(args.id) || ast_strlen_zero(args.field)) {
+ ast_log(LOG_WARNING, "%s requires an id and a field", cmd);
+ return -1;
+ }
+
+ ast_channel_lock(chan);
+ if (!(datastore = ast_channel_datastore_find(chan, &eventlist_datastore_info, args.id))) {
+ ast_log(LOG_WARNING, "There is no event notification datastore with id '%s' on '%s'!\n", args.id, chan->name);
+ ast_channel_unlock(chan);
+ return -1;
+ }
+ ast_channel_unlock(chan);
+
+ if (!(events = datastore->data)) {
+ ast_log(LOG_WARNING, "The datastore contains no data!\n");
+ return -1;
+ }
+
+ if (!ast_strlen_zero(args.row)) {
+ row = atoi(args.row);
+ }
+
+ AST_LIST_TRAVERSE(events, entry, list) {
+ if (--row) {
+ continue;
+ }
+ if (!strcasecmp(args.field, "summary")) {
+ ast_copy_string(buf, entry->event->summary, len);
+ } else if (!strcasecmp(args.field, "description")) {
+ ast_copy_string(buf, entry->event->description, len);
+ } else if (!strcasecmp(args.field, "organizer")) {
+ ast_copy_string(buf, entry->event->organizer, len);
+ } else if (!strcasecmp(args.field, "location")) {
+ ast_copy_string(buf, entry->event->location, len);
+ } else if (!strcasecmp(args.field, "calendar")) {
+ ast_copy_string(buf, entry->event->owner->name, len);
+ } else if (!strcasecmp(args.field, "uid")) {
+ ast_copy_string(buf, entry->event->uid, len);
+ } else if (!strcasecmp(args.field, "start")) {
+ snprintf(buf, len, "%ld", entry->event->start);
+ } else if (!strcasecmp(args.field, "end")) {
+ snprintf(buf, len, "%ld", entry->event->end);
+ } else if (!strcasecmp(args.field, "busystate")) {
+ snprintf(buf, len, "%d", entry->event->busy_state);
+ } else if (!strcasecmp(args.field, "attendees")) {
+ calendar_join_attendees(entry->event, buf, len);
+ } else {
+ ast_log(LOG_WARNING, "Unknown field '%s'\n", args.field);
+ }
+ break;
+ }
+
+ return 0;
+}
+
+static struct ast_custom_function calendar_query_result_function = {
+ .name = "CALENDAR_QUERY_RESULT",
+ .read = calendar_query_result_exec,
+};
+
+static int calendar_write_exec(struct ast_channel *chan, const char *cmd, char *data, const char *value)
+{
+ int i, j, ret = -1;
+ char *val_dup = NULL;
+ struct ast_calendar *cal = NULL;
+ struct ast_calendar_event *event = NULL;
+ AST_DECLARE_APP_ARGS(fields,
+ AST_APP_ARG(field)[10];
+ );
+ AST_DECLARE_APP_ARGS(values,
+ AST_APP_ARG(value)[10];
+ );
+
+ if (!(val_dup = ast_strdup(value))) {
+ ast_log(LOG_ERROR, "Could not allocate memory for values\n");
+ return -1;
+ }
+
+ AST_STANDARD_APP_ARGS(fields, data);
+ AST_STANDARD_APP_ARGS(values, val_dup);
+
+ /* XXX Eventually we will support unnamed calendars, so if we don't find one, we parse
+ * for a calendar type and create it */
+ if (!(cal = find_calendar(fields.field[0]))) {
+ ast_log(LOG_WARNING, "Couldn't find calendar '%s'\n", fields.field[0]);
+ goto write_cleanup;
+ }
+
+ if (!(cal->tech->write_event)) {
+ ast_log(LOG_WARNING, "Calendar '%s' has no write function!\n", cal->name);
+ goto write_cleanup;
+ }
+
+ if (!(event = ast_calendar_event_alloc(cal))) {
+ goto write_cleanup;
+ }
+
+ if (ast_strlen_zero(fields.field[0])) {
+ ast_log(LOG_WARNING, "CALENDAR_WRITE requires a calendar name!\n");
+ goto write_cleanup;
+ }
+
+ if (fields.argc - 1 != values.argc) {
+ ast_log(LOG_WARNING, "CALENDAR_WRITE should have the same number of fields (%d) and values (%d)!\n", fields.argc - 1, values.argc);
+ goto write_cleanup;
+ }
+
+ event->owner = cal;
+
+ for (i = 1, j = 0; i < fields.argc; i++, j++) {
+ if (!strcasecmp(fields.field[i], "summary")) {
+ ast_string_field_set(event, summary, values.value[j]);
+ } else if (!strcasecmp(fields.field[i], "description")) {
+ ast_string_field_set(event, description, values.value[j]);
+ } else if (!strcasecmp(fields.field[i], "organizer")) {
+ ast_string_field_set(event, organizer, values.value[j]);
+ } else if (!strcasecmp(fields.field[i], "location")) {
+ ast_string_field_set(event, location, values.value[j]);
+ } else if (!strcasecmp(fields.field[i], "uid")) {
+ ast_string_field_set(event, uid, values.value[j]);
+ } else if (!strcasecmp(fields.field[i], "start")) {
+ event->start = atoi(values.value[j]);
+ } else if (!strcasecmp(fields.field[i], "end")) {
+ event->end = atoi(values.value[j]);
+ } else if (!strcasecmp(fields.field[i], "busystate")) {
+ event->busy_state = atoi(values.value[j]);
+ } else {
+ ast_log(LOG_WARNING, "Unknown calendar event field '%s'\n", fields.field[i]);
+ }
+ }
+
+ if((ret = cal->tech->write_event(event))) {
+ ast_log(LOG_WARNING, "Writing event to calendar '%s' failed!\n", cal->name);
+ }
+
+write_cleanup:
+ if (cal) {
+ cal = unref_calendar(cal);
+ }
+ if (event) {
+ event = ast_calendar_unref_event(event);
+ }
+ if (val_dup) {
+ ast_free(val_dup);
+ }
+
+ return ret;
+}
+
+static struct ast_custom_function calendar_write_function = {
+ .name = "CALENDAR_WRITE",
+ .write = calendar_write_exec,
+};
+
+/*! \brief CLI command to list available calendars */
+static char *handle_show_calendars(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
+{
+#define FORMAT "%-20.20s %-10.10s %-6.6s\n"
+ struct ao2_iterator i;
+ struct ast_calendar *cal;
+
+ switch(cmd) {
+ case CLI_INIT:
+ e->command = "calendar show calendars";
+ e->usage =
+ "Usage: calendar show calendars\n"
+ " Lists all registered calendars.\n";
+ return NULL;
+ case CLI_GENERATE:
+ return NULL;
+ }
+
+ ast_cli(a->fd, FORMAT, "Calendar", "Type", "Status");
+ ast_cli(a->fd, FORMAT, "--------", "----", "------");
+ i = ao2_iterator_init(calendars, 0);
+ while ((cal = ao2_iterator_next(&i))) {
+ ast_cli(a->fd, FORMAT, cal->name, cal->tech->type, calendar_is_busy(cal) ? "busy" : "free");
+ cal = unref_calendar(cal);
+ }
+
+ return CLI_SUCCESS;
+#undef FORMAT
+}
+
+static char *epoch_to_string(char *buf, size_t buflen, time_t epoch)
+{
+ struct ast_tm tm;
+ struct timeval tv = {
+ .tv_sec = epoch,
+ };
+
+ if (!epoch) {
+ *buf = '\0';
+ return buf;
+ }
+ ast_localtime(&tv, &tm, NULL);
+ ast_strftime(buf, buflen, "%F %r", &tm);
+
+ return buf;
+}
+
+static char *handle_show_calendar(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
+{
+#define FORMAT "%-17.17s : %-20.20s\n"
+#define FORMAT2 "%-12.12s: %-40.60s\n"
+ struct ao2_iterator i;
+ struct ast_calendar *cal;
+ struct ast_calendar_event *event;
+ int which = 0;
+ char *ret = NULL;
+
+ switch(cmd) {
+ case CLI_INIT:
+ e->command = "calendar show calendar";
+ e->usage =
+ "Usage: calendar show calendar <calendar name>\n"
+ " Displays information about a calendar\n";
+ return NULL;
+
+ case CLI_GENERATE:
+ if (a->pos != 3) {
+ return NULL;
+ }
+ i = ao2_iterator_init(calendars, 0);
+ while ((cal = ao2_iterator_next(&i))) {
+ if (!strncasecmp(a->word, cal->name, strlen(a->word)) && ++which > a->n) {
+ ret = ast_strdup(cal->name);
+ cal = unref_calendar(cal);
+ break;
+ }
+ cal = unref_calendar(cal);
+ }
+ return ret;
+ }
+
+ if (a->argc != 4) {
+ return CLI_SHOWUSAGE;
+ }
+
+ if (!(cal = find_calendar(a->argv[3]))) {
+ return NULL;
+ }
+
+ ast_cli(a->fd, FORMAT, "Name", cal->name);
+ ast_cli(a->fd, FORMAT, "Notify channel", cal->notify_channel);
+ ast_cli(a->fd, FORMAT, "Notify context", cal->notify_context);
+ ast_cli(a->fd, FORMAT, "Notify extension", cal->notify_extension);
+ ast_cli(a->fd, FORMAT, "Notify application", cal->notify_app);
+ ast_cli(a->fd, FORMAT, "Notify appdata", cal->notify_appdata);
+ ast_cli(a->fd, "%-17.17s : %d\n", "Refresh time", cal->refresh);
+ ast_cli(a->fd, "%-17.17s : %d\n", "Timeframe", cal->timeframe);
+ ast_cli(a->fd, "%-17.17s : %d\n", "Autoreminder", cal->autoreminder);
+ ast_cli(a->fd, "%s\n", "Events");
+ ast_cli(a->fd, "%s\n", "------");
+
+ i = ao2_iterator_init(cal->events, 0);
+ while ((event = ao2_iterator_next(&i))) {
+ char buf[100];
+
+ ast_cli(a->fd, FORMAT2, "Summary", event->summary);
+ ast_cli(a->fd, FORMAT2, "Description", event->description);
+ ast_cli(a->fd, FORMAT2, "Organizer", event->organizer);
+ ast_cli(a->fd, FORMAT2, "Location", event->location);
+ ast_cli(a->fd, FORMAT2, "UID", event->uid);
+ ast_cli(a->fd, FORMAT2, "Start", epoch_to_string(buf, sizeof(buf), event->start));
+ ast_cli(a->fd, FORMAT2, "End", epoch_to_string(buf, sizeof(buf), event->end));
+ ast_cli(a->fd, FORMAT2, "Alarm", epoch_to_string(buf, sizeof(buf), event->alarm));
+ ast_cli(a->fd, "\n");
+
+ event = ast_calendar_unref_event(event);
+ }
+ cal = unref_calendar(cal);
+ return CLI_SUCCESS;
+#undef FORMAT
+#undef FORMAT2
+}
+
+static char *handle_dump_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
+{
+ switch(cmd) {
+ case CLI_INIT:
+ e->command = "calendar dump sched";
+ e->usage =
+ "Usage: calendar dump sched\n"
+ " Dump the calendar sched context";
+ return NULL;
+
+ case CLI_GENERATE:
+ return NULL;
+ }
+
+ ast_sched_dump(sched);
+
+ return CLI_SUCCESS;
+}
+
+static struct ast_cli_entry calendar_cli[] = {
+ AST_CLI_DEFINE(handle_show_calendar, "Display information about a calendar"),
+ AST_CLI_DEFINE(handle_show_calendars, "Show registered calendars"),
+ AST_CLI_DEFINE(handle_dump_sched, "Dump calendar sched context"),
+};
+
+static int calendar_event_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
+{
+ struct ast_datastore *datastore;
+ struct ast_calendar_event *event;
+
+ if (ast_strlen_zero(data)) {
+ ast_log(LOG_WARNING, "%s requires an argument\n", cmd);
+ return -1;
+ }
+
+ ast_channel_lock(chan);
+ if (!(datastore = ast_channel_datastore_find(chan, &event_notification_datastore, NULL))) {
+ ast_log(LOG_WARNING, "There is no event notification datastore on '%s'!\n", chan->name);
+ ast_channel_unlock(chan);
+ return -1;
+ }
+ ast_channel_unlock(chan);
+
+ if (!(event = datastore->data)) {
+ ast_log(LOG_WARNING, "The datastore contains no data!\n");
+ return -1;
+ }
+
+ if (!strcasecmp(data, "summary")) {
+ ast_copy_string(buf, event->summary, len);
+ } else if (!strcasecmp(data, "description")) {
+ ast_copy_string(buf, event->description, len);
+ } else if (!strcasecmp(data, "organizer")) {
+ ast_copy_string(buf, event->organizer, len);
+ } else if (!strcasecmp(data, "location")) {
+ ast_copy_string(buf, event->location, len);
+ } else if (!strcasecmp(data, "calendar")) {
+ ast_copy_string(buf, event->owner->name, len);
+ } else if (!strcasecmp(data, "uid")) {
+ ast_copy_string(buf, event->uid, len);
+ } else if (!strcasecmp(data, "start")) {
+ snprintf(buf, len, "%ld", (long)event->start);
+ } else if (!strcasecmp(data, "end")) {
+ snprintf(buf, len, "%ld", (long)event->end);
+ } else if (!strcasecmp(data, "busystate")) {
+ snprintf(buf, len, "%d", event->busy_state);
+ } else if (!strcasecmp(data, "attendees")) {
+ calendar_join_attendees(event, buf, len);
+ }
+
+
+ return 0;
+}
+
+static struct ast_custom_function calendar_event_function = {
+ .name = "CALENDAR_EVENT",
+ .read = calendar_event_read,
+};
+
+static int cb_pending_deletion(void *user_data, void *arg, int flags)
+{
+ struct ast_calendar *cal = user_data;
+
+ cal->pending_deletion = 1;
+
+ return CMP_MATCH;
+}
+
+static int cb_rm_pending_deletion(void *user_data, void *arg, int flags)
+{
+ struct ast_calendar *cal = user_data;
+
+ return cal->pending_deletion ? CMP_MATCH : 0;
+}
+
+static int reload(void)
+{
+ struct ast_calendar_tech *iter;
+
+ ast_mutex_lock(&reloadlock);
+
+ /* Mark existing calendars for deletion */
+ ao2_callback(calendars, OBJ_NODATA | OBJ_MULTIPLE, cb_pending_deletion, NULL);
+ load_config(NULL);
+
+ AST_LIST_LOCK(&techs);
+ AST_LIST_TRAVERSE(&techs, iter, list) {
+ if (load_tech_calendars(iter)) {
+ ast_log(LOG_WARNING, "Failed to reload %s calendars, module disabled\n", iter->type);
+ }
+ }
+ AST_LIST_UNLOCK(&techs);
+
+ /* Delete calendars that no longer show up in the config */
+ ao2_callback(calendars, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, cb_rm_pending_deletion, NULL);
+
+ ast_mutex_unlock(&reloadlock);
+
+ return 0;
+}
+
+static void *do_refresh(void *data)
+{
+ for (;;) {
+ struct timeval now = ast_tvnow();
+ struct timespec ts = {0,};
+ int res, wait;
+
+ ast_mutex_lock(&refreshlock);
+
+ if ((wait = ast_sched_wait(sched)) < 0) {
+ wait = 1000;
+ }
+
+ ts.tv_sec = (now.tv_sec + wait / 1000) + 1;
+ res = ast_cond_timedwait(&refresh_condition, &refreshlock, &ts);
+
+ ast_mutex_unlock(&refreshlock);
+
+ ast_sched_runq(sched);
+ }
+
+ return NULL;
+}
+
+/* If I were to allow unloading it would look something like this */
+static int unload_module(void)
+{
+ struct ast_calendar_tech *tech;
+
+ ast_devstate_prov_del("calendar");
+ ast_custom_function_unregister(&calendar_busy_function);
+ ast_custom_function_unregister(&calendar_event_function);
+ ast_custom_function_unregister(&calendar_query_function);
+ ast_custom_function_unregister(&calendar_query_result_function);
+ ast_custom_function_unregister(&calendar_write_function);
+ ast_cli_unregister_multiple(calendar_cli, ARRAY_LEN(calendar_cli));
+
+ /* Remove all calendars */
+ ao2_callback(calendars, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL);
+
+ AST_LIST_LOCK(&techs);
+ AST_LIST_TRAVERSE_SAFE_BEGIN(&techs, tech, list) {
+ ast_unload_resource(tech->module, 0);
+ }
+ AST_LIST_TRAVERSE_SAFE_END;
+ AST_LIST_UNLOCK(&techs);
+
+ return 0;
+}
+
+static int load_module(void)
+{
+ if (load_config(NULL)) {
+ /* We don't have calendar support enabled */
+ return 0;
+ }
+
+ if (!(calendars = ao2_container_alloc(CALENDAR_BUCKETS, calendar_hash_fn, calendar_cmp_fn))) {
+ ast_log(LOG_ERROR, "Unable to allocate calendars container!\n");
+ return -1;
+ }
+
+ ast_mutex_init(&refreshlock);
+ ast_cond_init(&refresh_condition, NULL);
+ ast_mutex_init(&reloadlock);
+
+ if (!(sched = sched_context_create())) {
+ ast_log(LOG_ERROR, "Unable to create sched context\n");
+ return -1;
+ }
+
+ if (ast_pthread_create_background(&refresh_thread, NULL, do_refresh, NULL) < 0) {
+ ast_log(LOG_ERROR, "Unable to start refresh thread--notifications disabled!\n");
+ }
+
+ ast_custom_function_register(&calendar_busy_function);
+ ast_custom_function_register(&calendar_event_function);
+ ast_custom_function_register(&calendar_query_function);
+ ast_custom_function_register(&calendar_query_result_function);
+ ast_custom_function_register(&calendar_write_function);
+ ast_cli_register_multiple(calendar_cli, ARRAY_LEN(calendar_cli));
+
+ ast_devstate_prov_add("Calendar", calendarstate);
+
+ /* Since other modules depend on this, disable unloading */
+ ast_module_ref(ast_module_info->self);
+
+ return 0;
+}
+AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "Asterisk Calendar integration",
+ .load = load_module,
+ .unload = unload_module,
+ .reload = reload,
+ );
diff --git a/res/res_calendar.exports b/res/res_calendar.exports
new file mode 100644
index 000000000..021d395b3
--- /dev/null
+++ b/res/res_calendar.exports
@@ -0,0 +1,7 @@
+{
+ global:
+ ast_*;
+ calendar_config;
+ local:
+ *;
+};
diff --git a/res/res_calendar_caldav.c b/res/res_calendar_caldav.c
new file mode 100644
index 000000000..57e2575d0
--- /dev/null
+++ b/res/res_calendar_caldav.c
@@ -0,0 +1,675 @@
+/*
+ * Asterisk -- An open source telephony toolkit.
+ *
+ * Copyright (C) 2008 - 2009, Digium, Inc.
+ *
+ * Terry Wilson <twilson@digium.com>
+ *
+ * See http://www.asterisk.org for more information about
+ * the Asterisk project. Please do not directly contact
+ * any of the maintainers of this project for assistance;
+ * the project provides a web site, mailing lists and IRC
+ * channels for your use.
+ *
+ * This program is free software, distributed under the terms of
+ * the GNU General Public License Version 2. See the LICENSE file
+ * at the top of the source tree.
+ */
+
+/*! \file
+ * \brief Resource for handling iCalnedar calendars
+ */
+
+/*** MODULEINFO
+ <depend>neon</depend>
+ <depend>ical</depend>
+ <depend>libxml2</depend>
+***/
+#include "asterisk.h"
+
+ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
+
+#include <libical/ical.h>
+#include <neon/ne_session.h>
+#include <neon/ne_uri.h>
+#include <neon/ne_request.h>
+#include <neon/ne_auth.h>
+#include <libxml/xmlmemory.h>
+#include <libxml/parser.h>
+
+#include "asterisk/module.h"
+#include "asterisk/calendar.h"
+#include "asterisk/lock.h"
+#include "asterisk/config.h"
+#include "asterisk/astobj2.h"
+
+static void *caldav_load_calendar(void *data);
+static void *unref_caldav(void *obj);
+static int caldav_write_event(struct ast_calendar_event *event);
+
+static struct ast_calendar_tech caldav_tech = {
+ .type = "caldav",
+ .description = "CalDAV calendars",
+ .module = AST_MODULE,
+ .load_calendar = caldav_load_calendar,
+ .unref_calendar = unref_caldav,
+ .write_event = caldav_write_event,
+};
+
+struct caldav_pvt {
+ AST_DECLARE_STRING_FIELDS(
+ AST_STRING_FIELD(url);
+ AST_STRING_FIELD(user);
+ AST_STRING_FIELD(secret);
+ );
+ struct ast_calendar *owner;
+ ne_uri uri;
+ ne_session *session;
+ struct ao2_container *events;
+};
+
+static int cb_true(void *user_data, void *arg, int flags)
+{
+ return CMP_MATCH;
+}
+
+static void caldav_destructor(void *obj)
+{
+ struct caldav_pvt *pvt = obj;
+
+ ast_debug(1, "Destroying pvt for CalDAV calendar %s\n", pvt->owner->name);
+ if (pvt->session) {
+ ne_session_destroy(pvt->session);
+ }
+ ast_string_field_free_memory(pvt);
+
+ ao2_callback(pvt->events, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, cb_true, NULL);
+
+ ao2_ref(pvt->events, -1);
+}
+
+static void *unref_caldav(void *obj)
+{
+ struct caldav_pvt *pvt = obj;
+
+ ao2_ref(pvt, -1);
+ return NULL;
+}
+
+static int fetch_response_reader(void *data, const char *block, size_t len)
+{
+ struct ast_str **response = data;
+ unsigned char *tmp;
+
+ if (!(tmp = ast_malloc(len + 1))) {
+ return -1;
+ }
+ memcpy(tmp, block, len);
+ tmp[len] = '\0';
+ ast_str_append(response, 0, "%s", tmp);
+ ast_free(tmp);
+
+ return 0;
+}
+
+static int auth_credentials(void *userdata, const char *realm, int attempts, char *username, char *secret)
+{
+ struct caldav_pvt *pvt = userdata;
+
+ if (attempts > 1) {
+ ast_log(LOG_WARNING, "Invalid username or password for CalDAV calendar '%s'\n", pvt->owner->name);
+ return -1;
+ }
+
+ ne_strnzcpy(username, pvt->user, NE_ABUFSIZ);
+ ne_strnzcpy(secret, pvt->secret, NE_ABUFSIZ);
+
+ return 0;
+}
+
+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)
+{
+ struct ast_str *response;
+ ne_request *req;
+ int ret;
+ char buf[1000];
+
+ if (!pvt) {
+ ast_log(LOG_ERROR, "There is no private!\n");
+ return NULL;
+ }
+
+ if (!(response = ast_str_create(512))) {
+ ast_log(LOG_ERROR, "Could not allocate memory for response.\n");
+ return NULL;
+ }
+
+ snprintf(buf, sizeof(buf), "%s%s", pvt->uri.path, subdir ? ast_str_buffer(subdir) : "");
+
+ req = ne_request_create(pvt->session, method, buf);
+ ne_add_response_body_reader(req, ne_accept_2xx, fetch_response_reader, &response);
+ ne_set_request_body_buffer(req, ast_str_buffer(req_body), ast_str_strlen(req_body));
+ ne_add_request_header(req, "Content-type", ast_strlen_zero(content_type) ? "text/xml" : content_type);
+
+ ret = ne_request_dispatch(req);
+ ne_request_destroy(req);
+
+ if (ret != NE_OK || !ast_str_strlen(response)) {
+ ast_log(LOG_WARNING, "Unknown response to CalDAV calendar %s, request %s to %s: %s\n", pvt->owner->name, method, pvt->url, ne_get_error(pvt->session));
+ ast_free(response);
+ return NULL;
+ }
+
+ return response;
+}
+
+static int caldav_write_event(struct ast_calendar_event *event)
+{
+ struct ast_str *body = NULL, *response = NULL, *subdir = NULL;
+ icalcomponent *calendar, *icalevent;
+ icaltimezone *utc = icaltimezone_get_utc_timezone();
+ int ret = -1;
+
+ if (!event) {
+ ast_log(LOG_WARNING, "No event passed!\n");
+ return -1;
+ }
+
+ if (!(event->start && event->end)) {
+ ast_log(LOG_WARNING, "The event must contain a start and an end\n");
+ return -1;
+ }
+ if (!(body = ast_str_create(512)) ||
+ !(subdir = ast_str_create(32)) ||
+ !(response = ast_str_create(512))) {
+ ast_log(LOG_ERROR, "Could not allocate memory for request and response!\n");
+ goto write_cleanup;
+ }
+
+ if (ast_strlen_zero(event->uid)) {
+ unsigned short val[8];
+ int x;
+ for (x = 0; x < 8; x++) {
+ val[x] = ast_random();
+ }
+ 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]);
+ }
+
+ calendar = icalcomponent_new(ICAL_VCALENDAR_COMPONENT);
+ icalcomponent_add_property(calendar, icalproperty_new_version("2.0"));
+ icalcomponent_add_property(calendar, icalproperty_new_prodid("-//Digium, Inc.//res_caldav//EN"));
+
+ icalevent = icalcomponent_new(ICAL_VEVENT_COMPONENT);
+ icalcomponent_add_property(icalevent, icalproperty_new_dtstamp(icaltime_current_time_with_zone(utc)));
+ icalcomponent_add_property(icalevent, icalproperty_new_uid(event->uid));
+ icalcomponent_add_property(icalevent, icalproperty_new_dtstart(icaltime_from_timet_with_zone(event->start, 0, utc)));
+ icalcomponent_add_property(icalevent, icalproperty_new_dtend(icaltime_from_timet_with_zone(event->end, 0, utc)));
+ if (!ast_strlen_zero(event->organizer)) {
+ icalcomponent_add_property(icalevent, icalproperty_new_organizer(event->organizer));
+ }
+ if (!ast_strlen_zero(event->summary)) {
+ icalcomponent_add_property(icalevent, icalproperty_new_summary(event->summary));
+ }
+ if (!ast_strlen_zero(event->description)) {
+ icalcomponent_add_property(icalevent, icalproperty_new_description(event->description));
+ }
+ if (!ast_strlen_zero(event->location)) {
+ icalcomponent_add_property(icalevent, icalproperty_new_location(event->location));
+ }
+
+ switch (event->busy_state) {
+ case AST_CALENDAR_BS_BUSY:
+ icalcomponent_add_property(icalevent, icalproperty_new_status(ICAL_STATUS_CONFIRMED));
+ break;
+
+ case AST_CALENDAR_BS_BUSY_TENTATIVE:
+ icalcomponent_add_property(icalevent, icalproperty_new_status(ICAL_STATUS_TENTATIVE));
+ break;
+
+ default:
+ icalcomponent_add_property(icalevent, icalproperty_new_status(ICAL_STATUS_NONE));
+ }
+
+ icalcomponent_add_component(calendar, icalevent);
+
+ ast_str_append(&body, 0, "%s", icalcomponent_as_ical_string(calendar));
+ ast_str_set(&subdir, 0, "%s%s.ics", ast_str_buffer(body)[ast_str_strlen(body)] == '/' ? "" : "/", event->uid);
+
+ response = caldav_request(event->owner->tech_pvt, "PUT", body, subdir, "text/calendar");
+
+ ret = 0;
+
+write_cleanup:
+ if (body) {
+ ast_free(body);
+ }
+ if (response) {
+ ast_free(response);
+ }
+ if (subdir) {
+ ast_free(subdir);
+ }
+
+ return ret;
+}
+
+static struct ast_str *caldav_get_events_between(struct caldav_pvt *pvt, time_t start_time, time_t end_time)
+{
+ struct ast_str *body, *response;
+ icaltimezone *utc = icaltimezone_get_utc_timezone();
+ icaltimetype start, end;
+ const char *start_str, *end_str;
+
+ if (!(body = ast_str_create(512))) {
+ ast_log(LOG_ERROR, "Could not allocate memory for body of request!\n");
+ return NULL;
+ }
+
+ start = icaltime_from_timet_with_zone(start_time, 0, utc);
+ end = icaltime_from_timet_with_zone(end_time, 0, utc);
+ start_str = icaltime_as_ical_string(start);
+ end_str = icaltime_as_ical_string(end);
+
+ /* If I was really being efficient, I would store a collection of event URIs and etags,
+ * first doing a query of just the etag and seeing if anything had changed. If it had,
+ * then I would do a request for each of the events that had changed, and only bother
+ * updating those. Oh well. */
+ ast_str_append(&body, 0,
+ "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n"
+ "<C:calendar-query xmlns:D=\"DAV:\" xmlns:C=\"urn:ietf:params:xml:ns:caldav\">\n"
+ " <D:prop>\n"
+ " <C:calendar-data>\n"
+ " <C:expand start=\"%s\" end=\"%s\"/>\n"
+ " </C:calendar-data>\n"
+ " </D:prop>\n"
+ " <C:filter>\n"
+ " <C:comp-filter name=\"VCALENDAR\">\n"
+ " <C:comp-filter name=\"VEVENT\">\n"
+ " <C:time-range start=\"%s\" end=\"%s\"/>\n"
+ " </C:comp-filter>\n"
+ " </C:comp-filter>\n"
+ " </C:filter>\n"
+ "</C:calendar-query>\n", start_str, end_str, start_str, end_str);
+
+ response = caldav_request(pvt, "REPORT", body, NULL, NULL);
+ ast_free(body);
+
+ return response;
+}
+
+static void caldav_add_event(icalcomponent *comp, struct icaltime_span *span, void *data)
+{
+ struct caldav_pvt *pvt = data;
+ struct ast_calendar_event *event;
+ icaltimezone *utc = icaltimezone_get_utc_timezone();
+ icaltimetype start, end, tmp;
+ icalcomponent *valarm;
+ icalproperty *prop;
+ struct icaltriggertype trigger;
+
+ if (!(pvt && pvt->owner)) {
+ ast_log(LOG_ERROR, "Require a private structure with an owner\n");
+ return;
+ }
+
+ if (!(event = ast_calendar_event_alloc(pvt->owner))) {
+ ast_log(LOG_ERROR, "Could not allocate an event!\n");
+ return;
+ }
+
+ start = icaltime_from_timet_with_zone(span->start, 0, utc);
+ end = icaltime_from_timet_with_zone(span->end, 0, utc);
+ event->start = span->start;
+ event->end = span->end;
+
+ switch(icalcomponent_get_status(comp)) {
+ case ICAL_STATUS_CONFIRMED:
+ event->busy_state = AST_CALENDAR_BS_BUSY;
+ break;
+
+ case ICAL_STATUS_TENTATIVE:
+ event->busy_state = AST_CALENDAR_BS_BUSY_TENTATIVE;
+ break;
+
+ default:
+ event->busy_state = AST_CALENDAR_BS_FREE;
+ }
+
+ if ((prop = icalcomponent_get_first_property(comp, ICAL_SUMMARY_PROPERTY))) {
+ ast_string_field_set(event, summary, icalproperty_get_value_as_string(prop));
+ }
+
+ if ((prop = icalcomponent_get_first_property(comp, ICAL_DESCRIPTION_PROPERTY))) {
+ ast_string_field_set(event, description, icalproperty_get_value_as_string(prop));
+ }
+
+ if ((prop = icalcomponent_get_first_property(comp, ICAL_ORGANIZER_PROPERTY))) {
+ ast_string_field_set(event, organizer, icalproperty_get_value_as_string(prop));
+ }
+
+ if ((prop = icalcomponent_get_first_property(comp, ICAL_LOCATION_PROPERTY))) {
+ ast_string_field_set(event, location, icalproperty_get_value_as_string(prop));
+ }
+
+ if ((prop = icalcomponent_get_first_property(comp, ICAL_UID_PROPERTY))) {
+ ast_string_field_set(event, uid, icalproperty_get_value_as_string(prop));
+ } else {
+ ast_log(LOG_WARNING, "No UID found, but one is required. Generating, but updates may not be acurate\n");
+ if (!ast_strlen_zero(event->summary)) {
+ ast_string_field_set(event, uid, event->summary);
+ } else {
+ char tmp[100];
+ snprintf(tmp, sizeof(tmp), "%lu", event->start);
+ ast_string_field_set(event, uid, tmp);
+ }
+ }
+
+ /* Get the attendees */
+ for (prop = icalcomponent_get_first_property(comp, ICAL_ATTENDEE_PROPERTY);
+ prop; prop = icalcomponent_get_next_property(comp, ICAL_ATTENDEE_PROPERTY)) {
+ struct ast_calendar_attendee *attendee;
+ const char *data;
+
+ if (!(attendee = ast_calloc(1, sizeof(*attendee)))) {
+ event = ast_calendar_unref_event(event);
+ return;
+ }
+ data = icalproperty_get_attendee(prop);
+ if (!ast_strlen_zero(data)) {
+ attendee->data = ast_strdup(data);;
+ AST_LIST_INSERT_TAIL(&event->attendees, attendee, next);
+ }
+ }
+
+
+ /* Only set values for alarm based on VALARM. Can be overriden in main/calendar.c by autoreminder
+ * therefore, go ahead and add events even if their is no VALARM or it is malformed
+ * Currently we are only getting the first VALARM and are handling repitition in main/calendar.c from calendar.conf */
+ if (!(valarm = icalcomponent_get_first_component(comp, ICAL_VALARM_COMPONENT))) {
+ ao2_link(pvt->events, event);
+ event = ast_calendar_unref_event(event);
+ return;
+ }
+
+ if (!(prop = icalcomponent_get_first_property(valarm, ICAL_TRIGGER_PROPERTY))) {
+ ast_log(LOG_WARNING, "VALARM has no TRIGGER, skipping!\n");
+ ao2_link(pvt->events, event);
+ event = ast_calendar_unref_event(event);
+ return;
+ }
+
+ trigger = icalproperty_get_trigger(prop);
+
+ if (icaltriggertype_is_null_trigger(trigger)) {
+ ast_log(LOG_WARNING, "Bad TRIGGER for VALARM, skipping!\n");
+ ao2_link(pvt->events, event);
+ event = ast_calendar_unref_event(event);
+ return;
+ }
+
+ if (!icaltime_is_null_time(trigger.time)) { /* This is an absolute time */
+ tmp = icaltime_convert_to_zone(trigger.time, utc);
+ event->alarm = icaltime_as_timet_with_zone(tmp, utc);
+ } else { /* Offset from either dtstart or dtend */
+ /* XXX Technically you can check RELATED to see if the event fires from the END of the event
+ * But, I'm not sure I've ever seen anyone implement it in calendaring software, so I'm ignoring for now */
+ tmp = icaltime_add(start, trigger.duration);
+ event->alarm = icaltime_as_timet_with_zone(tmp, utc);
+ }
+
+ ao2_link(pvt->events, event);
+ event = ast_calendar_unref_event(event);
+
+ return;
+}
+
+struct xmlstate {
+ int in_caldata;
+ struct caldav_pvt *pvt;
+ struct ast_str *cdata;
+ time_t start;
+ time_t end;
+};
+
+static void handle_start_element(void *data, const xmlChar *fullname, const xmlChar **atts)
+{
+ struct xmlstate *state = data;
+
+ if (!xmlStrcasecmp(fullname, BAD_CAST "C:calendar-data")) {
+ state->in_caldata = 1;
+ ast_str_reset(state->cdata);
+ }
+}
+
+static void handle_end_element(void *data, const xmlChar *name)
+{
+ struct xmlstate *state = data;
+ struct icaltimetype start, end;
+ icaltimezone *utc = icaltimezone_get_utc_timezone();
+ icalcomponent *iter;
+ icalcomponent *comp;
+
+ if (xmlStrcasecmp(name, BAD_CAST "C:calendar-data")) {
+ return;
+ }
+
+ state->in_caldata = 0;
+ if (!(state->cdata && ast_str_strlen(state->cdata))) {
+ return;
+ }
+ /* XXX Parse the calendar blurb for recurrence events in the time range,
+ * create an event, and add it to pvt->events */
+ start = icaltime_from_timet_with_zone(state->start, 0, utc);
+ end = icaltime_from_timet_with_zone(state->end, 0, utc);
+ comp = icalparser_parse_string(ast_str_buffer(state->cdata));
+
+ for (iter = icalcomponent_get_first_component(comp, ICAL_VEVENT_COMPONENT);
+ iter;
+ iter = icalcomponent_get_next_component(comp, ICAL_VEVENT_COMPONENT))
+ {
+ icalcomponent_foreach_recurrence(iter, start, end, caldav_add_event, state->pvt);
+ }
+
+ icalcomponent_free(comp);
+}
+
+static void handle_characters(void *data, const xmlChar *ch, int len)
+{
+ struct xmlstate *state = data;
+ xmlChar *tmp;
+
+ if (!state->in_caldata) {
+ return;
+ }
+
+ tmp = xmlStrndup(ch, len);
+ ast_str_append(&state->cdata, 0, "%s", (char *)tmp);
+ xmlFree(tmp);
+}
+
+static int update_caldav(struct caldav_pvt *pvt)
+{
+ struct timeval now = ast_tvnow();
+ time_t start, end;
+ struct ast_str *response;
+ xmlSAXHandler saxHandler;
+ struct xmlstate state = {
+ .in_caldata = 0,
+ .pvt = pvt
+ };
+
+ start = now.tv_sec;
+ end = now.tv_sec + 60 * pvt->owner->timeframe;
+ if (!(response = caldav_get_events_between(pvt, start, end))) {
+ return -1;
+ }
+
+ if (!(state.cdata = ast_str_create(512))) {
+ ast_free(response);
+ return -1;
+ }
+
+ state.start = start;
+ state.end = end;
+
+ memset(&saxHandler, 0, sizeof(saxHandler));
+ saxHandler.startElement = handle_start_element;
+ saxHandler.endElement = handle_end_element;
+ saxHandler.characters = handle_characters;
+
+ xmlSAXUserParseMemory(&saxHandler, &state, ast_str_buffer(response), ast_str_strlen(response));
+
+ ast_calendar_merge_events(pvt->owner, pvt->events);
+
+ ast_free(response);
+ ast_free(state.cdata);
+
+ return 0;
+}
+
+static int verify_cert(void *userdata, int failures, const ne_ssl_certificate *cert)
+{
+ /* Verify all certs */
+ return 0;
+}
+
+static void *caldav_load_calendar(void *void_data)
+{
+ struct caldav_pvt *pvt;
+ struct ast_variable *v;
+ struct ast_calendar *cal = void_data;
+ ast_mutex_t refreshlock;
+
+ if (!(cal && calendar_config)) {
+ ast_log(LOG_ERROR, "You must enable calendar support for res_caldav to load\n");
+ return NULL;
+ }
+
+ if (ao2_trylock(cal)) {
+ if (cal->unloading) {
+ ast_log(LOG_WARNING, "Unloading module, load_calendar cancelled.\n");
+ } else {
+ ast_log(LOG_WARNING, "Could not lock calendar, aborting!\n");
+ }
+ return NULL;
+ }
+
+ if (!(pvt = ao2_alloc(sizeof(*pvt), caldav_destructor))) {
+ ast_log(LOG_ERROR, "Could not allocate caldav_pvt structure for calendar: %s\n", cal->name);
+ return NULL;
+ }
+
+ pvt->owner = cal;
+
+ if (!(pvt->events = ast_calendar_event_container_alloc())) {
+ ast_log(LOG_ERROR, "Could not allocate space for fetching events for calendar: %s\n", cal->name);
+ pvt = unref_caldav(pvt);
+ ao2_unlock(cal);
+ return NULL;
+ }
+
+ if (ast_string_field_init(pvt, 32)) {
+ ast_log(LOG_ERROR, "Couldn't allocate string field space for calendar: %s\n", cal->name);
+ pvt = unref_caldav(pvt);
+ ao2_unlock(cal);
+ return NULL;
+ }
+
+ for (v = ast_variable_browse(calendar_config, cal->name); v; v = v->next) {
+ if (!strcasecmp(v->name, "url")) {
+ ast_string_field_set(pvt, url, v->value);
+ } else if (!strcasecmp(v->name, "user")) {
+ ast_string_field_set(pvt, user, v->value);
+ } else if (!strcasecmp(v->name, "secret")) {
+ ast_string_field_set(pvt, secret, v->value);
+ }
+ }
+
+ if (ast_strlen_zero(pvt->url)) {
+ ast_log(LOG_WARNING, "No URL was specified for CalDAV calendar '%s' - skipping.\n", cal->name);
+ pvt = unref_caldav(pvt);
+ ao2_unlock(cal);
+ return NULL;
+ }
+
+ if (ne_uri_parse(pvt->url, &pvt->uri) || pvt->uri.host == NULL || pvt->uri.path == NULL) {
+ ast_log(LOG_WARNING, "Could not parse url '%s' for CalDAV calendar '%s' - skipping.\n", pvt->url, cal->name);
+ pvt = unref_caldav(pvt);
+ ao2_unlock(cal);
+ return NULL;
+ }
+
+ if (pvt->uri.scheme == NULL) {
+ pvt->uri.scheme = "http";
+ }
+
+ if (pvt->uri.port == 0) {
+ pvt->uri.port = ne_uri_defaultport(pvt->uri.scheme);
+ }
+
+ pvt->session = ne_session_create(pvt->uri.scheme, pvt->uri.host, pvt->uri.port);
+ ne_set_server_auth(pvt->session, auth_credentials, pvt);
+ if (!strncasecmp(pvt->uri.scheme, "https", sizeof(pvt->uri.scheme))) {
+ ne_ssl_trust_default_ca(pvt->session);
+ ne_ssl_set_verify(pvt->session, verify_cert, NULL);
+ }
+
+ cal->tech_pvt = pvt;
+
+ ast_mutex_init(&refreshlock);
+
+ /* Load it the first time */
+ update_caldav(pvt);
+
+ ao2_unlock(cal);
+
+ /* The only writing from another thread will be if unload is true */
+ for (;;) {
+ struct timeval tv = ast_tvnow();
+ struct timespec ts = {0,};
+
+ ts.tv_sec = tv.tv_sec + (60 * pvt->owner->refresh);
+
+ ast_mutex_lock(&refreshlock);
+ while (!pvt->owner->unloading) {
+ if (ast_cond_timedwait(&pvt->owner->unload, &refreshlock, &ts) == ETIMEDOUT) {
+ break;
+ }
+ }
+ ast_mutex_unlock(&refreshlock);
+
+ if (pvt->owner->unloading) {
+ ast_debug(10, "Skipping refresh since we got a shutdown signal\n");
+ return NULL;
+ }
+
+ ast_debug(10, "Refreshing after %d minute timeout\n", pvt->owner->refresh);
+
+ update_caldav(pvt);
+ }
+
+ return NULL;
+}
+
+static int load_module(void)
+{
+ ne_sock_init();
+ if (ast_calendar_register(&caldav_tech)) {
+ ne_sock_exit();
+ return AST_MODULE_LOAD_DECLINE;
+ }
+
+ return AST_MODULE_LOAD_SUCCESS;
+}
+
+static int unload_module(void)
+{
+ ast_calendar_unregister(&caldav_tech);
+ ne_sock_exit();
+ return 0;
+}
+
+AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Asterisk CalDAV Calendar Integration",
+ .load = load_module,
+ .unload = unload_module,
+ );
diff --git a/res/res_calendar_exchange.c b/res/res_calendar_exchange.c
new file mode 100644
index 000000000..ec539e8e2
--- /dev/null
+++ b/res/res_calendar_exchange.c
@@ -0,0 +1,757 @@
+/*
+ * Asterisk -- An open source telephony toolkit.
+ *
+ * Copyright (C) 2008 - 2009, Digium, Inc.
+ *
+ * Terry Wilson <twilson@digium.com>
+ *
+ * See http://www.asterisk.org for more information about
+ * the Asterisk project. Please do not directly contact
+ * any of the maintainers of this project for assistance;
+ * the project provides a web site, mailing lists and IRC
+ * channels for your use.
+ *
+ * This program is free software, distributed under the terms of
+ * the GNU General Public License Version 2. See the LICENSE file
+ * at the top of the source tree.
+ */
+
+/*! \file
+ * \brief Resource for handling iCalnedar calendars
+ */
+
+/*** MODULEINFO
+ <depend>neon</depend>
+ <depend>ical</depend>
+ <depend>iksemel</depend>
+***/
+#include "asterisk.h"
+
+ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
+
+#include <libical/ical.h>
+#include <neon/ne_session.h>
+#include <neon/ne_uri.h>
+#include <neon/ne_request.h>
+#include <neon/ne_auth.h>
+#include <iksemel.h>
+
+#include "asterisk/module.h"
+#include "asterisk/calendar.h"
+#include "asterisk/lock.h"
+#include "asterisk/config.h"
+#include "asterisk/astobj2.h"
+
+static void *exchangecal_load_calendar(void *data);
+static void *unref_exchangecal(void *obj);
+static int exchangecal_write_event(struct ast_calendar_event *event);
+
+static struct ast_calendar_tech exchangecal_tech = {
+ .type = "exchange",
+ .description = "MS Exchange calendars",
+ .module = AST_MODULE,
+ .load_calendar = exchangecal_load_calendar,
+ .unref_calendar = unref_exchangecal,
+ .write_event = exchangecal_write_event,
+};
+
+struct exchangecal_pvt {
+ AST_DECLARE_STRING_FIELDS(
+ AST_STRING_FIELD(url);
+ AST_STRING_FIELD(user);
+ AST_STRING_FIELD(secret);
+ );
+ struct ast_calendar *owner;
+ ne_uri uri;
+ ne_session *session;
+ struct ao2_container *events;
+};
+
+struct xmlstate {
+ char tag[80];
+ int in_response;
+ int in_propstat;
+ int in_prop;
+ void *ptr;
+ struct exchangecal_pvt *pvt;
+};
+
+static int parse_tag(void *data, char *name, char **atts, int type)
+{
+ struct xmlstate *state = data;
+ char *tmp;
+
+ if ((tmp = strchr(name, ':'))) {
+ tmp++;
+ } else {
+ return IKS_HOOK;
+ }
+
+ ast_copy_string(state->tag, tmp, sizeof(state->tag));
+
+ switch (type) {
+ case IKS_OPEN:
+ if (!strcasecmp(state->tag, "response")) {
+ struct ast_calendar_event *event;
+
+ state->in_response = 1;
+ if (!(event = ast_calendar_event_alloc(state->pvt->owner))) {
+ return IKS_NOMEM;
+ }
+ state->ptr = event;
+ } else if (!strcasecmp(state->tag, "propstat")) {
+ state->in_propstat = 1;
+ } else if (!strcasecmp(state->tag, "prop")) {
+ state->in_prop = 1;
+ }
+ break;
+
+ case IKS_CLOSE:
+ if (!strcasecmp(state->tag, "response")) {
+ struct ao2_container *events = state->pvt->events;
+ struct ast_calendar_event *event = state->ptr;
+
+ state->in_response = 0;
+ if (ast_strlen_zero(event->uid)) {
+ ast_log(LOG_ERROR, "This event has no UID, something has gone wrong\n");
+ event = ast_calendar_unref_event(event);
+ return IKS_HOOK;
+ }
+ ao2_link(events, event);
+ event = ast_calendar_unref_event(event);
+ } else if (!strcasecmp(state->tag, "propstat")) {
+ state->in_propstat = 0;
+ } else if (!strcasecmp(state->tag, "prop")) {
+ state->in_prop = 0;
+ }
+ break;
+
+ default:
+ return IKS_OK;
+ }
+
+ return IKS_OK;
+}
+
+static time_t mstime_to_time_t(char *mstime)
+{
+ char *read, *write;
+ icaltimetype tt;
+ for (read = write = mstime; *read; read++) {
+ if (*read == '.') {
+ *write++ = 'Z';
+ *write = '\0';
+ break;
+ }
+ if (*read == '-' || *read == ':')
+ continue;
+ *write = *read;
+ write++;
+ }
+
+ tt = icaltime_from_string(mstime);
+ return icaltime_as_timet(tt);
+}
+
+static enum ast_calendar_busy_state msbusy_to_bs(const char *msbusy)
+{
+ if (!strcasecmp(msbusy, "FREE")) {
+ return AST_CALENDAR_BS_FREE;
+ } else if (!strcasecmp(msbusy, "TENTATIVE")) {
+ return AST_CALENDAR_BS_BUSY_TENTATIVE;
+ } else {
+ return AST_CALENDAR_BS_BUSY;
+ }
+}
+
+static int parse_cdata(void *data, char *value, size_t len)
+{
+ char *str;
+ struct xmlstate *state = data;
+ struct ast_calendar_event *event = state->ptr;
+
+
+ str = ast_skip_blanks(value);
+
+ if (str == value + len)
+ return IKS_OK;
+
+ if (!(str = ast_calloc(1, len + 1))) {
+ return IKS_NOMEM;
+ }
+ memcpy(str, value, len);
+ if (!(state->in_response && state->in_propstat && state->in_prop)) {
+ ast_free(str);
+ return IKS_OK;
+ }
+ /* We use ast_string_field_build here because libiksemel is parsing CDATA with &lt; as
+ * new elements which is a bit odd and shouldn't happen */
+ if (!strcasecmp(state->tag, "subject")) {
+ ast_string_field_build(event, summary, "%s%s", event->summary, str);
+ } else if (!strcasecmp(state->tag, "location")) {
+ ast_string_field_build(event, location, "%s%s", event->location, str);
+ } else if (!strcasecmp(state->tag, "uid")) {
+ ast_string_field_build(event, uid, "%s%s", event->location, str);
+ } else if (!strcasecmp(state->tag, "organizer")) {
+ ast_string_field_build(event, organizer, "%s%s", event->organizer, str);
+ } else if (!strcasecmp(state->tag, "textdescription")) {
+ ast_string_field_build(event, description, "%s%s", event->description, str);
+ } else if (!strcasecmp(state->tag, "dtstart")) {
+ event->start = mstime_to_time_t(str);
+ } else if (!strcasecmp(state->tag, "dtend")) {
+ event->end = mstime_to_time_t(str);
+ } else if (!strcasecmp(state->tag, "busystatus")) {
+ event->busy_state = msbusy_to_bs(str);
+ } else if (!strcasecmp(state->tag, "reminderoffset")) {
+ /*XXX Currently we rely on event->start being set first which means we rely on the response order
+ * which technically should be fine since the query returns in the order we ask for, but ... */
+ event->alarm = event->start - atoi(str);
+ }
+
+ ast_free(str);
+ return IKS_OK;
+}
+
+static int cb_true(void *user_data, void *arg, int flags)
+{
+ return CMP_MATCH;
+}
+
+static void exchangecal_destructor(void *obj)
+{
+ struct exchangecal_pvt *pvt = obj;
+
+ ast_debug(1, "Destroying pvt for Exchange calendar %s\n", pvt->owner->name);
+ if (pvt->session) {
+ ne_session_destroy(pvt->session);
+ }
+ ast_string_field_free_memory(pvt);
+
+ ao2_callback(pvt->events, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, cb_true, NULL);
+
+ ao2_ref(pvt->events, -1);
+}
+
+static void *unref_exchangecal(void *obj)
+{
+ struct exchangecal_pvt *pvt = obj;
+
+ ao2_ref(pvt, -1);
+ return NULL;
+}
+
+/* It is very important to use the return value of this function as a realloc could occur */
+static struct ast_str *generate_exchange_uuid(struct ast_str *uid)
+{
+ unsigned short val[8];
+ int x;
+
+ for (x = 0; x < 8; x++) {
+ val[x] = ast_random();
+ }
+ ast_str_set(&uid, 0, "%04x%04x-%04x-%04x-%04x-%04x%04x%04x", val[0], val[1], val[2], val[3], val[4], val[5], val[6], val[7]);
+
+ return uid;
+}
+
+static int is_valid_uuid(struct ast_str *uid)
+{
+ int i;
+
+ if (ast_str_strlen(uid) != 36) {
+ return 0;
+ }
+
+ for (i = 0; i < ast_str_strlen(uid); i++) {
+ if (i == 8 || i == 13 || i == 18 || i == 23) {
+ if (ast_str_buffer(uid)[i] != '-') {
+ return 0;
+ }
+ } else if (!((ast_str_buffer(uid)[i] > 47 && ast_str_buffer(uid)[i] < 58) || (ast_str_buffer(uid)[i] > 96 && ast_str_buffer(uid)[i] < 103))) {
+ return 0;
+ }
+ }
+
+ return 1;
+}
+
+static struct ast_str *xml_encode_str(struct ast_str *dst, const char *src)
+{
+ const char *tmp;
+ char buf[7];
+
+ for (tmp = src; *tmp; tmp++) {
+ switch (*tmp) {
+ case '\"':
+ strcpy(buf, "&quot;");
+ break;
+
+ case '\'':
+ strcpy(buf, "&apos;");
+ break;
+
+ case '&':
+ strcpy(buf, "&amp;");
+ break;
+
+ case '<':
+ strcpy(buf, "&lt;");
+ break;
+
+ case '>':
+ strcpy(buf, "&gt;");
+ break;
+
+ default:
+ sprintf(buf, "%c", *tmp);
+ }
+
+ ast_str_append(&dst, 0, "%s", buf);
+ }
+
+ return dst;
+}
+
+static struct ast_str *epoch_to_exchange_time(struct ast_str *dst, time_t epoch)
+{
+ icaltimezone *utc = icaltimezone_get_utc_timezone();
+ icaltimetype tt = icaltime_from_timet_with_zone(epoch, 0, utc);
+ char tmp[30];
+ int i;
+
+ ast_copy_string(tmp, icaltime_as_ical_string(tt), sizeof(tmp));
+ for (i = 0; tmp[i]; i++) {
+ ast_str_append(&dst, 0, "%c", tmp[i]);
+ if (i == 3 || i == 5)
+ ast_str_append(&dst, 0, "%c", '-');
+ if (i == 10 || i == 12)
+ ast_str_append(&dst, 0, "%c", ':');
+ if (i == 14)
+ ast_str_append(&dst, 0, "%s", ".000");
+ }
+
+ return dst;
+}
+
+static struct ast_str *bs_to_exchange_bs(struct ast_str *dst, enum ast_calendar_busy_state bs)
+{
+ switch (bs) {
+ case AST_CALENDAR_BS_BUSY:
+ ast_str_set(&dst, 0, "%s", "BUSY");
+ break;
+
+ case AST_CALENDAR_BS_BUSY_TENTATIVE:
+ ast_str_set(&dst, 0, "%s", "TENTATIVE");
+ break;
+
+ default:
+ ast_str_set(&dst, 0, "%s", "FREE");
+ }
+
+ return dst;
+}
+
+static int fetch_response_reader(void *data, const char *block, size_t len)
+{
+ struct ast_str **response = data;
+ unsigned char *tmp;
+
+ if (!(tmp = ast_malloc(len + 1))) {
+ return -1;
+ }
+ memcpy(tmp, block, len);
+ tmp[len] = '\0';
+ ast_str_append(response, 0, "%s", tmp);
+ ast_free(tmp);
+
+ return 0;
+}
+
+static int auth_credentials(void *userdata, const char *realm, int attempts, char *username, char *secret)
+{
+ struct exchangecal_pvt *pvt = userdata;
+
+ if (attempts > 1) {
+ ast_log(LOG_WARNING, "Invalid username or password for Exchange calendar '%s'\n", pvt->owner->name);
+ return -1;
+ }
+
+ ne_strnzcpy(username, pvt->user, NE_ABUFSIZ);
+ ne_strnzcpy(secret, pvt->secret, NE_ABUFSIZ);
+
+ return 0;
+}
+
+static struct ast_str *exchangecal_request(struct exchangecal_pvt *pvt, const char *method, struct ast_str *req_body, struct ast_str *subdir)
+{
+ struct ast_str *response;
+ ne_request *req;
+ int ret;
+ char buf[1000];
+
+ if (!pvt) {
+ ast_log(LOG_ERROR, "There is no private!\n");
+ return NULL;
+ }
+
+ if (!(response = ast_str_create(512))) {
+ ast_log(LOG_ERROR, "Could not allocate memory for response.\n");
+ return NULL;
+ }
+
+ snprintf(buf, sizeof(buf), "%s%s", pvt->uri.path, subdir ? ast_str_buffer(subdir) : "");
+
+ req = ne_request_create(pvt->session, method, buf);
+ ne_add_response_body_reader(req, ne_accept_2xx, fetch_response_reader, &response);
+ ne_set_request_body_buffer(req, ast_str_buffer(req_body), ast_str_strlen(req_body));
+ ne_add_request_header(req, "Content-type", "text/xml");
+
+ ret = ne_request_dispatch(req);
+
+ if (ret != NE_OK || !ast_str_strlen(response)) {
+ ast_log(LOG_WARNING, "Unknown response to CalDAV calendar %s, request %s to %s: %s\n", pvt->owner->name, method, pvt->url, ne_get_error(pvt->session));
+ ast_free(response);
+ return NULL;
+ }
+
+ return response;
+}
+
+static int exchangecal_write_event(struct ast_calendar_event *event)
+{
+ struct ast_str *body = NULL, *response = NULL, *subdir = NULL;
+ struct ast_str *uid = NULL, *summary = NULL, *description = NULL, *organizer = NULL,
+ *location = NULL, *start = NULL, *end = NULL, *busystate = NULL;
+ int ret = -1;
+
+ if (!event) {
+ ast_log(LOG_WARNING, "No event passed!\n");
+ return -1;
+ }
+
+ if (!(event->start && event->end)) {
+ ast_log(LOG_WARNING, "The event must contain a start and an end\n");
+ return -1;
+ }
+ if (!(body = ast_str_create(512)) ||
+ !(subdir = ast_str_create(32)) ||
+ !(response = ast_str_create(512))) {
+ ast_log(LOG_ERROR, "Could not allocate memory for request and response!\n");
+ goto write_cleanup;
+ }
+
+ if (!(uid = ast_str_create(32)) ||
+ !(summary = ast_str_create(32)) ||
+ !(description = ast_str_create(32)) ||
+ !(organizer = ast_str_create(32)) ||
+ !(location = ast_str_create(32)) ||
+ !(start = ast_str_create(32)) ||
+ !(end = ast_str_create(32)) ||
+ !(busystate = ast_str_create(32))) {
+ ast_log(LOG_ERROR, "Unable to allocate memory for request values\n");
+ goto write_cleanup;
+ }
+
+ if (ast_strlen_zero(event->uid)) {
+ uid = generate_exchange_uuid(uid);
+ } else {
+ ast_str_set(&uid, 36, "%s", event->uid);
+ }
+
+ if (!is_valid_uuid(uid)) {
+ ast_log(LOG_WARNING, "An invalid uid was provided, you may leave this field blank to have one generated for you\n");
+ goto write_cleanup;
+ }
+
+ summary = xml_encode_str(summary, event->summary);
+ description = xml_encode_str(description, event->description);
+ organizer = xml_encode_str(organizer, event->organizer);
+ location = xml_encode_str(location, event->location);
+ start = epoch_to_exchange_time(start, event->start);
+ end = epoch_to_exchange_time(end, event->end);
+ busystate = bs_to_exchange_bs(busystate, event->busy_state);
+
+ ast_str_append(&body, 0,
+ "<?xml version=\"1.0\"?>\n"
+ "<a:propertyupdate\n"
+ " xmlns:a=\"DAV:\"\n"
+ " xmlns:e=\"http://schemas.microsoft.com/exchange/\"\n"
+ " xmlns:mapi=\"http://schemas.microsoft.com/mapi/\"\n"
+ " xmlns:mapit=\"http://schemas.microsoft.com/mapi/proptag/\"\n"
+ " xmlns:x=\"xml:\" xmlns:cal=\"urn:schemas:calendar:\"\n"
+ " xmlns:dt=\"uuid:%s/\"\n" /* uid */
+ " xmlns:header=\"urn:schemas:mailheader:\"\n"
+ " xmlns:mail=\"urn:schemas:httpmail:\"\n"
+ ">\n"
+ " <a:set>\n"
+ " <a:prop>\n"
+ " <a:contentclass>urn:content-classes:appointment</a:contentclass>\n"
+ " <e:outlookmessageclass>IPM.Appointment</e:outlookmessageclass>\n"
+ " <mail:subject>%s</mail:subject>\n" /* summary */
+ " <mail:description>%s</mail:description>\n" /* description */
+ " <header:to>%s</header:to>\n" /* organizer */
+ " <cal:location>%s</cal:location>\n" /* location */
+ " <cal:dtstart dt:dt=\"dateTime.tz\">%s</cal:dtstart>\n" /* start */
+ " <cal:dtend dt:dt=\"dateTime.tz\">%s</cal:dtend>\n" /* end */
+ " <cal:instancetype dt:dt=\"int\">0</cal:instancetype>\n"
+ " <cal:busystatus>%s</cal:busystatus>\n" /* busy_state (BUSY, FREE, BUSY_TENTATIVE) */
+ " <cal:meetingstatus>CONFIRMED</cal:meetingstatus>\n"
+ " <cal:alldayevent dt:dt=\"boolean\">0</cal:alldayevent>\n" /* XXX need to add event support for all day events */
+ " <cal:responserequested dt:dt=\"boolean\">0</cal:responserequested>\n"
+ " <mapi:finvited dt:dt=\"boolean\">1</mapi:finvited>\n"
+ " </a:prop>\n"
+ " </a:set>\n"
+ "</a:propertyupdate>\n",
+ ast_str_buffer(uid), ast_str_buffer(summary), ast_str_buffer(description), ast_str_buffer(organizer), ast_str_buffer(location), ast_str_buffer(start), ast_str_buffer(end), ast_str_buffer(busystate));
+ ast_verb(0, "\n\n%s\n\n", ast_str_buffer(body));
+ ast_str_set(&subdir, 0, "/Calendar/%s.eml", ast_str_buffer(uid));
+
+ response = exchangecal_request(event->owner->tech_pvt, "PROPPATCH", body, subdir);
+
+ ret = 0;
+write_cleanup:
+ if (uid) {
+ ast_free(uid);
+ }
+ if (summary) {
+ ast_free(summary);
+ }
+ if (description) {
+ ast_free(description);
+ }
+ if (organizer) {
+ ast_free(organizer);
+ }
+ if (location) {
+ ast_free(location);
+ }
+ if (start) {
+ ast_free(start);
+ }
+ if (end) {
+ ast_free(end);
+ }
+ if (busystate) {
+ ast_free(busystate);
+ }
+ if (body) {
+ ast_free(body);
+ }
+ if (response) {
+ ast_free(response);
+ }
+ if (subdir) {
+ ast_free(subdir);
+ }
+
+ return ret;
+}
+
+
+static struct ast_str *exchangecal_get_events_between(struct exchangecal_pvt *pvt, time_t start_time, time_t end_time)
+{
+ struct ast_str *body, *response;
+ char start[80], end[80];
+ struct timeval tv = {0,};
+ struct ast_tm tm;
+
+ tv.tv_sec = start_time;
+ ast_localtime(&tv, &tm, "UTC");
+ ast_strftime(start, sizeof(start), "%Y/%m/%d %T", &tm);
+
+ tv.tv_sec = end_time;
+ ast_localtime(&tv, &tm, "UTC");
+ ast_strftime(end, sizeof(end), "%Y/%m/%d %T", &tm);
+
+ if (!(body = ast_str_create(512))) {
+ ast_log(LOG_ERROR, "Could not allocate memory for body of request!\n");
+ return NULL;
+ }
+
+ ast_str_append(&body, 0,
+ "<?xml version=\"1.0\"?>\n"
+ "<g:searchrequest xmlns:g=\"DAV:\">\n"
+ " <g:sql> SELECT \"urn:schemas:calendar:location\", \"urn:schemas:httpmail:subject\",\n"
+ " \"urn:schemas:calendar:dtstart\", \"urn:schemas:calendar:dtend\",\n"
+ " \"urn:schemas:calendar:busystatus\", \"urn:schemas:calendar:instancetype\",\n"
+ " \"urn:schemas:calendar:uid\", \"urn:schemas:httpmail:textdescription\",\n"
+ " \"urn:schemas:calendar:organizer\", \"urn:schemas:calendar:reminderoffset\"\n"
+ " FROM Scope('SHALLOW TRAVERSAL OF \"%s/Calendar\"')\n"
+ " WHERE NOT \"urn:schemas:calendar:instancetype\" = 1\n"
+ " AND \"DAV:contentclass\" = 'urn:content-classes:appointment'\n"
+ " AND NOT (\"urn:schemas:calendar:dtend\" &lt; '%s'\n"
+ " OR \"urn:schemas:calendar:dtstart\" &gt; '%s')\n"
+ " ORDER BY \"urn:schemas:calendar:dtstart\" ASC\n"
+ " </g:sql>\n"
+ "</g:searchrequest>\n", pvt->url, start, end);
+
+ ast_debug(5, "Request:\n%s\n", ast_str_buffer(body));
+ response = exchangecal_request(pvt, "SEARCH", body, NULL);
+ ast_debug(5, "Response:\n%s\n", ast_str_buffer(response));
+ ast_free(body);
+
+ return response;
+}
+
+static int update_exchangecal(struct exchangecal_pvt *pvt)
+{
+ struct xmlstate state;
+ struct timeval now = ast_tvnow();
+ time_t start, end;
+ struct ast_str *response;
+ iksparser *p;
+
+ state.pvt = pvt;
+ start = now.tv_sec;
+ end = now.tv_sec + 60 * pvt->owner->timeframe;
+ if (!(response = exchangecal_get_events_between(pvt, start, end))) {
+ return -1;
+ }
+
+ p = iks_sax_new(&state, parse_tag, parse_cdata);
+ iks_parse(p, ast_str_buffer(response), ast_str_strlen(response), 1);
+ ast_calendar_merge_events(pvt->owner, pvt->events);
+ ast_free(response);
+
+ return 0;
+}
+
+static void *exchangecal_load_calendar(void *void_data)
+{
+ struct exchangecal_pvt *pvt;
+ struct ast_variable *v;
+ struct ast_calendar *cal = void_data;
+ ast_mutex_t refreshlock;
+
+ if (!(cal && calendar_config)) {
+ ast_log(LOG_ERROR, "You must enable calendar support for res_exchangecal to load\n");
+ return NULL;
+ }
+
+ if (ao2_trylock(cal)) {
+ if (cal->unloading) {
+ ast_log(LOG_WARNING, "Unloading module, load_calendar cancelled.\n");
+ } else {
+ ast_log(LOG_WARNING, "Could not lock calendar, aborting!\n");
+ }
+ return NULL;
+ }
+
+ if (!(pvt = ao2_alloc(sizeof(*pvt), exchangecal_destructor))) {
+ ast_log(LOG_ERROR, "Could not allocate exchangecal_pvt structure for calendar: %s\n", cal->name);
+ return NULL;
+ }
+
+ pvt->owner = cal;
+
+ if (!(pvt->events = ast_calendar_event_container_alloc())) {
+ ast_log(LOG_ERROR, "Could not allocate space for fetching events for calendar: %s\n", cal->name);
+ pvt = unref_exchangecal(pvt);
+ ao2_unlock(cal);
+ return NULL;
+ }
+
+ if (ast_string_field_init(pvt, 32)) {
+ ast_log(LOG_ERROR, "Couldn't allocate string field space for calendar: %s\n", cal->name);
+ pvt = unref_exchangecal(pvt);
+ ao2_unlock(cal);
+ return NULL;
+ }
+
+ for (v = ast_variable_browse(calendar_config, cal->name); v; v = v->next) {
+ if (!strcasecmp(v->name, "url")) {
+ ast_string_field_set(pvt, url, v->value);
+ } else if (!strcasecmp(v->name, "user")) {
+ ast_string_field_set(pvt, user, v->value);
+ } else if (!strcasecmp(v->name, "secret")) {
+ ast_string_field_set(pvt, secret, v->value);
+ }
+ }
+
+ if (ast_strlen_zero(pvt->url)) {
+ ast_log(LOG_WARNING, "No URL was specified for Exchange calendar '%s' - skipping.\n", cal->name);
+ pvt = unref_exchangecal(pvt);
+ ao2_unlock(cal);
+ return NULL;
+ }
+
+ if (ne_uri_parse(pvt->url, &pvt->uri) || pvt->uri.host == NULL || pvt->uri.path == NULL) {
+ ast_log(LOG_WARNING, "Could not parse url '%s' for Exchange calendar '%s' - skipping.\n", pvt->url, cal->name);
+ pvt = unref_exchangecal(pvt);
+ ao2_unlock(cal);
+ return NULL;
+ }
+
+ if (pvt->uri.scheme == NULL) {
+ pvt->uri.scheme = "http";
+ }
+
+ if (pvt->uri.port == 0) {
+ pvt->uri.port = ne_uri_defaultport(pvt->uri.scheme);
+ }
+
+ pvt->session = ne_session_create(pvt->uri.scheme, pvt->uri.host, pvt->uri.port);
+ ne_set_server_auth(pvt->session, auth_credentials, pvt);
+ if (!strncasecmp(pvt->uri.scheme, "https", sizeof(pvt->uri.scheme))) {
+ ne_ssl_trust_default_ca(pvt->session);
+ }
+
+ cal->tech_pvt = pvt;
+
+ ast_mutex_init(&refreshlock);
+
+ /* Load it the first time */
+ update_exchangecal(pvt);
+
+ ao2_unlock(cal);
+
+ /* The only writing from another thread will be if unload is true */
+ for (;;) {
+ struct timeval tv = ast_tvnow();
+ struct timespec ts = {0,};
+
+ ts.tv_sec = tv.tv_sec + (60 * pvt->owner->refresh);
+
+ ast_mutex_lock(&refreshlock);
+ while (!pvt->owner->unloading) {
+ if (ast_cond_timedwait(&pvt->owner->unload, &refreshlock, &ts) == ETIMEDOUT) {
+ break;
+ }
+ }
+ ast_mutex_unlock(&refreshlock);
+
+ if (pvt->owner->unloading) {
+ ast_debug(10, "Skipping refresh since we got a shutdown signal\n");
+ return NULL;
+ }
+
+ ast_debug(10, "Refreshing after %d minute timeout\n", pvt->owner->refresh);
+
+ update_exchangecal(pvt);
+ }
+
+ return NULL;
+}
+
+static int load_module(void)
+{
+ ne_sock_init();
+ if (ast_calendar_register(&exchangecal_tech)) {
+ ne_sock_exit();
+ return AST_MODULE_LOAD_DECLINE;
+ }
+
+ return AST_MODULE_LOAD_SUCCESS;
+}
+
+static int unload_module(void)
+{
+ ast_calendar_unregister(&exchangecal_tech);
+ ne_sock_exit();
+ return 0;
+}
+
+AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Asterisk MS Exchange Calendar Integration",
+ .load = load_module,
+ .unload = unload_module,
+ );
diff --git a/res/res_calendar_icalendar.c b/res/res_calendar_icalendar.c
new file mode 100644
index 000000000..a5994ec66
--- /dev/null
+++ b/res/res_calendar_icalendar.c
@@ -0,0 +1,470 @@
+/*
+ * Asterisk -- An open source telephony toolkit.
+ *
+ * Copyright (C) 2008 - 2009, Digium, Inc.
+ *
+ * Terry Wilson <twilson@digium.com>
+ *
+ * See http://www.asterisk.org for more information about
+ * the Asterisk project. Please do not directly contact
+ * any of the maintainers of this project for assistance;
+ * the project provides a web site, mailing lists and IRC
+ * channels for your use.
+ *
+ * This program is free software, distributed under the terms of
+ * the GNU General Public License Version 2. See the LICENSE file
+ * at the top of the source tree.
+ */
+
+/*! \file
+ * \brief Resource for handling iCalnedar calendars
+ */
+
+/*** MODULEINFO
+ <depend>neon</depend>
+ <depend>ical</depend>
+***/
+#include "asterisk.h"
+
+ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
+
+#include <libical/ical.h>
+#include <neon/ne_session.h>
+#include <neon/ne_uri.h>
+#include <neon/ne_request.h>
+#include <neon/ne_auth.h>
+
+#include "asterisk/module.h"
+#include "asterisk/calendar.h"
+#include "asterisk/lock.h"
+#include "asterisk/config.h"
+#include "asterisk/astobj2.h"
+
+static void *ical_load_calendar(void *data);
+static void *unref_icalendar(void *obj);
+
+static struct ast_calendar_tech ical_tech = {
+ .type = "ical",
+ .module = AST_MODULE,
+ .description = "iCalendar .ics calendars",
+ .load_calendar = ical_load_calendar,
+ .unref_calendar = unref_icalendar,
+};
+
+struct icalendar_pvt {
+ AST_DECLARE_STRING_FIELDS(
+ AST_STRING_FIELD(url);
+ AST_STRING_FIELD(user);
+ AST_STRING_FIELD(secret);
+ );
+ struct ast_calendar *owner;
+ ne_uri uri;
+ ne_session *session;
+ icalcomponent *data;
+ struct ao2_container *events;
+};
+
+static int cb_true(void *user_data, void *arg, int flags)
+{
+ return CMP_MATCH;
+}
+
+static void icalendar_destructor(void *obj)
+{
+ struct icalendar_pvt *pvt = obj;
+
+ ast_debug(1, "Destroying pvt for iCalendar %s\n", pvt->owner->name);
+ if (pvt->session) {
+ ne_session_destroy(pvt->session);
+ }
+ if (pvt->data) {
+ icalcomponent_free(pvt->data);
+ }
+ ast_string_field_free_memory(pvt);
+
+ ao2_callback(pvt->events, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, cb_true, NULL);
+
+ ao2_ref(pvt->events, -1);
+}
+
+static void *unref_icalendar(void *obj)
+{
+ struct icalendar_pvt *pvt = obj;
+
+ ao2_ref(pvt, -1);
+ return NULL;
+}
+
+static int fetch_response_reader(void *data, const char *block, size_t len)
+{
+ struct ast_str **response = data;
+ unsigned char *tmp;
+
+ if (!(tmp = ast_malloc(len + 1))) {
+ return -1;
+ }
+ memcpy(tmp, block, len);
+ tmp[len] = '\0';
+ ast_str_append(response, 0, "%s", tmp);
+ ast_free(tmp);
+
+ return 0;
+}
+
+static int auth_credentials(void *userdata, const char *realm, int attempts, char *username, char *secret)
+{
+ struct icalendar_pvt *pvt = userdata;
+
+ if (attempts > 1) {
+ ast_log(LOG_WARNING, "Invalid username or password for iCalendar '%s'\n", pvt->owner->name);
+ return -1;
+ }
+
+ ne_strnzcpy(username, pvt->user, NE_ABUFSIZ);
+ ne_strnzcpy(secret, pvt->secret, NE_ABUFSIZ);
+
+ return 0;
+}
+
+static icalcomponent *fetch_icalendar(struct icalendar_pvt *pvt)
+{
+ int ret;
+ struct ast_str *response;
+ ne_request *req;
+ icalcomponent *comp = NULL;
+
+ if (!pvt) {
+ ast_log(LOG_ERROR, "There is no private!\n");
+ }
+
+ if (!(response = ast_str_create(512))) {
+ ast_log(LOG_ERROR, "Could not allocate memory for response.\n");
+ return NULL;
+ }
+
+ req = ne_request_create(pvt->session, "GET", pvt->uri.path);
+ ne_add_response_body_reader(req, ne_accept_2xx, fetch_response_reader, &response);
+
+ ret = ne_request_dispatch(req);
+ if (ret != NE_OK || !ast_str_strlen(response)) {
+ ast_log(LOG_WARNING, "Unable to retrieve iCalendar '%s' from '%s': %s\n", pvt->owner->name, pvt->url, ne_get_error(pvt->session));
+ ast_free(response);
+ return NULL;
+ }
+
+ if (!ast_strlen_zero(ast_str_buffer(response))) {
+ comp = icalparser_parse_string(ast_str_buffer(response));
+ }
+ ast_free(response);
+
+ return comp;
+}
+
+static void icalendar_add_event(icalcomponent *comp, struct icaltime_span *span, void *data)
+{
+ struct icalendar_pvt *pvt = data;
+ struct ast_calendar_event *event;
+ icaltimezone *utc = icaltimezone_get_utc_timezone();
+ icaltimetype start, end, tmp;
+ icalcomponent *valarm;
+ icalproperty *prop;
+ struct icaltriggertype trigger;
+
+ if (!(pvt && pvt->owner)) {
+ ast_log(LOG_ERROR, "Require a private structure with an ownenr\n");
+ return;
+ }
+
+ if (!(event = ast_calendar_event_alloc(pvt->owner))) {
+ ast_log(LOG_ERROR, "Could not allocate an event!\n");
+ return;
+ }
+
+ start = icaltime_from_timet_with_zone(span->start, 0, utc);
+ end = icaltime_from_timet_with_zone(span->end, 0, utc);
+ event->start = span->start;
+ event->end = span->end;
+
+ switch(icalcomponent_get_status(comp)) {
+ case ICAL_STATUS_CONFIRMED:
+ event->busy_state = AST_CALENDAR_BS_BUSY;
+ break;
+
+ case ICAL_STATUS_TENTATIVE:
+ event->busy_state = AST_CALENDAR_BS_BUSY_TENTATIVE;
+ break;
+
+ default:
+ event->busy_state = AST_CALENDAR_BS_FREE;
+ }
+
+ if ((prop = icalcomponent_get_first_property(comp, ICAL_SUMMARY_PROPERTY))) {
+ ast_string_field_set(event, summary, icalproperty_get_value_as_string(prop));
+ }
+
+ if ((prop = icalcomponent_get_first_property(comp, ICAL_DESCRIPTION_PROPERTY))) {
+ ast_string_field_set(event, description, icalproperty_get_value_as_string(prop));
+ }
+
+ if ((prop = icalcomponent_get_first_property(comp, ICAL_ORGANIZER_PROPERTY))) {
+ ast_string_field_set(event, organizer, icalproperty_get_value_as_string(prop));
+ }
+
+ if ((prop = icalcomponent_get_first_property(comp, ICAL_LOCATION_PROPERTY))) {
+ ast_string_field_set(event, location, icalproperty_get_value_as_string(prop));
+ }
+
+ if ((prop = icalcomponent_get_first_property(comp, ICAL_UID_PROPERTY))) {
+ ast_string_field_set(event, uid, icalproperty_get_value_as_string(prop));
+ } else {
+ ast_log(LOG_WARNING, "No UID found, but one is required. Generating, but updates may not be acurate\n");
+ if (!ast_strlen_zero(event->summary)) {
+ ast_string_field_set(event, uid, event->summary);
+ } else {
+ char tmp[100];
+ snprintf(tmp, sizeof(tmp), "%lu", event->start);
+ ast_string_field_set(event, uid, tmp);
+ }
+ }
+
+ /* Get the attendees */
+ for (prop = icalcomponent_get_first_property(comp, ICAL_ATTENDEE_PROPERTY);
+ prop; prop = icalcomponent_get_next_property(comp, ICAL_ATTENDEE_PROPERTY)) {
+ struct ast_calendar_attendee *attendee;
+ const char *data;
+
+ if (!(attendee = ast_calloc(1, sizeof(*attendee)))) {
+ event = ast_calendar_unref_event(event);
+ return;
+ }
+ data = icalproperty_get_attendee(prop);
+ if (!ast_strlen_zero(data)) {
+ attendee->data = ast_strdup(data);;
+ AST_LIST_INSERT_TAIL(&event->attendees, attendee, next);
+ }
+ }
+
+
+ /* Only set values for alarm based on VALARM. Can be overriden in main/calendar.c by autoreminder
+ * therefore, go ahead and add events even if their is no VALARM or it is malformed
+ * Currently we are only getting the first VALARM and are handling repitition in main/calendar.c from calendar.conf */
+ if (!(valarm = icalcomponent_get_first_component(comp, ICAL_VALARM_COMPONENT))) {
+ ao2_link(pvt->events, event);
+ event = ast_calendar_unref_event(event);
+ return;
+ }
+
+ if (!(prop = icalcomponent_get_first_property(valarm, ICAL_TRIGGER_PROPERTY))) {
+ ast_log(LOG_WARNING, "VALARM has no TRIGGER, skipping!\n");
+ ao2_link(pvt->events, event);
+ event = ast_calendar_unref_event(event);
+ return;
+ }
+
+ trigger = icalproperty_get_trigger(prop);
+
+ if (icaltriggertype_is_null_trigger(trigger)) {
+ ast_log(LOG_WARNING, "Bad TRIGGER for VALARM, skipping!\n");
+ ao2_link(pvt->events, event);
+ event = ast_calendar_unref_event(event);
+ return;
+ }
+
+ if (!icaltime_is_null_time(trigger.time)) { /* This is an absolute time */
+ tmp = icaltime_convert_to_zone(trigger.time, utc);
+ event->alarm = icaltime_as_timet_with_zone(tmp, utc);
+ } else { /* Offset from either dtstart or dtend */
+ /* XXX Technically you can check RELATED to see if the event fires from the END of the event
+ * But, I'm not sure I've ever seen anyone implement it in calendaring software, so I'm ignoring for now */
+ tmp = icaltime_add(start, trigger.duration);
+ event->alarm = icaltime_as_timet_with_zone(tmp, utc);
+ }
+
+ ao2_link(pvt->events, event);
+ event = ast_calendar_unref_event(event);
+
+ return;
+}
+
+ static void icalendar_update_events(struct icalendar_pvt *pvt)
+{
+ struct icaltimetype start_time, end_time;
+ icalcomponent *iter;
+
+ if (!pvt) {
+ ast_log(LOG_ERROR, "iCalendar is NULL\n");
+ return;
+ }
+
+ if (!pvt->owner) {
+ ast_log(LOG_ERROR, "iCalendar is an orphan!\n");
+ return;
+ }
+
+ if (!pvt->data) {
+ ast_log(LOG_ERROR, "The iCalendar has not been parsed!\n");
+ return;
+ }
+
+ start_time = icaltime_current_time_with_zone(icaltimezone_get_utc_timezone());
+ end_time = icaltime_current_time_with_zone(icaltimezone_get_utc_timezone());
+ end_time.second += pvt->owner->timeframe * 60;
+ icaltime_normalize(end_time);
+
+ for (iter = icalcomponent_get_first_component(pvt->data, ICAL_VEVENT_COMPONENT);
+ iter;
+ iter = icalcomponent_get_next_component(pvt->data, ICAL_VEVENT_COMPONENT))
+ {
+ icalcomponent_foreach_recurrence(iter, start_time, end_time, icalendar_add_event, pvt);
+ }
+
+ ast_calendar_merge_events(pvt->owner, pvt->events);
+}
+
+static void *ical_load_calendar(void *void_data)
+{
+ struct icalendar_pvt *pvt;
+ struct ast_variable *v;
+ struct ast_calendar *cal = void_data;
+ ast_mutex_t refreshlock;
+
+ if (!(cal && calendar_config)) {
+ ast_log(LOG_ERROR, "You must enable calendar support for res_icalendar to load\n");
+ return NULL;
+ }
+ if (ao2_trylock(cal)) {
+ if (cal->unloading) {
+ ast_log(LOG_WARNING, "Unloading module, load_calendar cancelled.\n");
+ } else {
+ ast_log(LOG_WARNING, "Could not lock calendar, aborting!\n");
+ }
+ return NULL;
+ }
+
+ if (!(pvt = ao2_alloc(sizeof(*pvt), icalendar_destructor))) {
+ ast_log(LOG_ERROR, "Could not allocate icalendar_pvt structure for calendar: %s\n", cal->name);
+ return NULL;
+ }
+
+ pvt->owner = cal;
+
+ if (!(pvt->events = ast_calendar_event_container_alloc())) {
+ ast_log(LOG_ERROR, "Could not allocate space for fetching events for calendar: %s\n", cal->name);
+ pvt = unref_icalendar(pvt);
+ ao2_unlock(cal);
+ return NULL;
+ }
+
+ if (ast_string_field_init(pvt, 32)) {
+ ast_log(LOG_ERROR, "Couldn't allocate string field space for calendar: %s\n", cal->name);
+ pvt = unref_icalendar(pvt);
+ ao2_unlock(cal);
+ return NULL;
+ }
+
+ for (v = ast_variable_browse(calendar_config, cal->name); v; v = v->next) {
+ if (!strcasecmp(v->name, "url")) {
+ ast_string_field_set(pvt, url, v->value);
+ } else if (!strcasecmp(v->name, "user")) {
+ ast_string_field_set(pvt, user, v->value);
+ } else if (!strcasecmp(v->name, "secret")) {
+ ast_string_field_set(pvt, secret, v->value);
+ }
+ }
+
+ if (ast_strlen_zero(pvt->url)) {
+ ast_log(LOG_WARNING, "No URL was specified for iCalendar '%s' - skipping.\n", cal->name);
+ pvt = unref_icalendar(pvt);
+ ao2_unlock(cal);
+ return NULL;
+ }
+
+ if (ne_uri_parse(pvt->url, &pvt->uri) || pvt->uri.host == NULL || pvt->uri.path == NULL) {
+ ast_log(LOG_WARNING, "Could not parse url '%s' for iCalendar '%s' - skipping.\n", pvt->url, cal->name);
+ pvt = unref_icalendar(pvt);
+ ao2_unlock(cal);
+ return NULL;
+ }
+
+ if (pvt->uri.scheme == NULL) {
+ pvt->uri.scheme = "http";
+ }
+
+ if (pvt->uri.port == 0) {
+ pvt->uri.port = ne_uri_defaultport(pvt->uri.scheme);
+ }
+
+ pvt->session = ne_session_create(pvt->uri.scheme, pvt->uri.host, pvt->uri.port);
+ ne_set_server_auth(pvt->session, auth_credentials, pvt);
+ if (!strncasecmp(pvt->uri.scheme, "https", sizeof(pvt->uri.scheme))) {
+ ne_ssl_trust_default_ca(pvt->session);
+ }
+
+ cal->tech_pvt = pvt;
+
+ ast_mutex_init(&refreshlock);
+
+ /* Load it the first time */
+ if (!(pvt->data = fetch_icalendar(pvt))) {
+ ast_log(LOG_WARNING, "Unable to parse iCalendar '%s'\n", cal->name);
+ }
+
+ icalendar_update_events(pvt);
+
+ ao2_unlock(cal);
+
+ /* The only writing from another thread will be if unload is true */
+ for(;;) {
+ struct timeval tv = ast_tvnow();
+ struct timespec ts = {0,};
+
+ ts.tv_sec = tv.tv_sec + (60 * pvt->owner->refresh);
+
+ ast_mutex_lock(&refreshlock);
+ while (!pvt->owner->unloading) {
+ if (ast_cond_timedwait(&pvt->owner->unload, &refreshlock, &ts) == ETIMEDOUT) {
+ break;
+ }
+ }
+ ast_mutex_unlock(&refreshlock);
+
+ if (pvt->owner->unloading) {
+ ast_debug(10, "Skipping refresh since we got a shutdown signal\n");
+ return NULL;
+ }
+
+ ast_debug(10, "Refreshing after %d minute timeout\n", pvt->owner->refresh);
+
+ if (!(pvt->data = fetch_icalendar(pvt))) {
+ ast_log(LOG_WARNING, "Unable to parse iCalendar '%s'\n", pvt->owner->name);
+ continue;
+ }
+
+ icalendar_update_events(pvt);
+ }
+
+ return NULL;
+}
+
+static int load_module(void)
+{
+ ne_sock_init();
+ if (ast_calendar_register(&ical_tech)) {
+ ne_sock_exit();
+ return AST_MODULE_LOAD_DECLINE;
+ }
+
+ return AST_MODULE_LOAD_SUCCESS;
+}
+
+static int unload_module(void)
+{
+ ast_calendar_unregister(&ical_tech);
+ ne_sock_exit();
+ return 0;
+}
+
+AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Asterisk iCalendar .ics file integration",
+ .load = load_module,
+ .unload = unload_module,
+ );