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