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_REGISTER_FILE()
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/channel.h"
44 #include "asterisk/calendar.h"
45 #include "asterisk/lock.h"
46 #include "asterisk/config.h"
47 #include "asterisk/astobj2.h"
48 #include "asterisk/uuid.h"
50 static void *exchangecal_load_calendar(void *data);
51 static void *unref_exchangecal(void *obj);
52 static int exchangecal_write_event(struct ast_calendar_event *event);
54 static struct ast_calendar_tech exchangecal_tech = {
56 .description = "MS Exchange calendars",
58 .load_calendar = exchangecal_load_calendar,
59 .unref_calendar = unref_exchangecal,
60 .write_event = exchangecal_write_event,
63 struct exchangecal_pvt {
64 AST_DECLARE_STRING_FIELDS(
65 AST_STRING_FIELD(url);
66 AST_STRING_FIELD(user);
67 AST_STRING_FIELD(secret);
69 struct ast_calendar *owner;
72 struct ao2_container *events;
81 struct exchangecal_pvt *pvt;
84 static int parse_tag(void *data, char *name, char **atts, int type)
86 struct xmlstate *state = data;
89 if ((tmp = strchr(name, ':'))) {
95 ast_copy_string(state->tag, tmp, sizeof(state->tag));
99 if (!strcasecmp(state->tag, "response")) {
100 struct ast_calendar_event *event;
102 state->in_response = 1;
103 if (!(event = ast_calendar_event_alloc(state->pvt->owner))) {
107 } else if (!strcasecmp(state->tag, "propstat")) {
108 state->in_propstat = 1;
109 } else if (!strcasecmp(state->tag, "prop")) {
115 if (!strcasecmp(state->tag, "response")) {
116 struct ao2_container *events = state->pvt->events;
117 struct ast_calendar_event *event = state->ptr;
119 state->in_response = 0;
120 if (ast_strlen_zero(event->uid)) {
121 ast_log(LOG_ERROR, "This event has no UID, something has gone wrong\n");
122 event = ast_calendar_unref_event(event);
125 ao2_link(events, event);
126 event = ast_calendar_unref_event(event);
127 } else if (!strcasecmp(state->tag, "propstat")) {
128 state->in_propstat = 0;
129 } else if (!strcasecmp(state->tag, "prop")) {
141 static time_t mstime_to_time_t(char *mstime)
145 for (read = write = mstime; *read; read++) {
151 if (*read == '-' || *read == ':')
157 tt = icaltime_from_string(mstime);
158 return icaltime_as_timet(tt);
161 static enum ast_calendar_busy_state msbusy_to_bs(const char *msbusy)
163 if (!strcasecmp(msbusy, "FREE")) {
164 return AST_CALENDAR_BS_FREE;
165 } else if (!strcasecmp(msbusy, "TENTATIVE")) {
166 return AST_CALENDAR_BS_BUSY_TENTATIVE;
168 return AST_CALENDAR_BS_BUSY;
172 static int parse_cdata(void *data, char *value, size_t len)
175 struct xmlstate *state = data;
176 struct ast_calendar_event *event = state->ptr;
179 str = ast_skip_blanks(value);
181 if (str == value + len)
184 if (!(str = ast_calloc(1, len + 1))) {
187 memcpy(str, value, len);
188 if (!(state->in_response && state->in_propstat && state->in_prop)) {
192 /* We use ast_string_field_build here because libiksemel is parsing CDATA with < as
193 * new elements which is a bit odd and shouldn't happen */
194 if (!strcasecmp(state->tag, "subject")) {
195 ast_string_field_build(event, summary, "%s%s", event->summary, str);
196 } else if (!strcasecmp(state->tag, "location")) {
197 ast_string_field_build(event, location, "%s%s", event->location, str);
198 } else if (!strcasecmp(state->tag, "uid")) {
199 ast_string_field_build(event, uid, "%s%s", event->location, str);
200 } else if (!strcasecmp(state->tag, "organizer")) {
201 ast_string_field_build(event, organizer, "%s%s", event->organizer, str);
202 } else if (!strcasecmp(state->tag, "textdescription")) {
203 ast_string_field_build(event, description, "%s%s", event->description, str);
204 } else if (!strcasecmp(state->tag, "dtstart")) {
205 event->start = mstime_to_time_t(str);
206 } else if (!strcasecmp(state->tag, "dtend")) {
207 event->end = mstime_to_time_t(str);
208 } else if (!strcasecmp(state->tag, "busystatus")) {
209 event->busy_state = msbusy_to_bs(str);
210 } else if (!strcasecmp(state->tag, "reminderoffset")) {
211 /*XXX Currently we rely on event->start being set first which means we rely on the response order
212 * which technically should be fine since the query returns in the order we ask for, but ... */
213 event->alarm = event->start - atoi(str);
220 static void exchangecal_destructor(void *obj)
222 struct exchangecal_pvt *pvt = obj;
224 ast_debug(1, "Destroying pvt for Exchange calendar %s\n", pvt->owner->name);
226 ne_session_destroy(pvt->session);
228 ast_string_field_free_memory(pvt);
230 ao2_callback(pvt->events, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL);
232 ao2_ref(pvt->events, -1);
235 static void *unref_exchangecal(void *obj)
237 struct exchangecal_pvt *pvt = obj;
243 /* It is very important to use the return value of this function as a realloc could occur */
244 static struct ast_str *generate_exchange_uuid(struct ast_str *uid)
246 char buffer[AST_UUID_STR_LEN];
248 ast_uuid_generate_str(buffer, sizeof(buffer));
249 ast_str_set(&uid, 0, "%s", buffer);
253 static int is_valid_uuid(struct ast_str *uid)
255 struct ast_uuid *uuid = ast_str_to_uuid(ast_str_buffer(uid));
265 static struct ast_str *xml_encode_str(struct ast_str *dst, const char *src)
270 for (tmp = src; *tmp; tmp++) {
273 strcpy(buf, """);
277 strcpy(buf, "'");
281 strcpy(buf, "&");
293 sprintf(buf, "%c", *tmp);
296 ast_str_append(&dst, 0, "%s", buf);
302 static struct ast_str *epoch_to_exchange_time(struct ast_str *dst, time_t epoch)
304 icaltimezone *utc = icaltimezone_get_utc_timezone();
305 icaltimetype tt = icaltime_from_timet_with_zone(epoch, 0, utc);
309 ast_copy_string(tmp, icaltime_as_ical_string(tt), sizeof(tmp));
310 for (i = 0; tmp[i]; i++) {
311 ast_str_append(&dst, 0, "%c", tmp[i]);
312 if (i == 3 || i == 5)
313 ast_str_append(&dst, 0, "%c", '-');
314 if (i == 10 || i == 12)
315 ast_str_append(&dst, 0, "%c", ':');
317 ast_str_append(&dst, 0, "%s", ".000");
323 static struct ast_str *bs_to_exchange_bs(struct ast_str *dst, enum ast_calendar_busy_state bs)
326 case AST_CALENDAR_BS_BUSY:
327 ast_str_set(&dst, 0, "%s", "BUSY");
330 case AST_CALENDAR_BS_BUSY_TENTATIVE:
331 ast_str_set(&dst, 0, "%s", "TENTATIVE");
335 ast_str_set(&dst, 0, "%s", "FREE");
341 static int fetch_response_reader(void *data, const char *block, size_t len)
343 struct ast_str **response = data;
346 if (!(tmp = ast_malloc(len + 1))) {
349 memcpy(tmp, block, len);
351 ast_str_append(response, 0, "%s", tmp);
357 static int auth_credentials(void *userdata, const char *realm, int attempts, char *username, char *secret)
359 struct exchangecal_pvt *pvt = userdata;
362 ast_log(LOG_WARNING, "Invalid username or password for Exchange calendar '%s'\n", pvt->owner->name);
366 ne_strnzcpy(username, pvt->user, NE_ABUFSIZ);
367 ne_strnzcpy(secret, pvt->secret, NE_ABUFSIZ);
372 static struct ast_str *exchangecal_request(struct exchangecal_pvt *pvt, const char *method, struct ast_str *req_body, struct ast_str *subdir)
374 struct ast_str *response;
380 ast_log(LOG_ERROR, "There is no private!\n");
384 if (!(response = ast_str_create(512))) {
385 ast_log(LOG_ERROR, "Could not allocate memory for response.\n");
389 snprintf(buf, sizeof(buf), "%s%s", pvt->uri.path, subdir ? ast_str_buffer(subdir) : "");
391 req = ne_request_create(pvt->session, method, buf);
392 ne_add_response_body_reader(req, ne_accept_2xx, fetch_response_reader, &response);
393 ne_set_request_body_buffer(req, ast_str_buffer(req_body), ast_str_strlen(req_body));
394 ne_add_request_header(req, "Content-type", "text/xml");
396 ret = ne_request_dispatch(req);
397 ne_request_destroy(req);
399 if (ret != NE_OK || !ast_str_strlen(response)) {
400 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));
408 static int exchangecal_write_event(struct ast_calendar_event *event)
410 struct ast_str *body = NULL;
411 struct ast_str *response = NULL;
412 struct ast_str *subdir = NULL;
413 struct ast_str *uid = NULL;
414 struct ast_str *summary = NULL;
415 struct ast_str *description = NULL;
416 struct ast_str *organizer = NULL;
417 struct ast_str *location = NULL;
418 struct ast_str *start = NULL;
419 struct ast_str *end = NULL;
420 struct ast_str *busystate = NULL;
424 ast_log(LOG_WARNING, "No event passed!\n");
428 if (!(event->start && event->end)) {
429 ast_log(LOG_WARNING, "The event must contain a start and an end\n");
432 if (!(body = ast_str_create(512)) ||
433 !(subdir = ast_str_create(32))) {
434 ast_log(LOG_ERROR, "Could not allocate memory for request!\n");
438 if (!(uid = ast_str_create(AST_UUID_STR_LEN)) ||
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, AST_UUID_STR_LEN, "%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",
501 ast_str_buffer(summary),
502 ast_str_buffer(description),
503 ast_str_buffer(organizer),
504 ast_str_buffer(location),
505 ast_str_buffer(start),
507 ast_str_buffer(busystate));
508 ast_verb(0, "\n\n%s\n\n", ast_str_buffer(body));
509 ast_str_set(&subdir, 0, "/Calendar/%s.eml", ast_str_buffer(uid));
511 if ((response = exchangecal_request(event->owner->tech_pvt, "PROPPATCH", body, subdir))) {
518 ast_free(description);
532 static struct ast_str *exchangecal_get_events_between(struct exchangecal_pvt *pvt, time_t start_time, time_t end_time)
534 struct ast_str *body, *response;
535 char start[80], end[80];
536 struct timeval tv = {0,};
539 tv.tv_sec = start_time;
540 ast_localtime(&tv, &tm, "UTC");
541 ast_strftime(start, sizeof(start), "%Y/%m/%d %T", &tm);
543 tv.tv_sec = end_time;
544 ast_localtime(&tv, &tm, "UTC");
545 ast_strftime(end, sizeof(end), "%Y/%m/%d %T", &tm);
547 if (!(body = ast_str_create(512))) {
548 ast_log(LOG_ERROR, "Could not allocate memory for body of request!\n");
552 ast_str_append(&body, 0,
553 "<?xml version=\"1.0\"?>\n"
554 "<g:searchrequest xmlns:g=\"DAV:\">\n"
555 " <g:sql> SELECT \"urn:schemas:calendar:location\", \"urn:schemas:httpmail:subject\",\n"
556 " \"urn:schemas:calendar:dtstart\", \"urn:schemas:calendar:dtend\",\n"
557 " \"urn:schemas:calendar:busystatus\", \"urn:schemas:calendar:instancetype\",\n"
558 " \"urn:schemas:calendar:uid\", \"urn:schemas:httpmail:textdescription\",\n"
559 " \"urn:schemas:calendar:organizer\", \"urn:schemas:calendar:reminderoffset\"\n"
560 " FROM Scope('SHALLOW TRAVERSAL OF \"%s/Calendar\"')\n"
561 " WHERE NOT \"urn:schemas:calendar:instancetype\" = 1\n"
562 " AND \"DAV:contentclass\" = 'urn:content-classes:appointment'\n"
563 " AND NOT (\"urn:schemas:calendar:dtend\" < '%s'\n"
564 " OR \"urn:schemas:calendar:dtstart\" > '%s')\n"
565 " ORDER BY \"urn:schemas:calendar:dtstart\" ASC\n"
567 "</g:searchrequest>\n", pvt->url, start, end);
569 ast_debug(5, "Request:\n%s\n", ast_str_buffer(body));
570 response = exchangecal_request(pvt, "SEARCH", body, NULL);
571 ast_debug(5, "Response:\n%s\n", ast_str_buffer(response));
577 static int update_exchangecal(struct exchangecal_pvt *pvt)
579 struct xmlstate state;
580 struct timeval now = ast_tvnow();
582 struct ast_str *response;
587 end = now.tv_sec + 60 * pvt->owner->timeframe;
588 if (!(response = exchangecal_get_events_between(pvt, start, end))) {
592 p = iks_sax_new(&state, parse_tag, parse_cdata);
593 iks_parse(p, ast_str_buffer(response), ast_str_strlen(response), 1);
594 ast_calendar_merge_events(pvt->owner, pvt->events);
600 static void *exchangecal_load_calendar(void *void_data)
602 struct exchangecal_pvt *pvt;
603 const struct ast_config *cfg;
604 struct ast_variable *v;
605 struct ast_calendar *cal = void_data;
606 ast_mutex_t refreshlock;
608 if (!(cal && (cfg = ast_calendar_config_acquire()))) {
609 ast_log(LOG_ERROR, "You must enable calendar support for res_exchangecal to load\n");
613 if (ao2_trylock(cal)) {
614 if (cal->unloading) {
615 ast_log(LOG_WARNING, "Unloading module, load_calendar cancelled.\n");
617 ast_log(LOG_WARNING, "Could not lock calendar, aborting!\n");
619 ast_calendar_config_release();
623 if (!(pvt = ao2_alloc(sizeof(*pvt), exchangecal_destructor))) {
624 ast_log(LOG_ERROR, "Could not allocate exchangecal_pvt structure for calendar: %s\n", cal->name);
625 ast_calendar_config_release();
631 if (!(pvt->events = ast_calendar_event_container_alloc())) {
632 ast_log(LOG_ERROR, "Could not allocate space for fetching events for calendar: %s\n", cal->name);
633 pvt = unref_exchangecal(pvt);
635 ast_calendar_config_release();
639 if (ast_string_field_init(pvt, 32)) {
640 ast_log(LOG_ERROR, "Couldn't allocate string field space for calendar: %s\n", cal->name);
641 pvt = unref_exchangecal(pvt);
643 ast_calendar_config_release();
647 for (v = ast_variable_browse(cfg, cal->name); v; v = v->next) {
648 if (!strcasecmp(v->name, "url")) {
649 ast_string_field_set(pvt, url, v->value);
650 } else if (!strcasecmp(v->name, "user")) {
651 ast_string_field_set(pvt, user, v->value);
652 } else if (!strcasecmp(v->name, "secret")) {
653 ast_string_field_set(pvt, secret, v->value);
657 ast_calendar_config_release();
659 if (ast_strlen_zero(pvt->url)) {
660 ast_log(LOG_WARNING, "No URL was specified for Exchange calendar '%s' - skipping.\n", cal->name);
661 pvt = unref_exchangecal(pvt);
666 if (ne_uri_parse(pvt->url, &pvt->uri) || pvt->uri.host == NULL || pvt->uri.path == NULL) {
667 ast_log(LOG_WARNING, "Could not parse url '%s' for Exchange calendar '%s' - skipping.\n", pvt->url, cal->name);
668 pvt = unref_exchangecal(pvt);
673 if (pvt->uri.scheme == NULL) {
674 pvt->uri.scheme = "http";
677 if (pvt->uri.port == 0) {
678 pvt->uri.port = ne_uri_defaultport(pvt->uri.scheme);
681 pvt->session = ne_session_create(pvt->uri.scheme, pvt->uri.host, pvt->uri.port);
682 ne_redirect_register(pvt->session);
683 ne_set_server_auth(pvt->session, auth_credentials, pvt);
684 if (!strcasecmp(pvt->uri.scheme, "https")) {
685 ne_ssl_trust_default_ca(pvt->session);
690 ast_mutex_init(&refreshlock);
692 /* Load it the first time */
693 update_exchangecal(pvt);
697 /* The only writing from another thread will be if unload is true */
699 struct timeval tv = ast_tvnow();
700 struct timespec ts = {0,};
702 ts.tv_sec = tv.tv_sec + (60 * pvt->owner->refresh);
704 ast_mutex_lock(&refreshlock);
705 while (!pvt->owner->unloading) {
706 if (ast_cond_timedwait(&pvt->owner->unload, &refreshlock, &ts) == ETIMEDOUT) {
710 ast_mutex_unlock(&refreshlock);
712 if (pvt->owner->unloading) {
713 ast_debug(10, "Skipping refresh since we got a shutdown signal\n");
717 ast_debug(10, "Refreshing after %d minute timeout\n", pvt->owner->refresh);
719 update_exchangecal(pvt);
725 static int load_module(void)
728 if (ast_calendar_register(&exchangecal_tech)) {
730 return AST_MODULE_LOAD_DECLINE;
733 return AST_MODULE_LOAD_SUCCESS;
736 static int unload_module(void)
738 ast_calendar_unregister(&exchangecal_tech);
743 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Asterisk MS Exchange Calendar Integration",
744 .support_level = AST_MODULE_SUPPORT_CORE,
746 .unload = unload_module,
747 .load_pri = AST_MODPRI_DEVSTATE_PLUGIN,