Remove ASTERISK_REGISTER_FILE.
[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 #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/channel.h"
40 #include "asterisk/calendar.h"
41 #include "asterisk/lock.h"
42 #include "asterisk/config.h"
43 #include "asterisk/astobj2.h"
44
45 static void *ical_load_calendar(void *data);
46 static void *unref_icalendar(void *obj);
47
48 static struct ast_calendar_tech ical_tech = {
49         .type = "ical",
50         .module = AST_MODULE,
51         .description = "iCalendar .ics calendars",
52         .load_calendar = ical_load_calendar,
53         .unref_calendar = unref_icalendar,
54 };
55
56 struct icalendar_pvt {
57         AST_DECLARE_STRING_FIELDS(
58                 AST_STRING_FIELD(url);
59                 AST_STRING_FIELD(user);
60                 AST_STRING_FIELD(secret);
61         );
62         struct ast_calendar *owner;
63         ne_uri uri;
64         ne_session *session;
65         icalcomponent *data;
66         struct ao2_container *events;
67 };
68
69 static void icalendar_destructor(void *obj)
70 {
71         struct icalendar_pvt *pvt = obj;
72
73         ast_debug(1, "Destroying pvt for iCalendar %s\n", pvt->owner->name);
74         if (pvt->session) {
75                 ne_session_destroy(pvt->session);
76         }
77         if (pvt->data) {
78                 icalcomponent_free(pvt->data);
79         }
80         ast_string_field_free_memory(pvt);
81
82         ao2_callback(pvt->events, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL);
83
84         ao2_ref(pvt->events, -1);
85 }
86
87 static void *unref_icalendar(void *obj)
88 {
89         struct icalendar_pvt *pvt = obj;
90
91         ao2_ref(pvt, -1);
92         return NULL;
93 }
94
95 static int fetch_response_reader(void *data, const char *block, size_t len)
96 {
97         struct ast_str **response = data;
98         unsigned char *tmp;
99
100         if (!(tmp = ast_malloc(len + 1))) {
101                 return -1;
102         }
103         memcpy(tmp, block, len);
104         tmp[len] = '\0';
105         ast_str_append(response, 0, "%s", tmp);
106         ast_free(tmp);
107
108         return 0;
109 }
110
111 static int auth_credentials(void *userdata, const char *realm, int attempts, char *username, char *secret)
112 {
113         struct icalendar_pvt *pvt = userdata;
114
115         if (attempts > 1) {
116                 ast_log(LOG_WARNING, "Invalid username or password for iCalendar '%s'\n", pvt->owner->name);
117                 return -1;
118         }
119
120         ne_strnzcpy(username, pvt->user, NE_ABUFSIZ);
121         ne_strnzcpy(secret, pvt->secret, NE_ABUFSIZ);
122
123         return 0;
124 }
125
126 static icalcomponent *fetch_icalendar(struct icalendar_pvt *pvt)
127 {
128         int ret;
129         struct ast_str *response;
130         ne_request *req;
131         icalcomponent *comp = NULL;
132
133         if (!pvt) {
134                 ast_log(LOG_ERROR, "There is no private!\n");
135                 return NULL;
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), "%ld", 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                         ast_free(attendee);
265                         continue;
266                 }
267                 attendee->data = ast_strdup(data);;
268                 AST_LIST_INSERT_TAIL(&event->attendees, attendee, next);
269         }
270
271
272         /* Only set values for alarm based on VALARM.  Can be overriden in main/calendar.c by autoreminder
273          * therefore, go ahead and add events even if their is no VALARM or it is malformed
274          * Currently we are only getting the first VALARM and are handling repitition in main/calendar.c from calendar.conf */
275         if (!(valarm = icalcomponent_get_first_component(comp, ICAL_VALARM_COMPONENT))) {
276                 ao2_link(pvt->events, event);
277                 event = ast_calendar_unref_event(event);
278                 return;
279         }
280
281         if (!(prop = icalcomponent_get_first_property(valarm, ICAL_TRIGGER_PROPERTY))) {
282                 ast_log(LOG_WARNING, "VALARM has no TRIGGER, skipping!\n");
283                 ao2_link(pvt->events, event);
284                 event = ast_calendar_unref_event(event);
285                 return;
286         }
287
288         trigger = icalproperty_get_trigger(prop);
289
290         if (icaltriggertype_is_null_trigger(trigger)) {
291                 ast_log(LOG_WARNING, "Bad TRIGGER for VALARM, skipping!\n");
292                 ao2_link(pvt->events, event);
293                 event = ast_calendar_unref_event(event);
294                 return;
295         }
296
297         if (!icaltime_is_null_time(trigger.time)) { /* This is an absolute time */
298                 tmp = icaltime_convert_to_zone(trigger.time, utc);
299                 event->alarm = icaltime_as_timet_with_zone(tmp, utc);
300         } else { /* Offset from either dtstart or dtend */
301                 /* XXX Technically you can check RELATED to see if the event fires from the END of the event
302                  * But, I'm not sure I've ever seen anyone implement it in calendaring software, so I'm ignoring for now */
303                 tmp = icaltime_add(start, trigger.duration);
304                 event->alarm = icaltime_as_timet_with_zone(tmp, icaltime_get_timezone(start));
305         }
306
307         ao2_link(pvt->events, event);
308         event = ast_calendar_unref_event(event);
309
310         return;
311 }
312
313  static void icalendar_update_events(struct icalendar_pvt *pvt)
314 {
315         struct icaltimetype start_time, end_time;
316         icalcomponent *iter;
317
318         if (!pvt) {
319                 ast_log(LOG_ERROR, "iCalendar is NULL\n");
320                 return;
321         }
322
323         if (!pvt->owner) {
324                 ast_log(LOG_ERROR, "iCalendar is an orphan!\n");
325                 return;
326         }
327
328         if (!pvt->data) {
329                 ast_log(LOG_ERROR, "The iCalendar has not been parsed!\n");
330                 return;
331         }
332
333         start_time = icaltime_current_time_with_zone(icaltimezone_get_utc_timezone());
334         end_time = icaltime_current_time_with_zone(icaltimezone_get_utc_timezone());
335         end_time.second += pvt->owner->timeframe * 60;
336         icaltime_normalize(end_time);
337
338         for (iter = icalcomponent_get_first_component(pvt->data, ICAL_VEVENT_COMPONENT);
339              iter;
340                  iter = icalcomponent_get_next_component(pvt->data, ICAL_VEVENT_COMPONENT))
341         {
342                 icalcomponent_foreach_recurrence(iter, start_time, end_time, icalendar_add_event, pvt);
343         }
344
345         ast_calendar_merge_events(pvt->owner, pvt->events);
346 }
347
348 static void *ical_load_calendar(void *void_data)
349 {
350         struct icalendar_pvt *pvt;
351         const struct ast_config *cfg;
352         struct ast_variable *v;
353         struct ast_calendar *cal = void_data;
354         ast_mutex_t refreshlock;
355
356         if (!(cal && (cfg = ast_calendar_config_acquire()))) {
357                 ast_log(LOG_ERROR, "You must enable calendar support for res_icalendar to load\n");
358                 return NULL;
359         }
360         if (ao2_trylock(cal)) {
361                 if (cal->unloading) {
362                         ast_log(LOG_WARNING, "Unloading module, load_calendar cancelled.\n");
363                 } else {
364                         ast_log(LOG_WARNING, "Could not lock calendar, aborting!\n");
365                 }
366                 ast_calendar_config_release();
367                 return NULL;
368         }
369
370         if (!(pvt = ao2_alloc(sizeof(*pvt), icalendar_destructor))) {
371                 ast_log(LOG_ERROR, "Could not allocate icalendar_pvt structure for calendar: %s\n", cal->name);
372                 ast_calendar_config_release();
373                 return NULL;
374         }
375
376         pvt->owner = cal;
377
378         if (!(pvt->events = ast_calendar_event_container_alloc())) {
379                 ast_log(LOG_ERROR, "Could not allocate space for fetching events for calendar: %s\n", cal->name);
380                 pvt = unref_icalendar(pvt);
381                 ao2_unlock(cal);
382                 ast_calendar_config_release();
383                 return NULL;
384         }
385
386         if (ast_string_field_init(pvt, 32)) {
387                 ast_log(LOG_ERROR, "Couldn't allocate string field space for calendar: %s\n", cal->name);
388                 pvt = unref_icalendar(pvt);
389                 ao2_unlock(cal);
390                 ast_calendar_config_release();
391                 return NULL;
392         }
393
394         for (v = ast_variable_browse(cfg, cal->name); v; v = v->next) {
395                 if (!strcasecmp(v->name, "url")) {
396                         ast_string_field_set(pvt, url, v->value);
397                 } else if (!strcasecmp(v->name, "user")) {
398                         ast_string_field_set(pvt, user, v->value);
399                 } else if (!strcasecmp(v->name, "secret")) {
400                         ast_string_field_set(pvt, secret, v->value);
401                 }
402         }
403
404         ast_calendar_config_release();
405
406         if (ast_strlen_zero(pvt->url)) {
407                 ast_log(LOG_WARNING, "No URL was specified for iCalendar '%s' - skipping.\n", cal->name);
408                 pvt = unref_icalendar(pvt);
409                 ao2_unlock(cal);
410                 return NULL;
411         }
412
413         if (ne_uri_parse(pvt->url, &pvt->uri) || pvt->uri.host == NULL || pvt->uri.path == NULL) {
414                 ast_log(LOG_WARNING, "Could not parse url '%s' for iCalendar '%s' - skipping.\n", pvt->url, cal->name);
415                 pvt = unref_icalendar(pvt);
416                 ao2_unlock(cal);
417                 return NULL;
418         }
419
420         if (pvt->uri.scheme == NULL) {
421                 pvt->uri.scheme = "http";
422         }
423
424         if (pvt->uri.port == 0) {
425                 pvt->uri.port = ne_uri_defaultport(pvt->uri.scheme);
426         }
427
428         pvt->session = ne_session_create(pvt->uri.scheme, pvt->uri.host, pvt->uri.port);
429         ne_redirect_register(pvt->session);
430         ne_set_server_auth(pvt->session, auth_credentials, pvt);
431         if (!strcasecmp(pvt->uri.scheme, "https")) {
432                 ne_ssl_trust_default_ca(pvt->session);
433         }
434
435         cal->tech_pvt = pvt;
436
437         ast_mutex_init(&refreshlock);
438
439         /* Load it the first time */
440         if (!(pvt->data = fetch_icalendar(pvt))) {
441                 ast_log(LOG_WARNING, "Unable to parse iCalendar '%s'\n", cal->name);
442         }
443
444         icalendar_update_events(pvt);
445
446         ao2_unlock(cal);
447
448         /* The only writing from another thread will be if unload is true */
449         for(;;) {
450                 struct timeval tv = ast_tvnow();
451                 struct timespec ts = {0,};
452
453                 ts.tv_sec = tv.tv_sec + (60 * pvt->owner->refresh);
454
455                 ast_mutex_lock(&refreshlock);
456                 while (!pvt->owner->unloading) {
457                         if (ast_cond_timedwait(&pvt->owner->unload, &refreshlock, &ts) == ETIMEDOUT) {
458                                 break;
459                         }
460                 }
461                 ast_mutex_unlock(&refreshlock);
462
463                 if (pvt->owner->unloading) {
464                         ast_debug(10, "Skipping refresh since we got a shutdown signal\n");
465                         return NULL;
466                 }
467
468                 ast_debug(10, "Refreshing after %d minute timeout\n", pvt->owner->refresh);
469
470                 /* Free the old calendar data */
471                 if (pvt->data) {
472                         icalcomponent_free(pvt->data);
473                         pvt->data = NULL;
474                 }
475                 if (!(pvt->data = fetch_icalendar(pvt))) {
476                         ast_log(LOG_WARNING, "Unable to parse iCalendar '%s'\n", pvt->owner->name);
477                         continue;
478                 }
479
480                 icalendar_update_events(pvt);
481         }
482
483         return NULL;
484 }
485
486 static int load_module(void)
487 {
488         ne_sock_init();
489         if (ast_calendar_register(&ical_tech)) {
490                 ne_sock_exit();
491                 return AST_MODULE_LOAD_DECLINE;
492         }
493
494         return AST_MODULE_LOAD_SUCCESS;
495 }
496
497 static int unload_module(void)
498 {
499         ast_calendar_unregister(&ical_tech);
500         ne_sock_exit();
501         return 0;
502 }
503
504 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Asterisk iCalendar .ics file integration",
505         .support_level = AST_MODULE_SUPPORT_CORE,
506         .load = load_module,
507         .unload = unload_module,
508         .load_pri = AST_MODPRI_DEVSTATE_PLUGIN,
509 );