res_calendar_icalendar.c 14 KB

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