More 'static' qualifiers on module global variables.
[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 int cb_true(void *user_data, void *arg, int flags)
68 {
69         return CMP_MATCH;
70 }
71
72 static void icalendar_destructor(void *obj)
73 {
74         struct icalendar_pvt *pvt = obj;
75
76         ast_debug(1, "Destroying pvt for iCalendar %s\n", pvt->owner->name);
77         if (pvt->session) {
78                 ne_session_destroy(pvt->session);
79         }
80         if (pvt->data) {
81                 icalcomponent_free(pvt->data);
82         }
83         ast_string_field_free_memory(pvt);
84
85         ao2_callback(pvt->events, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, cb_true, NULL);
86
87         ao2_ref(pvt->events, -1);
88 }
89
90 static void *unref_icalendar(void *obj)
91 {
92         struct icalendar_pvt *pvt = obj;
93
94         ao2_ref(pvt, -1);
95         return NULL;
96 }
97
98 static int fetch_response_reader(void *data, const char *block, size_t len)
99 {
100         struct ast_str **response = data;
101         unsigned char *tmp;
102
103         if (!(tmp = ast_malloc(len + 1))) {
104                 return -1;
105         }
106         memcpy(tmp, block, len);
107         tmp[len] = '\0';
108         ast_str_append(response, 0, "%s", tmp);
109         ast_free(tmp);
110
111         return 0;
112 }
113
114 static int auth_credentials(void *userdata, const char *realm, int attempts, char *username, char *secret)
115 {
116         struct icalendar_pvt *pvt = userdata;
117
118         if (attempts > 1) {
119                 ast_log(LOG_WARNING, "Invalid username or password for iCalendar '%s'\n", pvt->owner->name);
120                 return -1;
121         }
122
123         ne_strnzcpy(username, pvt->user, NE_ABUFSIZ);
124         ne_strnzcpy(secret, pvt->secret, NE_ABUFSIZ);
125
126         return 0;
127 }
128
129 static icalcomponent *fetch_icalendar(struct icalendar_pvt *pvt)
130 {
131         int ret;
132         struct ast_str *response;
133         ne_request *req;
134         icalcomponent *comp = NULL;
135
136         if (!pvt) {
137                 ast_log(LOG_ERROR, "There is no private!\n");
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         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 void icalendar_add_event(icalcomponent *comp, struct icaltime_span *span, void *data)
164 {
165         struct icalendar_pvt *pvt = data;
166         struct ast_calendar_event *event;
167         icaltimezone *utc = icaltimezone_get_utc_timezone();
168         icaltimetype start, end, tmp;
169         icalcomponent *valarm;
170         icalproperty *prop;
171         struct icaltriggertype trigger;
172
173         if (!(pvt && pvt->owner)) {
174                 ast_log(LOG_ERROR, "Require a private structure with an ownenr\n");
175                 return;
176         }
177
178         if (!(event = ast_calendar_event_alloc(pvt->owner))) {
179                 ast_log(LOG_ERROR, "Could not allocate an event!\n");
180                 return;
181         }
182
183         start = icaltime_from_timet_with_zone(span->start, 0, utc);
184         end = icaltime_from_timet_with_zone(span->end, 0, utc);
185         event->start = span->start;
186         event->end = span->end;
187
188         switch(icalcomponent_get_status(comp)) {
189         case ICAL_STATUS_CONFIRMED:
190                 event->busy_state = AST_CALENDAR_BS_BUSY;
191                 break;
192
193         case ICAL_STATUS_TENTATIVE:
194                 event->busy_state = AST_CALENDAR_BS_BUSY_TENTATIVE;
195                 break;
196
197         default:
198                 event->busy_state = AST_CALENDAR_BS_FREE;
199         }
200
201         if ((prop = icalcomponent_get_first_property(comp, ICAL_SUMMARY_PROPERTY))) {
202                 ast_string_field_set(event, summary, icalproperty_get_value_as_string(prop));
203         }
204
205         if ((prop = icalcomponent_get_first_property(comp, ICAL_DESCRIPTION_PROPERTY))) {
206                 ast_string_field_set(event, description, icalproperty_get_value_as_string(prop));
207         }
208
209         if ((prop = icalcomponent_get_first_property(comp, ICAL_ORGANIZER_PROPERTY))) {
210                 ast_string_field_set(event, organizer, icalproperty_get_value_as_string(prop));
211         }
212
213         if ((prop = icalcomponent_get_first_property(comp, ICAL_LOCATION_PROPERTY))) {
214                 ast_string_field_set(event, location, icalproperty_get_value_as_string(prop));
215         }
216
217         if ((prop = icalcomponent_get_first_property(comp, ICAL_UID_PROPERTY))) {
218                 ast_string_field_set(event, uid, icalproperty_get_value_as_string(prop));
219         } else {
220                 ast_log(LOG_WARNING, "No UID found, but one is required. Generating, but updates may not be acurate\n");
221                 if (!ast_strlen_zero(event->summary)) {
222                         ast_string_field_set(event, uid, event->summary);
223                 } else {
224                         char tmp[100];
225                         snprintf(tmp, sizeof(tmp), "%lu", event->start);
226                         ast_string_field_set(event, uid, tmp);
227                 }
228         }
229
230         /* Get the attendees */
231         for (prop = icalcomponent_get_first_property(comp, ICAL_ATTENDEE_PROPERTY);
232                         prop; prop = icalcomponent_get_next_property(comp, ICAL_ATTENDEE_PROPERTY)) {
233                 struct ast_calendar_attendee *attendee;
234                 const char *data;
235
236                 if (!(attendee = ast_calloc(1, sizeof(*attendee)))) {
237                         event = ast_calendar_unref_event(event);
238                         return;
239                 }
240                 data = icalproperty_get_attendee(prop);
241                 if (!ast_strlen_zero(data)) {
242                         attendee->data = ast_strdup(data);;
243                         AST_LIST_INSERT_TAIL(&event->attendees, attendee, next);
244                 }
245         }
246
247
248         /* Only set values for alarm based on VALARM.  Can be overriden in main/calendar.c by autoreminder
249          * therefore, go ahead and add events even if their is no VALARM or it is malformed
250          * Currently we are only getting the first VALARM and are handling repitition in main/calendar.c from calendar.conf */
251         if (!(valarm = icalcomponent_get_first_component(comp, ICAL_VALARM_COMPONENT))) {
252                 ao2_link(pvt->events, event);
253                 event = ast_calendar_unref_event(event);
254                 return;
255         }
256
257         if (!(prop = icalcomponent_get_first_property(valarm, ICAL_TRIGGER_PROPERTY))) {
258                 ast_log(LOG_WARNING, "VALARM has no TRIGGER, skipping!\n");
259                 ao2_link(pvt->events, event);
260                 event = ast_calendar_unref_event(event);
261                 return;
262         }
263
264         trigger = icalproperty_get_trigger(prop);
265
266         if (icaltriggertype_is_null_trigger(trigger)) {
267                 ast_log(LOG_WARNING, "Bad TRIGGER for VALARM, skipping!\n");
268                 ao2_link(pvt->events, event);
269                 event = ast_calendar_unref_event(event);
270                 return;
271         }
272
273         if (!icaltime_is_null_time(trigger.time)) { /* This is an absolute time */
274                 tmp = icaltime_convert_to_zone(trigger.time, utc);
275                 event->alarm = icaltime_as_timet_with_zone(tmp, utc);
276         } else { /* Offset from either dtstart or dtend */
277                 /* XXX Technically you can check RELATED to see if the event fires from the END of the event
278                  * But, I'm not sure I've ever seen anyone implement it in calendaring software, so I'm ignoring for now */
279                 tmp = icaltime_add(start, trigger.duration);
280                 event->alarm = icaltime_as_timet_with_zone(tmp, utc);
281         }
282
283         ao2_link(pvt->events, event);
284         event = ast_calendar_unref_event(event);
285
286         return;
287 }
288
289  static void icalendar_update_events(struct icalendar_pvt *pvt)
290 {
291         struct icaltimetype start_time, end_time;
292         icalcomponent *iter;
293
294         if (!pvt) {
295                 ast_log(LOG_ERROR, "iCalendar is NULL\n");
296                 return;
297         }
298
299         if (!pvt->owner) {
300                 ast_log(LOG_ERROR, "iCalendar is an orphan!\n");
301                 return;
302         }
303
304         if (!pvt->data) {
305                 ast_log(LOG_ERROR, "The iCalendar has not been parsed!\n");
306                 return;
307         }
308
309         start_time = icaltime_current_time_with_zone(icaltimezone_get_utc_timezone());
310         end_time = icaltime_current_time_with_zone(icaltimezone_get_utc_timezone());
311         end_time.second += pvt->owner->timeframe * 60;
312         icaltime_normalize(end_time);
313
314         for (iter = icalcomponent_get_first_component(pvt->data, ICAL_VEVENT_COMPONENT);
315              iter;
316                  iter = icalcomponent_get_next_component(pvt->data, ICAL_VEVENT_COMPONENT))
317         {
318                 icalcomponent_foreach_recurrence(iter, start_time, end_time, icalendar_add_event, pvt);
319         }
320
321         ast_calendar_merge_events(pvt->owner, pvt->events);
322 }
323
324 static void *ical_load_calendar(void *void_data)
325 {
326         struct icalendar_pvt *pvt;
327         struct ast_variable *v;
328         struct ast_calendar *cal = void_data;
329         ast_mutex_t refreshlock;
330
331         if (!(cal && ast_calendar_config)) {
332                 ast_log(LOG_ERROR, "You must enable calendar support for res_icalendar to load\n");
333                 return NULL;
334         }
335         if (ao2_trylock(cal)) {
336                 if (cal->unloading) {
337                         ast_log(LOG_WARNING, "Unloading module, load_calendar cancelled.\n");
338                 } else {
339                         ast_log(LOG_WARNING, "Could not lock calendar, aborting!\n");
340                 }
341                 return NULL;
342         }
343
344         if (!(pvt = ao2_alloc(sizeof(*pvt), icalendar_destructor))) {
345                 ast_log(LOG_ERROR, "Could not allocate icalendar_pvt structure for calendar: %s\n", cal->name);
346                 return NULL;
347         }
348
349         pvt->owner = cal;
350
351         if (!(pvt->events = ast_calendar_event_container_alloc())) {
352                 ast_log(LOG_ERROR, "Could not allocate space for fetching events for calendar: %s\n", cal->name);
353                 pvt = unref_icalendar(pvt);
354                 ao2_unlock(cal);
355                 return NULL;
356         }
357
358         if (ast_string_field_init(pvt, 32)) {
359                 ast_log(LOG_ERROR, "Couldn't allocate string field space for calendar: %s\n", cal->name);
360                 pvt = unref_icalendar(pvt);
361                 ao2_unlock(cal);
362                 return NULL;
363         }
364
365         for (v = ast_variable_browse(ast_calendar_config, cal->name); v; v = v->next) {
366                 if (!strcasecmp(v->name, "url")) {
367                         ast_string_field_set(pvt, url, v->value);
368                 } else if (!strcasecmp(v->name, "user")) {
369                         ast_string_field_set(pvt, user, v->value);
370                 } else if (!strcasecmp(v->name, "secret")) {
371                         ast_string_field_set(pvt, secret, v->value);
372                 }
373         }
374
375         if (ast_strlen_zero(pvt->url)) {
376                 ast_log(LOG_WARNING, "No URL was specified for iCalendar '%s' - skipping.\n", cal->name);
377                 pvt = unref_icalendar(pvt);
378                 ao2_unlock(cal);
379                 return NULL;
380         }
381
382         if (ne_uri_parse(pvt->url, &pvt->uri) || pvt->uri.host == NULL || pvt->uri.path == NULL) {
383                 ast_log(LOG_WARNING, "Could not parse url '%s' for iCalendar '%s' - skipping.\n", pvt->url, cal->name);
384                 pvt = unref_icalendar(pvt);
385                 ao2_unlock(cal);
386                 return NULL;
387         }
388
389         if (pvt->uri.scheme == NULL) {
390                 pvt->uri.scheme = "http";
391         }
392
393         if (pvt->uri.port == 0) {
394                 pvt->uri.port = ne_uri_defaultport(pvt->uri.scheme);
395         }
396
397         pvt->session = ne_session_create(pvt->uri.scheme, pvt->uri.host, pvt->uri.port);
398         ne_set_server_auth(pvt->session, auth_credentials, pvt);
399         if (!strncasecmp(pvt->uri.scheme, "https", sizeof(pvt->uri.scheme))) {
400                 ne_ssl_trust_default_ca(pvt->session);
401         }
402
403         cal->tech_pvt = pvt;
404
405         ast_mutex_init(&refreshlock);
406
407         /* Load it the first time */
408         if (!(pvt->data = fetch_icalendar(pvt))) {
409                 ast_log(LOG_WARNING, "Unable to parse iCalendar '%s'\n", cal->name);
410         }
411
412         icalendar_update_events(pvt);
413
414         ao2_unlock(cal);
415
416         /* The only writing from another thread will be if unload is true */
417         for(;;) {
418                 struct timeval tv = ast_tvnow();
419                 struct timespec ts = {0,};
420
421                 ts.tv_sec = tv.tv_sec + (60 * pvt->owner->refresh);
422
423                 ast_mutex_lock(&refreshlock);
424                 while (!pvt->owner->unloading) {
425                         if (ast_cond_timedwait(&pvt->owner->unload, &refreshlock, &ts) == ETIMEDOUT) {
426                                 break;
427                         }
428                 }
429                 ast_mutex_unlock(&refreshlock);
430
431                 if (pvt->owner->unloading) {
432                         ast_debug(10, "Skipping refresh since we got a shutdown signal\n");
433                         return NULL;
434                 }
435
436                 ast_debug(10, "Refreshing after %d minute timeout\n", pvt->owner->refresh);
437
438                 if (!(pvt->data = fetch_icalendar(pvt))) {
439                         ast_log(LOG_WARNING, "Unable to parse iCalendar '%s'\n", pvt->owner->name);
440                         continue;
441                 }
442
443                 icalendar_update_events(pvt);
444         }
445
446         return NULL;
447 }
448
449 static int load_module(void)
450 {
451         ne_sock_init();
452         if (ast_calendar_register(&ical_tech)) {
453                 ne_sock_exit();
454                 return AST_MODULE_LOAD_DECLINE;
455         }
456
457         return AST_MODULE_LOAD_SUCCESS;
458 }
459
460 static int unload_module(void)
461 {
462         ast_calendar_unregister(&ical_tech);
463         ne_sock_exit();
464         return 0;
465 }
466
467 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Asterisk iCalendar .ics file integration",
468                 .load = load_module,
469                 .unload = unload_module,
470         );