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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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 requestURL = queueServiceURL.."/job/recording"
  177. if type=="LeaveQueue" then
  178. requestURL = requestURL .."/cancel"
  179. end
  180. local request = http.request(requestURL, {
  181. headers = headers,
  182. method = "POST",
  183. body = json.encode(out_event)
  184. }, function (content_, code_, response_, request_)
  185. if code_ == 200 or code_ == 204 then
  186. module:log("debug", "URL Callback: Code %s, Content %s, Request (host %s, path %s, body %s), Response: %s",
  187. code_, content_, request_.host, request_.path, inspect(request_.body), inspect(response_));
  188. module:log("info", "sending reply IQ %s",inspect(replyIq));
  189. module:send(replyIq);
  190. else
  191. module:log("warn", "URL Callback non successful: Code %s, Content %s, Request (%s), Response: %s",
  192. code_, content_, inspect(request_), inspect(response_));
  193. module:log("warn", "sending reply error IQ %s",inspect(replyError));
  194. module:send(replyError);
  195. end
  196. end);
  197. end
  198. -- receives iq from client currently connected to the room
  199. function on_iq(event)
  200. local requestId;
  201. -- Check the type of the incoming stanza to avoid loops:
  202. if event.stanza.attr.type == "error" then
  203. return; -- We do not want to reply to these, so leave.
  204. end
  205. if event.stanza.attr.to == module:get_host() then
  206. if event.stanza.attr.type == "set" then
  207. log("info", "Jibri Queue Messsage Event found: %s ",inspect(event.stanza));
  208. local reply = st.reply(event.stanza);
  209. local replyError = st.error_reply(event.stanza,'cancel','internal-server-error',"Queue Server Error");
  210. module:log("info","Reply stanza %s",inspect(reply));
  211. local jibriQueue
  212. = event.stanza:get_child('jibri-queue', 'http://jitsi.org/protocol/jibri-queue');
  213. if jibriQueue then
  214. module:log("info", "Jibri Queue Request: %s ",inspect(jibriQueue));
  215. local roomAddress = jibriQueue.attr.room;
  216. local room = get_room_from_jid(room_jid_match_rewrite(roomAddress));
  217. if not room then
  218. module:log("warn", "No room found %s", roomAddress);
  219. return false;
  220. end
  221. local from = event.stanza.attr.from;
  222. local occupant = room:get_occupant_by_real_jid(from);
  223. if not occupant then
  224. module:log("warn", "No occupant %s found for %s", from, roomAddress);
  225. return false;
  226. end
  227. local action = jibriQueue.attr.action;
  228. if action == 'join' then
  229. -- join action, so send event out
  230. requestId = uuid_gen();
  231. -- now handle new jibri queue message
  232. room.jibriQueue[occupant.jid] = requestId;
  233. reply:add_child(st.stanza("jibri-queue", { xmlns = 'http://jitsi.org/protocol/jibri-queue', requestId = requestId})):up()
  234. replyError:add_child(st.stanza("jibri-queue", { xmlns = 'http://jitsi.org/protocol/jibri-queue', requestId = requestId})):up()
  235. module:log("info","Sending JoinQueue event for jid %s occupant %s reply %s",roomAddress,occupant.jid,inspect(reply));
  236. sendEvent('JoinQueue',roomAddress,occupant.jid,requestId,reply,replyError);
  237. end
  238. if action == 'leave' then
  239. requestId = jibriQueue.attr.requestId;
  240. -- TODO: check that requestId is the same as cached value
  241. room.jibriQueue[occupant.jid] = nil;
  242. reply:add_child(st.stanza("jibri-queue", { xmlns = 'http://jitsi.org/protocol/jibri-queue', requestId = requestId})):up()
  243. replyError:add_child(st.stanza("jibri-queue", { xmlns = 'http://jitsi.org/protocol/jibri-queue', requestId = requestId})):up()
  244. sendEvent('LeaveQueue',roomAddress,occupant.jid,requestId,reply,replyError);
  245. end
  246. else
  247. module:log("warn","Jibri Queue Stanza missing child %s",inspect(event.stanza))
  248. end
  249. end
  250. end
  251. return true
  252. end
  253. -- create recorder queue cache for the room
  254. function room_created(event)
  255. local room = event.room;
  256. if is_healthcheck_room(room.jid) then
  257. return;
  258. end
  259. room.jibriQueue = {};
  260. end
  261. -- Conference ended, clear all queue cache jids
  262. function room_destroyed(event)
  263. local room = event.room;
  264. if is_healthcheck_room(room.jid) then
  265. return;
  266. end
  267. for jid, x in pairs(room.jibriQueue) do
  268. if x then
  269. sendEvent('LeaveQueue',internal_room_jid_match_rewrite(room.jid),jid,x);
  270. end
  271. end
  272. end
  273. -- Occupant left remove it from the queue if it joined the queue
  274. function occupant_leaving(event)
  275. local room = event.room;
  276. if is_healthcheck_room(room.jid) then
  277. return;
  278. end
  279. local occupant = event.occupant;
  280. local requestId = room.jibriQueue[occupant.jid];
  281. -- check if user has cached queue request
  282. if requestId then
  283. -- remove occupant from queue cache, signal backend
  284. room.jibriQueue[occupant.jid] = nil;
  285. sendEvent('LeaveQueue',internal_room_jid_match_rewrite(room.jid),occupant.jid,requestId);
  286. end
  287. end
  288. module:hook("iq/host", on_iq);
  289. -- executed on every host added internally in prosody, including components
  290. function process_host(host)
  291. if host == muc_component_host then -- the conference muc component
  292. module:log("info","Hook to muc events on %s", host);
  293. local muc_module = module:context(host);
  294. muc_module:hook("muc-room-created", room_created, -1);
  295. -- muc_module:hook("muc-occupant-joined", occupant_joined, -1);
  296. muc_module:hook("muc-occupant-pre-leave", occupant_leaving, -1);
  297. muc_module:hook("muc-room-destroyed", room_destroyed, -1);
  298. end
  299. end
  300. if prosody.hosts[muc_component_host] == nil then
  301. module:log("info","No muc component found, will listen for it: %s", muc_component_host)
  302. -- when a host or component is added
  303. prosody.events.add_handler("host-activated", process_host);
  304. else
  305. process_host(muc_component_host);
  306. end
  307. module:log("info", "Loading jibri_queue_component");
  308. --- Verifies room name, domain name with the values in the token
  309. -- @param token the token we received
  310. -- @param room_name the room name
  311. -- @param group name of the group (optional)
  312. -- @param session the session to use for storing token specific fields
  313. -- @return true if values are ok or false otherwise
  314. function verify_token(token, room_name, session)
  315. if disableTokenVerification then
  316. return true;
  317. end
  318. -- if not disableTokenVerification and we do not have token
  319. -- stop here, cause the main virtual host can have guest access enabled
  320. -- (allowEmptyToken = true) and we will allow access to rooms info without
  321. -- a token
  322. if token == nil then
  323. log("warn", "no token provided");
  324. return false;
  325. end
  326. session.auth_token = token;
  327. local verified, reason = token_util:process_and_verify_token(session);
  328. if not verified then
  329. log("warn", "not a valid token %s", tostring(reason));
  330. return false;
  331. end
  332. local room_address = jid.join(room_name, module:get_host());
  333. -- if there is a group we are in multidomain mode and that group is not
  334. -- our parent host
  335. if group and group ~= "" and group ~= parentHostName then
  336. room_address = "["..group.."]"..room_address;
  337. end
  338. if not token_util:verify_room(session, room_address) then
  339. log("warn", "Token %s not allowed to join: %s",
  340. tostring(token), tostring(room_address));
  341. return false;
  342. end
  343. return true;
  344. end
  345. --- Handles request for updating jibri queue status
  346. -- @param event the http event, holds the request query
  347. -- @return GET response, containing a json with response details
  348. function handle_update_jibri_queue(event)
  349. module:log("info","Update Jibri Queue Event Received");
  350. -- if (not event.request.url.query) then
  351. -- return { status_code = 400; };
  352. -- end
  353. local body = json.decode(event.request.body);
  354. -- local params = parse(event.request.url.query);
  355. module:log("info","Update Jibri Event Body %s",inspect(body));
  356. -- local token = params["token"];
  357. local token
  358. if not token then
  359. token = event.request.headers["authorization"];
  360. if not token then
  361. token = ''
  362. else
  363. local prefixStart, prefixEnd = token:find("Bearer ");
  364. if prefixStart ~= 1 then
  365. module:log("error", "Invalid authorization header format. The header must start with the string 'Bearer '");
  366. return 403
  367. end
  368. token = token:sub(prefixEnd + 1);
  369. end
  370. end
  371. local user_jid = body["participant"];
  372. local roomAddress = body["conference"];
  373. local userJWT = body["token"];
  374. local action = body["action"];
  375. local time = body["time"];
  376. local position = body["position"];
  377. local requestId = body["requestId"];
  378. if not verify_token(token, roomAddress, {}) then
  379. return { status_code = 403; };
  380. end
  381. local room = get_room_from_jid(room_jid_match_rewrite(roomAddress));
  382. if (not room) then
  383. log("error", "no room found %s", roomAddress);
  384. return { status_code = 404; };
  385. end
  386. local occupant = room:get_occupant_by_real_jid(user_jid);
  387. if not occupant then
  388. log("warn", "No occupant %s found for %s", user_jid, roomAddress);
  389. return { status_code = 404; };
  390. end
  391. if not room.jibriQueue[occupant.jid] then
  392. log("warn", "No queue request found for occupant %s in conference %s",occupant.jid,room.jid)
  393. return { status_code = 404; };
  394. end
  395. if not action then
  396. if userJWT then
  397. action = 'token';
  398. else
  399. action = 'info';
  400. end
  401. end
  402. if not requestId then
  403. requestId = room.jibriQueue[occupant.jid];
  404. end
  405. -- TODO: actually implement udpate code here
  406. sendIq(occupant.jid,action,requestId,time,position,userJWT);
  407. return { status_code = 200; };
  408. end
  409. module:depends("http");
  410. module:provides("http", {
  411. default_path = "/";
  412. name = "jibriqueue";
  413. route = {
  414. ["POST /jibriqueue/update"] = function (event) return async_handler_wrapper(event,handle_update_jibri_queue) end;
  415. };
  416. });