res_calendar_ews.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 2008 - 2009, Digium, Inc.
  5. *
  6. * Jan Kalab <pitlicek@gmail.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 MS Exchange Web Service calendars
  20. */
  21. /*** MODULEINFO
  22. <depend>neon29</depend>
  23. <support_level>core</support_level>
  24. ***/
  25. #include "asterisk.h"
  26. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  27. #include <ne_request.h>
  28. #include <ne_session.h>
  29. #include <ne_uri.h>
  30. #include <ne_socket.h>
  31. #include <ne_auth.h>
  32. #include <ne_xml.h>
  33. #include <ne_xmlreq.h>
  34. #include <ne_utils.h>
  35. #include <ne_redirect.h>
  36. #include "asterisk/module.h"
  37. #include "asterisk/calendar.h"
  38. #include "asterisk/lock.h"
  39. #include "asterisk/config.h"
  40. #include "asterisk/astobj2.h"
  41. static void *ewscal_load_calendar(void *data);
  42. static void *unref_ewscal(void *obj);
  43. static int ewscal_write_event(struct ast_calendar_event *event);
  44. static struct ast_calendar_tech ewscal_tech = {
  45. .type = "ews",
  46. .description = "MS Exchange Web Service calendars",
  47. .module = AST_MODULE,
  48. .load_calendar = ewscal_load_calendar,
  49. .unref_calendar = unref_ewscal,
  50. .write_event = ewscal_write_event,
  51. };
  52. enum xml_op {
  53. XML_OP_FIND = 100,
  54. XML_OP_GET,
  55. XML_OP_CREATE,
  56. };
  57. struct calendar_id {
  58. struct ast_str *id;
  59. AST_LIST_ENTRY(calendar_id) next;
  60. };
  61. struct xml_context {
  62. ne_xml_parser *parser;
  63. struct ast_str *cdata;
  64. struct ast_calendar_event *event;
  65. enum xml_op op;
  66. struct ewscal_pvt *pvt;
  67. AST_LIST_HEAD_NOLOCK(ids, calendar_id) ids;
  68. };
  69. /* Important states of XML parsing */
  70. enum {
  71. XML_EVENT_CALENDAR_ITEM = 9,
  72. XML_EVENT_NAME = 10,
  73. XML_EVENT_DESCRIPTION,
  74. XML_EVENT_START,
  75. XML_EVENT_END,
  76. XML_EVENT_BUSY,
  77. XML_EVENT_ORGANIZER,
  78. XML_EVENT_LOCATION,
  79. XML_EVENT_ATTENDEE_LIST,
  80. XML_EVENT_ATTENDEE,
  81. XML_EVENT_MAILBOX,
  82. XML_EVENT_EMAIL_ADDRESS,
  83. XML_EVENT_CATEGORIES,
  84. XML_EVENT_CATEGORY,
  85. XML_EVENT_IMPORTANCE,
  86. };
  87. struct ewscal_pvt {
  88. AST_DECLARE_STRING_FIELDS(
  89. AST_STRING_FIELD(url);
  90. AST_STRING_FIELD(user);
  91. AST_STRING_FIELD(secret);
  92. );
  93. struct ast_calendar *owner;
  94. ne_uri uri;
  95. ne_session *session;
  96. struct ao2_container *events;
  97. unsigned int items;
  98. };
  99. static void ewscal_destructor(void *obj)
  100. {
  101. struct ewscal_pvt *pvt = obj;
  102. ast_debug(1, "Destroying pvt for Exchange Web Service calendar %s\n", "pvt->owner->name");
  103. if (pvt->session) {
  104. ne_session_destroy(pvt->session);
  105. }
  106. ast_string_field_free_memory(pvt);
  107. ao2_callback(pvt->events, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL);
  108. ao2_ref(pvt->events, -1);
  109. }
  110. static void *unref_ewscal(void *obj)
  111. {
  112. struct ewscal_pvt *pvt = obj;
  113. ast_debug(5, "EWS: unref_ewscal()\n");
  114. ao2_ref(pvt, -1);
  115. return NULL;
  116. }
  117. static int auth_credentials(void *userdata, const char *realm, int attempts, char *username, char *secret)
  118. {
  119. struct ewscal_pvt *pvt = userdata;
  120. if (attempts > 1) {
  121. ast_log(LOG_WARNING, "Invalid username or password for Exchange Web Service calendar '%s'\n", pvt->owner->name);
  122. return -1;
  123. }
  124. ne_strnzcpy(username, pvt->user, NE_ABUFSIZ);
  125. ne_strnzcpy(secret, pvt->secret, NE_ABUFSIZ);
  126. return 0;
  127. }
  128. static int ssl_verify(void *userdata, int failures, const ne_ssl_certificate *cert)
  129. {
  130. struct ewscal_pvt *pvt = userdata;
  131. if (failures & NE_SSL_UNTRUSTED) {
  132. ast_log(LOG_WARNING, "Untrusted SSL certificate for calendar %s!\n", pvt->owner->name);
  133. return 0;
  134. }
  135. return 1; /* NE_SSL_NOTYETVALID, NE_SSL_EXPIRED, NE_SSL_IDMISMATCH */
  136. }
  137. static time_t mstime_to_time_t(char *mstime)
  138. {
  139. struct ast_tm tm;
  140. struct timeval tv;
  141. if (ast_strptime(mstime, "%FT%TZ", &tm)) {
  142. tv = ast_mktime(&tm, "UTC");
  143. return tv.tv_sec;
  144. }
  145. return 0;
  146. }
  147. static int startelm(void *userdata, int parent, const char *nspace, const char *name, const char **atts)
  148. {
  149. struct xml_context *ctx = userdata;
  150. ast_debug(5, "EWS: XML: Start: %s\n", name);
  151. if (ctx->op == XML_OP_CREATE) {
  152. return NE_XML_DECLINE;
  153. }
  154. /* Nodes needed for traversing until CalendarItem is found */
  155. if (!strcmp(name, "Envelope") ||
  156. (!strcmp(name, "Body") && parent != XML_EVENT_CALENDAR_ITEM) ||
  157. !strcmp(name, "FindItemResponse") ||
  158. !strcmp(name, "GetItemResponse") ||
  159. !strcmp(name, "CreateItemResponse") ||
  160. !strcmp(name, "ResponseMessages") ||
  161. !strcmp(name, "FindItemResponseMessage") || !strcmp(name, "GetItemResponseMessage") ||
  162. !strcmp(name, "Items")
  163. ) {
  164. return 1;
  165. } else if (!strcmp(name, "RootFolder")) {
  166. /* Get number of events */
  167. unsigned int items;
  168. ast_debug(3, "EWS: XML: <RootFolder>\n");
  169. if (sscanf(ne_xml_get_attr(ctx->parser, atts, NULL, "TotalItemsInView"), "%u", &items) != 1) {
  170. /* Couldn't read enything */
  171. ne_xml_set_error(ctx->parser, "Could't read number of events.");
  172. return NE_XML_ABORT;
  173. }
  174. ast_debug(3, "EWS: %u calendar items to load\n", items);
  175. ctx->pvt->items = items;
  176. if (items < 1) {
  177. /* Stop processing XML if there are no events */
  178. ast_calendar_merge_events(ctx->pvt->owner, ctx->pvt->events);
  179. return NE_XML_DECLINE;
  180. }
  181. return 1;
  182. } else if (!strcmp(name, "CalendarItem")) {
  183. /* Event start */
  184. ast_debug(3, "EWS: XML: <CalendarItem>\n");
  185. if (!(ctx->pvt && ctx->pvt->owner)) {
  186. ast_log(LOG_ERROR, "Require a private structure with an owner\n");
  187. return NE_XML_ABORT;
  188. }
  189. ctx->event = ast_calendar_event_alloc(ctx->pvt->owner);
  190. if (!ctx->event) {
  191. ast_log(LOG_ERROR, "Could not allocate an event!\n");
  192. return NE_XML_ABORT;
  193. }
  194. ctx->cdata = ast_str_create(64);
  195. if (!ctx->cdata) {
  196. ast_log(LOG_ERROR, "Could not allocate CDATA!\n");
  197. return NE_XML_ABORT;
  198. }
  199. return XML_EVENT_CALENDAR_ITEM;
  200. } else if (!strcmp(name, "ItemId")) {
  201. /* Event UID */
  202. if (ctx->op == XML_OP_FIND) {
  203. struct calendar_id *id;
  204. if (!(id = ast_calloc(1, sizeof(*id)))) {
  205. return NE_XML_ABORT;
  206. }
  207. if (!(id->id = ast_str_create(256))) {
  208. ast_free(id);
  209. return NE_XML_ABORT;
  210. }
  211. ast_str_set(&id->id, 0, "%s", ne_xml_get_attr(ctx->parser, atts, NULL, "Id"));
  212. AST_LIST_INSERT_TAIL(&ctx->ids, id, next);
  213. ast_debug(3, "EWS_FIND: XML: UID: %s\n", ast_str_buffer(id->id));
  214. } else {
  215. ast_debug(3, "EWS_GET: XML: UID: %s\n", ne_xml_get_attr(ctx->parser, atts, NULL, "Id"));
  216. ast_string_field_set(ctx->event, uid, ne_xml_get_attr(ctx->parser, atts, NULL, "Id"));
  217. }
  218. return XML_EVENT_NAME;
  219. } else if (!strcmp(name, "Subject")) {
  220. /* Event name */
  221. if (!ctx->cdata) {
  222. return NE_XML_ABORT;
  223. }
  224. ast_str_reset(ctx->cdata);
  225. return XML_EVENT_NAME;
  226. } else if (!strcmp(name, "Body") && parent == XML_EVENT_CALENDAR_ITEM) {
  227. /* Event body/description */
  228. if (!ctx->cdata) {
  229. return NE_XML_ABORT;
  230. }
  231. ast_str_reset(ctx->cdata);
  232. return XML_EVENT_DESCRIPTION;
  233. } else if (!strcmp(name, "Start")) {
  234. /* Event start time */
  235. return XML_EVENT_START;
  236. } else if (!strcmp(name, "End")) {
  237. /* Event end time */
  238. return XML_EVENT_END;
  239. } else if (!strcmp(name, "LegacyFreeBusyStatus")) {
  240. /* Event busy state */
  241. return XML_EVENT_BUSY;
  242. } else if (!strcmp(name, "Organizer") ||
  243. (parent == XML_EVENT_ORGANIZER && (!strcmp(name, "Mailbox") ||
  244. !strcmp(name, "Name")))) {
  245. /* Event organizer */
  246. if (!ctx->cdata) {
  247. return NE_XML_ABORT;
  248. }
  249. ast_str_reset(ctx->cdata);
  250. return XML_EVENT_ORGANIZER;
  251. } else if (!strcmp(name, "Location")) {
  252. /* Event location */
  253. if (!ctx->cdata) {
  254. return NE_XML_ABORT;
  255. }
  256. ast_str_reset(ctx->cdata);
  257. return XML_EVENT_LOCATION;
  258. } else if (!strcmp(name, "Categories")) {
  259. /* Event categories */
  260. if (!ctx->cdata) {
  261. return NE_XML_ABORT;
  262. }
  263. ast_str_reset(ctx->cdata);
  264. return XML_EVENT_CATEGORIES;
  265. } else if (parent == XML_EVENT_CATEGORIES && !strcmp(name, "String")) {
  266. /* Event category */
  267. return XML_EVENT_CATEGORY;
  268. } else if (!strcmp(name, "Importance")) {
  269. /* Event importance (priority) */
  270. if (!ctx->cdata) {
  271. return NE_XML_ABORT;
  272. }
  273. ast_str_reset(ctx->cdata);
  274. return XML_EVENT_IMPORTANCE;
  275. } else if (!strcmp(name, "RequiredAttendees") || !strcmp(name, "OptionalAttendees")) {
  276. return XML_EVENT_ATTENDEE_LIST;
  277. } else if (!strcmp(name, "Attendee") && parent == XML_EVENT_ATTENDEE_LIST) {
  278. return XML_EVENT_ATTENDEE;
  279. } else if (!strcmp(name, "Mailbox") && parent == XML_EVENT_ATTENDEE) {
  280. return XML_EVENT_MAILBOX;
  281. } else if (!strcmp(name, "EmailAddress") && parent == XML_EVENT_MAILBOX) {
  282. if (!ctx->cdata) {
  283. return NE_XML_ABORT;
  284. }
  285. ast_str_reset(ctx->cdata);
  286. return XML_EVENT_EMAIL_ADDRESS;
  287. }
  288. return NE_XML_DECLINE;
  289. }
  290. static int cdata(void *userdata, int state, const char *cdata, size_t len)
  291. {
  292. struct xml_context *ctx = userdata;
  293. char data[len + 1];
  294. /* !!! DON'T USE AST_STRING_FIELD FUNCTIONS HERE, JUST COLLECT CTX->CDATA !!! */
  295. if (state < XML_EVENT_NAME || ctx->op == XML_OP_CREATE) {
  296. return 0;
  297. }
  298. if (!ctx->event) {
  299. ast_log(LOG_ERROR, "Parsing event data, but event object does not exist!\n");
  300. return 1;
  301. }
  302. if (!ctx->cdata) {
  303. ast_log(LOG_ERROR, "String for storing CDATA is unitialized!\n");
  304. return 1;
  305. }
  306. ast_copy_string(data, cdata, len + 1);
  307. switch (state) {
  308. case XML_EVENT_START:
  309. ctx->event->start = mstime_to_time_t(data);
  310. break;
  311. case XML_EVENT_END:
  312. ctx->event->end = mstime_to_time_t(data);
  313. break;
  314. case XML_EVENT_BUSY:
  315. if (!strcmp(data, "Busy") || !strcmp(data, "OOF")) {
  316. ast_debug(3, "EWS: XML: Busy: yes\n");
  317. ctx->event->busy_state = AST_CALENDAR_BS_BUSY;
  318. }
  319. else if (!strcmp(data, "Tentative")) {
  320. ast_debug(3, "EWS: XML: Busy: tentative\n");
  321. ctx->event->busy_state = AST_CALENDAR_BS_BUSY_TENTATIVE;
  322. }
  323. else {
  324. ast_debug(3, "EWS: XML: Busy: no\n");
  325. ctx->event->busy_state = AST_CALENDAR_BS_FREE;
  326. }
  327. break;
  328. case XML_EVENT_CATEGORY:
  329. if (ast_str_strlen(ctx->cdata) == 0) {
  330. ast_str_set(&ctx->cdata, 0, "%s", data);
  331. } else {
  332. ast_str_append(&ctx->cdata, 0, ",%s", data);
  333. }
  334. break;
  335. default:
  336. ast_str_append(&ctx->cdata, 0, "%s", data);
  337. }
  338. ast_debug(5, "EWS: XML: CDATA: %s\n", ast_str_buffer(ctx->cdata));
  339. return 0;
  340. }
  341. static int endelm(void *userdata, int state, const char *nspace, const char *name)
  342. {
  343. struct xml_context *ctx = userdata;
  344. ast_debug(5, "EWS: XML: End: %s\n", name);
  345. if (ctx->op == XML_OP_FIND || ctx->op == XML_OP_CREATE) {
  346. return NE_XML_DECLINE;
  347. }
  348. if (!strcmp(name, "Subject")) {
  349. /* Event name end*/
  350. ast_string_field_set(ctx->event, summary, ast_str_buffer(ctx->cdata));
  351. ast_debug(3, "EWS: XML: Summary: %s\n", ctx->event->summary);
  352. ast_str_reset(ctx->cdata);
  353. } else if (!strcmp(name, "Body") && state == XML_EVENT_DESCRIPTION) {
  354. /* Event body/description end */
  355. ast_string_field_set(ctx->event, description, ast_str_buffer(ctx->cdata));
  356. ast_debug(3, "EWS: XML: Description: %s\n", ctx->event->description);
  357. ast_str_reset(ctx->cdata);
  358. } else if (!strcmp(name, "Organizer")) {
  359. /* Event organizer end */
  360. ast_string_field_set(ctx->event, organizer, ast_str_buffer(ctx->cdata));
  361. ast_debug(3, "EWS: XML: Organizer: %s\n", ctx->event->organizer);
  362. ast_str_reset(ctx->cdata);
  363. } else if (!strcmp(name, "Location")) {
  364. /* Event location end */
  365. ast_string_field_set(ctx->event, location, ast_str_buffer(ctx->cdata));
  366. ast_debug(3, "EWS: XML: Location: %s\n", ctx->event->location);
  367. ast_str_reset(ctx->cdata);
  368. } else if (!strcmp(name, "Categories")) {
  369. /* Event categories end */
  370. ast_string_field_set(ctx->event, categories, ast_str_buffer(ctx->cdata));
  371. ast_debug(3, "EWS: XML: Categories: %s\n", ctx->event->categories);
  372. ast_str_reset(ctx->cdata);
  373. } else if (!strcmp(name, "Importance")) {
  374. /* Event importance end */
  375. if (!strcmp(ast_str_buffer(ctx->cdata), "Low")) {
  376. ctx->event->priority = 9;
  377. } else if (!strcmp(ast_str_buffer(ctx->cdata), "Normal")) {
  378. ctx->event->priority = 5;
  379. } else if (!strcmp(ast_str_buffer(ctx->cdata), "High")) {
  380. ctx->event->priority = 1;
  381. }
  382. ast_debug(3, "EWS: XML: Importance: %s (%d)\n", ast_str_buffer(ctx->cdata), ctx->event->priority);
  383. ast_str_reset(ctx->cdata);
  384. } else if (state == XML_EVENT_EMAIL_ADDRESS) {
  385. struct ast_calendar_attendee *attendee;
  386. if (!(attendee = ast_calloc(1, sizeof(*attendee)))) {
  387. ctx->event = ast_calendar_unref_event(ctx->event);
  388. return 1;
  389. }
  390. if (ast_str_strlen(ctx->cdata)) {
  391. attendee->data = ast_strdup(ast_str_buffer(ctx->cdata));
  392. AST_LIST_INSERT_TAIL(&ctx->event->attendees, attendee, next);
  393. } else {
  394. ast_free(attendee);
  395. }
  396. ast_debug(3, "EWS: XML: attendee address '%s'\n", ast_str_buffer(ctx->cdata));
  397. ast_str_reset(ctx->cdata);
  398. } else if (!strcmp(name, "CalendarItem")) {
  399. /* Event end */
  400. ast_debug(3, "EWS: XML: </CalendarItem>\n");
  401. ast_free(ctx->cdata);
  402. if (ctx->event) {
  403. ao2_link(ctx->pvt->events, ctx->event);
  404. ctx->event = ast_calendar_unref_event(ctx->event);
  405. } else {
  406. ast_log(LOG_ERROR, "Event data ended in XML, but event object does not exist!\n");
  407. return 1;
  408. }
  409. } else if (!strcmp(name, "Envelope")) {
  410. /* Events end */
  411. ast_debug(3, "EWS: XML: %d of %d event(s) has been parsed…\n", ao2_container_count(ctx->pvt->events), ctx->pvt->items);
  412. if (ao2_container_count(ctx->pvt->events) >= ctx->pvt->items) {
  413. ast_debug(3, "EWS: XML: All events has been parsed, merging…\n");
  414. ast_calendar_merge_events(ctx->pvt->owner, ctx->pvt->events);
  415. }
  416. }
  417. return 0;
  418. }
  419. static const char *mstime(time_t t, char *buf, size_t buflen)
  420. {
  421. struct timeval tv = {
  422. .tv_sec = t,
  423. };
  424. struct ast_tm tm;
  425. ast_localtime(&tv, &tm, "utc");
  426. ast_strftime(buf, buflen, "%FT%TZ", &tm);
  427. return S_OR(buf, "");
  428. }
  429. static const char *msstatus(enum ast_calendar_busy_state state)
  430. {
  431. switch (state) {
  432. case AST_CALENDAR_BS_BUSY_TENTATIVE:
  433. return "Tentative";
  434. case AST_CALENDAR_BS_BUSY:
  435. return "Busy";
  436. case AST_CALENDAR_BS_FREE:
  437. return "Free";
  438. default:
  439. return "";
  440. }
  441. }
  442. static const char *get_soap_action(enum xml_op op)
  443. {
  444. switch (op) {
  445. case XML_OP_FIND:
  446. return "\"http://schemas.microsoft.com/exchange/services/2006/messages/FindItem\"";
  447. case XML_OP_GET:
  448. return "\"http://schemas.microsoft.com/exchange/services/2006/messages/GetItem\"";
  449. case XML_OP_CREATE:
  450. return "\"http://schemas.microsoft.com/exchange/services/2006/messages/CreateItem\"";
  451. }
  452. return "";
  453. }
  454. static int send_ews_request_and_parse(struct ast_str *request, struct xml_context *ctx)
  455. {
  456. int ret;
  457. ne_request *req;
  458. ne_xml_parser *parser;
  459. ast_debug(3, "EWS: HTTP request...\n");
  460. if (!(ctx && ctx->pvt)) {
  461. ast_log(LOG_ERROR, "There is no private!\n");
  462. return -1;
  463. }
  464. if (!ast_str_strlen(request)) {
  465. ast_log(LOG_ERROR, "No request to send!\n");
  466. return -1;
  467. }
  468. ast_debug(3, "%s\n", ast_str_buffer(request));
  469. /* Prepare HTTP POST request */
  470. req = ne_request_create(ctx->pvt->session, "POST", ctx->pvt->uri.path);
  471. ne_set_request_flag(req, NE_REQFLAG_IDEMPOTENT, 0);
  472. /* Set headers--should be application/soap+xml, but MS… :/ */
  473. ne_add_request_header(req, "Content-Type", "text/xml; charset=utf-8");
  474. ne_add_request_header(req, "SOAPAction", get_soap_action(ctx->op));
  475. /* Set body to SOAP request */
  476. ne_set_request_body_buffer(req, ast_str_buffer(request), ast_str_strlen(request));
  477. /* Prepare XML parser */
  478. parser = ne_xml_create();
  479. ctx->parser = parser;
  480. ne_xml_push_handler(parser, startelm, cdata, endelm, ctx); /* Callbacks */
  481. /* Dispatch request and parse response as XML */
  482. ret = ne_xml_dispatch_request(req, parser);
  483. if (ret != NE_OK) { /* Error handling */
  484. ast_log(LOG_WARNING, "Unable to communicate with Exchange Web Service at '%s': %s\n", ctx->pvt->url, ne_get_error(ctx->pvt->session));
  485. ne_request_destroy(req);
  486. ne_xml_destroy(parser);
  487. return -1;
  488. }
  489. /* Cleanup */
  490. ne_request_destroy(req);
  491. ne_xml_destroy(parser);
  492. return 0;
  493. }
  494. static int ewscal_write_event(struct ast_calendar_event *event)
  495. {
  496. struct ast_str *request;
  497. struct ewscal_pvt *pvt = event->owner->tech_pvt;
  498. char start[21], end[21];
  499. struct xml_context ctx = {
  500. .op = XML_OP_CREATE,
  501. .pvt = pvt,
  502. };
  503. int ret;
  504. char *category, *categories;
  505. if (!pvt) {
  506. return -1;
  507. }
  508. if (!(request = ast_str_create(1024))) {
  509. return -1;
  510. }
  511. ast_str_set(&request, 0,
  512. "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
  513. "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "
  514. "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" "
  515. "xmlns:t=\"http://schemas.microsoft.com/exchange/services/2006/types\">"
  516. "<soap:Body>"
  517. "<CreateItem xmlns=\"http://schemas.microsoft.com/exchange/services/2006/messages\" "
  518. "xmlns:t=\"http://schemas.microsoft.com/exchange/services/2006/types\" "
  519. "SendMeetingInvitations=\"SendToNone\" >"
  520. "<SavedItemFolderId>"
  521. "<t:DistinguishedFolderId Id=\"calendar\"/>"
  522. "</SavedItemFolderId>"
  523. "<Items>"
  524. "<t:CalendarItem xmlns=\"http://schemas.microsoft.com/exchange/services/2006/types\">"
  525. "<Subject>%s</Subject>"
  526. "<Body BodyType=\"Text\">%s</Body>"
  527. "<ReminderIsSet>false</ReminderIsSet>"
  528. "<Start>%s</Start>"
  529. "<End>%s</End>"
  530. "<IsAllDayEvent>false</IsAllDayEvent>"
  531. "<LegacyFreeBusyStatus>%s</LegacyFreeBusyStatus>"
  532. "<Location>%s</Location>",
  533. event->summary,
  534. event->description,
  535. mstime(event->start, start, sizeof(start)),
  536. mstime(event->end, end, sizeof(end)),
  537. msstatus(event->busy_state),
  538. event->location
  539. );
  540. /* Event priority */
  541. switch (event->priority) {
  542. case 1:
  543. case 2:
  544. case 3:
  545. case 4:
  546. ast_str_append(&request, 0, "<Importance>High</Importance>");
  547. break;
  548. case 5:
  549. ast_str_append(&request, 0, "<Importance>Normal</Importance>");
  550. break;
  551. case 6:
  552. case 7:
  553. case 8:
  554. case 9:
  555. ast_str_append(&request, 0, "<Importance>Low</Importance>");
  556. break;
  557. }
  558. /* Event categories*/
  559. if (strlen(event->categories) > 0) {
  560. ast_str_append(&request, 0, "<Categories>");
  561. categories = ast_strdupa(event->categories); /* Duplicate string, since strsep() is destructive */
  562. category = strsep(&categories, ",");
  563. while (category != NULL) {
  564. ast_str_append(&request, 0, "<String>%s</String>", category);
  565. category = strsep(&categories, ",");
  566. }
  567. ast_str_append(&request, 0, "</Categories>");
  568. }
  569. /* Finish request */
  570. ast_str_append(&request, 0, "</t:CalendarItem></Items></CreateItem></soap:Body></soap:Envelope>");
  571. ret = send_ews_request_and_parse(request, &ctx);
  572. ast_free(request);
  573. return ret;
  574. }
  575. static struct calendar_id *get_ewscal_ids_for(struct ewscal_pvt *pvt)
  576. {
  577. char start[21], end[21];
  578. struct ast_tm tm;
  579. struct timeval tv;
  580. struct ast_str *request;
  581. struct xml_context ctx = {
  582. .op = XML_OP_FIND,
  583. .pvt = pvt,
  584. };
  585. ast_debug(5, "EWS: get_ewscal_ids_for()\n");
  586. if (!pvt) {
  587. ast_log(LOG_ERROR, "There is no private!\n");
  588. return NULL;
  589. }
  590. /* Prepare timeframe strings */
  591. tv = ast_tvnow();
  592. ast_localtime(&tv, &tm, "UTC");
  593. ast_strftime(start, sizeof(start), "%FT%TZ", &tm);
  594. tv.tv_sec += 60 * pvt->owner->timeframe;
  595. ast_localtime(&tv, &tm, "UTC");
  596. ast_strftime(end, sizeof(end), "%FT%TZ", &tm);
  597. /* Prepare SOAP request */
  598. if (!(request = ast_str_create(512))) {
  599. return NULL;
  600. }
  601. ast_str_set(&request, 0,
  602. "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" "
  603. "xmlns:ns1=\"http://schemas.microsoft.com/exchange/services/2006/types\" "
  604. "xmlns:ns2=\"http://schemas.microsoft.com/exchange/services/2006/messages\">"
  605. "<SOAP-ENV:Body>"
  606. "<ns2:FindItem Traversal=\"Shallow\">"
  607. "<ns2:ItemShape>"
  608. "<ns1:BaseShape>IdOnly</ns1:BaseShape>"
  609. "</ns2:ItemShape>"
  610. "<ns2:CalendarView StartDate=\"%s\" EndDate=\"%s\"/>" /* Timeframe */
  611. "<ns2:ParentFolderIds>"
  612. "<ns1:DistinguishedFolderId Id=\"calendar\"/>"
  613. "</ns2:ParentFolderIds>"
  614. "</ns2:FindItem>"
  615. "</SOAP-ENV:Body>"
  616. "</SOAP-ENV:Envelope>",
  617. start, end /* Timeframe */
  618. );
  619. AST_LIST_HEAD_INIT_NOLOCK(&ctx.ids);
  620. /* Dispatch request and parse response as XML */
  621. if (send_ews_request_and_parse(request, &ctx)) {
  622. ast_free(request);
  623. return NULL;
  624. }
  625. /* Cleanup */
  626. ast_free(request);
  627. return AST_LIST_FIRST(&ctx.ids);
  628. }
  629. static int parse_ewscal_id(struct ewscal_pvt *pvt, const char *id) {
  630. struct ast_str *request;
  631. struct xml_context ctx = {
  632. .pvt = pvt,
  633. .op = XML_OP_GET,
  634. };
  635. if (!(request = ast_str_create(512))) {
  636. return -1;
  637. }
  638. ast_str_set(&request, 0,
  639. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  640. "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" "
  641. "xmlns:t=\"http://schemas.microsoft.com/exchange/services/2006/types\">"
  642. "<soap:Body>"
  643. "<GetItem xmlns=\"http://schemas.microsoft.com/exchange/services/2006/messages\">"
  644. "<ItemShape>"
  645. "<t:BaseShape>AllProperties</t:BaseShape>"
  646. "</ItemShape>"
  647. "<ItemIds>"
  648. "<t:ItemId Id=\"%s\"/>"
  649. "</ItemIds>"
  650. "</GetItem>"
  651. "</soap:Body>"
  652. "</soap:Envelope>", id
  653. );
  654. if (send_ews_request_and_parse(request, &ctx)) {
  655. ast_free(request);
  656. return -1;
  657. }
  658. ast_free(request);
  659. return 0;
  660. }
  661. static int update_ewscal(struct ewscal_pvt *pvt)
  662. {
  663. struct calendar_id *id_head;
  664. struct calendar_id *iter;
  665. if (!(id_head = get_ewscal_ids_for(pvt))) {
  666. return 0;
  667. }
  668. for (iter = id_head; iter; iter = AST_LIST_NEXT(iter, next)) {
  669. parse_ewscal_id(pvt, ast_str_buffer(iter->id));
  670. ast_free(iter->id);
  671. ast_free(iter);
  672. }
  673. return 0;
  674. }
  675. static void *ewscal_load_calendar(void *void_data)
  676. {
  677. struct ewscal_pvt *pvt;
  678. const struct ast_config *cfg;
  679. struct ast_variable *v;
  680. struct ast_calendar *cal = void_data;
  681. ast_mutex_t refreshlock;
  682. ast_debug(5, "EWS: ewscal_load_calendar()\n");
  683. if (!(cal && (cfg = ast_calendar_config_acquire()))) {
  684. ast_log(LOG_ERROR, "You must enable calendar support for res_ewscal to load\n");
  685. return NULL;
  686. }
  687. if (ao2_trylock(cal)) {
  688. if (cal->unloading) {
  689. ast_log(LOG_WARNING, "Unloading module, load_calendar cancelled.\n");
  690. } else {
  691. ast_log(LOG_WARNING, "Could not lock calendar, aborting!\n");
  692. }
  693. ast_calendar_config_release();
  694. return NULL;
  695. }
  696. if (!(pvt = ao2_alloc(sizeof(*pvt), ewscal_destructor))) {
  697. ast_log(LOG_ERROR, "Could not allocate ewscal_pvt structure for calendar: %s\n", cal->name);
  698. ast_calendar_config_release();
  699. return NULL;
  700. }
  701. pvt->owner = cal;
  702. if (!(pvt->events = ast_calendar_event_container_alloc())) {
  703. ast_log(LOG_ERROR, "Could not allocate space for fetching events for calendar: %s\n", cal->name);
  704. pvt = unref_ewscal(pvt);
  705. ao2_unlock(cal);
  706. ast_calendar_config_release();
  707. return NULL;
  708. }
  709. if (ast_string_field_init(pvt, 32)) {
  710. ast_log(LOG_ERROR, "Couldn't allocate string field space for calendar: %s\n", cal->name);
  711. pvt = unref_ewscal(pvt);
  712. ao2_unlock(cal);
  713. ast_calendar_config_release();
  714. return NULL;
  715. }
  716. for (v = ast_variable_browse(cfg, cal->name); v; v = v->next) {
  717. if (!strcasecmp(v->name, "url")) {
  718. ast_string_field_set(pvt, url, v->value);
  719. } else if (!strcasecmp(v->name, "user")) {
  720. ast_string_field_set(pvt, user, v->value);
  721. } else if (!strcasecmp(v->name, "secret")) {
  722. ast_string_field_set(pvt, secret, v->value);
  723. }
  724. }
  725. ast_calendar_config_release();
  726. if (ast_strlen_zero(pvt->url)) {
  727. ast_log(LOG_WARNING, "No URL was specified for Exchange Web Service calendar '%s' - skipping.\n", cal->name);
  728. pvt = unref_ewscal(pvt);
  729. ao2_unlock(cal);
  730. return NULL;
  731. }
  732. if (ne_uri_parse(pvt->url, &pvt->uri) || pvt->uri.host == NULL || pvt->uri.path == NULL) {
  733. ast_log(LOG_WARNING, "Could not parse url '%s' for Exchange Web Service calendar '%s' - skipping.\n", pvt->url, cal->name);
  734. pvt = unref_ewscal(pvt);
  735. ao2_unlock(cal);
  736. return NULL;
  737. }
  738. if (pvt->uri.scheme == NULL) {
  739. pvt->uri.scheme = "http";
  740. }
  741. if (pvt->uri.port == 0) {
  742. pvt->uri.port = ne_uri_defaultport(pvt->uri.scheme);
  743. }
  744. ast_debug(3, "ne_uri.scheme = %s\n", pvt->uri.scheme);
  745. ast_debug(3, "ne_uri.host = %s\n", pvt->uri.host);
  746. ast_debug(3, "ne_uri.port = %u\n", pvt->uri.port);
  747. ast_debug(3, "ne_uri.path = %s\n", pvt->uri.path);
  748. ast_debug(3, "user = %s\n", pvt->user);
  749. ast_debug(3, "secret = %s\n", pvt->secret);
  750. pvt->session = ne_session_create(pvt->uri.scheme, pvt->uri.host, pvt->uri.port);
  751. ne_redirect_register(pvt->session);
  752. ne_set_server_auth(pvt->session, auth_credentials, pvt);
  753. ne_set_useragent(pvt->session, "Asterisk");
  754. if (!strcasecmp(pvt->uri.scheme, "https")) {
  755. ne_ssl_trust_default_ca(pvt->session);
  756. ne_ssl_set_verify(pvt->session, ssl_verify, pvt);
  757. }
  758. cal->tech_pvt = pvt;
  759. ast_mutex_init(&refreshlock);
  760. /* Load it the first time */
  761. update_ewscal(pvt);
  762. ao2_unlock(cal);
  763. /* The only writing from another thread will be if unload is true */
  764. for (;;) {
  765. struct timeval tv = ast_tvnow();
  766. struct timespec ts = {0,};
  767. ts.tv_sec = tv.tv_sec + (60 * pvt->owner->refresh);
  768. ast_mutex_lock(&refreshlock);
  769. while (!pvt->owner->unloading) {
  770. if (ast_cond_timedwait(&pvt->owner->unload, &refreshlock, &ts) == ETIMEDOUT) {
  771. break;
  772. }
  773. }
  774. ast_mutex_unlock(&refreshlock);
  775. if (pvt->owner->unloading) {
  776. ast_debug(10, "Skipping refresh since we got a shutdown signal\n");
  777. return NULL;
  778. }
  779. ast_debug(10, "Refreshing after %d minute timeout\n", pvt->owner->refresh);
  780. update_ewscal(pvt);
  781. }
  782. return NULL;
  783. }
  784. static int load_module(void)
  785. {
  786. /* Actualy, 0.29.1 is required (because of NTLM authentication), but this
  787. * function does not support matching patch version. */
  788. if (ne_version_match(0, 29)) {
  789. ast_log(LOG_ERROR, "Exchange Web Service calendar module require neon >= 0.29.1, but %s is installed.\n", ne_version_string());
  790. return AST_MODULE_LOAD_DECLINE;
  791. }
  792. if (ast_calendar_register(&ewscal_tech) && (ne_sock_init() == 0)) {
  793. return AST_MODULE_LOAD_DECLINE;
  794. }
  795. return AST_MODULE_LOAD_SUCCESS;
  796. }
  797. static int unload_module(void)
  798. {
  799. ne_sock_exit();
  800. ast_calendar_unregister(&ewscal_tech);
  801. return 0;
  802. }
  803. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Asterisk MS Exchange Web Service Calendar Integration",
  804. .load = load_module,
  805. .unload = unload_module,
  806. .load_pri = AST_MODPRI_DEVSTATE_PLUGIN,
  807. );