Debian Codegraph @

res/res_calendar_icalendar.c

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