You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

mod_jibri_queue_component.lua 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. local st = require "util.stanza";
  2. local jid = require "util.jid";
  3. local http = require "net.http";
  4. local json = require "cjson";
  5. local inspect = require('inspect');
  6. local socket = require "socket";
  7. local uuid_gen = require "util.uuid".generate;
  8. local jwt = require "luajwtjitsi";
  9. local it = require "util.iterators";
  10. local neturl = require "net.url";
  11. local parse = neturl.parseQuery;
  12. local get_room_from_jid = module:require "util".get_room_from_jid;
  13. local room_jid_match_rewrite = module:require "util".room_jid_match_rewrite;
  14. local is_healthcheck_room = module:require "util".is_healthcheck_room;
  15. local room_jid_split_subdomain = module:require "util".room_jid_split_subdomain;
  16. local internal_room_jid_match_rewrite = module:require "util".internal_room_jid_match_rewrite;
  17. local async_handler_wrapper = module:require "util".async_handler_wrapper;
  18. -- this basically strips the domain from the conference.domain address
  19. local parentHostName = string.gmatch(tostring(module.host), "%w+.(%w.+)")();
  20. if parentHostName == nil then
  21. log("error", "Failed to start - unable to get parent hostname");
  22. return;
  23. end
  24. local parentCtx = module:context(parentHostName);
  25. if parentCtx == nil then
  26. log("error",
  27. "Failed to start - unable to get parent context for host: %s",
  28. tostring(parentHostName));
  29. return;
  30. end
  31. local token_util = module:require "token/util".new(parentCtx);
  32. local ASAPKeyPath
  33. = module:get_option_string("asap_key_path", '/etc/prosody/certs/asap.key');
  34. local ASAPKeyId
  35. = module:get_option_string("asap_key_id", 'jitsi');
  36. local ASAPIssuer
  37. = module:get_option_string("asap_issuer", 'jitsi');
  38. local ASAPAudience
  39. = module:get_option_string("asap_audience", 'jibriqueue');
  40. local ASAPTTL
  41. = module:get_option_number("asap_ttl", 3600);
  42. local ASAPTTL_THRESHOLD
  43. = module:get_option_number("asap_ttl_threshold", 600);
  44. local ASAPKey;
  45. local queueServiceURL
  46. = module:get_option_string("jibri_queue_url");
  47. if queueServiceURL == nil then
  48. log("error", "No jibri_queue_url specified. No service to contact!");
  49. return;
  50. end
  51. -- option to enable/disable token verifications
  52. local disableTokenVerification
  53. = module:get_option_boolean("disable_jibri_queue_token_verification", false);
  54. local http_headers = {
  55. ["User-Agent"] = "Prosody ("..prosody.version.."; "..prosody.platform..")",
  56. ["Content-Type"] = "application/json"
  57. };
  58. -- we use async to detect Prosody 0.10 and earlier
  59. local have_async = pcall(require, "util.async");
  60. if not have_async then
  61. module:log("warn", "conference duration will not work with Prosody version 0.10 or less.");
  62. return;
  63. end
  64. local muc_component_host = module:get_option_string("muc_component");
  65. if muc_component_host == nil then
  66. log("error", "No muc_component specified. No muc to operate on for jibri queue!");
  67. return;
  68. end
  69. log("info", "Starting jibri queue handling for %s", muc_component_host);
  70. local external_api_url = module:get_option_string("external_api_url",tostring(parentHostName));
  71. module:log("info", "External advertised API URL", external_api_url);
  72. -- Read ASAP key once on module startup
  73. local f = io.open(ASAPKeyPath, "r");
  74. if f then
  75. ASAPKey = f:read("*all");
  76. f:close();
  77. if not ASAPKey then
  78. module:log("warn", "No ASAP Key read, disabling muc_events plugin");
  79. return
  80. end
  81. else
  82. module:log("warn", "Error reading ASAP Key, disabling muc_events plugin");
  83. return
  84. end
  85. -- TODO: Figure out a less arbitrary default cache size.
  86. local jwtKeyCacheSize = module:get_option_number("jwt_pubkey_cache_size", 128);
  87. local jwtKeyCache = require"util.cache".new(jwtKeyCacheSize);
  88. local function round(num, numDecimalPlaces)
  89. local mult = 10^(numDecimalPlaces or 0)
  90. return math.floor(num * mult + 0.5) / mult
  91. end
  92. local function generateToken(audience)
  93. audience = audience or ASAPAudience
  94. local t = os.time()
  95. local err
  96. local exp_key = 'asap_exp.'..audience
  97. local token_key = 'asap_token.'..audience
  98. local exp = jwtKeyCache:get(exp_key)
  99. local token = jwtKeyCache:get(token_key)
  100. --if we find a token and it isn't too far from expiry, then use it
  101. if token ~= nil and exp ~= nil then
  102. exp = tonumber(exp)
  103. if (exp - t) > ASAPTTL_THRESHOLD then
  104. return token
  105. end
  106. end
  107. --expiry is the current time plus TTL
  108. exp = t + ASAPTTL
  109. local payload = {
  110. iss = ASAPIssuer,
  111. aud = audience,
  112. nbf = t,
  113. exp = exp,
  114. }
  115. -- encode
  116. local alg = "RS256"
  117. token, err = jwt.encode(payload, ASAPKey, alg, {kid = ASAPKeyId})
  118. if not err then
  119. token = 'Bearer '..token
  120. jwtKeyCache:set(exp_key,exp)
  121. jwtKeyCache:set(token_key,token)
  122. return token
  123. else
  124. return ''
  125. end
  126. end
  127. local function sendIq(participant,action,requestId,time,position,token)
  128. local iqId = uuid_gen();
  129. local from = module:get_host();
  130. module:log("info","Oubound iq id %s",iqId);
  131. local outStanza = st.iq({type = 'set', from = from, to = participant, id = iqId}):tag("jibri-queue",
  132. { xmlns = 'http://jitsi.org/protocol/jibri-queue', requestId = requestId, action = action });
  133. module:log("info","Oubound base stanza %s",inspect(outStanza));
  134. if token then
  135. outStanza:tag("token"):text(token):up()
  136. end
  137. if time then
  138. outStanza:tag("time"):text(time):up()
  139. end
  140. if position then
  141. outStanza:tag("position"):text(position):up()
  142. end
  143. module:log("info","Oubound stanza %s",inspect(outStanza));
  144. module:send(outStanza);
  145. end
  146. local function cb(content_, code_, response_, request_)
  147. if code_ == 200 or code_ == 204 then
  148. module:log("debug", "URL Callback: Code %s, Content %s, Request (host %s, path %s, body %s), Response: %s",
  149. code_, content_, request_.host, request_.path, inspect(request_.body), inspect(response_));
  150. else
  151. module:log("warn", "URL Callback non successful: Code %s, Content %s, Request (%s), Response: %s",
  152. code_, content_, inspect(request_), inspect(response_));
  153. end
  154. end
  155. local function sendEvent(type,room_address,participant,requestId,replyIq,replyError)
  156. local event_ts = round(socket.gettime()*1000);
  157. local node, host, resource, target_subdomain = room_jid_split_subdomain(room_address);
  158. local room_param = '';
  159. if target_subdomain then
  160. room_param = target_subdomain..'/'..node;
  161. else
  162. room_param = node;
  163. end
  164. local out_event = {
  165. ["conference"] = room_address,
  166. ["roomParam"] = room_param,
  167. ["eventType"] = type,
  168. ["participant"] = participant,
  169. ["externalApiUrl"] = external_api_url.."/jibriqueue/update",
  170. ["requestId"] = requestId,
  171. }
  172. module:log("debug","Sending event %s",inspect(out_event));
  173. local headers = http_headers or {}
  174. headers['Authorization'] = generateToken()
  175. module:log("debug","Sending headers %s",inspect(headers));
  176. local request = http.request(queueServiceURL, {
  177. headers = headers,
  178. method = "POST",
  179. body = json.encode(out_event)
  180. }, function (content_, code_, response_, request_)
  181. if code_ == 200 or code_ == 204 then
  182. module:log("debug", "URL Callback: Code %s, Content %s, Request (host %s, path %s, body %s), Response: %s",
  183. code_, content_, request_.host, request_.path, inspect(request_.body), inspect(response_));
  184. module:log("info", "sending reply IQ %s",inspect(replyIq));
  185. module:send(replyIq);
  186. else
  187. module:log("warn", "URL Callback non successful: Code %s, Content %s, Request (%s), Response: %s",
  188. code_, content_, inspect(request_), inspect(response_));
  189. module:log("warn", "sending reply error IQ %s",inspect(replyError));
  190. module:send(replyError);
  191. end
  192. end);
  193. end
  194. -- receives iq from client currently connected to the room
  195. function on_iq(event)
  196. local requestId;
  197. -- Check the type of the incoming stanza to avoid loops:
  198. if event.stanza.attr.type == "error" then
  199. return; -- We do not want to reply to these, so leave.
  200. end
  201. if event.stanza.attr.to == module:get_host() then
  202. if event.stanza.attr.type == "set" then
  203. log("info", "Jibri Queue Messsage Event found: %s ",inspect(event.stanza));
  204. local reply = st.reply(event.stanza);
  205. local replyError = st.error_reply(event.stanza,'cancel','internal-server-error',"Queue Server Error");
  206. module:log("info","Reply stanza %s",inspect(reply));
  207. local jibriQueue
  208. = event.stanza:get_child('jibri-queue', 'http://jitsi.org/protocol/jibri-queue');
  209. if jibriQueue then
  210. module:log("info", "Jibri Queue Request: %s ",inspect(jibriQueue));
  211. local roomAddress = jibriQueue.attr.room;
  212. local room = get_room_from_jid(room_jid_match_rewrite(roomAddress));
  213. if not room then
  214. module:log("warn", "No room found %s", roomAddress);
  215. return false;
  216. end
  217. local from = event.stanza.attr.from;
  218. local occupant = room:get_occupant_by_real_jid(from);
  219. if not occupant then
  220. module:log("warn", "No occupant %s found for %s", from, roomAddress);
  221. return false;
  222. end
  223. local action = jibriQueue.attr.action;
  224. if action == 'join' then
  225. -- join action, so send event out
  226. requestId = uuid_gen();
  227. -- now handle new jibri queue message
  228. room.jibriQueue[occupant.jid] = requestId;
  229. reply:add_child(st.stanza("jibri-queue", { xmlns = 'http://jitsi.org/protocol/jibri-queue', requestId = requestId})):up()
  230. replyError:add_child(st.stanza("jibri-queue", { xmlns = 'http://jitsi.org/protocol/jibri-queue', requestId = requestId})):up()
  231. module:log("info","Sending JoinQueue event for jid %s occupant %s reply %s",roomAddress,occupant.jid,inspect(reply));
  232. sendEvent('JoinQueue',roomAddress,occupant.jid,requestId,reply,replyError);
  233. end
  234. if action == 'leave' then
  235. requestId = jibriQueue.attr.requestId;
  236. -- TODO: check that requestId is the same as cached value
  237. room.jibriQueue[occupant.jid] = nil;
  238. reply:add_child(st.stanza("jibri-queue", { xmlns = 'http://jitsi.org/protocol/jibri-queue', requestId = requestId})):up()
  239. replyError:add_child(st.stanza("jibri-queue", { xmlns = 'http://jitsi.org/protocol/jibri-queue', requestId = requestId})):up()
  240. sendEvent('LeaveQueue',roomAddress,occupant.jid,requestId,reply,replyError);
  241. end
  242. else
  243. module:log("warn","Jibri Queue Stanza missing child %s",inspect(event.stanza))
  244. end
  245. end
  246. end
  247. return true
  248. end
  249. -- create recorder queue cache for the room
  250. function room_created(event)
  251. local room = event.room;
  252. if is_healthcheck_room(room.jid) then
  253. return;
  254. end
  255. room.jibriQueue = {};
  256. end
  257. -- Conference ended, clear all queue cache jids
  258. function room_destroyed(event)
  259. local room = event.room;
  260. if is_healthcheck_room(room.jid) then
  261. return;
  262. end
  263. for jid, x in pairs(room.jibriQueue) do
  264. if x then
  265. sendEvent('LeaveQueue',internal_room_jid_match_rewrite(room.jid),jid,x);
  266. end
  267. end
  268. end
  269. -- Occupant left remove it from the queue if it joined the queue
  270. function occupant_leaving(event)
  271. local room = event.room;
  272. if is_healthcheck_room(room.jid) then
  273. return;
  274. end
  275. local occupant = event.occupant;
  276. local requestId = room.jibriQueue[occupant.jid];
  277. -- check if user has cached queue request
  278. if requestId then
  279. -- remove occupant from queue cache, signal backend
  280. room.jibriQueue[occupant.jid] = nil;
  281. sendEvent('LeaveQueue',internal_room_jid_match_rewrite(room.jid),occupant.jid,requestId);
  282. end
  283. end
  284. module:hook("iq/host", on_iq);
  285. -- executed on every host added internally in prosody, including components
  286. function process_host(host)
  287. if host == muc_component_host then -- the conference muc component
  288. module:log("info","Hook to muc events on %s", host);
  289. local muc_module = module:context(host);
  290. muc_module:hook("muc-room-created", room_created, -1);
  291. -- muc_module:hook("muc-occupant-joined", occupant_joined, -1);
  292. muc_module:hook("muc-occupant-pre-leave", occupant_leaving, -1);
  293. muc_module:hook("muc-room-destroyed", room_destroyed, -1);
  294. end
  295. end
  296. if prosody.hosts[muc_component_host] == nil then
  297. module:log("info","No muc component found, will listen for it: %s", muc_component_host)
  298. -- when a host or component is added
  299. prosody.events.add_handler("host-activated", process_host);
  300. else
  301. process_host(muc_component_host);
  302. end
  303. module:log("info", "Loading jibri_queue_component");
  304. --- Verifies room name, domain name with the values in the token
  305. -- @param token the token we received
  306. -- @param room_name the room name
  307. -- @param group name of the group (optional)
  308. -- @param session the session to use for storing token specific fields
  309. -- @return true if values are ok or false otherwise
  310. function verify_token(token, room_name, session)
  311. if disableTokenVerification then
  312. return true;
  313. end
  314. -- if not disableTokenVerification and we do not have token
  315. -- stop here, cause the main virtual host can have guest access enabled
  316. -- (allowEmptyToken = true) and we will allow access to rooms info without
  317. -- a token
  318. if token == nil then
  319. log("warn", "no token provided");
  320. return false;
  321. end
  322. session.auth_token = token;
  323. local verified, reason = token_util:process_and_verify_token(session);
  324. if not verified then
  325. log("warn", "not a valid token %s", tostring(reason));
  326. return false;
  327. end
  328. local room_address = jid.join(room_name, module:get_host());
  329. -- if there is a group we are in multidomain mode and that group is not
  330. -- our parent host
  331. if group and group ~= "" and group ~= parentHostName then
  332. room_address = "["..group.."]"..room_address;
  333. end
  334. if not token_util:verify_room(session, room_address) then
  335. log("warn", "Token %s not allowed to join: %s",
  336. tostring(token), tostring(room_address));
  337. return false;
  338. end
  339. return true;
  340. end
  341. --- Handles request for updating jibri queue status
  342. -- @param event the http event, holds the request query
  343. -- @return GET response, containing a json with response details
  344. function handle_update_jibri_queue(event)
  345. module:log("info","Update Jibri Queue Event Received");
  346. -- if (not event.request.url.query) then
  347. -- return { status_code = 400; };
  348. -- end
  349. local body = json.decode(event.request.body);
  350. -- local params = parse(event.request.url.query);
  351. module:log("info","Update Jibri Event Body %s",inspect(body));
  352. -- local token = params["token"];
  353. local token
  354. if not token then
  355. token = event.request.headers["authorization"];
  356. if not token then
  357. token = ''
  358. else
  359. local prefixStart, prefixEnd = token:find("Bearer ");
  360. if prefixStart ~= 1 then
  361. module:log("error", "Invalid authorization header format. The header must start with the string 'Bearer '");
  362. return 403
  363. end
  364. token = token:sub(prefixEnd + 1);
  365. end
  366. end
  367. local user_jid = body["participant"];
  368. local roomAddress = body["conference"];
  369. local userJWT = body["token"];
  370. local action = body["action"];
  371. local time = body["time"];
  372. local position = body["position"];
  373. local requestId = body["requestId"];
  374. if not verify_token(token, roomAddress, {}) then
  375. return { status_code = 403; };
  376. end
  377. local room = get_room_from_jid(room_jid_match_rewrite(roomAddress));
  378. if (not room) then
  379. log("error", "no room found %s", roomAddress);
  380. return { status_code = 404; };
  381. end
  382. local occupant = room:get_occupant_by_real_jid(user_jid);
  383. if not occupant then
  384. log("warn", "No occupant %s found for %s", user_jid, roomAddress);
  385. return { status_code = 404; };
  386. end
  387. if not room.jibriQueue[occupant.jid] then
  388. log("warn", "No queue request found for occupant %s in conference %s",occupant.jid,room.jid)
  389. return { status_code = 404; };
  390. end
  391. if not action then
  392. if userJWT then
  393. action = 'token';
  394. else
  395. action = 'info';
  396. end
  397. end
  398. if not requestId then
  399. requestId = room.jibriQueue[occupant.jid];
  400. end
  401. -- TODO: actually implement udpate code here
  402. sendIq(occupant.jid,action,requestId,time,position,userJWT);
  403. return { status_code = 200; };
  404. end
  405. module:depends("http");
  406. module:provides("http", {
  407. default_path = "/";
  408. name = "jibriqueue";
  409. route = {
  410. ["POST /jibriqueue/update"] = function (event) return async_handler_wrapper(event,handle_update_jibri_queue) end;
  411. };
  412. });