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