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