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