2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 2008 - 2009, Digium, Inc.
6 * Terry Wilson <twilson@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
20 * \brief Resource for handling iCalnedar calendars
26 <depend>iksemel</depend>
30 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
32 #include <libical/ical.h>
33 #include <neon/ne_session.h>
34 #include <neon/ne_uri.h>
35 #include <neon/ne_request.h>
36 #include <neon/ne_auth.h>
39 #include "asterisk/module.h"
40 #include "asterisk/calendar.h"
41 #include "asterisk/lock.h"
42 #include "asterisk/config.h"
43 #include "asterisk/astobj2.h"
45 static void *exchangecal_load_calendar(void *data);
46 static void *unref_exchangecal(void *obj);
47 static int exchangecal_write_event(struct ast_calendar_event *event);
49 static struct ast_calendar_tech exchangecal_tech = {
51 .description = "MS Exchange calendars",
53 .load_calendar = exchangecal_load_calendar,
54 .unref_calendar = unref_exchangecal,
55 .write_event = exchangecal_write_event,
58 struct exchangecal_pvt {
59 AST_DECLARE_STRING_FIELDS(
60 AST_STRING_FIELD(url);
61 AST_STRING_FIELD(user);
62 AST_STRING_FIELD(secret);
64 struct ast_calendar *owner;
67 struct ao2_container *events;
76 struct exchangecal_pvt *pvt;
79 static int parse_tag(void *data, char *name, char **atts, int type)
81 struct xmlstate *state = data;
84 if ((tmp = strchr(name, ':'))) {
90 ast_copy_string(state->tag, tmp, sizeof(state->tag));
94 if (!strcasecmp(state->tag, "response")) {
95 struct ast_calendar_event *event;
97 state->in_response = 1;
98 if (!(event = ast_calendar_event_alloc(state->pvt->owner))) {
102 } else if (!strcasecmp(state->tag, "propstat")) {
103 state->in_propstat = 1;
104 } else if (!strcasecmp(state->tag, "prop")) {
110 if (!strcasecmp(state->tag, "response")) {
111 struct ao2_container *events = state->pvt->events;
112 struct ast_calendar_event *event = state->ptr;
114 state->in_response = 0;
115 if (ast_strlen_zero(event->uid)) {
116 ast_log(LOG_ERROR, "This event has no UID, something has gone wrong\n");
117 event = ast_calendar_unref_event(event);
120 ao2_link(events, event);
121 event = ast_calendar_unref_event(event);
122 } else if (!strcasecmp(state->tag, "propstat")) {
123 state->in_propstat = 0;
124 } else if (!strcasecmp(state->tag, "prop")) {
136 static time_t mstime_to_time_t(char *mstime)
140 for (read = write = mstime; *read; read++) {
146 if (*read == '-' || *read == ':')
152 tt = icaltime_from_string(mstime);
153 return icaltime_as_timet(tt);
156 static enum ast_calendar_busy_state msbusy_to_bs(const char *msbusy)
158 if (!strcasecmp(msbusy, "FREE")) {
159 return AST_CALENDAR_BS_FREE;
160 } else if (!strcasecmp(msbusy, "TENTATIVE")) {
161 return AST_CALENDAR_BS_BUSY_TENTATIVE;
163 return AST_CALENDAR_BS_BUSY;
167 static int parse_cdata(void *data, char *value, size_t len)
170 struct xmlstate *state = data;
171 struct ast_calendar_event *event = state->ptr;
174 str = ast_skip_blanks(value);
176 if (str == value + len)
179 if (!(str = ast_calloc(1, len + 1))) {
182 memcpy(str, value, len);
183 if (!(state->in_response && state->in_propstat && state->in_prop)) {
187 /* We use ast_string_field_build here because libiksemel is parsing CDATA with < as
188 * new elements which is a bit odd and shouldn't happen */
189 if (!strcasecmp(state->tag, "subject")) {
190 ast_string_field_build(event, summary, "%s%s", event->summary, str);
191 } else if (!strcasecmp(state->tag, "location")) {
192 ast_string_field_build(event, location, "%s%s", event->location, str);
193 } else if (!strcasecmp(state->tag, "uid")) {
194 ast_string_field_build(event, uid, "%s%s", event->location, str);
195 } else if (!strcasecmp(state->tag, "organizer")) {
196 ast_string_field_build(event, organizer, "%s%s", event->organizer, str);
197 } else if (!strcasecmp(state->tag, "textdescription")) {
198 ast_string_field_build(event, description, "%s%s", event->description, str);
199 } else if (!strcasecmp(state->tag, "dtstart")) {
200 event->start = mstime_to_time_t(str);
201 } else if (!strcasecmp(state->tag, "dtend")) {
202 event->end = mstime_to_time_t(str);
203 } else if (!strcasecmp(state->tag, "busystatus")) {
204 event->busy_state = msbusy_to_bs(str);
205 } else if (!strcasecmp(state->tag, "reminderoffset")) {
206 /*XXX Currently we rely on event->start being set first which means we rely on the response order
207 * which technically should be fine since the query returns in the order we ask for, but ... */
208 event->alarm = event->start - atoi(str);
215 static void exchangecal_destructor(void *obj)
217 struct exchangecal_pvt *pvt = obj;
219 ast_debug(1, "Destroying pvt for Exchange calendar %s\n", pvt->owner->name);
221 ne_session_destroy(pvt->session);
223 ast_string_field_free_memory(pvt);
225 ao2_callback(pvt->events, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL);
227 ao2_ref(pvt->events, -1);
230 static void *unref_exchangecal(void *obj)
232 struct exchangecal_pvt *pvt = obj;
238 /* It is very important to use the return value of this function as a realloc could occur */
239 static struct ast_str *generate_exchange_uuid(struct ast_str *uid)
241 unsigned short val[8];
244 for (x = 0; x < 8; x++) {
245 val[x] = ast_random();
247 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]);
252 static int is_valid_uuid(struct ast_str *uid)
256 if (ast_str_strlen(uid) != 36) {
260 for (i = 0; i < ast_str_strlen(uid); i++) {
261 if (i == 8 || i == 13 || i == 18 || i == 23) {
262 if (ast_str_buffer(uid)[i] != '-') {
265 } 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))) {
273 static struct ast_str *xml_encode_str(struct ast_str *dst, const char *src)
278 for (tmp = src; *tmp; tmp++) {
281 strcpy(buf, """);
285 strcpy(buf, "'");
289 strcpy(buf, "&");
301 sprintf(buf, "%c", *tmp);
304 ast_str_append(&dst, 0, "%s", buf);
310 static struct ast_str *epoch_to_exchange_time(struct ast_str *dst, time_t epoch)
312 icaltimezone *utc = icaltimezone_get_utc_timezone();
313 icaltimetype tt = icaltime_from_timet_with_zone(epoch, 0, utc);
317 ast_copy_string(tmp, icaltime_as_ical_string(tt), sizeof(tmp));
318 for (i = 0; tmp[i]; i++) {
319 ast_str_append(&dst, 0, "%c", tmp[i]);
320 if (i == 3 || i == 5)
321 ast_str_append(&dst, 0, "%c", '-');
322 if (i == 10 || i == 12)
323 ast_str_append(&dst, 0, "%c", ':');
325 ast_str_append(&dst, 0, "%s", ".000");
331 static struct ast_str *bs_to_exchange_bs(struct ast_str *dst, enum ast_calendar_busy_state bs)
334 case AST_CALENDAR_BS_BUSY:
335 ast_str_set(&dst, 0, "%s", "BUSY");
338 case AST_CALENDAR_BS_BUSY_TENTATIVE:
339 ast_str_set(&dst, 0, "%s", "TENTATIVE");
343 ast_str_set(&dst, 0, "%s", "FREE");
349 static int fetch_response_reader(void *data, const char *block, size_t len)
351 struct ast_str **response = data;
354 if (!(tmp = ast_malloc(len + 1))) {
357 memcpy(tmp, block, len);
359 ast_str_append(response, 0, "%s", tmp);
365 static int auth_credentials(void *userdata, const char *realm, int attempts, char *username, char *secret)
367 struct exchangecal_pvt *pvt = userdata;
370 ast_log(LOG_WARNING, "Invalid username or password for Exchange calendar '%s'\n", pvt->owner->name);
374 ne_strnzcpy(username, pvt->user, NE_ABUFSIZ);
375 ne_strnzcpy(secret, pvt->secret, NE_ABUFSIZ);
380 static struct ast_str *exchangecal_request(struct exchangecal_pvt *pvt, const char *method, struct ast_str *req_body, struct ast_str *subdir)
382 struct ast_str *response;
388 ast_log(LOG_ERROR, "There is no private!\n");
392 if (!(response = ast_str_create(512))) {
393 ast_log(LOG_ERROR, "Could not allocate memory for response.\n");
397 snprintf(buf, sizeof(buf), "%s%s", pvt->uri.path, subdir ? ast_str_buffer(subdir) : "");
399 req = ne_request_create(pvt->session, method, buf);
400 ne_add_response_body_reader(req, ne_accept_2xx, fetch_response_reader, &response);
401 ne_set_request_body_buffer(req, ast_str_buffer(req_body), ast_str_strlen(req_body));
402 ne_add_request_header(req, "Content-type", "text/xml");
404 ret = ne_request_dispatch(req);
406 if (ret != NE_OK || !ast_str_strlen(response)) {
407 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));
415 static int exchangecal_write_event(struct ast_calendar_event *event)
417 struct ast_str *body = NULL, *response = NULL, *subdir = NULL;
418 struct ast_str *uid = NULL, *summary = NULL, *description = NULL, *organizer = NULL,
419 *location = NULL, *start = NULL, *end = NULL, *busystate = NULL;
423 ast_log(LOG_WARNING, "No event passed!\n");
427 if (!(event->start && event->end)) {
428 ast_log(LOG_WARNING, "The event must contain a start and an end\n");
431 if (!(body = ast_str_create(512)) ||
432 !(subdir = ast_str_create(32)) ||
433 !(response = ast_str_create(512))) {
434 ast_log(LOG_ERROR, "Could not allocate memory for request and response!\n");
438 if (!(uid = ast_str_create(32)) ||
439 !(summary = ast_str_create(32)) ||
440 !(description = ast_str_create(32)) ||
441 !(organizer = ast_str_create(32)) ||
442 !(location = ast_str_create(32)) ||
443 !(start = ast_str_create(32)) ||
444 !(end = ast_str_create(32)) ||
445 !(busystate = ast_str_create(32))) {
446 ast_log(LOG_ERROR, "Unable to allocate memory for request values\n");
450 if (ast_strlen_zero(event->uid)) {
451 uid = generate_exchange_uuid(uid);
453 ast_str_set(&uid, 36, "%s", event->uid);
456 if (!is_valid_uuid(uid)) {
457 ast_log(LOG_WARNING, "An invalid uid was provided, you may leave this field blank to have one generated for you\n");
461 summary = xml_encode_str(summary, event->summary);
462 description = xml_encode_str(description, event->description);
463 organizer = xml_encode_str(organizer, event->organizer);
464 location = xml_encode_str(location, event->location);
465 start = epoch_to_exchange_time(start, event->start);
466 end = epoch_to_exchange_time(end, event->end);
467 busystate = bs_to_exchange_bs(busystate, event->busy_state);
469 ast_str_append(&body, 0,
470 "<?xml version=\"1.0\"?>\n"
471 "<a:propertyupdate\n"
472 " xmlns:a=\"DAV:\"\n"
473 " xmlns:e=\"http://schemas.microsoft.com/exchange/\"\n"
474 " xmlns:mapi=\"http://schemas.microsoft.com/mapi/\"\n"
475 " xmlns:mapit=\"http://schemas.microsoft.com/mapi/proptag/\"\n"
476 " xmlns:x=\"xml:\" xmlns:cal=\"urn:schemas:calendar:\"\n"
477 " xmlns:dt=\"uuid:%s/\"\n" /* uid */
478 " xmlns:header=\"urn:schemas:mailheader:\"\n"
479 " xmlns:mail=\"urn:schemas:httpmail:\"\n"
483 " <a:contentclass>urn:content-classes:appointment</a:contentclass>\n"
484 " <e:outlookmessageclass>IPM.Appointment</e:outlookmessageclass>\n"
485 " <mail:subject>%s</mail:subject>\n" /* summary */
486 " <mail:description>%s</mail:description>\n" /* description */
487 " <header:to>%s</header:to>\n" /* organizer */
488 " <cal:location>%s</cal:location>\n" /* location */
489 " <cal:dtstart dt:dt=\"dateTime.tz\">%s</cal:dtstart>\n" /* start */
490 " <cal:dtend dt:dt=\"dateTime.tz\">%s</cal:dtend>\n" /* end */
491 " <cal:instancetype dt:dt=\"int\">0</cal:instancetype>\n"
492 " <cal:busystatus>%s</cal:busystatus>\n" /* busy_state (BUSY, FREE, BUSY_TENTATIVE) */
493 " <cal:meetingstatus>CONFIRMED</cal:meetingstatus>\n"
494 " <cal:alldayevent dt:dt=\"boolean\">0</cal:alldayevent>\n" /* XXX need to add event support for all day events */
495 " <cal:responserequested dt:dt=\"boolean\">0</cal:responserequested>\n"
496 " <mapi:finvited dt:dt=\"boolean\">1</mapi:finvited>\n"
499 "</a:propertyupdate>\n",
500 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));
501 ast_verb(0, "\n\n%s\n\n", ast_str_buffer(body));
502 ast_str_set(&subdir, 0, "/Calendar/%s.eml", ast_str_buffer(uid));
504 response = exchangecal_request(event->owner->tech_pvt, "PROPPATCH", body, subdir);
515 ast_free(description);
546 static struct ast_str *exchangecal_get_events_between(struct exchangecal_pvt *pvt, time_t start_time, time_t end_time)
548 struct ast_str *body, *response;
549 char start[80], end[80];
550 struct timeval tv = {0,};
553 tv.tv_sec = start_time;
554 ast_localtime(&tv, &tm, "UTC");
555 ast_strftime(start, sizeof(start), "%Y/%m/%d %T", &tm);
557 tv.tv_sec = end_time;
558 ast_localtime(&tv, &tm, "UTC");
559 ast_strftime(end, sizeof(end), "%Y/%m/%d %T", &tm);
561 if (!(body = ast_str_create(512))) {
562 ast_log(LOG_ERROR, "Could not allocate memory for body of request!\n");
566 ast_str_append(&body, 0,
567 "<?xml version=\"1.0\"?>\n"
568 "<g:searchrequest xmlns:g=\"DAV:\">\n"
569 " <g:sql> SELECT \"urn:schemas:calendar:location\", \"urn:schemas:httpmail:subject\",\n"
570 " \"urn:schemas:calendar:dtstart\", \"urn:schemas:calendar:dtend\",\n"
571 " \"urn:schemas:calendar:busystatus\", \"urn:schemas:calendar:instancetype\",\n"
572 " \"urn:schemas:calendar:uid\", \"urn:schemas:httpmail:textdescription\",\n"
573 " \"urn:schemas:calendar:organizer\", \"urn:schemas:calendar:reminderoffset\"\n"
574 " FROM Scope('SHALLOW TRAVERSAL OF \"%s/Calendar\"')\n"
575 " WHERE NOT \"urn:schemas:calendar:instancetype\" = 1\n"
576 " AND \"DAV:contentclass\" = 'urn:content-classes:appointment'\n"
577 " AND NOT (\"urn:schemas:calendar:dtend\" < '%s'\n"
578 " OR \"urn:schemas:calendar:dtstart\" > '%s')\n"
579 " ORDER BY \"urn:schemas:calendar:dtstart\" ASC\n"
581 "</g:searchrequest>\n", pvt->url, start, end);
583 ast_debug(5, "Request:\n%s\n", ast_str_buffer(body));
584 response = exchangecal_request(pvt, "SEARCH", body, NULL);
585 ast_debug(5, "Response:\n%s\n", ast_str_buffer(response));
591 static int update_exchangecal(struct exchangecal_pvt *pvt)
593 struct xmlstate state;
594 struct timeval now = ast_tvnow();
596 struct ast_str *response;
601 end = now.tv_sec + 60 * pvt->owner->timeframe;
602 if (!(response = exchangecal_get_events_between(pvt, start, end))) {
606 p = iks_sax_new(&state, parse_tag, parse_cdata);
607 iks_parse(p, ast_str_buffer(response), ast_str_strlen(response), 1);
608 ast_calendar_merge_events(pvt->owner, pvt->events);
614 static void *exchangecal_load_calendar(void *void_data)
616 struct exchangecal_pvt *pvt;
617 const struct ast_config *cfg;
618 struct ast_variable *v;
619 struct ast_calendar *cal = void_data;
620 ast_mutex_t refreshlock;
622 if (!(cal && (cfg = ast_calendar_config_acquire()))) {
623 ast_log(LOG_ERROR, "You must enable calendar support for res_exchangecal to load\n");
627 if (ao2_trylock(cal)) {
628 if (cal->unloading) {
629 ast_log(LOG_WARNING, "Unloading module, load_calendar cancelled.\n");
631 ast_log(LOG_WARNING, "Could not lock calendar, aborting!\n");
633 ast_calendar_config_release();
637 if (!(pvt = ao2_alloc(sizeof(*pvt), exchangecal_destructor))) {
638 ast_log(LOG_ERROR, "Could not allocate exchangecal_pvt structure for calendar: %s\n", cal->name);
639 ast_calendar_config_release();
645 if (!(pvt->events = ast_calendar_event_container_alloc())) {
646 ast_log(LOG_ERROR, "Could not allocate space for fetching events for calendar: %s\n", cal->name);
647 pvt = unref_exchangecal(pvt);
649 ast_calendar_config_release();
653 if (ast_string_field_init(pvt, 32)) {
654 ast_log(LOG_ERROR, "Couldn't allocate string field space for calendar: %s\n", cal->name);
655 pvt = unref_exchangecal(pvt);
657 ast_calendar_config_release();
661 for (v = ast_variable_browse(cfg, cal->name); v; v = v->next) {
662 if (!strcasecmp(v->name, "url")) {
663 ast_string_field_set(pvt, url, v->value);
664 } else if (!strcasecmp(v->name, "user")) {
665 ast_string_field_set(pvt, user, v->value);
666 } else if (!strcasecmp(v->name, "secret")) {
667 ast_string_field_set(pvt, secret, v->value);
671 ast_calendar_config_release();
673 if (ast_strlen_zero(pvt->url)) {
674 ast_log(LOG_WARNING, "No URL was specified for Exchange calendar '%s' - skipping.\n", cal->name);
675 pvt = unref_exchangecal(pvt);
680 if (ne_uri_parse(pvt->url, &pvt->uri) || pvt->uri.host == NULL || pvt->uri.path == NULL) {
681 ast_log(LOG_WARNING, "Could not parse url '%s' for Exchange calendar '%s' - skipping.\n", pvt->url, cal->name);
682 pvt = unref_exchangecal(pvt);
687 if (pvt->uri.scheme == NULL) {
688 pvt->uri.scheme = "http";
691 if (pvt->uri.port == 0) {
692 pvt->uri.port = ne_uri_defaultport(pvt->uri.scheme);
695 pvt->session = ne_session_create(pvt->uri.scheme, pvt->uri.host, pvt->uri.port);
696 ne_set_server_auth(pvt->session, auth_credentials, pvt);
697 if (!strcasecmp(pvt->uri.scheme, "https")) {
698 ne_ssl_trust_default_ca(pvt->session);
703 ast_mutex_init(&refreshlock);
705 /* Load it the first time */
706 update_exchangecal(pvt);
710 /* The only writing from another thread will be if unload is true */
712 struct timeval tv = ast_tvnow();
713 struct timespec ts = {0,};
715 ts.tv_sec = tv.tv_sec + (60 * pvt->owner->refresh);
717 ast_mutex_lock(&refreshlock);
718 while (!pvt->owner->unloading) {
719 if (ast_cond_timedwait(&pvt->owner->unload, &refreshlock, &ts) == ETIMEDOUT) {
723 ast_mutex_unlock(&refreshlock);
725 if (pvt->owner->unloading) {
726 ast_debug(10, "Skipping refresh since we got a shutdown signal\n");
730 ast_debug(10, "Refreshing after %d minute timeout\n", pvt->owner->refresh);
732 update_exchangecal(pvt);
738 static int load_module(void)
741 if (ast_calendar_register(&exchangecal_tech)) {
743 return AST_MODULE_LOAD_DECLINE;
746 return AST_MODULE_LOAD_SUCCESS;
749 static int unload_module(void)
751 ast_calendar_unregister(&exchangecal_tech);
756 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Asterisk MS Exchange Calendar Integration",
758 .unload = unload_module,