res_calendar_icalendar.c 16 KB

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