res_calendar_caldav.c 21 KB

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