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