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