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