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