6c0982a63add1cb5f1a6b454e07f2ef25952e49f
[asterisk/asterisk.git] / res / res_calendar_exchange.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2008 - 2009, Digium, Inc.
5  *
6  * Terry Wilson <twilson@digium.com>
7  *
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.
13  *
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.
17  */
18
19 /*! \file
20  * \brief Resource for handling MS Exchange calendars
21  */
22
23 /*** MODULEINFO
24         <depend>neon</depend>
25         <depend>ical</depend>
26         <depend>iksemel</depend>
27         <support_level>core</support_level>
28 ***/
29
30 #include "asterisk.h"
31
32 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
33
34 #include <libical/ical.h>
35 #include <ne_session.h>
36 #include <ne_uri.h>
37 #include <ne_request.h>
38 #include <ne_auth.h>
39 #include <ne_redirect.h>
40 #include <iksemel.h>
41
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"
47
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);
51
52 static struct ast_calendar_tech exchangecal_tech = {
53         .type = "exchange",
54         .description = "MS Exchange calendars",
55         .module = AST_MODULE,
56         .load_calendar = exchangecal_load_calendar,
57         .unref_calendar = unref_exchangecal,
58         .write_event = exchangecal_write_event,
59 };
60
61 struct exchangecal_pvt {
62         AST_DECLARE_STRING_FIELDS(
63                 AST_STRING_FIELD(url);
64                 AST_STRING_FIELD(user);
65                 AST_STRING_FIELD(secret);
66         );
67         struct ast_calendar *owner;
68         ne_uri uri;
69         ne_session *session;
70         struct ao2_container *events;
71 };
72
73 struct xmlstate {
74         char tag[80];
75         int in_response;
76         int in_propstat;
77         int in_prop;
78         void *ptr;
79         struct exchangecal_pvt *pvt;
80 };
81
82 static int parse_tag(void *data, char *name, char **atts, int type)
83 {
84         struct xmlstate *state = data;
85         char *tmp;
86
87         if ((tmp = strchr(name, ':'))) {
88                 tmp++;
89         } else {
90                 return IKS_HOOK;
91         }
92
93         ast_copy_string(state->tag, tmp, sizeof(state->tag));
94
95         switch (type) {
96         case IKS_OPEN:
97                 if (!strcasecmp(state->tag, "response")) {
98                         struct ast_calendar_event *event;
99
100                         state->in_response = 1;
101                         if (!(event = ast_calendar_event_alloc(state->pvt->owner))) {
102                                 return IKS_NOMEM;
103                         }
104                         state->ptr = event;
105                 } else if (!strcasecmp(state->tag, "propstat")) {
106                         state->in_propstat = 1;
107                 } else if (!strcasecmp(state->tag, "prop")) {
108                         state->in_prop = 1;
109                 }
110                 break;
111
112         case IKS_CLOSE:
113                 if (!strcasecmp(state->tag, "response")) {
114                         struct ao2_container *events = state->pvt->events;
115                         struct ast_calendar_event *event = state->ptr;
116
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);
121                                 return IKS_HOOK;
122                         }
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")) {
128                         state->in_prop = 0;
129                 }
130                 break;
131
132         default:
133                 return IKS_OK;
134         }
135
136         return IKS_OK;
137 }
138
139 static time_t mstime_to_time_t(char *mstime)
140 {
141         char *read, *write;
142         icaltimetype tt;
143         for (read = write = mstime; *read; read++) {
144                 if (*read == '.') {
145                         *write++ = 'Z';
146                         *write = '\0';
147                         break;
148                 }
149                 if (*read == '-' || *read == ':')
150                         continue;
151                 *write = *read;
152                 write++;
153         }
154
155         tt = icaltime_from_string(mstime);
156         return icaltime_as_timet(tt);
157 }
158
159 static enum ast_calendar_busy_state msbusy_to_bs(const char *msbusy)
160 {
161         if (!strcasecmp(msbusy, "FREE")) {
162                 return AST_CALENDAR_BS_FREE;
163         } else if (!strcasecmp(msbusy, "TENTATIVE")) {
164                 return AST_CALENDAR_BS_BUSY_TENTATIVE;
165         } else {
166                 return AST_CALENDAR_BS_BUSY;
167         }
168 }
169
170 static int parse_cdata(void *data, char *value, size_t len)
171 {
172         char *str;
173         struct xmlstate *state = data;
174         struct ast_calendar_event *event = state->ptr;
175
176
177         str = ast_skip_blanks(value);
178
179         if (str == value + len)
180                 return IKS_OK;
181
182         if (!(str = ast_calloc(1, len + 1))) {
183                 return IKS_NOMEM;
184         }
185         memcpy(str, value, len);
186         if (!(state->in_response && state->in_propstat && state->in_prop)) {
187                 ast_free(str);
188                 return IKS_OK;
189         }
190         /* We use ast_string_field_build here because libiksemel is parsing CDATA with &lt; 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);
212         }
213
214         ast_free(str);
215         return IKS_OK;
216 }
217
218 static void exchangecal_destructor(void *obj)
219 {
220         struct exchangecal_pvt *pvt = obj;
221
222         ast_debug(1, "Destroying pvt for Exchange calendar %s\n", pvt->owner->name);
223         if (pvt->session) {
224                 ne_session_destroy(pvt->session);
225         }
226         ast_string_field_free_memory(pvt);
227
228         ao2_callback(pvt->events, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL);
229
230         ao2_ref(pvt->events, -1);
231 }
232
233 static void *unref_exchangecal(void *obj)
234 {
235         struct exchangecal_pvt *pvt = obj;
236
237         ao2_ref(pvt, -1);
238         return NULL;
239 }
240
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)
243 {
244         unsigned short val[8];
245         int x;
246
247         for (x = 0; x < 8; x++) {
248                 val[x] = ast_random();
249         }
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]);
251
252         return uid;
253 }
254
255 static int is_valid_uuid(struct ast_str *uid)
256 {
257         int i;
258
259         if (ast_str_strlen(uid) != 36) {
260                 return 0;
261         }
262
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] != '-') {
266                                 return 0;
267                         }
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))) {
269                         return 0;
270                 }
271         }
272
273         return 1;
274 }
275
276 static struct ast_str *xml_encode_str(struct ast_str *dst, const char *src)
277 {
278         const char *tmp;
279         char buf[7];
280
281         for (tmp = src; *tmp; tmp++) {
282                 switch (*tmp) {
283                 case '\"':
284                         strcpy(buf, "&quot;");
285                         break;
286
287                 case '\'':
288                         strcpy(buf, "&apos;");
289                         break;
290
291                 case '&':
292                         strcpy(buf, "&amp;");
293                         break;
294
295                 case '<':
296                         strcpy(buf, "&lt;");
297                         break;
298
299                 case '>':
300                         strcpy(buf, "&gt;");
301                         break;
302
303                 default:
304                         sprintf(buf, "%c", *tmp);
305                 }
306
307                 ast_str_append(&dst, 0, "%s", buf);
308         }
309
310         return dst;
311 }
312
313 static struct ast_str *epoch_to_exchange_time(struct ast_str *dst, time_t epoch)
314 {
315         icaltimezone *utc = icaltimezone_get_utc_timezone();
316         icaltimetype tt = icaltime_from_timet_with_zone(epoch, 0, utc);
317         char tmp[30];
318         int i;
319
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", ':');
327                 if (i == 14)
328                         ast_str_append(&dst, 0, "%s", ".000");
329         }
330
331         return dst;
332 }
333
334 static struct ast_str *bs_to_exchange_bs(struct ast_str *dst, enum ast_calendar_busy_state bs)
335 {
336         switch (bs) {
337         case AST_CALENDAR_BS_BUSY:
338                 ast_str_set(&dst, 0, "%s", "BUSY");
339                 break;
340
341         case AST_CALENDAR_BS_BUSY_TENTATIVE:
342                 ast_str_set(&dst, 0, "%s", "TENTATIVE");
343                 break;
344
345         default:
346                 ast_str_set(&dst, 0, "%s", "FREE");
347         }
348
349         return dst;
350 }
351
352 static int fetch_response_reader(void *data, const char *block, size_t len)
353 {
354         struct ast_str **response = data;
355         unsigned char *tmp;
356
357         if (!(tmp = ast_malloc(len + 1))) {
358                 return -1;
359         }
360         memcpy(tmp, block, len);
361         tmp[len] = '\0';
362         ast_str_append(response, 0, "%s", tmp);
363         ast_free(tmp);
364
365         return 0;
366 }
367
368 static int auth_credentials(void *userdata, const char *realm, int attempts, char *username, char *secret)
369 {
370         struct exchangecal_pvt *pvt = userdata;
371
372         if (attempts > 1) {
373                 ast_log(LOG_WARNING, "Invalid username or password for Exchange calendar '%s'\n", pvt->owner->name);
374                 return -1;
375         }
376
377         ne_strnzcpy(username, pvt->user, NE_ABUFSIZ);
378         ne_strnzcpy(secret, pvt->secret, NE_ABUFSIZ);
379
380         return 0;
381 }
382
383 static struct ast_str *exchangecal_request(struct exchangecal_pvt *pvt, const char *method, struct ast_str *req_body, struct ast_str *subdir)
384 {
385         struct ast_str *response;
386         ne_request *req;
387         int ret;
388         char buf[1000];
389
390         if (!pvt) {
391                 ast_log(LOG_ERROR, "There is no private!\n");
392                 return NULL;
393         }
394
395         if (!(response = ast_str_create(512))) {
396                 ast_log(LOG_ERROR, "Could not allocate memory for response.\n");
397                 return NULL;
398         }
399
400         snprintf(buf, sizeof(buf), "%s%s", pvt->uri.path, subdir ? ast_str_buffer(subdir) : "");
401
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");
406
407         ret = ne_request_dispatch(req);
408         ne_request_destroy(req);
409
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));
412                 ast_free(response);
413                 return NULL;
414         }
415
416         return response;
417 }
418
419 static int exchangecal_write_event(struct ast_calendar_event *event)
420 {
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;
424         int ret = -1;
425
426         if (!event) {
427                 ast_log(LOG_WARNING, "No event passed!\n");
428                 return -1;
429         }
430
431         if (!(event->start && event->end)) {
432                 ast_log(LOG_WARNING, "The event must contain a start and an end\n");
433                 return -1;
434         }
435         if (!(body = ast_str_create(512)) ||
436                 !(subdir = ast_str_create(32)) ||
437                 !(response = ast_str_create(512))) {
438                 ast_log(LOG_ERROR, "Could not allocate memory for request and response!\n");
439                 goto write_cleanup;
440         }
441
442         if (!(uid = ast_str_create(32)) ||
443                 !(summary = ast_str_create(32)) ||
444                 !(description = ast_str_create(32)) ||
445                 !(organizer = ast_str_create(32)) ||
446                 !(location = ast_str_create(32)) ||
447                 !(start = ast_str_create(32)) ||
448                 !(end = ast_str_create(32)) ||
449                 !(busystate = ast_str_create(32))) {
450                 ast_log(LOG_ERROR, "Unable to allocate memory for request values\n");
451                 goto write_cleanup;
452         }
453
454         if (ast_strlen_zero(event->uid)) {
455                 uid = generate_exchange_uuid(uid);
456         } else {
457                 ast_str_set(&uid, 36, "%s", event->uid);
458         }
459
460         if (!is_valid_uuid(uid)) {
461                 ast_log(LOG_WARNING, "An invalid uid was provided, you may leave this field blank to have one generated for you\n");
462                 goto write_cleanup;
463         }
464
465         summary = xml_encode_str(summary, event->summary);
466         description = xml_encode_str(description, event->description);
467         organizer = xml_encode_str(organizer, event->organizer);
468         location = xml_encode_str(location, event->location);
469         start = epoch_to_exchange_time(start, event->start);
470         end = epoch_to_exchange_time(end, event->end);
471         busystate = bs_to_exchange_bs(busystate, event->busy_state);
472
473         ast_str_append(&body, 0,
474                 "<?xml version=\"1.0\"?>\n"
475                 "<a:propertyupdate\n"
476                 "  xmlns:a=\"DAV:\"\n"
477                 "  xmlns:e=\"http://schemas.microsoft.com/exchange/\"\n"
478                 "  xmlns:mapi=\"http://schemas.microsoft.com/mapi/\"\n"
479                 "  xmlns:mapit=\"http://schemas.microsoft.com/mapi/proptag/\"\n"
480                 "  xmlns:x=\"xml:\" xmlns:cal=\"urn:schemas:calendar:\"\n"
481                 "  xmlns:dt=\"uuid:%s/\"\n" /* uid */
482                 "  xmlns:header=\"urn:schemas:mailheader:\"\n"
483                 "  xmlns:mail=\"urn:schemas:httpmail:\"\n"
484                 ">\n"
485                 "    <a:set>\n"
486                 "      <a:prop>\n"
487                 "        <a:contentclass>urn:content-classes:appointment</a:contentclass>\n"
488                 "        <e:outlookmessageclass>IPM.Appointment</e:outlookmessageclass>\n"
489                 "        <mail:subject>%s</mail:subject>\n" /* summary */
490                 "        <mail:description>%s</mail:description>\n" /* description */
491                 "        <header:to>%s</header:to>\n" /* organizer */
492                 "        <cal:location>%s</cal:location>\n" /* location */
493                 "        <cal:dtstart dt:dt=\"dateTime.tz\">%s</cal:dtstart>\n" /* start */
494                 "        <cal:dtend dt:dt=\"dateTime.tz\">%s</cal:dtend>\n" /* end */
495                 "        <cal:instancetype dt:dt=\"int\">0</cal:instancetype>\n"
496                 "        <cal:busystatus>%s</cal:busystatus>\n" /* busy_state (BUSY, FREE, BUSY_TENTATIVE) */
497                 "        <cal:meetingstatus>CONFIRMED</cal:meetingstatus>\n"
498                 "        <cal:alldayevent dt:dt=\"boolean\">0</cal:alldayevent>\n" /* XXX need to add event support for all day events */
499                 "        <cal:responserequested dt:dt=\"boolean\">0</cal:responserequested>\n"
500                 "        <mapi:finvited dt:dt=\"boolean\">1</mapi:finvited>\n"
501                 "      </a:prop>\n"
502                 "    </a:set>\n"
503                 "</a:propertyupdate>\n",
504                 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));
505         ast_verb(0, "\n\n%s\n\n", ast_str_buffer(body));
506         ast_str_set(&subdir, 0, "/Calendar/%s.eml", ast_str_buffer(uid));
507
508         if ((response = exchangecal_request(event->owner->tech_pvt, "PROPPATCH", body, subdir))) {
509                 ret = 0;
510         }
511
512 write_cleanup:
513         if (uid) {
514                 ast_free(uid);
515         }
516         if (summary) {
517                 ast_free(summary);
518         }
519         if (description) {
520                 ast_free(description);
521         }
522         if (organizer) {
523                 ast_free(organizer);
524         }
525         if (location) {
526                 ast_free(location);
527         }
528         if (start) {
529                 ast_free(start);
530         }
531         if (end) {
532                 ast_free(end);
533         }
534         if (busystate) {
535                 ast_free(busystate);
536         }
537         if (body) {
538                 ast_free(body);
539         }
540         if (response) {
541                 ast_free(response);
542         }
543         if (subdir) {
544                 ast_free(subdir);
545         }
546
547         return ret;
548 }
549
550
551 static struct ast_str *exchangecal_get_events_between(struct exchangecal_pvt *pvt, time_t start_time, time_t end_time)
552 {
553         struct ast_str *body, *response;
554         char start[80], end[80];
555         struct timeval tv = {0,};
556         struct ast_tm tm;
557
558         tv.tv_sec = start_time;
559         ast_localtime(&tv, &tm, "UTC");
560         ast_strftime(start, sizeof(start), "%Y/%m/%d %T", &tm);
561
562         tv.tv_sec = end_time;
563         ast_localtime(&tv, &tm, "UTC");
564         ast_strftime(end, sizeof(end), "%Y/%m/%d %T", &tm);
565
566         if (!(body = ast_str_create(512))) {
567                 ast_log(LOG_ERROR, "Could not allocate memory for body of request!\n");
568                 return NULL;
569         }
570
571         ast_str_append(&body, 0,
572                 "<?xml version=\"1.0\"?>\n"
573                 "<g:searchrequest xmlns:g=\"DAV:\">\n"
574                 "        <g:sql> SELECT \"urn:schemas:calendar:location\", \"urn:schemas:httpmail:subject\",\n"
575                 "                \"urn:schemas:calendar:dtstart\", \"urn:schemas:calendar:dtend\",\n"
576                 "                \"urn:schemas:calendar:busystatus\", \"urn:schemas:calendar:instancetype\",\n"
577                 "                \"urn:schemas:calendar:uid\", \"urn:schemas:httpmail:textdescription\",\n"
578                 "                \"urn:schemas:calendar:organizer\", \"urn:schemas:calendar:reminderoffset\"\n"
579                 "                FROM Scope('SHALLOW TRAVERSAL OF \"%s/Calendar\"')\n"
580                 "                WHERE NOT \"urn:schemas:calendar:instancetype\" = 1\n"
581                 "                AND \"DAV:contentclass\" = 'urn:content-classes:appointment'\n"
582                 "                AND NOT (\"urn:schemas:calendar:dtend\" &lt; '%s'\n"
583                 "                OR \"urn:schemas:calendar:dtstart\" &gt; '%s')\n"
584                 "                ORDER BY \"urn:schemas:calendar:dtstart\" ASC\n"
585                 "         </g:sql>\n"
586                 "</g:searchrequest>\n", pvt->url, start, end);
587
588         ast_debug(5, "Request:\n%s\n", ast_str_buffer(body));
589         response = exchangecal_request(pvt, "SEARCH", body, NULL);
590         ast_debug(5, "Response:\n%s\n", ast_str_buffer(response));
591         ast_free(body);
592
593         return response;
594 }
595
596 static int update_exchangecal(struct exchangecal_pvt *pvt)
597 {
598         struct xmlstate state;
599         struct timeval now = ast_tvnow();
600         time_t start, end;
601         struct ast_str *response;
602         iksparser *p;
603
604         state.pvt = pvt;
605         start = now.tv_sec;
606         end = now.tv_sec + 60 * pvt->owner->timeframe;
607         if (!(response = exchangecal_get_events_between(pvt, start, end))) {
608                 return -1;
609         }
610
611         p = iks_sax_new(&state, parse_tag, parse_cdata);
612         iks_parse(p, ast_str_buffer(response), ast_str_strlen(response), 1);
613         ast_calendar_merge_events(pvt->owner, pvt->events);
614         ast_free(response);
615
616         return 0;
617 }
618
619 static void *exchangecal_load_calendar(void *void_data)
620 {
621         struct exchangecal_pvt *pvt;
622         const struct ast_config *cfg;
623         struct ast_variable *v;
624         struct ast_calendar *cal = void_data;
625         ast_mutex_t refreshlock;
626
627         if (!(cal && (cfg = ast_calendar_config_acquire()))) {
628                 ast_log(LOG_ERROR, "You must enable calendar support for res_exchangecal to load\n");
629                 return NULL;
630         }
631
632         if (ao2_trylock(cal)) {
633                 if (cal->unloading) {
634                         ast_log(LOG_WARNING, "Unloading module, load_calendar cancelled.\n");
635                 } else {
636                         ast_log(LOG_WARNING, "Could not lock calendar, aborting!\n");
637                 }
638                 ast_calendar_config_release();
639                 return NULL;
640         }
641
642         if (!(pvt = ao2_alloc(sizeof(*pvt), exchangecal_destructor))) {
643                 ast_log(LOG_ERROR, "Could not allocate exchangecal_pvt structure for calendar: %s\n", cal->name);
644                 ast_calendar_config_release();
645                 return NULL;
646         }
647
648         pvt->owner = cal;
649
650         if (!(pvt->events = ast_calendar_event_container_alloc())) {
651                 ast_log(LOG_ERROR, "Could not allocate space for fetching events for calendar: %s\n", cal->name);
652                 pvt = unref_exchangecal(pvt);
653                 ao2_unlock(cal);
654                 ast_calendar_config_release();
655                 return NULL;
656         }
657
658         if (ast_string_field_init(pvt, 32)) {
659                 ast_log(LOG_ERROR, "Couldn't allocate string field space for calendar: %s\n", cal->name);
660                 pvt = unref_exchangecal(pvt);
661                 ao2_unlock(cal);
662                 ast_calendar_config_release();
663                 return NULL;
664         }
665
666         for (v = ast_variable_browse(cfg, cal->name); v; v = v->next) {
667                 if (!strcasecmp(v->name, "url")) {
668                         ast_string_field_set(pvt, url, v->value);
669                 } else if (!strcasecmp(v->name, "user")) {
670                         ast_string_field_set(pvt, user, v->value);
671                 } else if (!strcasecmp(v->name, "secret")) {
672                         ast_string_field_set(pvt, secret, v->value);
673                 }
674         }
675
676         ast_calendar_config_release();
677
678         if (ast_strlen_zero(pvt->url)) {
679                 ast_log(LOG_WARNING, "No URL was specified for Exchange calendar '%s' - skipping.\n", cal->name);
680                 pvt = unref_exchangecal(pvt);
681                 ao2_unlock(cal);
682                 return NULL;
683         }
684
685         if (ne_uri_parse(pvt->url, &pvt->uri) || pvt->uri.host == NULL || pvt->uri.path == NULL) {
686                 ast_log(LOG_WARNING, "Could not parse url '%s' for Exchange calendar '%s' - skipping.\n", pvt->url, cal->name);
687                 pvt = unref_exchangecal(pvt);
688                 ao2_unlock(cal);
689                 return NULL;
690         }
691
692         if (pvt->uri.scheme == NULL) {
693                 pvt->uri.scheme = "http";
694         }
695
696         if (pvt->uri.port == 0) {
697                 pvt->uri.port = ne_uri_defaultport(pvt->uri.scheme);
698         }
699
700         pvt->session = ne_session_create(pvt->uri.scheme, pvt->uri.host, pvt->uri.port);
701         ne_redirect_register(pvt->session);
702         ne_set_server_auth(pvt->session, auth_credentials, pvt);
703         if (!strcasecmp(pvt->uri.scheme, "https")) {
704                 ne_ssl_trust_default_ca(pvt->session);
705         }
706
707         cal->tech_pvt = pvt;
708
709         ast_mutex_init(&refreshlock);
710
711         /* Load it the first time */
712         update_exchangecal(pvt);
713
714         ao2_unlock(cal);
715
716         /* The only writing from another thread will be if unload is true */
717         for (;;) {
718                 struct timeval tv = ast_tvnow();
719                 struct timespec ts = {0,};
720
721                 ts.tv_sec = tv.tv_sec + (60 * pvt->owner->refresh);
722
723                 ast_mutex_lock(&refreshlock);
724                 while (!pvt->owner->unloading) {
725                         if (ast_cond_timedwait(&pvt->owner->unload, &refreshlock, &ts) == ETIMEDOUT) {
726                                 break;
727                         }
728                 }
729                 ast_mutex_unlock(&refreshlock);
730
731                 if (pvt->owner->unloading) {
732                         ast_debug(10, "Skipping refresh since we got a shutdown signal\n");
733                         return NULL;
734                 }
735
736                 ast_debug(10, "Refreshing after %d minute timeout\n", pvt->owner->refresh);
737
738                 update_exchangecal(pvt);
739         }
740
741         return NULL;
742 }
743
744 static int load_module(void)
745 {
746         ne_sock_init();
747         if (ast_calendar_register(&exchangecal_tech)) {
748                 ne_sock_exit();
749                 return AST_MODULE_LOAD_DECLINE;
750         }
751
752         return AST_MODULE_LOAD_SUCCESS;
753 }
754
755 static int unload_module(void)
756 {
757         ast_calendar_unregister(&exchangecal_tech);
758         ne_sock_exit();
759         return 0;
760 }
761
762 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Asterisk MS Exchange Calendar Integration",
763                 .load = load_module,
764                 .unload = unload_module,
765                 .load_pri = AST_MODPRI_DEVSTATE_PLUGIN,
766         );