res_calendar_icalendar.c 14 KB

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