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