res_calendar_caldav.c 22 KB

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