res_srtp: Add support for libsrtp2.1.
[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 #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/channel.h"
42 #include "asterisk/calendar.h"
43 #include "asterisk/lock.h"
44 #include "asterisk/config.h"
45 #include "asterisk/astobj2.h"
46 #include "asterisk/uuid.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         char buffer[AST_UUID_STR_LEN];
245
246         ast_uuid_generate_str(buffer, sizeof(buffer));
247         ast_str_set(&uid, 0, "%s", buffer);
248         return uid;
249 }
250
251 static int is_valid_uuid(struct ast_str *uid)
252 {
253         struct ast_uuid *uuid = ast_str_to_uuid(ast_str_buffer(uid));
254
255         if (uuid) {
256                 ast_free(uuid);
257                 return 1;
258         }
259
260         return 0;
261 }
262
263 static struct ast_str *xml_encode_str(struct ast_str *dst, const char *src)
264 {
265         const char *tmp;
266         char buf[7];
267
268         for (tmp = src; *tmp; tmp++) {
269                 switch (*tmp) {
270                 case '\"':
271                         strcpy(buf, "&quot;");
272                         break;
273
274                 case '\'':
275                         strcpy(buf, "&apos;");
276                         break;
277
278                 case '&':
279                         strcpy(buf, "&amp;");
280                         break;
281
282                 case '<':
283                         strcpy(buf, "&lt;");
284                         break;
285
286                 case '>':
287                         strcpy(buf, "&gt;");
288                         break;
289
290                 default:
291                         sprintf(buf, "%c", *tmp);
292                 }
293
294                 ast_str_append(&dst, 0, "%s", buf);
295         }
296
297         return dst;
298 }
299
300 static struct ast_str *epoch_to_exchange_time(struct ast_str *dst, time_t epoch)
301 {
302         icaltimezone *utc = icaltimezone_get_utc_timezone();
303         icaltimetype tt = icaltime_from_timet_with_zone(epoch, 0, utc);
304         char tmp[30];
305         int i;
306
307         ast_copy_string(tmp, icaltime_as_ical_string(tt), sizeof(tmp));
308         for (i = 0; tmp[i]; i++) {
309                 ast_str_append(&dst, 0, "%c", tmp[i]);
310                 if (i == 3 || i == 5)
311                         ast_str_append(&dst, 0, "%c", '-');
312                 if (i == 10 || i == 12)
313                         ast_str_append(&dst, 0, "%c", ':');
314                 if (i == 14)
315                         ast_str_append(&dst, 0, "%s", ".000");
316         }
317
318         return dst;
319 }
320
321 static struct ast_str *bs_to_exchange_bs(struct ast_str *dst, enum ast_calendar_busy_state bs)
322 {
323         switch (bs) {
324         case AST_CALENDAR_BS_BUSY:
325                 ast_str_set(&dst, 0, "%s", "BUSY");
326                 break;
327
328         case AST_CALENDAR_BS_BUSY_TENTATIVE:
329                 ast_str_set(&dst, 0, "%s", "TENTATIVE");
330                 break;
331
332         default:
333                 ast_str_set(&dst, 0, "%s", "FREE");
334         }
335
336         return dst;
337 }
338
339 static int fetch_response_reader(void *data, const char *block, size_t len)
340 {
341         struct ast_str **response = data;
342         unsigned char *tmp;
343
344         if (!(tmp = ast_malloc(len + 1))) {
345                 return -1;
346         }
347         memcpy(tmp, block, len);
348         tmp[len] = '\0';
349         ast_str_append(response, 0, "%s", tmp);
350         ast_free(tmp);
351
352         return 0;
353 }
354
355 static int auth_credentials(void *userdata, const char *realm, int attempts, char *username, char *secret)
356 {
357         struct exchangecal_pvt *pvt = userdata;
358
359         if (attempts > 1) {
360                 ast_log(LOG_WARNING, "Invalid username or password for Exchange calendar '%s'\n", pvt->owner->name);
361                 return -1;
362         }
363
364         ne_strnzcpy(username, pvt->user, NE_ABUFSIZ);
365         ne_strnzcpy(secret, pvt->secret, NE_ABUFSIZ);
366
367         return 0;
368 }
369
370 static struct ast_str *exchangecal_request(struct exchangecal_pvt *pvt, const char *method, struct ast_str *req_body, struct ast_str *subdir)
371 {
372         struct ast_str *response;
373         ne_request *req;
374         int ret;
375         char buf[1000];
376
377         if (!pvt) {
378                 ast_log(LOG_ERROR, "There is no private!\n");
379                 return NULL;
380         }
381
382         if (!(response = ast_str_create(512))) {
383                 ast_log(LOG_ERROR, "Could not allocate memory for response.\n");
384                 return NULL;
385         }
386
387         snprintf(buf, sizeof(buf), "%s%s", pvt->uri.path, subdir ? ast_str_buffer(subdir) : "");
388
389         req = ne_request_create(pvt->session, method, buf);
390         ne_add_response_body_reader(req, ne_accept_2xx, fetch_response_reader, &response);
391         ne_set_request_body_buffer(req, ast_str_buffer(req_body), ast_str_strlen(req_body));
392         ne_add_request_header(req, "Content-type", "text/xml");
393
394         ret = ne_request_dispatch(req);
395         ne_request_destroy(req);
396
397         if (ret != NE_OK || !ast_str_strlen(response)) {
398                 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));
399                 ast_free(response);
400                 return NULL;
401         }
402
403         return response;
404 }
405
406 static int exchangecal_write_event(struct ast_calendar_event *event)
407 {
408         struct ast_str *body = NULL;
409         struct ast_str *response = NULL;
410         struct ast_str *subdir = NULL;
411         struct ast_str *uid = NULL;
412         struct ast_str *summary = NULL;
413         struct ast_str *description = NULL;
414         struct ast_str *organizer = NULL;
415         struct ast_str *location = NULL;
416         struct ast_str *start = NULL;
417         struct ast_str *end = NULL;
418         struct ast_str *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(AST_UUID_STR_LEN)) ||
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, AST_UUID_STR_LEN, "%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),
499                 ast_str_buffer(summary),
500                 ast_str_buffer(description),
501                 ast_str_buffer(organizer),
502                 ast_str_buffer(location),
503                 ast_str_buffer(start),
504                 ast_str_buffer(end),
505                 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         if ((response = exchangecal_request(event->owner->tech_pvt, "PROPPATCH", body, subdir))) {
510                 ret = 0;
511         }
512
513 write_cleanup:
514         ast_free(uid);
515         ast_free(summary);
516         ast_free(description);
517         ast_free(organizer);
518         ast_free(location);
519         ast_free(start);
520         ast_free(end);
521         ast_free(busystate);
522         ast_free(body);
523         ast_free(response);
524         ast_free(subdir);
525
526         return ret;
527 }
528
529
530 static struct ast_str *exchangecal_get_events_between(struct exchangecal_pvt *pvt, time_t start_time, time_t end_time)
531 {
532         struct ast_str *body, *response;
533         char start[80], end[80];
534         struct timeval tv = {0,};
535         struct ast_tm tm;
536
537         tv.tv_sec = start_time;
538         ast_localtime(&tv, &tm, "UTC");
539         ast_strftime(start, sizeof(start), "%Y/%m/%d %T", &tm);
540
541         tv.tv_sec = end_time;
542         ast_localtime(&tv, &tm, "UTC");
543         ast_strftime(end, sizeof(end), "%Y/%m/%d %T", &tm);
544
545         if (!(body = ast_str_create(512))) {
546                 ast_log(LOG_ERROR, "Could not allocate memory for body of request!\n");
547                 return NULL;
548         }
549
550         ast_str_append(&body, 0,
551                 "<?xml version=\"1.0\"?>\n"
552                 "<g:searchrequest xmlns:g=\"DAV:\">\n"
553                 "        <g:sql> SELECT \"urn:schemas:calendar:location\", \"urn:schemas:httpmail:subject\",\n"
554                 "                \"urn:schemas:calendar:dtstart\", \"urn:schemas:calendar:dtend\",\n"
555                 "                \"urn:schemas:calendar:busystatus\", \"urn:schemas:calendar:instancetype\",\n"
556                 "                \"urn:schemas:calendar:uid\", \"urn:schemas:httpmail:textdescription\",\n"
557                 "                \"urn:schemas:calendar:organizer\", \"urn:schemas:calendar:reminderoffset\"\n"
558                 "                FROM Scope('SHALLOW TRAVERSAL OF \"%s/Calendar\"')\n"
559                 "                WHERE NOT \"urn:schemas:calendar:instancetype\" = 1\n"
560                 "                AND \"DAV:contentclass\" = 'urn:content-classes:appointment'\n"
561                 "                AND NOT (\"urn:schemas:calendar:dtend\" &lt; '%s'\n"
562                 "                OR \"urn:schemas:calendar:dtstart\" &gt; '%s')\n"
563                 "                ORDER BY \"urn:schemas:calendar:dtstart\" ASC\n"
564                 "         </g:sql>\n"
565                 "</g:searchrequest>\n", pvt->url, start, end);
566
567         ast_debug(5, "Request:\n%s\n", ast_str_buffer(body));
568         response = exchangecal_request(pvt, "SEARCH", body, NULL);
569         ast_debug(5, "Response:\n%s\n", ast_str_buffer(response));
570         ast_free(body);
571
572         return response;
573 }
574
575 static int update_exchangecal(struct exchangecal_pvt *pvt)
576 {
577         struct xmlstate state;
578         struct timeval now = ast_tvnow();
579         time_t start, end;
580         struct ast_str *response;
581         iksparser *p;
582
583         state.pvt = pvt;
584         start = now.tv_sec;
585         end = now.tv_sec + 60 * pvt->owner->timeframe;
586         if (!(response = exchangecal_get_events_between(pvt, start, end))) {
587                 return -1;
588         }
589
590         p = iks_sax_new(&state, parse_tag, parse_cdata);
591         iks_parse(p, ast_str_buffer(response), ast_str_strlen(response), 1);
592         ast_calendar_merge_events(pvt->owner, pvt->events);
593         ast_free(response);
594
595         return 0;
596 }
597
598 static void *exchangecal_load_calendar(void *void_data)
599 {
600         struct exchangecal_pvt *pvt;
601         const struct ast_config *cfg;
602         struct ast_variable *v;
603         struct ast_calendar *cal = void_data;
604         ast_mutex_t refreshlock;
605
606         if (!(cal && (cfg = ast_calendar_config_acquire()))) {
607                 ast_log(LOG_ERROR, "You must enable calendar support for res_exchangecal to load\n");
608                 return NULL;
609         }
610
611         if (ao2_trylock(cal)) {
612                 if (cal->unloading) {
613                         ast_log(LOG_WARNING, "Unloading module, load_calendar cancelled.\n");
614                 } else {
615                         ast_log(LOG_WARNING, "Could not lock calendar, aborting!\n");
616                 }
617                 ast_calendar_config_release();
618                 return NULL;
619         }
620
621         if (!(pvt = ao2_alloc(sizeof(*pvt), exchangecal_destructor))) {
622                 ast_log(LOG_ERROR, "Could not allocate exchangecal_pvt structure for calendar: %s\n", cal->name);
623                 ast_calendar_config_release();
624                 return NULL;
625         }
626
627         pvt->owner = cal;
628
629         if (!(pvt->events = ast_calendar_event_container_alloc())) {
630                 ast_log(LOG_ERROR, "Could not allocate space for fetching events for calendar: %s\n", cal->name);
631                 pvt = unref_exchangecal(pvt);
632                 ao2_unlock(cal);
633                 ast_calendar_config_release();
634                 return NULL;
635         }
636
637         if (ast_string_field_init(pvt, 32)) {
638                 ast_log(LOG_ERROR, "Couldn't allocate string field space for calendar: %s\n", cal->name);
639                 pvt = unref_exchangecal(pvt);
640                 ao2_unlock(cal);
641                 ast_calendar_config_release();
642                 return NULL;
643         }
644
645         for (v = ast_variable_browse(cfg, cal->name); v; v = v->next) {
646                 if (!strcasecmp(v->name, "url")) {
647                         ast_string_field_set(pvt, url, v->value);
648                 } else if (!strcasecmp(v->name, "user")) {
649                         ast_string_field_set(pvt, user, v->value);
650                 } else if (!strcasecmp(v->name, "secret")) {
651                         ast_string_field_set(pvt, secret, v->value);
652                 }
653         }
654
655         ast_calendar_config_release();
656
657         if (ast_strlen_zero(pvt->url)) {
658                 ast_log(LOG_WARNING, "No URL was specified for Exchange calendar '%s' - skipping.\n", cal->name);
659                 pvt = unref_exchangecal(pvt);
660                 ao2_unlock(cal);
661                 return NULL;
662         }
663
664         if (ne_uri_parse(pvt->url, &pvt->uri) || pvt->uri.host == NULL || pvt->uri.path == NULL) {
665                 ast_log(LOG_WARNING, "Could not parse url '%s' for Exchange calendar '%s' - skipping.\n", pvt->url, cal->name);
666                 pvt = unref_exchangecal(pvt);
667                 ao2_unlock(cal);
668                 return NULL;
669         }
670
671         if (pvt->uri.scheme == NULL) {
672                 pvt->uri.scheme = "http";
673         }
674
675         if (pvt->uri.port == 0) {
676                 pvt->uri.port = ne_uri_defaultport(pvt->uri.scheme);
677         }
678
679         pvt->session = ne_session_create(pvt->uri.scheme, pvt->uri.host, pvt->uri.port);
680         ne_redirect_register(pvt->session);
681         ne_set_server_auth(pvt->session, auth_credentials, pvt);
682         if (!strcasecmp(pvt->uri.scheme, "https")) {
683                 ne_ssl_trust_default_ca(pvt->session);
684         }
685
686         cal->tech_pvt = pvt;
687
688         ast_mutex_init(&refreshlock);
689
690         /* Load it the first time */
691         update_exchangecal(pvt);
692
693         ao2_unlock(cal);
694
695         /* The only writing from another thread will be if unload is true */
696         for (;;) {
697                 struct timeval tv = ast_tvnow();
698                 struct timespec ts = {0,};
699
700                 ts.tv_sec = tv.tv_sec + (60 * pvt->owner->refresh);
701
702                 ast_mutex_lock(&refreshlock);
703                 while (!pvt->owner->unloading) {
704                         if (ast_cond_timedwait(&pvt->owner->unload, &refreshlock, &ts) == ETIMEDOUT) {
705                                 break;
706                         }
707                 }
708                 ast_mutex_unlock(&refreshlock);
709
710                 if (pvt->owner->unloading) {
711                         ast_debug(10, "Skipping refresh since we got a shutdown signal\n");
712                         return NULL;
713                 }
714
715                 ast_debug(10, "Refreshing after %d minute timeout\n", pvt->owner->refresh);
716
717                 update_exchangecal(pvt);
718         }
719
720         return NULL;
721 }
722
723 static int load_module(void)
724 {
725         ne_sock_init();
726         if (ast_calendar_register(&exchangecal_tech)) {
727                 ne_sock_exit();
728                 return AST_MODULE_LOAD_DECLINE;
729         }
730
731         return AST_MODULE_LOAD_SUCCESS;
732 }
733
734 static int unload_module(void)
735 {
736         ast_calendar_unregister(&exchangecal_tech);
737         ne_sock_exit();
738         return 0;
739 }
740
741 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Asterisk MS Exchange Calendar Integration",
742         .support_level = AST_MODULE_SUPPORT_CORE,
743         .load = load_module,
744         .unload = unload_module,
745         .load_pri = AST_MODPRI_DEVSTATE_PLUGIN,
746 );