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 MS Exchange calendars
26 <depend>iksemel</depend>
27 <support_level>core</support_level>
32 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
34 #include <libical/ical.h>
35 #include <ne_session.h>
37 #include <ne_request.h>
39 #include <ne_redirect.h>
42 #include "asterisk/module.h"
43 #include "asterisk/calendar.h"
44 #include "asterisk/lock.h"
45 #include "asterisk/config.h"
46 #include "asterisk/astobj2.h"
48 static void *exchangecal_load_calendar(void *data);
49 static void *unref_exchangecal(void *obj);
50 static int exchangecal_write_event(struct ast_calendar_event *event);
52 static struct ast_calendar_tech exchangecal_tech = {
54 .description = "MS Exchange calendars",
56 .load_calendar = exchangecal_load_calendar,
57 .unref_calendar = unref_exchangecal,
58 .write_event = exchangecal_write_event,
61 struct exchangecal_pvt {
62 AST_DECLARE_STRING_FIELDS(
63 AST_STRING_FIELD(url);
64 AST_STRING_FIELD(user);
65 AST_STRING_FIELD(secret);
67 struct ast_calendar *owner;
70 struct ao2_container *events;
79 struct exchangecal_pvt *pvt;
82 static int parse_tag(void *data, char *name, char **atts, int type)
84 struct xmlstate *state = data;
87 if ((tmp = strchr(name, ':'))) {
93 ast_copy_string(state->tag, tmp, sizeof(state->tag));
97 if (!strcasecmp(state->tag, "response")) {
98 struct ast_calendar_event *event;
100 state->in_response = 1;
101 if (!(event = ast_calendar_event_alloc(state->pvt->owner))) {
105 } else if (!strcasecmp(state->tag, "propstat")) {
106 state->in_propstat = 1;
107 } else if (!strcasecmp(state->tag, "prop")) {
113 if (!strcasecmp(state->tag, "response")) {
114 struct ao2_container *events = state->pvt->events;
115 struct ast_calendar_event *event = state->ptr;
117 state->in_response = 0;
118 if (ast_strlen_zero(event->uid)) {
119 ast_log(LOG_ERROR, "This event has no UID, something has gone wrong\n");
120 event = ast_calendar_unref_event(event);
123 ao2_link(events, event);
124 event = ast_calendar_unref_event(event);
125 } else if (!strcasecmp(state->tag, "propstat")) {
126 state->in_propstat = 0;
127 } else if (!strcasecmp(state->tag, "prop")) {
139 static time_t mstime_to_time_t(char *mstime)
143 for (read = write = mstime; *read; read++) {
149 if (*read == '-' || *read == ':')
155 tt = icaltime_from_string(mstime);
156 return icaltime_as_timet(tt);
159 static enum ast_calendar_busy_state msbusy_to_bs(const char *msbusy)
161 if (!strcasecmp(msbusy, "FREE")) {
162 return AST_CALENDAR_BS_FREE;
163 } else if (!strcasecmp(msbusy, "TENTATIVE")) {
164 return AST_CALENDAR_BS_BUSY_TENTATIVE;
166 return AST_CALENDAR_BS_BUSY;
170 static int parse_cdata(void *data, char *value, size_t len)
173 struct xmlstate *state = data;
174 struct ast_calendar_event *event = state->ptr;
177 str = ast_skip_blanks(value);
179 if (str == value + len)
182 if (!(str = ast_calloc(1, len + 1))) {
185 memcpy(str, value, len);
186 if (!(state->in_response && state->in_propstat && state->in_prop)) {
190 /* We use ast_string_field_build here because libiksemel is parsing CDATA with < as
191 * new elements which is a bit odd and shouldn't happen */
192 if (!strcasecmp(state->tag, "subject")) {
193 ast_string_field_build(event, summary, "%s%s", event->summary, str);
194 } else if (!strcasecmp(state->tag, "location")) {
195 ast_string_field_build(event, location, "%s%s", event->location, str);
196 } else if (!strcasecmp(state->tag, "uid")) {
197 ast_string_field_build(event, uid, "%s%s", event->location, str);
198 } else if (!strcasecmp(state->tag, "organizer")) {
199 ast_string_field_build(event, organizer, "%s%s", event->organizer, str);
200 } else if (!strcasecmp(state->tag, "textdescription")) {
201 ast_string_field_build(event, description, "%s%s", event->description, str);
202 } else if (!strcasecmp(state->tag, "dtstart")) {
203 event->start = mstime_to_time_t(str);
204 } else if (!strcasecmp(state->tag, "dtend")) {
205 event->end = mstime_to_time_t(str);
206 } else if (!strcasecmp(state->tag, "busystatus")) {
207 event->busy_state = msbusy_to_bs(str);
208 } else if (!strcasecmp(state->tag, "reminderoffset")) {
209 /*XXX Currently we rely on event->start being set first which means we rely on the response order
210 * which technically should be fine since the query returns in the order we ask for, but ... */
211 event->alarm = event->start - atoi(str);
218 static void exchangecal_destructor(void *obj)
220 struct exchangecal_pvt *pvt = obj;
222 ast_debug(1, "Destroying pvt for Exchange calendar %s\n", pvt->owner->name);
224 ne_session_destroy(pvt->session);
226 ast_string_field_free_memory(pvt);
228 ao2_callback(pvt->events, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL);
230 ao2_ref(pvt->events, -1);
233 static void *unref_exchangecal(void *obj)
235 struct exchangecal_pvt *pvt = obj;
241 /* It is very important to use the return value of this function as a realloc could occur */
242 static struct ast_str *generate_exchange_uuid(struct ast_str *uid)
244 unsigned short val[8];
247 for (x = 0; x < 8; x++) {
248 val[x] = ast_random();
250 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]);
255 static int is_valid_uuid(struct ast_str *uid)
259 if (ast_str_strlen(uid) != 36) {
263 for (i = 0; i < ast_str_strlen(uid); i++) {
264 if (i == 8 || i == 13 || i == 18 || i == 23) {
265 if (ast_str_buffer(uid)[i] != '-') {
268 } 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))) {
276 static struct ast_str *xml_encode_str(struct ast_str *dst, const char *src)
281 for (tmp = src; *tmp; tmp++) {
284 strcpy(buf, """);
288 strcpy(buf, "'");
292 strcpy(buf, "&");
304 sprintf(buf, "%c", *tmp);
307 ast_str_append(&dst, 0, "%s", buf);
313 static struct ast_str *epoch_to_exchange_time(struct ast_str *dst, time_t epoch)
315 icaltimezone *utc = icaltimezone_get_utc_timezone();
316 icaltimetype tt = icaltime_from_timet_with_zone(epoch, 0, utc);
320 ast_copy_string(tmp, icaltime_as_ical_string(tt), sizeof(tmp));
321 for (i = 0; tmp[i]; i++) {
322 ast_str_append(&dst, 0, "%c", tmp[i]);
323 if (i == 3 || i == 5)
324 ast_str_append(&dst, 0, "%c", '-');
325 if (i == 10 || i == 12)
326 ast_str_append(&dst, 0, "%c", ':');
328 ast_str_append(&dst, 0, "%s", ".000");
334 static struct ast_str *bs_to_exchange_bs(struct ast_str *dst, enum ast_calendar_busy_state bs)
337 case AST_CALENDAR_BS_BUSY:
338 ast_str_set(&dst, 0, "%s", "BUSY");
341 case AST_CALENDAR_BS_BUSY_TENTATIVE:
342 ast_str_set(&dst, 0, "%s", "TENTATIVE");
346 ast_str_set(&dst, 0, "%s", "FREE");
352 static int fetch_response_reader(void *data, const char *block, size_t len)
354 struct ast_str **response = data;
357 if (!(tmp = ast_malloc(len + 1))) {
360 memcpy(tmp, block, len);
362 ast_str_append(response, 0, "%s", tmp);
368 static int auth_credentials(void *userdata, const char *realm, int attempts, char *username, char *secret)
370 struct exchangecal_pvt *pvt = userdata;
373 ast_log(LOG_WARNING, "Invalid username or password for Exchange calendar '%s'\n", pvt->owner->name);
377 ne_strnzcpy(username, pvt->user, NE_ABUFSIZ);
378 ne_strnzcpy(secret, pvt->secret, NE_ABUFSIZ);
383 static struct ast_str *exchangecal_request(struct exchangecal_pvt *pvt, const char *method, struct ast_str *req_body, struct ast_str *subdir)
385 struct ast_str *response;
391 ast_log(LOG_ERROR, "There is no private!\n");
395 if (!(response = ast_str_create(512))) {
396 ast_log(LOG_ERROR, "Could not allocate memory for response.\n");
400 snprintf(buf, sizeof(buf), "%s%s", pvt->uri.path, subdir ? ast_str_buffer(subdir) : "");
402 req = ne_request_create(pvt->session, method, buf);
403 ne_add_response_body_reader(req, ne_accept_2xx, fetch_response_reader, &response);
404 ne_set_request_body_buffer(req, ast_str_buffer(req_body), ast_str_strlen(req_body));
405 ne_add_request_header(req, "Content-type", "text/xml");
407 ret = ne_request_dispatch(req);
408 ne_request_destroy(req);
410 if (ret != NE_OK || !ast_str_strlen(response)) {
411 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));
419 static int exchangecal_write_event(struct ast_calendar_event *event)
421 struct ast_str *body = NULL, *response = NULL, *subdir = NULL;
422 struct ast_str *uid = NULL, *summary = NULL, *description = NULL, *organizer = NULL,
423 *location = NULL, *start = NULL, *end = NULL, *busystate = NULL;
427 ast_log(LOG_WARNING, "No event passed!\n");
431 if (!(event->start && event->end)) {
432 ast_log(LOG_WARNING, "The event must contain a start and an end\n");
435 if (!(body = ast_str_create(512)) ||
436 !(subdir = ast_str_create(32))) {
437 ast_log(LOG_ERROR, "Could not allocate memory for request!\n");
441 if (!(uid = ast_str_create(32)) ||
442 !(summary = ast_str_create(32)) ||
443 !(description = ast_str_create(32)) ||
444 !(organizer = ast_str_create(32)) ||
445 !(location = ast_str_create(32)) ||
446 !(start = ast_str_create(32)) ||
447 !(end = ast_str_create(32)) ||
448 !(busystate = ast_str_create(32))) {
449 ast_log(LOG_ERROR, "Unable to allocate memory for request values\n");
453 if (ast_strlen_zero(event->uid)) {
454 uid = generate_exchange_uuid(uid);
456 ast_str_set(&uid, 36, "%s", event->uid);
459 if (!is_valid_uuid(uid)) {
460 ast_log(LOG_WARNING, "An invalid uid was provided, you may leave this field blank to have one generated for you\n");
464 summary = xml_encode_str(summary, event->summary);
465 description = xml_encode_str(description, event->description);
466 organizer = xml_encode_str(organizer, event->organizer);
467 location = xml_encode_str(location, event->location);
468 start = epoch_to_exchange_time(start, event->start);
469 end = epoch_to_exchange_time(end, event->end);
470 busystate = bs_to_exchange_bs(busystate, event->busy_state);
472 ast_str_append(&body, 0,
473 "<?xml version=\"1.0\"?>\n"
474 "<a:propertyupdate\n"
475 " xmlns:a=\"DAV:\"\n"
476 " xmlns:e=\"http://schemas.microsoft.com/exchange/\"\n"
477 " xmlns:mapi=\"http://schemas.microsoft.com/mapi/\"\n"
478 " xmlns:mapit=\"http://schemas.microsoft.com/mapi/proptag/\"\n"
479 " xmlns:x=\"xml:\" xmlns:cal=\"urn:schemas:calendar:\"\n"
480 " xmlns:dt=\"uuid:%s/\"\n" /* uid */
481 " xmlns:header=\"urn:schemas:mailheader:\"\n"
482 " xmlns:mail=\"urn:schemas:httpmail:\"\n"
486 " <a:contentclass>urn:content-classes:appointment</a:contentclass>\n"
487 " <e:outlookmessageclass>IPM.Appointment</e:outlookmessageclass>\n"
488 " <mail:subject>%s</mail:subject>\n" /* summary */
489 " <mail:description>%s</mail:description>\n" /* description */
490 " <header:to>%s</header:to>\n" /* organizer */
491 " <cal:location>%s</cal:location>\n" /* location */
492 " <cal:dtstart dt:dt=\"dateTime.tz\">%s</cal:dtstart>\n" /* start */
493 " <cal:dtend dt:dt=\"dateTime.tz\">%s</cal:dtend>\n" /* end */
494 " <cal:instancetype dt:dt=\"int\">0</cal:instancetype>\n"
495 " <cal:busystatus>%s</cal:busystatus>\n" /* busy_state (BUSY, FREE, BUSY_TENTATIVE) */
496 " <cal:meetingstatus>CONFIRMED</cal:meetingstatus>\n"
497 " <cal:alldayevent dt:dt=\"boolean\">0</cal:alldayevent>\n" /* XXX need to add event support for all day events */
498 " <cal:responserequested dt:dt=\"boolean\">0</cal:responserequested>\n"
499 " <mapi:finvited dt:dt=\"boolean\">1</mapi:finvited>\n"
502 "</a:propertyupdate>\n",
503 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));
504 ast_verb(0, "\n\n%s\n\n", ast_str_buffer(body));
505 ast_str_set(&subdir, 0, "/Calendar/%s.eml", ast_str_buffer(uid));
507 if ((response = exchangecal_request(event->owner->tech_pvt, "PROPPATCH", body, subdir))) {
519 ast_free(description);
550 static struct ast_str *exchangecal_get_events_between(struct exchangecal_pvt *pvt, time_t start_time, time_t end_time)
552 struct ast_str *body, *response;
553 char start[80], end[80];
554 struct timeval tv = {0,};
557 tv.tv_sec = start_time;
558 ast_localtime(&tv, &tm, "UTC");
559 ast_strftime(start, sizeof(start), "%Y/%m/%d %T", &tm);
561 tv.tv_sec = end_time;
562 ast_localtime(&tv, &tm, "UTC");
563 ast_strftime(end, sizeof(end), "%Y/%m/%d %T", &tm);
565 if (!(body = ast_str_create(512))) {
566 ast_log(LOG_ERROR, "Could not allocate memory for body of request!\n");
570 ast_str_append(&body, 0,
571 "<?xml version=\"1.0\"?>\n"
572 "<g:searchrequest xmlns:g=\"DAV:\">\n"
573 " <g:sql> SELECT \"urn:schemas:calendar:location\", \"urn:schemas:httpmail:subject\",\n"
574 " \"urn:schemas:calendar:dtstart\", \"urn:schemas:calendar:dtend\",\n"
575 " \"urn:schemas:calendar:busystatus\", \"urn:schemas:calendar:instancetype\",\n"
576 " \"urn:schemas:calendar:uid\", \"urn:schemas:httpmail:textdescription\",\n"
577 " \"urn:schemas:calendar:organizer\", \"urn:schemas:calendar:reminderoffset\"\n"
578 " FROM Scope('SHALLOW TRAVERSAL OF \"%s/Calendar\"')\n"
579 " WHERE NOT \"urn:schemas:calendar:instancetype\" = 1\n"
580 " AND \"DAV:contentclass\" = 'urn:content-classes:appointment'\n"
581 " AND NOT (\"urn:schemas:calendar:dtend\" < '%s'\n"
582 " OR \"urn:schemas:calendar:dtstart\" > '%s')\n"
583 " ORDER BY \"urn:schemas:calendar:dtstart\" ASC\n"
585 "</g:searchrequest>\n", pvt->url, start, end);
587 ast_debug(5, "Request:\n%s\n", ast_str_buffer(body));
588 response = exchangecal_request(pvt, "SEARCH", body, NULL);
589 ast_debug(5, "Response:\n%s\n", ast_str_buffer(response));
595 static int update_exchangecal(struct exchangecal_pvt *pvt)
597 struct xmlstate state;
598 struct timeval now = ast_tvnow();
600 struct ast_str *response;
605 end = now.tv_sec + 60 * pvt->owner->timeframe;
606 if (!(response = exchangecal_get_events_between(pvt, start, end))) {
610 p = iks_sax_new(&state, parse_tag, parse_cdata);
611 iks_parse(p, ast_str_buffer(response), ast_str_strlen(response), 1);
612 ast_calendar_merge_events(pvt->owner, pvt->events);
618 static void *exchangecal_load_calendar(void *void_data)
620 struct exchangecal_pvt *pvt;
621 const struct ast_config *cfg;
622 struct ast_variable *v;
623 struct ast_calendar *cal = void_data;
624 ast_mutex_t refreshlock;
626 if (!(cal && (cfg = ast_calendar_config_acquire()))) {
627 ast_log(LOG_ERROR, "You must enable calendar support for res_exchangecal to load\n");
631 if (ao2_trylock(cal)) {
632 if (cal->unloading) {
633 ast_log(LOG_WARNING, "Unloading module, load_calendar cancelled.\n");
635 ast_log(LOG_WARNING, "Could not lock calendar, aborting!\n");
637 ast_calendar_config_release();
641 if (!(pvt = ao2_alloc(sizeof(*pvt), exchangecal_destructor))) {
642 ast_log(LOG_ERROR, "Could not allocate exchangecal_pvt structure for calendar: %s\n", cal->name);
643 ast_calendar_config_release();
649 if (!(pvt->events = ast_calendar_event_container_alloc())) {
650 ast_log(LOG_ERROR, "Could not allocate space for fetching events for calendar: %s\n", cal->name);
651 pvt = unref_exchangecal(pvt);
653 ast_calendar_config_release();
657 if (ast_string_field_init(pvt, 32)) {
658 ast_log(LOG_ERROR, "Couldn't allocate string field space for calendar: %s\n", cal->name);
659 pvt = unref_exchangecal(pvt);
661 ast_calendar_config_release();
665 for (v = ast_variable_browse(cfg, cal->name); v; v = v->next) {
666 if (!strcasecmp(v->name, "url")) {
667 ast_string_field_set(pvt, url, v->value);
668 } else if (!strcasecmp(v->name, "user")) {
669 ast_string_field_set(pvt, user, v->value);
670 } else if (!strcasecmp(v->name, "secret")) {
671 ast_string_field_set(pvt, secret, v->value);
675 ast_calendar_config_release();
677 if (ast_strlen_zero(pvt->url)) {
678 ast_log(LOG_WARNING, "No URL was specified for Exchange calendar '%s' - skipping.\n", cal->name);
679 pvt = unref_exchangecal(pvt);
684 if (ne_uri_parse(pvt->url, &pvt->uri) || pvt->uri.host == NULL || pvt->uri.path == NULL) {
685 ast_log(LOG_WARNING, "Could not parse url '%s' for Exchange calendar '%s' - skipping.\n", pvt->url, cal->name);
686 pvt = unref_exchangecal(pvt);
691 if (pvt->uri.scheme == NULL) {
692 pvt->uri.scheme = "http";
695 if (pvt->uri.port == 0) {
696 pvt->uri.port = ne_uri_defaultport(pvt->uri.scheme);
699 pvt->session = ne_session_create(pvt->uri.scheme, pvt->uri.host, pvt->uri.port);
700 ne_redirect_register(pvt->session);
701 ne_set_server_auth(pvt->session, auth_credentials, pvt);
702 if (!strcasecmp(pvt->uri.scheme, "https")) {
703 ne_ssl_trust_default_ca(pvt->session);
708 ast_mutex_init(&refreshlock);
710 /* Load it the first time */
711 update_exchangecal(pvt);
715 /* The only writing from another thread will be if unload is true */
717 struct timeval tv = ast_tvnow();
718 struct timespec ts = {0,};
720 ts.tv_sec = tv.tv_sec + (60 * pvt->owner->refresh);
722 ast_mutex_lock(&refreshlock);
723 while (!pvt->owner->unloading) {
724 if (ast_cond_timedwait(&pvt->owner->unload, &refreshlock, &ts) == ETIMEDOUT) {
728 ast_mutex_unlock(&refreshlock);
730 if (pvt->owner->unloading) {
731 ast_debug(10, "Skipping refresh since we got a shutdown signal\n");
735 ast_debug(10, "Refreshing after %d minute timeout\n", pvt->owner->refresh);
737 update_exchangecal(pvt);
743 static int load_module(void)
746 if (ast_calendar_register(&exchangecal_tech)) {
748 return AST_MODULE_LOAD_DECLINE;
751 return AST_MODULE_LOAD_SUCCESS;
754 static int unload_module(void)
756 ast_calendar_unregister(&exchangecal_tech);
761 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Asterisk MS Exchange Calendar Integration",
763 .unload = unload_module,
764 .load_pri = AST_MODPRI_DEVSTATE_PLUGIN,