Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

mod_jibri_queue_component.lua 19KB

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