Merged revisions 300214 via svnmerge from
[asterisk/asterisk.git] / res / res_calendar_icalendar.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 iCalendar calendars
21  */
22
23 /*** MODULEINFO
24         <depend>neon</depend>
25         <depend>ical</depend>
26 ***/
27 #include "asterisk.h"
28
29 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
30
31 #include <libical/ical.h>
32 #include <ne_session.h>
33 #include <ne_uri.h>
34 #include <ne_request.h>
35 #include <ne_auth.h>
36 #include <ne_redirect.h>
37
38 #include "asterisk/module.h"
39 #include "asterisk/calendar.h"
40 #include "asterisk/lock.h"
41 #include "asterisk/config.h"
42 #include "asterisk/astobj2.h"
43
44 static void *ical_load_calendar(void *data);
45 static void *unref_icalendar(void *obj);
46
47 static struct ast_calendar_tech ical_tech = {
48         .type = "ical",
49         .module = AST_MODULE,
50         .description = "iCalendar .ics calendars",
51         .load_calendar = ical_load_calendar,
52         .unref_calendar = unref_icalendar,
53 };
54
55 struct icalendar_pvt {
56         AST_DECLARE_STRING_FIELDS(
57                 AST_STRING_FIELD(url);
58                 AST_STRING_FIELD(user);
59                 AST_STRING_FIELD(secret);
60         );
61         struct ast_calendar *owner;
62         ne_uri uri;
63         ne_session *session;
64         icalcomponent *data;
65         struct ao2_container *events;
66 };
67
68 static void icalendar_destructor(void *obj)
69 {
70         struct icalendar_pvt *pvt = obj;
71
72         ast_debug(1, "Destroying pvt for iCalendar %s\n", pvt->owner->name);
73         if (pvt->session) {
74                 ne_session_destroy(pvt->session);
75         }
76         if (pvt->data) {
77                 icalcomponent_free(pvt->data);
78         }
79         ast_string_field_free_memory(pvt);
80
81         ao2_callback(pvt->events, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL);
82
83         ao2_ref(pvt->events, -1);
84 }
85
86 static void *unref_icalendar(void *obj)
87 {
88         struct icalendar_pvt *pvt = obj;
89
90         ao2_ref(pvt, -1);
91         return NULL;
92 }
93
94 static int fetch_response_reader(void *data, const char *block, size_t len)
95 {
96         struct ast_str **response = data;
97         unsigned char *tmp;
98
99         if (!(tmp = ast_malloc(len + 1))) {
100                 return -1;
101         }
102         memcpy(tmp, block, len);
103         tmp[len] = '\0';
104         ast_str_append(response, 0, "%s", tmp);
105         ast_free(tmp);
106
107         return 0;
108 }
109
110 static int auth_credentials(void *userdata, const char *realm, int attempts, char *username, char *secret)
111 {
112         struct icalendar_pvt *pvt = userdata;
113
114         if (attempts > 1) {
115                 ast_log(LOG_WARNING, "Invalid username or password for iCalendar '%s'\n", pvt->owner->name);
116                 return -1;
117         }
118
119         ne_strnzcpy(username, pvt->user, NE_ABUFSIZ);
120         ne_strnzcpy(secret, pvt->secret, NE_ABUFSIZ);
121
122         return 0;
123 }
124
125 static icalcomponent *fetch_icalendar(struct icalendar_pvt *pvt)
126 {
127         int ret;
128         struct ast_str *response;
129         ne_request *req;
130         icalcomponent *comp = NULL;
131
132         if (!pvt) {
133                 ast_log(LOG_ERROR, "There is no private!\n");
134         }
135
136         if (!(response = ast_str_create(512))) {
137                 ast_log(LOG_ERROR, "Could not allocate memory for response.\n");
138                 return NULL;
139         }
140
141         req = ne_request_create(pvt->session, "GET", pvt->uri.path);
142         ne_add_response_body_reader(req, ne_accept_2xx, fetch_response_reader, &response);
143
144         ret = ne_request_dispatch(req);
145         ne_request_destroy(req);
146         if (ret != NE_OK || !ast_str_strlen(response)) {
147                 ast_log(LOG_WARNING, "Unable to retrieve iCalendar '%s' from '%s': %s\n", pvt->owner->name, pvt->url, ne_get_error(pvt->session));
148                 ast_free(response);
149                 return NULL;
150         }
151
152         if (!ast_strlen_zero(ast_str_buffer(response))) {
153                 comp = icalparser_parse_string(ast_str_buffer(response));
154         }
155         ast_free(response);
156
157         return comp;
158 }
159
160 static time_t icalfloat_to_timet(icaltimetype time) 
161 {
162         struct ast_tm tm = {0,};
163         struct timeval tv;
164
165         tm.tm_mday = time.day;
166         tm.tm_mon = time.month - 1;
167         tm.tm_year = time.year - 1900;
168         tm.tm_hour = time.hour;
169         tm.tm_min = time.minute;
170         tm.tm_sec = time.second;
171         tm.tm_isdst = -1;
172         tv = ast_mktime(&tm, NULL);
173
174         return tv.tv_sec;
175 }
176
177 /* span->start & span->end may be dates or floating times which have no timezone,
178  * which would mean that they should apply to the local timezone for all recepients.
179  * For example, if a meeting was set for 1PM-2PM floating time, people in different time
180  * zones would not be scheduled at the same local times.  Dates are often treated as
181  * floating times, so all day events will need to be converted--so we can trust the
182  * span here, and instead will grab the start and end from the component, which will
183  * allow us to test for floating times or dates.
184  */
185
186 static void icalendar_add_event(icalcomponent *comp, struct icaltime_span *span, void *data)
187 {
188         struct icalendar_pvt *pvt = data;
189         struct ast_calendar_event *event;
190         icaltimezone *utc = icaltimezone_get_utc_timezone();
191         icaltimetype start, end, tmp;
192         icalcomponent *valarm;
193         icalproperty *prop;
194         struct icaltriggertype trigger;
195
196         if (!(pvt && pvt->owner)) {
197                 ast_log(LOG_ERROR, "Require a private structure with an ownenr\n");
198                 return;
199         }
200
201         if (!(event = ast_calendar_event_alloc(pvt->owner))) {
202                 ast_log(LOG_ERROR, "Could not allocate an event!\n");
203                 return;
204         }
205
206         start = icalcomponent_get_dtstart(comp);
207         end = icalcomponent_get_dtend(comp);
208
209         event->start = icaltime_get_tzid(start) ? span->start : icalfloat_to_timet(start);
210         event->end = icaltime_get_tzid(end) ? span->end : icalfloat_to_timet(end);
211         event->busy_state = span->is_busy ? AST_CALENDAR_BS_BUSY : AST_CALENDAR_BS_FREE;
212
213         if ((prop = icalcomponent_get_first_property(comp, ICAL_SUMMARY_PROPERTY))) {
214                 ast_string_field_set(event, summary, icalproperty_get_value_as_string(prop));
215         }
216
217         if ((prop = icalcomponent_get_first_property(comp, ICAL_DESCRIPTION_PROPERTY))) {
218                 ast_string_field_set(event, description, icalproperty_get_value_as_string(prop));
219         }
220
221         if ((prop = icalcomponent_get_first_property(comp, ICAL_ORGANIZER_PROPERTY))) {
222                 ast_string_field_set(event, organizer, icalproperty_get_value_as_string(prop));
223         }
224
225         if ((prop = icalcomponent_get_first_property(comp, ICAL_LOCATION_PROPERTY))) {
226                 ast_string_field_set(event, location, icalproperty_get_value_as_string(prop));
227         }
228
229         if ((prop = icalcomponent_get_first_property(comp, ICAL_CATEGORIES_PROPERTY))) {
230                 ast_string_field_set(event, categories, icalproperty_get_value_as_string(prop));
231         }
232
233         if ((prop = icalcomponent_get_first_property(comp, ICAL_PRIORITY_PROPERTY))) {
234                 event->priority = icalvalue_get_integer(icalproperty_get_value(prop));
235         }
236
237         if ((prop = icalcomponent_get_first_property(comp, ICAL_UID_PROPERTY))) {
238                 ast_string_field_set(event, uid, icalproperty_get_value_as_string(prop));
239         } else {
240                 ast_log(LOG_WARNING, "No UID found, but one is required. Generating, but updates may not be acurate\n");
241                 if (!ast_strlen_zero(event->summary)) {
242                         ast_string_field_set(event, uid, event->summary);
243                 } else {
244                         char tmp[100];
245                         snprintf(tmp, sizeof(tmp), "%lu", event->start);
246                         ast_string_field_set(event, uid, tmp);
247                 }
248         }
249
250         /* Get the attendees */
251         for (prop = icalcomponent_get_first_property(comp, ICAL_ATTENDEE_PROPERTY);
252                         prop; prop = icalcomponent_get_next_property(comp, ICAL_ATTENDEE_PROPERTY)) {
253                 struct ast_calendar_attendee *attendee;
254                 const char *data;
255
256                 if (!(attendee = ast_calloc(1, sizeof(*attendee)))) {
257                         event = ast_calendar_unref_event(event);
258                         return;
259                 }
260                 data = icalproperty_get_attendee(prop);
261                 if (!ast_strlen_zero(data)) {
262                         attendee->data = ast_strdup(data);;
263                         AST_LIST_INSERT_TAIL(&event->attendees, attendee, next);
264                 }
265         }
266
267
268         /* Only set values for alarm based on VALARM.  Can be overriden in main/calendar.c by autoreminder
269          * therefore, go ahead and add events even if their is no VALARM or it is malformed
270          * Currently we are only getting the first VALARM and are handling repitition in main/calendar.c from calendar.conf */
271         if (!(valarm = icalcomponent_get_first_component(comp, ICAL_VALARM_COMPONENT))) {
272                 ao2_link(pvt->events, event);
273                 event = ast_calendar_unref_event(event);
274                 return;
275         }
276
277         if (!(prop = icalcomponent_get_first_property(valarm, ICAL_TRIGGER_PROPERTY))) {
278                 ast_log(LOG_WARNING, "VALARM has no TRIGGER, skipping!\n");
279                 ao2_link(pvt->events, event);
280                 event = ast_calendar_unref_event(event);
281                 return;
282         }
283
284         trigger = icalproperty_get_trigger(prop);
285
286         if (icaltriggertype_is_null_trigger(trigger)) {
287                 ast_log(LOG_WARNING, "Bad TRIGGER for VALARM, skipping!\n");
288                 ao2_link(pvt->events, event);
289                 event = ast_calendar_unref_event(event);
290                 return;
291         }
292
293         if (!icaltime_is_null_time(trigger.time)) { /* This is an absolute time */
294                 tmp = icaltime_convert_to_zone(trigger.time, utc);
295                 event->alarm = icaltime_as_timet_with_zone(tmp, utc);
296         } else { /* Offset from either dtstart or dtend */
297                 /* XXX Technically you can check RELATED to see if the event fires from the END of the event
298                  * But, I'm not sure I've ever seen anyone implement it in calendaring software, so I'm ignoring for now */
299                 tmp = icaltime_add(start, trigger.duration);
300                 event->alarm = icaltime_as_timet_with_zone(tmp, utc);
301         }
302
303         ao2_link(pvt->events, event);
304         event = ast_calendar_unref_event(event);
305
306         return;
307 }
308
309  static void icalendar_update_events(struct icalendar_pvt *pvt)
310 {
311         struct icaltimetype start_time, end_time;
312         icalcomponent *iter;
313
314         if (!pvt) {
315                 ast_log(LOG_ERROR, "iCalendar is NULL\n");
316                 return;
317         }
318
319         if (!pvt->owner) {
320                 ast_log(LOG_ERROR, "iCalendar is an orphan!\n");
321                 return;
322         }
323
324         if (!pvt->data) {
325                 ast_log(LOG_ERROR, "The iCalendar has not been parsed!\n");
326                 return;
327         }
328
329         start_time = icaltime_current_time_with_zone(icaltimezone_get_utc_timezone());
330         end_time = icaltime_current_time_with_zone(icaltimezone_get_utc_timezone());
331         end_time.second += pvt->owner->timeframe * 60;
332         icaltime_normalize(end_time);
333
334         for (iter = icalcomponent_get_first_component(pvt->data, ICAL_VEVENT_COMPONENT);
335              iter;
336                  iter = icalcomponent_get_next_component(pvt->data, ICAL_VEVENT_COMPONENT))
337         {
338                 icalcomponent_foreach_recurrence(iter, start_time, end_time, icalendar_add_event, pvt);
339         }
340
341         ast_calendar_merge_events(pvt->owner, pvt->events);
342 }
343
344 static void *ical_load_calendar(void *void_data)
345 {
346         struct icalendar_pvt *pvt;
347         const struct ast_config *cfg;
348         struct ast_variable *v;
349         struct ast_calendar *cal = void_data;
350         ast_mutex_t refreshlock;
351
352         if (!(cal && (cfg = ast_calendar_config_acquire()))) {
353                 ast_log(LOG_ERROR, "You must enable calendar support for res_icalendar to load\n");
354                 return NULL;
355         }
356         if (ao2_trylock(cal)) {
357                 if (cal->unloading) {
358                         ast_log(LOG_WARNING, "Unloading module, load_calendar cancelled.\n");
359                 } else {
360                         ast_log(LOG_WARNING, "Could not lock calendar, aborting!\n");
361                 }
362                 ast_calendar_config_release();
363                 return NULL;
364         }
365
366         if (!(pvt = ao2_alloc(sizeof(*pvt), icalendar_destructor))) {
367                 ast_log(LOG_ERROR, "Could not allocate icalendar_pvt structure for calendar: %s\n", cal->name);
368                 ast_calendar_config_release();
369                 return NULL;
370         }
371
372         pvt->owner = cal;
373
374         if (!(pvt->events = ast_calendar_event_container_alloc())) {
375                 ast_log(LOG_ERROR, "Could not allocate space for fetching events for calendar: %s\n", cal->name);
376                 pvt = unref_icalendar(pvt);
377                 ao2_unlock(cal);
378                 ast_calendar_config_release();
379                 return NULL;
380         }
381
382         if (ast_string_field_init(pvt, 32)) {
383                 ast_log(LOG_ERROR, "Couldn't allocate string field space for calendar: %s\n", cal->name);
384                 pvt = unref_icalendar(pvt);
385                 ao2_unlock(cal);
386                 ast_calendar_config_release();
387                 return NULL;
388         }
389
390         for (v = ast_variable_browse(cfg, cal->name); v; v = v->next) {
391                 if (!strcasecmp(v->name, "url")) {
392                         ast_string_field_set(pvt, url, v->value);
393                 } else if (!strcasecmp(v->name, "user")) {
394                         ast_string_field_set(pvt, user, v->value);
395                 } else if (!strcasecmp(v->name, "secret")) {
396                         ast_string_field_set(pvt, secret, v->value);
397                 }
398         }
399
400         ast_calendar_config_release();
401
402         if (ast_strlen_zero(pvt->url)) {
403                 ast_log(LOG_WARNING, "No URL was specified for iCalendar '%s' - skipping.\n", cal->name);
404                 pvt = unref_icalendar(pvt);
405                 ao2_unlock(cal);
406                 return NULL;
407         }
408
409         if (ne_uri_parse(pvt->url, &pvt->uri) || pvt->uri.host == NULL || pvt->uri.path == NULL) {
410                 ast_log(LOG_WARNING, "Could not parse url '%s' for iCalendar '%s' - skipping.\n", pvt->url, cal->name);
411                 pvt = unref_icalendar(pvt);
412                 ao2_unlock(cal);
413                 return NULL;
414         }
415
416         if (pvt->uri.scheme == NULL) {
417                 pvt->uri.scheme = "http";
418         }
419
420         if (pvt->uri.port == 0) {
421                 pvt->uri.port = ne_uri_defaultport(pvt->uri.scheme);
422         }
423
424         pvt->session = ne_session_create(pvt->uri.scheme, pvt->uri.host, pvt->uri.port);
425         ne_redirect_register(pvt->session);
426         ne_set_server_auth(pvt->session, auth_credentials, pvt);
427         if (!strcasecmp(pvt->uri.scheme, "https")) {
428                 ne_ssl_trust_default_ca(pvt->session);
429         }
430
431         cal->tech_pvt = pvt;
432
433         ast_mutex_init(&refreshlock);
434
435         /* Load it the first time */
436         if (!(pvt->data = fetch_icalendar(pvt))) {
437                 ast_log(LOG_WARNING, "Unable to parse iCalendar '%s'\n", cal->name);
438         }
439
440         icalendar_update_events(pvt);
441
442         ao2_unlock(cal);
443
444         /* The only writing from another thread will be if unload is true */
445         for(;;) {
446                 struct timeval tv = ast_tvnow();
447                 struct timespec ts = {0,};
448
449                 ts.tv_sec = tv.tv_sec + (60 * pvt->owner->refresh);
450
451                 ast_mutex_lock(&refreshlock);
452                 while (!pvt->owner->unloading) {
453                         if (ast_cond_timedwait(&pvt->owner->unload, &refreshlock, &ts) == ETIMEDOUT) {
454                                 break;
455                         }
456                 }
457                 ast_mutex_unlock(&refreshlock);
458
459                 if (pvt->owner->unloading) {
460                         ast_debug(10, "Skipping refresh since we got a shutdown signal\n");
461                         return NULL;
462                 }
463
464                 ast_debug(10, "Refreshing after %d minute timeout\n", pvt->owner->refresh);
465
466                 if (!(pvt->data = fetch_icalendar(pvt))) {
467                         ast_log(LOG_WARNING, "Unable to parse iCalendar '%s'\n", pvt->owner->name);
468                         continue;
469                 }
470
471                 icalendar_update_events(pvt);
472         }
473
474         return NULL;
475 }
476
477 static int load_module(void)
478 {
479         ne_sock_init();
480         if (ast_calendar_register(&ical_tech)) {
481                 ne_sock_exit();
482                 return AST_MODULE_LOAD_DECLINE;
483         }
484
485         return AST_MODULE_LOAD_SUCCESS;
486 }
487
488 static int unload_module(void)
489 {
490         ast_calendar_unregister(&ical_tech);
491         ne_sock_exit();
492         return 0;
493 }
494
495 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Asterisk iCalendar .ics file integration",
496                 .load = load_module,
497                 .unload = unload_module,
498                 .load_pri = AST_MODPRI_DEVSTATE_PLUGIN,
499         );