res_calendar_ews.c 25 KB

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