Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

mod_jibri_queue_component.lua 18KB

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