res_calendar_ews.c 26 KB

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