res_calendar_caldav.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  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 CalDAV calendars
  20. */
  21. /*** MODULEINFO
  22. <depend>res_calendar</depend>
  23. <depend>neon</depend>
  24. <depend>ical</depend>
  25. <depend>libxml2</depend>
  26. <support_level>extended</support_level>
  27. ***/
  28. #include "asterisk.h"
  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 <libxml/xmlreader.h>
  36. #include "asterisk/module.h"
  37. #include "asterisk/channel.h"
  38. #include "asterisk/calendar.h"
  39. #include "asterisk/lock.h"
  40. #include "asterisk/config.h"
  41. #include "asterisk/astobj2.h"
  42. static void *caldav_load_calendar(void *data);
  43. static void *unref_caldav(void *obj);
  44. static int caldav_write_event(struct ast_calendar_event *event);
  45. static struct ast_calendar_tech caldav_tech = {
  46. .type = "caldav",
  47. .description = "CalDAV calendars",
  48. .module = AST_MODULE,
  49. .load_calendar = caldav_load_calendar,
  50. .unref_calendar = unref_caldav,
  51. .write_event = caldav_write_event,
  52. };
  53. struct caldav_pvt {
  54. AST_DECLARE_STRING_FIELDS(
  55. AST_STRING_FIELD(url);
  56. AST_STRING_FIELD(user);
  57. AST_STRING_FIELD(secret);
  58. );
  59. struct ast_calendar *owner;
  60. ne_uri uri;
  61. ne_session *session;
  62. struct ao2_container *events;
  63. };
  64. static void caldav_destructor(void *obj)
  65. {
  66. struct caldav_pvt *pvt = obj;
  67. ast_debug(1, "Destroying pvt for CalDAV calendar %s\n", pvt->owner->name);
  68. if (pvt->session) {
  69. ne_session_destroy(pvt->session);
  70. }
  71. ne_uri_free(&pvt->uri);
  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_caldav(void *obj)
  77. {
  78. struct caldav_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 caldav_pvt *pvt = userdata;
  98. if (attempts > 1) {
  99. ast_log(LOG_WARNING, "Invalid username or password for CalDAV calendar '%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 int debug_response_handler(void *userdata, ne_request *req, const ne_status *st)
  107. {
  108. if (st->code < 200 || st->code > 299) {
  109. if (st->code == 401) {
  110. ast_debug(1, "Got a 401 from the server but we expect this to happen when authenticating, %d: %s\n", st->code, st->reason_phrase);
  111. } else {
  112. ast_debug(1, "Unexpected response from server, %d: %s\n", st->code, st->reason_phrase);
  113. }
  114. return 0;
  115. }
  116. return 1;
  117. }
  118. static struct ast_str *caldav_request(struct caldav_pvt *pvt, const char *method, struct ast_str *req_body, struct ast_str *subdir, const char *content_type)
  119. {
  120. struct ast_str *response;
  121. ne_request *req;
  122. int ret;
  123. char buf[1000];
  124. if (!pvt) {
  125. ast_log(LOG_ERROR, "There is no private!\n");
  126. return NULL;
  127. }
  128. if (!(response = ast_str_create(512))) {
  129. ast_log(LOG_ERROR, "Could not allocate memory for response.\n");
  130. return NULL;
  131. }
  132. snprintf(buf, sizeof(buf), "%s%s", pvt->uri.path, subdir ? ast_str_buffer(subdir) : "");
  133. req = ne_request_create(pvt->session, method, buf);
  134. ne_add_response_body_reader(req, debug_response_handler, fetch_response_reader, &response);
  135. ne_set_request_body_buffer(req, ast_str_buffer(req_body), ast_str_strlen(req_body));
  136. ne_add_request_header(req, "Content-type", ast_strlen_zero(content_type) ? "text/xml" : content_type);
  137. ne_add_request_header(req, "Depth", "1");
  138. ret = ne_request_dispatch(req);
  139. ne_request_destroy(req);
  140. if (ret != NE_OK) {
  141. ast_log(LOG_WARNING, "Unknown response to CalDAV calendar %s, request %s to %s: %s\n", pvt->owner->name, method, buf, ne_get_error(pvt->session));
  142. ast_free(response);
  143. return NULL;
  144. }
  145. return response;
  146. }
  147. static int caldav_write_event(struct ast_calendar_event *event)
  148. {
  149. struct caldav_pvt *pvt;
  150. struct ast_str *body = NULL, *response = NULL, *subdir = NULL;
  151. icalcomponent *calendar, *icalevent;
  152. icaltimezone *utc = icaltimezone_get_utc_timezone();
  153. int ret = -1;
  154. if (!event) {
  155. ast_log(LOG_WARNING, "No event passed!\n");
  156. return -1;
  157. }
  158. if (!(event->start && event->end)) {
  159. ast_log(LOG_WARNING, "The event must contain a start and an end\n");
  160. return -1;
  161. }
  162. if (!(body = ast_str_create(512)) ||
  163. !(subdir = ast_str_create(32))) {
  164. ast_log(LOG_ERROR, "Could not allocate memory for request!\n");
  165. goto write_cleanup;
  166. }
  167. pvt = event->owner->tech_pvt;
  168. if (ast_strlen_zero(event->uid)) {
  169. unsigned short val[8];
  170. int x;
  171. for (x = 0; x < 8; x++) {
  172. val[x] = ast_random();
  173. }
  174. ast_string_field_build(event, uid, "%04x%04x-%04x-%04x-%04x-%04x%04x%04x",
  175. (unsigned)val[0], (unsigned)val[1], (unsigned)val[2],
  176. (unsigned)val[3], (unsigned)val[4], (unsigned)val[5],
  177. (unsigned)val[6], (unsigned)val[7]);
  178. }
  179. calendar = icalcomponent_new(ICAL_VCALENDAR_COMPONENT);
  180. icalcomponent_add_property(calendar, icalproperty_new_version("2.0"));
  181. icalcomponent_add_property(calendar, icalproperty_new_prodid("-//Digium, Inc.//res_caldav//EN"));
  182. icalevent = icalcomponent_new(ICAL_VEVENT_COMPONENT);
  183. icalcomponent_add_property(icalevent, icalproperty_new_dtstamp(icaltime_current_time_with_zone(utc)));
  184. icalcomponent_add_property(icalevent, icalproperty_new_uid(event->uid));
  185. icalcomponent_add_property(icalevent, icalproperty_new_dtstart(icaltime_from_timet_with_zone(event->start, 0, utc)));
  186. icalcomponent_add_property(icalevent, icalproperty_new_dtend(icaltime_from_timet_with_zone(event->end, 0, utc)));
  187. if (!ast_strlen_zero(event->organizer)) {
  188. icalcomponent_add_property(icalevent, icalproperty_new_organizer(event->organizer));
  189. }
  190. if (!ast_strlen_zero(event->summary)) {
  191. icalcomponent_add_property(icalevent, icalproperty_new_summary(event->summary));
  192. }
  193. if (!ast_strlen_zero(event->description)) {
  194. icalcomponent_add_property(icalevent, icalproperty_new_description(event->description));
  195. }
  196. if (!ast_strlen_zero(event->location)) {
  197. icalcomponent_add_property(icalevent, icalproperty_new_location(event->location));
  198. }
  199. if (!ast_strlen_zero(event->categories)) {
  200. icalcomponent_add_property(icalevent, icalproperty_new_categories(event->categories));
  201. }
  202. if (event->priority > 0) {
  203. icalcomponent_add_property(icalevent, icalproperty_new_priority(event->priority));
  204. }
  205. switch (event->busy_state) {
  206. case AST_CALENDAR_BS_BUSY:
  207. icalcomponent_add_property(icalevent, icalproperty_new_status(ICAL_STATUS_CONFIRMED));
  208. break;
  209. case AST_CALENDAR_BS_BUSY_TENTATIVE:
  210. icalcomponent_add_property(icalevent, icalproperty_new_status(ICAL_STATUS_TENTATIVE));
  211. break;
  212. default:
  213. icalcomponent_add_property(icalevent, icalproperty_new_status(ICAL_STATUS_NONE));
  214. }
  215. icalcomponent_add_component(calendar, icalevent);
  216. ast_str_append(&body, 0, "%s", icalcomponent_as_ical_string(calendar));
  217. ast_str_set(&subdir, 0, "%s%s.ics", pvt->url[strlen(pvt->url) - 1] == '/' ? "" : "/", event->uid);
  218. if ((response = caldav_request(pvt, "PUT", body, subdir, "text/calendar"))) {
  219. ret = 0;
  220. }
  221. write_cleanup:
  222. if (body) {
  223. ast_free(body);
  224. }
  225. if (response) {
  226. ast_free(response);
  227. }
  228. if (subdir) {
  229. ast_free(subdir);
  230. }
  231. return ret;
  232. }
  233. static struct ast_str *caldav_get_events_between(struct caldav_pvt *pvt, time_t start_time, time_t end_time)
  234. {
  235. struct ast_str *body, *response;
  236. icaltimezone *utc = icaltimezone_get_utc_timezone();
  237. icaltimetype start, end;
  238. const char *start_str, *end_str;
  239. if (!(body = ast_str_create(512))) {
  240. ast_log(LOG_ERROR, "Could not allocate memory for body of request!\n");
  241. return NULL;
  242. }
  243. start = icaltime_from_timet_with_zone(start_time, 0, utc);
  244. end = icaltime_from_timet_with_zone(end_time, 0, utc);
  245. start_str = icaltime_as_ical_string(start);
  246. end_str = icaltime_as_ical_string(end);
  247. /* If I was really being efficient, I would store a collection of event URIs and etags,
  248. * first doing a query of just the etag and seeing if anything had changed. If it had,
  249. * then I would do a request for each of the events that had changed, and only bother
  250. * updating those. Oh well. */
  251. ast_str_append(&body, 0,
  252. "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n"
  253. "<C:calendar-query xmlns:D=\"DAV:\" xmlns:C=\"urn:ietf:params:xml:ns:caldav\">\n"
  254. " <D:prop>\n"
  255. " <C:calendar-data>\n"
  256. " <C:expand start=\"%s\" end=\"%s\"/>\n"
  257. " </C:calendar-data>\n"
  258. " </D:prop>\n"
  259. " <C:filter>\n"
  260. " <C:comp-filter name=\"VCALENDAR\">\n"
  261. " <C:comp-filter name=\"VEVENT\">\n"
  262. " <C:time-range start=\"%s\" end=\"%s\"/>\n"
  263. " </C:comp-filter>\n"
  264. " </C:comp-filter>\n"
  265. " </C:filter>\n"
  266. "</C:calendar-query>\n", start_str, end_str, start_str, end_str);
  267. response = caldav_request(pvt, "REPORT", body, NULL, NULL);
  268. ast_free(body);
  269. if (response && !ast_str_strlen(response)) {
  270. ast_free(response);
  271. return NULL;
  272. }
  273. return response;
  274. }
  275. static time_t icalfloat_to_timet(icaltimetype time)
  276. {
  277. struct ast_tm tm = {0,};
  278. struct timeval tv;
  279. tm.tm_mday = time.day;
  280. tm.tm_mon = time.month - 1;
  281. tm.tm_year = time.year - 1900;
  282. tm.tm_hour = time.hour;
  283. tm.tm_min = time.minute;
  284. tm.tm_sec = time.second;
  285. tm.tm_isdst = -1;
  286. tv = ast_mktime(&tm, NULL);
  287. return tv.tv_sec;
  288. }
  289. /* span->start & span->end may be dates or floating times which have no timezone,
  290. * which would mean that they should apply to the local timezone for all recipients.
  291. * For example, if a meeting was set for 1PM-2PM floating time, people in different time
  292. * zones would not be scheduled at the same local times. Dates are often treated as
  293. * floating times, so all day events will need to be converted--so we can trust the
  294. * span here, and instead will grab the start and end from the component, which will
  295. * allow us to test for floating times or dates.
  296. */
  297. static void caldav_add_event(icalcomponent *comp, struct icaltime_span *span, void *data)
  298. {
  299. struct caldav_pvt *pvt = data;
  300. struct ast_calendar_event *event;
  301. icaltimezone *utc = icaltimezone_get_utc_timezone();
  302. icaltimetype start, end, tmp;
  303. icalcomponent *valarm;
  304. icalproperty *prop;
  305. struct icaltriggertype trigger;
  306. if (!(pvt && pvt->owner)) {
  307. ast_log(LOG_ERROR, "Require a private structure with an owner\n");
  308. return;
  309. }
  310. if (!(event = ast_calendar_event_alloc(pvt->owner))) {
  311. ast_log(LOG_ERROR, "Could not allocate an event!\n");
  312. return;
  313. }
  314. start = icalcomponent_get_dtstart(comp);
  315. end = icalcomponent_get_dtend(comp);
  316. event->start = icaltime_get_tzid(start) ? span->start : icalfloat_to_timet(start);
  317. event->end = icaltime_get_tzid(end) ? span->end : icalfloat_to_timet(end);
  318. event->busy_state = span->is_busy ? AST_CALENDAR_BS_BUSY : AST_CALENDAR_BS_FREE;
  319. if ((prop = icalcomponent_get_first_property(comp, ICAL_SUMMARY_PROPERTY))) {
  320. ast_string_field_set(event, summary, icalproperty_get_value_as_string(prop));
  321. }
  322. if ((prop = icalcomponent_get_first_property(comp, ICAL_DESCRIPTION_PROPERTY))) {
  323. ast_string_field_set(event, description, icalproperty_get_value_as_string(prop));
  324. }
  325. if ((prop = icalcomponent_get_first_property(comp, ICAL_ORGANIZER_PROPERTY))) {
  326. ast_string_field_set(event, organizer, icalproperty_get_value_as_string(prop));
  327. }
  328. if ((prop = icalcomponent_get_first_property(comp, ICAL_LOCATION_PROPERTY))) {
  329. ast_string_field_set(event, location, icalproperty_get_value_as_string(prop));
  330. }
  331. if ((prop = icalcomponent_get_first_property(comp, ICAL_CATEGORIES_PROPERTY))) {
  332. ast_string_field_set(event, categories, icalproperty_get_value_as_string(prop));
  333. }
  334. if ((prop = icalcomponent_get_first_property(comp, ICAL_PRIORITY_PROPERTY))) {
  335. event->priority = icalvalue_get_integer(icalproperty_get_value(prop));
  336. }
  337. if ((prop = icalcomponent_get_first_property(comp, ICAL_UID_PROPERTY))) {
  338. ast_string_field_set(event, uid, icalproperty_get_value_as_string(prop));
  339. } else {
  340. ast_log(LOG_WARNING, "No UID found, but one is required. Generating, but updates may not be accurate\n");
  341. if (!ast_strlen_zero(event->summary)) {
  342. ast_string_field_set(event, uid, event->summary);
  343. } else {
  344. char tmp[AST_TIME_T_LEN];
  345. ast_time_t_to_string(event->start, tmp, sizeof(tmp));
  346. ast_string_field_set(event, uid, tmp);
  347. }
  348. }
  349. /* Get the attendees */
  350. for (prop = icalcomponent_get_first_property(comp, ICAL_ATTENDEE_PROPERTY);
  351. prop; prop = icalcomponent_get_next_property(comp, ICAL_ATTENDEE_PROPERTY)) {
  352. struct ast_calendar_attendee *attendee;
  353. const char *data;
  354. if (!(attendee = ast_calloc(1, sizeof(*attendee)))) {
  355. event = ast_calendar_unref_event(event);
  356. return;
  357. }
  358. data = icalproperty_get_attendee(prop);
  359. if (ast_strlen_zero(data)) {
  360. ast_free(attendee);
  361. continue;
  362. }
  363. attendee->data = ast_strdup(data);
  364. AST_LIST_INSERT_TAIL(&event->attendees, attendee, next);
  365. }
  366. /* Only set values for alarm based on VALARM. Can be overriden in main/calendar.c by autoreminder
  367. * therefore, go ahead and add events even if their is no VALARM or it is malformed
  368. * Currently we are only getting the first VALARM and are handling repitition in main/calendar.c from calendar.conf */
  369. if (!(valarm = icalcomponent_get_first_component(comp, ICAL_VALARM_COMPONENT))) {
  370. ao2_link(pvt->events, event);
  371. event = ast_calendar_unref_event(event);
  372. return;
  373. }
  374. if (!(prop = icalcomponent_get_first_property(valarm, ICAL_TRIGGER_PROPERTY))) {
  375. ast_log(LOG_WARNING, "VALARM has no TRIGGER, skipping!\n");
  376. ao2_link(pvt->events, event);
  377. event = ast_calendar_unref_event(event);
  378. return;
  379. }
  380. trigger = icalproperty_get_trigger(prop);
  381. if (icaltriggertype_is_null_trigger(trigger)) {
  382. ast_log(LOG_WARNING, "Bad TRIGGER for VALARM, skipping!\n");
  383. ao2_link(pvt->events, event);
  384. event = ast_calendar_unref_event(event);
  385. return;
  386. }
  387. if (!icaltime_is_null_time(trigger.time)) { /* This is an absolute time */
  388. tmp = icaltime_convert_to_zone(trigger.time, utc);
  389. event->alarm = icaltime_as_timet_with_zone(tmp, utc);
  390. } else { /* Offset from either dtstart or dtend */
  391. /* XXX Technically you can check RELATED to see if the event fires from the END of the event
  392. * But, I'm not sure I've ever seen anyone implement it in calendaring software, so I'm ignoring for now */
  393. tmp = icaltime_add(start, trigger.duration);
  394. event->alarm = icaltime_as_timet_with_zone(tmp, icaltime_get_timezone(start));
  395. }
  396. ao2_link(pvt->events, event);
  397. event = ast_calendar_unref_event(event);
  398. return;
  399. }
  400. struct xmlstate {
  401. int in_caldata;
  402. struct caldav_pvt *pvt;
  403. struct ast_str *cdata;
  404. time_t start;
  405. time_t end;
  406. };
  407. static const xmlChar *caldav_node_localname = BAD_CAST "calendar-data";
  408. static const xmlChar *caldav_node_nsuri = BAD_CAST "urn:ietf:params:xml:ns:caldav";
  409. static void handle_start_element(xmlTextReaderPtr reader, struct xmlstate *state)
  410. {
  411. const xmlChar *localname = xmlTextReaderConstLocalName(reader);
  412. const xmlChar *uri = xmlTextReaderConstNamespaceUri(reader);
  413. if (!xmlStrEqual(localname, caldav_node_localname) || !xmlStrEqual(uri, caldav_node_nsuri)) {
  414. return;
  415. }
  416. state->in_caldata = 1;
  417. ast_str_reset(state->cdata);
  418. }
  419. static void handle_end_element(xmlTextReaderPtr reader, struct xmlstate *state)
  420. {
  421. struct icaltimetype start, end;
  422. icaltimezone *utc = icaltimezone_get_utc_timezone();
  423. icalcomponent *iter;
  424. icalcomponent *comp;
  425. const xmlChar *localname = xmlTextReaderConstLocalName(reader);
  426. const xmlChar *uri = xmlTextReaderConstNamespaceUri(reader);
  427. if (!xmlStrEqual(localname, caldav_node_localname) || !xmlStrEqual(uri, caldav_node_nsuri)) {
  428. return;
  429. }
  430. state->in_caldata = 0;
  431. if (!(state->cdata && ast_str_strlen(state->cdata))) {
  432. return;
  433. }
  434. /* XXX Parse the calendar blurb for recurrence events in the time range,
  435. * create an event, and add it to pvt->events */
  436. start = icaltime_from_timet_with_zone(state->start, 0, utc);
  437. end = icaltime_from_timet_with_zone(state->end, 0, utc);
  438. comp = icalparser_parse_string(ast_str_buffer(state->cdata));
  439. for (iter = icalcomponent_get_first_component(comp, ICAL_VEVENT_COMPONENT);
  440. iter;
  441. iter = icalcomponent_get_next_component(comp, ICAL_VEVENT_COMPONENT))
  442. {
  443. icalcomponent_foreach_recurrence(iter, start, end, caldav_add_event, state->pvt);
  444. }
  445. icalcomponent_free(comp);
  446. }
  447. static void handle_characters(xmlTextReaderPtr reader, struct xmlstate *state)
  448. {
  449. xmlChar *text;
  450. if (!state->in_caldata) {
  451. return;
  452. }
  453. text = xmlTextReaderValue(reader);
  454. if (text) {
  455. ast_str_append(&state->cdata, 0, "%s", text);
  456. xmlFree(text);
  457. }
  458. }
  459. static void parse_error_handler(void *arg, const char *msg,
  460. xmlParserSeverities severity, xmlTextReaderLocatorPtr locator)
  461. {
  462. switch (severity) {
  463. case XML_PARSER_SEVERITY_VALIDITY_WARNING:
  464. case XML_PARSER_SEVERITY_WARNING:
  465. ast_log(LOG_WARNING, "While parsing CalDAV response at line %d: %s\n",
  466. xmlTextReaderLocatorLineNumber(locator),
  467. msg);
  468. break;
  469. case XML_PARSER_SEVERITY_VALIDITY_ERROR:
  470. case XML_PARSER_SEVERITY_ERROR:
  471. default:
  472. ast_log(LOG_ERROR, "While parsing CalDAV response at line %d: %s\n",
  473. xmlTextReaderLocatorLineNumber(locator),
  474. msg);
  475. break;
  476. }
  477. }
  478. static int update_caldav(struct caldav_pvt *pvt)
  479. {
  480. struct timeval now = ast_tvnow();
  481. time_t start, end;
  482. struct ast_str *response;
  483. xmlTextReaderPtr reader;
  484. struct xmlstate state = {
  485. .in_caldata = 0,
  486. .pvt = pvt
  487. };
  488. start = now.tv_sec;
  489. end = now.tv_sec + 60 * pvt->owner->timeframe;
  490. if (!(response = caldav_get_events_between(pvt, start, end))) {
  491. return -1;
  492. }
  493. if (!(state.cdata = ast_str_create(512))) {
  494. ast_free(response);
  495. return -1;
  496. }
  497. state.start = start;
  498. state.end = end;
  499. reader = xmlReaderForMemory(
  500. ast_str_buffer(response),
  501. ast_str_strlen(response),
  502. NULL,
  503. NULL,
  504. 0);
  505. if (reader) {
  506. int res;
  507. xmlTextReaderSetErrorHandler(reader, parse_error_handler, NULL);
  508. res = xmlTextReaderRead(reader);
  509. while (res == 1) {
  510. int node_type = xmlTextReaderNodeType(reader);
  511. switch (node_type) {
  512. case XML_READER_TYPE_ELEMENT:
  513. handle_start_element(reader, &state);
  514. break;
  515. case XML_READER_TYPE_END_ELEMENT:
  516. handle_end_element(reader, &state);
  517. break;
  518. case XML_READER_TYPE_TEXT:
  519. case XML_READER_TYPE_CDATA:
  520. handle_characters(reader, &state);
  521. break;
  522. default:
  523. break;
  524. }
  525. res = xmlTextReaderRead(reader);
  526. }
  527. xmlFreeTextReader(reader);
  528. }
  529. ast_calendar_merge_events(pvt->owner, pvt->events);
  530. ast_free(response);
  531. ast_free(state.cdata);
  532. return 0;
  533. }
  534. static int verify_cert(void *userdata, int failures, const ne_ssl_certificate *cert)
  535. {
  536. /* Verify all certs */
  537. return 0;
  538. }
  539. static void *caldav_load_calendar(void *void_data)
  540. {
  541. struct caldav_pvt *pvt;
  542. const struct ast_config *cfg;
  543. struct ast_variable *v;
  544. struct ast_calendar *cal = void_data;
  545. ast_mutex_t refreshlock;
  546. if (!(cal && (cfg = ast_calendar_config_acquire()))) {
  547. ast_log(LOG_ERROR, "You must enable calendar support for res_caldav to load\n");
  548. return NULL;
  549. }
  550. if (ao2_trylock(cal)) {
  551. if (cal->unloading) {
  552. ast_log(LOG_WARNING, "Unloading module, load_calendar cancelled.\n");
  553. } else {
  554. ast_log(LOG_WARNING, "Could not lock calendar, aborting!\n");
  555. }
  556. ast_calendar_config_release();
  557. return NULL;
  558. }
  559. if (!(pvt = ao2_alloc(sizeof(*pvt), caldav_destructor))) {
  560. ast_log(LOG_ERROR, "Could not allocate caldav_pvt structure for calendar: %s\n", cal->name);
  561. ast_calendar_config_release();
  562. return NULL;
  563. }
  564. pvt->owner = cal;
  565. if (!(pvt->events = ast_calendar_event_container_alloc())) {
  566. ast_log(LOG_ERROR, "Could not allocate space for fetching events for calendar: %s\n", cal->name);
  567. pvt = unref_caldav(pvt);
  568. ao2_unlock(cal);
  569. ast_calendar_config_release();
  570. return NULL;
  571. }
  572. if (ast_string_field_init(pvt, 32)) {
  573. ast_log(LOG_ERROR, "Couldn't allocate string field space for calendar: %s\n", cal->name);
  574. pvt = unref_caldav(pvt);
  575. ao2_unlock(cal);
  576. ast_calendar_config_release();
  577. return NULL;
  578. }
  579. for (v = ast_variable_browse(cfg, cal->name); v; v = v->next) {
  580. if (!strcasecmp(v->name, "url")) {
  581. ast_string_field_set(pvt, url, v->value);
  582. } else if (!strcasecmp(v->name, "user")) {
  583. ast_string_field_set(pvt, user, v->value);
  584. } else if (!strcasecmp(v->name, "secret")) {
  585. ast_string_field_set(pvt, secret, v->value);
  586. }
  587. }
  588. ast_calendar_config_release();
  589. if (ast_strlen_zero(pvt->url)) {
  590. ast_log(LOG_WARNING, "No URL was specified for CalDAV calendar '%s' - skipping.\n", cal->name);
  591. pvt = unref_caldav(pvt);
  592. ao2_unlock(cal);
  593. return NULL;
  594. }
  595. if (ne_uri_parse(pvt->url, &pvt->uri) || pvt->uri.host == NULL || pvt->uri.path == NULL) {
  596. ast_log(LOG_WARNING, "Could not parse url '%s' for CalDAV calendar '%s' - skipping.\n", pvt->url, cal->name);
  597. pvt = unref_caldav(pvt);
  598. ao2_unlock(cal);
  599. return NULL;
  600. }
  601. if (pvt->uri.scheme == NULL) {
  602. pvt->uri.scheme = "http";
  603. }
  604. if (pvt->uri.port == 0) {
  605. pvt->uri.port = ne_uri_defaultport(pvt->uri.scheme);
  606. }
  607. pvt->session = ne_session_create(pvt->uri.scheme, pvt->uri.host, pvt->uri.port);
  608. ne_redirect_register(pvt->session);
  609. ne_set_server_auth(pvt->session, auth_credentials, pvt);
  610. if (!strcasecmp(pvt->uri.scheme, "https")) {
  611. ne_ssl_trust_default_ca(pvt->session);
  612. ne_ssl_set_verify(pvt->session, verify_cert, NULL);
  613. }
  614. cal->tech_pvt = pvt;
  615. ast_mutex_init(&refreshlock);
  616. /* Load it the first time */
  617. update_caldav(pvt);
  618. ao2_unlock(cal);
  619. /* The only writing from another thread will be if unload is true */
  620. for (;;) {
  621. struct timeval tv = ast_tvnow();
  622. struct timespec ts = {0,};
  623. ts.tv_sec = tv.tv_sec + (60 * pvt->owner->refresh);
  624. ast_mutex_lock(&refreshlock);
  625. while (!pvt->owner->unloading) {
  626. if (ast_cond_timedwait(&pvt->owner->unload, &refreshlock, &ts) == ETIMEDOUT) {
  627. break;
  628. }
  629. }
  630. ast_mutex_unlock(&refreshlock);
  631. if (pvt->owner->unloading) {
  632. ast_debug(10, "Skipping refresh since we got a shutdown signal\n");
  633. return NULL;
  634. }
  635. ast_debug(10, "Refreshing after %d minute timeout\n", pvt->owner->refresh);
  636. update_caldav(pvt);
  637. }
  638. return NULL;
  639. }
  640. static int load_module(void)
  641. {
  642. ne_sock_init();
  643. if (ast_calendar_register(&caldav_tech)) {
  644. ne_sock_exit();
  645. return AST_MODULE_LOAD_DECLINE;
  646. }
  647. return AST_MODULE_LOAD_SUCCESS;
  648. }
  649. static int unload_module(void)
  650. {
  651. ast_calendar_unregister(&caldav_tech);
  652. ne_sock_exit();
  653. return 0;
  654. }
  655. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Asterisk CalDAV Calendar Integration",
  656. .support_level = AST_MODULE_SUPPORT_EXTENDED,
  657. .load = load_module,
  658. .unload = unload_module,
  659. .load_pri = AST_MODPRI_DEVSTATE_PLUGIN,
  660. .requires = "res_calendar",
  661. );