您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

mod_jibri_queue_component.lua 19KB

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