res_calendar_icalendar.c 14 KB

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